frankensearch-core 0.2.2

Core traits, types, and error types for frankensearch
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
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
//! Central typed semantic [`RecoveryPlan`] and truthful readiness planner
//! (bd-vmv7).
//!
//! One versioned, machine-readable contract that maps the current semantic
//! readiness state plus the requested mode and policy to a truthful next
//! action. Products (facade, fsfs, CASS) consume this shared type instead of
//! parsing error strings; the terminal integration bead wires state
//! producers and executors around it.
//!
//! # Truthfulness invariants
//!
//! - Installing a model never claims semantic-searchable: the acquire
//!   action's postcondition is model-acquired-unverified, and readiness
//!   additionally requires a load self-test and a compatible non-empty
//!   index. This is enforced by test, not convention.
//! - Explicit semantic requests fail closed for every unavailable state.
//!   Typed partial-quality coverage remains semantically available at its
//!   measured coverage; hybrid requests may otherwise proceed lexical-only,
//!   but only with a [`SemanticResponseContract`] that names the requested
//!   and realized topologies, reports zero coverage, and admits zero semantic
//!   scores.
//! - The planner is pure and exhaustive: every enumerated state is matched
//!   without wildcards, so a new readiness state fails compilation until it
//!   is planned for.
//! - Model acquisition is always scoped to one logical model, tier, complete
//!   mathematical embedding-space identity, frozen manifest, revision,
//!   license assertion, source, byte budget, path-free destination identity,
//!   document census, and caller-computed reindex estimate. An authorization
//!   for any other scope is not interchangeable.
//! - Serialized plans are deliberately untrusted and non-executable. A caller
//!   must validate one against independently obtained readiness, request,
//!   policy, and frozen-target inputs; success returns a newly planned
//!   [`RecoveryPlan`] rather than promoting payload fields.
//! - A recovery action exposes argv only when the current product command
//!   enforces the complete authorization and semantic identity contract.
//!   Model acquisition, daemon/ANN repair, and all semantic index mutations
//!   are capability-blocked in this core-only tranche because current generic
//!   commands do not provide that binding.
//!
//! # Why schema v4
//!
//! The original v1 foundation represented offline recovery as a blocked
//! network download, represented request mode without retrieval topology,
//! and had no producer provenance, response-admission contract, or scoped
//! acquisition authorization. Correcting those facts changes required wire
//! fields and reverses the meaning of the offline transition, so decoding the
//! v2 contract as v1 would be unsafe. V3 additionally bound acquisition
//! consent to the exact model ID, tier, and mathematical space plus the
//! caller-supplied document count and estimated reindex duration, and refuses
//! to emit acquisition argv until an executor can consume that entire scope.
//! It also separated untrusted wire payloads from executable plans and pinned
//! recovery-local tier values to lowercase `fast` / `quality` spellings
//! instead of inheriting the Rust enum's incidental serde representation.
//! V4 makes every acquisition authorization short-lived, nonce-bound, and
//! evaluated only against caller-supplied trusted time. A v3 client cannot
//! safely present or validate those required anti-replay facts, so v4
//! deliberately fails closed on older payloads instead of installing a
//! compatibility shim. Every v1/v2/v3 stable
//! state/action/postcondition/policy code remains unchanged.
//!
//! # Stable codes
//!
//! Every state, action, postcondition, and policy-prerequisite code is a
//! three-segment lowercase dotted identifier (the same format the
//! observability lint enforces for reason codes) and is append-only within
//! a schema version. All codes live in this module so the full table is
//! auditable in one place; a test validates format and uniqueness against
//! [`crate::decision_plane::ReasonCode`] rules.

use serde::{Deserialize, Serialize};

use crate::{
    config::ZeroSignalReason,
    generation::{EmbeddingSpaceIdentityV1, EmbeddingSpaceKindV1},
    traits::ModelTier,
    types::{RetrievalTopology, retrieval_topology_fits_request},
};

mod recovery_model_tier_wire {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    use crate::traits::ModelTier;

    #[derive(Serialize, Deserialize)]
    #[serde(rename_all = "snake_case")]
    enum WireModelTier {
        Fast,
        Quality,
    }

    // Serde's `with` module contract passes the field by reference even
    // though ModelTier is Copy.
    #[allow(clippy::trivially_copy_pass_by_ref)]
    pub fn serialize<S>(tier: &ModelTier, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match tier {
            ModelTier::Fast => WireModelTier::Fast,
            ModelTier::Quality => WireModelTier::Quality,
        }
        .serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<ModelTier, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(match WireModelTier::deserialize(deserializer)? {
            WireModelTier::Fast => ModelTier::Fast,
            WireModelTier::Quality => ModelTier::Quality,
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Default)]
enum WireField<T> {
    #[default]
    Missing,
    Present(T),
}

impl<'de, T> Deserialize<'de> for WireField<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        T::deserialize(deserializer).map(Self::Present)
    }
}

impl<T> WireField<Option<T>> {
    fn required_option_ref(&self) -> Result<Option<&T>, ()> {
        match self {
            Self::Missing => Err(()),
            Self::Present(value) => Ok(value.as_ref()),
        }
    }
}

/// Schema version for serialized [`RecoveryPlan`] payloads.
pub const RECOVERY_PLAN_SCHEMA_VERSION: &str = "frankensearch.recovery_plan.v4";

/// Schema version for a scoped [`ModelAcquisitionAuthorization`].
pub const MODEL_ACQUISITION_AUTHORIZATION_SCHEMA_VERSION: &str =
    "frankensearch.model_acquisition_authorization.v3";

/// Maximum lifetime of one exact model-acquisition authorization.
///
/// The planner is clock-free: callers freeze issuance, expiry, and trusted
/// evaluation time. This bound limits replay exposure but does not claim
/// single-use semantics; an executor promising single use must additionally
/// consume nonces atomically.
pub const MAX_MODEL_ACQUISITION_AUTHORIZATION_LIFETIME_SECONDS: u64 = 15 * 60;

/// One million parts per million: complete semantic document coverage.
pub const COMPLETE_COVERAGE_PPM: u32 = 1_000_000;

/// Placeholder token integrators substitute with the resolved index
/// directory.
///
/// The pure planner never sees real user paths (they are redacted from
/// telemetry); rendering a runnable command is the integrator's job.
pub const ARG_INDEX_DIR: &str = "<index-dir>";

/// Placeholder token integrators substitute with the corpus source
/// directory to (re-)ingest.
pub const ARG_SOURCE_DIR: &str = "<source-dir>";

/// Reserved placeholder for a future operator-supplied local model bundle.
///
/// The current fsfs parser does not implement offline model import, so the
/// planner never emits this token in executable argv. It remains a public
/// schema vocabulary item for the future capability rather than pretending a
/// fictional command is runnable today.
pub const ARG_MODEL_BUNDLE: &str = "ARG_MODEL_BUNDLE";

/// Wire discriminator for [`RecoveryPlan`].
///
/// Using a closed enum rather than an arbitrary string makes serde reject
/// older or unknown schemas before a caller can accidentally execute their
/// actions with v4 semantics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum RecoveryPlanSchemaVersion {
    #[serde(rename = "frankensearch.recovery_plan.v4")]
    V4,
}

/// Wire discriminator for [`ModelAcquisitionAuthorization`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ModelAcquisitionAuthorizationSchemaVersion {
    #[serde(rename = "frankensearch.model_acquisition_authorization.v3")]
    V3,
}

/// Verified producer provenance for a semantic-ready lane.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerifiedSemanticProvenance {
    /// Frozen local artifacts passed manifest verification and load self-test.
    Local,
    /// A remote producer passed the pinned response-attestation contract.
    Remote,
    /// A daemon producer passed the pinned daemon-attestation contract.
    Daemon,
}

/// Trust classification exposed with every recovery plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SemanticProvenance {
    VerifiedLocal,
    VerifiedRemote,
    VerifiedDaemon,
    /// Explicit remote intent exists, but its producer space is not attested.
    UnverifiedRemote,
    /// Explicit non-semantic hash test/control lane.
    HashControl,
    /// No producer is currently admissible.
    Unavailable,
}

impl From<VerifiedSemanticProvenance> for SemanticProvenance {
    fn from(value: VerifiedSemanticProvenance) -> Self {
        match value {
            VerifiedSemanticProvenance::Local => Self::VerifiedLocal,
            VerifiedSemanticProvenance::Remote => Self::VerifiedRemote,
            VerifiedSemanticProvenance::Daemon => Self::VerifiedDaemon,
        }
    }
}

/// Why the caller's request cannot be served semantically right now.
///
/// This is the planner's input state, produced by readiness probes
/// (model manifest checks, index census, generation binding). Variants
/// mirror the states bd-vmv7 enumerates; [`ZeroSignalReason`] carries the
/// finer classification for empty-index states so the two vocabularies
/// stay aligned rather than diverging.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case", tag = "state", content = "detail")]
pub enum SemanticReadiness {
    /// The semantic lane is fully usable: verified model, loadable, and a
    /// compatible index with usable live vectors.
    Ready {
        provenance: VerifiedSemanticProvenance,
    },
    /// No usable model artifact exists in the configured cache for this exact
    /// progressive tier.
    ModelMissing {
        #[serde(with = "recovery_model_tier_wire")]
        tier: ModelTier,
    },
    /// A model artifact exists for this exact progressive tier but failed
    /// verification or load self-test.
    ModelUnloadable {
        #[serde(with = "recovery_model_tier_wire")]
        tier: ModelTier,
    },
    /// A verified, loadable model exists but no vector index does.
    IndexAbsent,
    /// The index exists but its embedding-space identity does not match the
    /// configured model (legacy generation or intentional identity change).
    IdentityMismatch,
    /// A daemon serves a different embedding space than the local
    /// configuration expects.
    DaemonMismatch,
    /// The index exists and is readable but produced zero signal; the typed
    /// reason distinguishes benign emptiness from availability failures.
    IndexEmpty(ZeroSignalReason),
    /// The index or model manifest is corrupt or fails safety validation
    /// and must not be trusted.
    ManifestUnsafe,
    /// The ANN sidecar belongs to an older generation than the vector
    /// index; exact search works but ANN must not serve.
    AnnStale,
    /// An index generation was interrupted before publication.
    GenerationIncomplete,
    /// Fast-tier search works but some records lack quality-tier
    /// embeddings, so refinement coverage is partial.
    PartialQualityCoverage {
        provenance: VerifiedSemanticProvenance,
        /// Fraction of live documents with quality-tier embeddings.
        coverage_ppm: u32,
    },
    /// Explicit remote intent exists, but the producer cannot be attested.
    /// This state is durable, non-indexable, and never becomes local/hash
    /// fallback inside the planner.
    RemoteUnverified,
    /// Explicit non-semantic hash test/control lane.
    HashControl,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ReadyDetailWire {
    provenance: VerifiedSemanticProvenance,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ModelTierDetailWire {
    #[serde(with = "recovery_model_tier_wire")]
    tier: ModelTier,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PartialQualityCoverageDetailWire {
    provenance: VerifiedSemanticProvenance,
    coverage_ppm: u32,
}

#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum SemanticReadinessTagWire {
    Ready,
    ModelMissing,
    ModelUnloadable,
    IndexAbsent,
    IdentityMismatch,
    DaemonMismatch,
    IndexEmpty,
    ManifestUnsafe,
    AnnStale,
    GenerationIncomplete,
    PartialQualityCoverage,
    RemoteUnverified,
    HashControl,
}

#[derive(Deserialize)]
#[serde(untagged)]
enum SemanticReadinessDetailWire {
    Ready(ReadyDetailWire),
    ModelTier(ModelTierDetailWire),
    PartialQualityCoverage(PartialQualityCoverageDetailWire),
    ZeroSignal(ZeroSignalReason),
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct SemanticReadinessWire {
    state: SemanticReadinessTagWire,
    #[serde(default)]
    detail: WireField<SemanticReadinessDetailWire>,
}

impl<'de> Deserialize<'de> for SemanticReadiness {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = SemanticReadinessWire::deserialize(deserializer)?;
        match (wire.state, wire.detail) {
            (
                SemanticReadinessTagWire::Ready,
                WireField::Present(SemanticReadinessDetailWire::Ready(ReadyDetailWire {
                    provenance,
                })),
            ) => Ok(Self::Ready { provenance }),
            (
                SemanticReadinessTagWire::ModelMissing,
                WireField::Present(SemanticReadinessDetailWire::ModelTier(ModelTierDetailWire {
                    tier,
                })),
            ) => Ok(Self::ModelMissing { tier }),
            (
                SemanticReadinessTagWire::ModelUnloadable,
                WireField::Present(SemanticReadinessDetailWire::ModelTier(ModelTierDetailWire {
                    tier,
                })),
            ) => Ok(Self::ModelUnloadable { tier }),
            (SemanticReadinessTagWire::IndexAbsent, WireField::Missing) => Ok(Self::IndexAbsent),
            (SemanticReadinessTagWire::IdentityMismatch, WireField::Missing) => {
                Ok(Self::IdentityMismatch)
            }
            (SemanticReadinessTagWire::DaemonMismatch, WireField::Missing) => {
                Ok(Self::DaemonMismatch)
            }
            (
                SemanticReadinessTagWire::IndexEmpty,
                WireField::Present(SemanticReadinessDetailWire::ZeroSignal(reason)),
            ) => Ok(Self::IndexEmpty(reason)),
            (SemanticReadinessTagWire::ManifestUnsafe, WireField::Missing) => {
                Ok(Self::ManifestUnsafe)
            }
            (SemanticReadinessTagWire::AnnStale, WireField::Missing) => Ok(Self::AnnStale),
            (SemanticReadinessTagWire::GenerationIncomplete, WireField::Missing) => {
                Ok(Self::GenerationIncomplete)
            }
            (
                SemanticReadinessTagWire::PartialQualityCoverage,
                WireField::Present(SemanticReadinessDetailWire::PartialQualityCoverage(
                    PartialQualityCoverageDetailWire {
                        provenance,
                        coverage_ppm,
                    },
                )),
            ) => Ok(Self::PartialQualityCoverage {
                provenance,
                coverage_ppm,
            }),
            (SemanticReadinessTagWire::RemoteUnverified, WireField::Missing) => {
                Ok(Self::RemoteUnverified)
            }
            (SemanticReadinessTagWire::HashControl, WireField::Missing) => Ok(Self::HashControl),
            _ => Err(serde::de::Error::custom(
                "readiness detail is missing, forbidden, or inconsistent with state",
            )),
        }
    }
}

impl SemanticReadiness {
    /// Stable three-segment state code.
    #[must_use]
    pub const fn state_code(&self) -> &'static str {
        match self {
            Self::Ready { .. } => "recovery.state.ready",
            Self::ModelMissing { .. } => "recovery.state.model_missing",
            Self::ModelUnloadable { .. } => "recovery.state.model_unloadable",
            Self::IndexAbsent => "recovery.state.index_absent",
            Self::IdentityMismatch => "recovery.state.identity_mismatch",
            Self::DaemonMismatch => "recovery.state.daemon_mismatch",
            Self::IndexEmpty(_) => "recovery.state.index_empty",
            Self::ManifestUnsafe => "recovery.state.manifest_unsafe",
            Self::AnnStale => "recovery.state.ann_stale",
            Self::GenerationIncomplete => "recovery.state.generation_incomplete",
            Self::PartialQualityCoverage { .. } => "recovery.state.partial_quality_coverage",
            Self::RemoteUnverified => "recovery.state.remote_unverified",
            Self::HashControl => "recovery.state.hash_control",
        }
    }

    /// True when semantic results can be served (possibly with reduced
    /// refinement quality). Only [`Self::Ready`] and
    /// [`Self::PartialQualityCoverage`] qualify: partial coverage degrades
    /// refinement, not availability.
    #[must_use]
    pub const fn semantic_available(&self) -> bool {
        matches!(
            self,
            Self::Ready { .. } | Self::PartialQualityCoverage { .. }
        )
    }

    /// Producer trust associated with the current readiness state.
    #[must_use]
    pub const fn provenance(&self) -> SemanticProvenance {
        match self {
            Self::Ready { provenance } | Self::PartialQualityCoverage { provenance, .. } => {
                match provenance {
                    VerifiedSemanticProvenance::Local => SemanticProvenance::VerifiedLocal,
                    VerifiedSemanticProvenance::Remote => SemanticProvenance::VerifiedRemote,
                    VerifiedSemanticProvenance::Daemon => SemanticProvenance::VerifiedDaemon,
                }
            }
            Self::RemoteUnverified => SemanticProvenance::UnverifiedRemote,
            Self::HashControl => SemanticProvenance::HashControl,
            Self::ModelMissing { .. }
            | Self::ModelUnloadable { .. }
            | Self::IndexAbsent
            | Self::IdentityMismatch
            | Self::DaemonMismatch
            | Self::IndexEmpty(_)
            | Self::ManifestUnsafe
            | Self::AnnStale
            | Self::GenerationIncomplete => SemanticProvenance::Unavailable,
        }
    }
}

/// What the caller asked for.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RequestMode {
    /// The caller explicitly requires semantic results: fail closed when
    /// the lane is unavailable.
    ExplicitSemantic,
    /// The caller accepts hybrid results: lexical fallback is permitted,
    /// but only with explicit degradation metadata.
    Hybrid,
    /// Explicit non-semantic hash test/control request.
    HashControl,
}

/// Requested operation, including the exact retrieval topology.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct RecoveryRequest {
    pub mode: RequestMode,
    pub requested_topology: RetrievalTopology,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RecoveryRequestWire {
    mode: RequestMode,
    requested_topology: RetrievalTopology,
}

impl<'de> Deserialize<'de> for RecoveryRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = RecoveryRequestWire::deserialize(deserializer)?;
        Self {
            mode: wire.mode,
            requested_topology: wire.requested_topology,
        }
        .validate()
        .map_err(serde::de::Error::custom)
    }
}

impl RecoveryRequest {
    /// Validate that mode and topology describe one unambiguous request.
    ///
    /// `PartialQuality` and `LexicalOnly` are realized topologies, never
    /// semantic request targets. Hash is legal only through the explicit
    /// `HashControl` mode.
    ///
    /// # Errors
    ///
    /// Returns [`RecoveryContractError::InvalidRequestTopology`] for an
    /// ambiguous or silently degrading combination.
    pub fn validate(self) -> Result<Self, RecoveryContractError> {
        let valid = match self.mode {
            RequestMode::ExplicitSemantic | RequestMode::Hybrid => matches!(
                self.requested_topology,
                RetrievalTopology::FastOnly
                    | RetrievalTopology::QualityOnly
                    | RetrievalTopology::FullProgressive
            ),
            RequestMode::HashControl => {
                matches!(self.requested_topology, RetrievalTopology::HashControl)
            }
        };
        if valid {
            Ok(self)
        } else {
            Err(RecoveryContractError::InvalidRequestTopology {
                mode: self.mode,
                topology: self.requested_topology,
            })
        }
    }
}

/// Whether a human can be asked for consent right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InteractionPolicy {
    Interactive,
    NonInteractive,
}

/// Whether network access is permitted for recovery actions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NetworkPolicy {
    Allowed,
    Offline,
}

/// The caller's environment policy, combined.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RecoveryPolicy {
    pub interaction: InteractionPolicy,
    pub network: NetworkPolicy,
    /// Exact non-TTY/programmatic model-acquisition authorization, when
    /// already granted. It satisfies consent only when byte-for-byte equal
    /// to the action's required authorization.
    pub acquisition_authorization: Option<ModelAcquisitionAuthorization>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RecoveryPolicyWire {
    interaction: InteractionPolicy,
    network: NetworkPolicy,
    #[serde(default)]
    acquisition_authorization: WireField<Option<ModelAcquisitionAuthorization>>,
}

impl<'de> Deserialize<'de> for RecoveryPolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = RecoveryPolicyWire::deserialize(deserializer)?;
        let WireField::Present(acquisition_authorization) = wire.acquisition_authorization else {
            return Err(serde::de::Error::missing_field("acquisition_authorization"));
        };
        Ok(Self {
            interaction: wire.interaction,
            network: wire.network,
            acquisition_authorization,
        })
    }
}

/// Path-free class of destination bound by model-acquisition consent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ModelDestinationClass {
    /// Product-managed model cache.
    ManagedCache,
    /// Caller-selected model directory outside the managed cache.
    ExplicitDirectory,
}

/// Machine-distinguishable byte source authorized for acquisition.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum ModelAcquisitionSource {
    /// Immutable HTTPS sources named by credential-free host.
    Network { source_hosts: Vec<String> },
    /// Complete operator-supplied artifact tree.
    LocalBundle,
}

#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum ModelAcquisitionSourceTagWire {
    Network,
    LocalBundle,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ModelAcquisitionSourceWire {
    kind: ModelAcquisitionSourceTagWire,
    #[serde(default)]
    source_hosts: WireField<Vec<String>>,
}

impl<'de> Deserialize<'de> for ModelAcquisitionSource {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = ModelAcquisitionSourceWire::deserialize(deserializer)?;
        match (wire.kind, wire.source_hosts) {
            (ModelAcquisitionSourceTagWire::Network, WireField::Present(source_hosts)) => {
                Ok(Self::Network { source_hosts })
            }
            (ModelAcquisitionSourceTagWire::Network, WireField::Missing) => {
                Err(serde::de::Error::missing_field("source_hosts"))
            }
            (ModelAcquisitionSourceTagWire::LocalBundle, WireField::Missing) => {
                Ok(Self::LocalBundle)
            }
            (ModelAcquisitionSourceTagWire::LocalBundle, WireField::Present(_)) => Err(
                serde::de::Error::custom("source_hosts is forbidden for local_bundle source"),
            ),
        }
    }
}

/// Exact, path-free authorization required before model bytes are acquired.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ModelAcquisitionAuthorization {
    pub schema_version: ModelAcquisitionAuthorizationSchemaVersion,
    /// Stable logical ID passed to the exact-model acquisition command.
    pub model_id: String,
    /// Progressive tier this artifact will serve.
    #[serde(with = "recovery_model_tier_wire")]
    pub model_tier: ModelTier,
    /// Complete mathematical identity of the vectors this model produces.
    ///
    /// A model name, revision, or dimension alone never establishes space
    /// compatibility.
    pub embedding_space: EmbeddingSpaceIdentityV1,
    pub manifest_fingerprint: String,
    pub upstream_revision: String,
    pub license_spdx: String,
    pub source: ModelAcquisitionSource,
    pub byte_budget: u64,
    pub destination_class: ModelDestinationClass,
    /// Bounded hash of the canonical destination, never the raw path.
    pub destination_fingerprint: String,
    /// Exact corpus size shown when consent is requested.
    pub document_count: u64,
    /// Caller-supplied estimate of the reindex wall-clock cost.
    ///
    /// The unit is explicit so renderers never guess. The pure planner does
    /// not derive this value from ambient telemetry or filesystem state.
    pub estimated_reindex_duration_ms: u64,
    /// Caller-frozen issuance time for this exact authorization.
    pub issued_at_unix_seconds: u64,
    /// Caller-frozen exclusive expiry time for this exact authorization.
    pub expires_at_unix_seconds: u64,
    /// Caller-generated 128-bit nonce encoded as exactly 32 lowercase
    /// hexadecimal characters.
    pub nonce: String,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ModelAcquisitionAuthorizationWire {
    schema_version: ModelAcquisitionAuthorizationSchemaVersion,
    model_id: String,
    #[serde(with = "recovery_model_tier_wire")]
    model_tier: ModelTier,
    embedding_space: EmbeddingSpaceIdentityV1,
    manifest_fingerprint: String,
    upstream_revision: String,
    license_spdx: String,
    source: ModelAcquisitionSource,
    byte_budget: u64,
    destination_class: ModelDestinationClass,
    destination_fingerprint: String,
    document_count: u64,
    estimated_reindex_duration_ms: u64,
    issued_at_unix_seconds: u64,
    expires_at_unix_seconds: u64,
    nonce: String,
}

impl<'de> Deserialize<'de> for ModelAcquisitionAuthorization {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = ModelAcquisitionAuthorizationWire::deserialize(deserializer)?;
        let authorization = Self {
            schema_version: wire.schema_version,
            model_id: wire.model_id,
            model_tier: wire.model_tier,
            embedding_space: wire.embedding_space,
            manifest_fingerprint: wire.manifest_fingerprint,
            upstream_revision: wire.upstream_revision,
            license_spdx: wire.license_spdx,
            source: wire.source,
            byte_budget: wire.byte_budget,
            destination_class: wire.destination_class,
            destination_fingerprint: wire.destination_fingerprint,
            document_count: wire.document_count,
            estimated_reindex_duration_ms: wire.estimated_reindex_duration_ms,
            issued_at_unix_seconds: wire.issued_at_unix_seconds,
            expires_at_unix_seconds: wire.expires_at_unix_seconds,
            nonce: wire.nonce,
        };
        authorization.validate().map_err(serde::de::Error::custom)?;
        Ok(authorization)
    }
}

impl ModelAcquisitionAuthorization {
    /// Validate that every exact authorization scope is present and usable.
    ///
    /// # Errors
    ///
    /// Rejects blank or control-bearing scope fields, zero byte budgets,
    /// network acquisition without at least one source host, and source hosts
    /// that are not credential-free DNS names, IPv4 addresses, or bracketed
    /// IPv6 addresses (each optionally followed by an explicit non-zero port).
    pub fn validate(&self) -> Result<(), RecoveryContractError> {
        validate_scope_text("model_id", &self.model_id)?;
        self.embedding_space.validate().map_err(|error| {
            RecoveryContractError::InvalidAcquisitionSpaceIdentity {
                reason: error.to_string(),
            }
        })?;
        if self.embedding_space.kind != EmbeddingSpaceKindV1::Semantic {
            return Err(RecoveryContractError::NonSemanticAcquisitionSpace);
        }
        // ubs:ignore — model IDs are public embedding-space identities, not authenticators.
        if self.model_id != self.embedding_space.logical_model_id {
            return Err(RecoveryContractError::InconsistentAcquisitionIdentity {
                field: "model_id",
            });
        }
        validate_scope_text("manifest_fingerprint", &self.manifest_fingerprint)?;
        validate_scope_text("upstream_revision", &self.upstream_revision)?;
        if self.upstream_revision != self.embedding_space.immutable_revision {
            return Err(RecoveryContractError::InconsistentAcquisitionIdentity {
                field: "upstream_revision",
            });
        }
        validate_scope_text("license_spdx", &self.license_spdx)?;
        validate_scope_text("destination_fingerprint", &self.destination_fingerprint)?;
        if self.byte_budget == 0 {
            return Err(RecoveryContractError::ZeroAcquisitionByteBudget);
        }
        if let ModelAcquisitionSource::Network { source_hosts } = &self.source {
            if source_hosts.is_empty() {
                return Err(RecoveryContractError::MissingNetworkSourceHosts);
            }
            for host in source_hosts {
                validate_network_source_host(host)?;
            }
        }
        validate_acquisition_authorization_window(
            self.issued_at_unix_seconds,
            self.expires_at_unix_seconds,
        )?;
        validate_acquisition_authorization_nonce(&self.nonce)?;
        Ok(())
    }

    /// Revalidate this authorization against caller-supplied trusted time.
    ///
    /// Executors must call this immediately before the first acquisition side
    /// effect. A prior planning or wire-promotion check does not keep an
    /// authorization valid after its exclusive expiry boundary.
    ///
    /// # Errors
    ///
    /// Returns the same structural validation errors as [`Self::validate`],
    /// [`RecoveryContractError::AcquisitionAuthorizationNotYetValid`] before
    /// issuance, or [`RecoveryContractError::AcquisitionAuthorizationExpired`]
    /// at and after expiry.
    pub fn validate_at(
        &self,
        evaluation_time_unix_seconds: u64,
    ) -> Result<(), RecoveryContractError> {
        self.validate()?;
        if evaluation_time_unix_seconds < self.issued_at_unix_seconds {
            return Err(RecoveryContractError::AcquisitionAuthorizationNotYetValid {
                issued_at_unix_seconds: self.issued_at_unix_seconds,
                evaluation_time_unix_seconds,
            });
        }
        if evaluation_time_unix_seconds >= self.expires_at_unix_seconds {
            return Err(RecoveryContractError::AcquisitionAuthorizationExpired {
                expires_at_unix_seconds: self.expires_at_unix_seconds,
                evaluation_time_unix_seconds,
            });
        }
        Ok(())
    }
}

/// Source-independent target from which the planner derives the exact
/// network or local-bundle authorization required by policy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelAcquisitionTarget {
    /// Stable logical ID selected by the caller's frozen manifest.
    pub model_id: String,
    /// Progressive tier selected by the caller's requested topology.
    pub model_tier: ModelTier,
    /// Complete mathematical identity selected by the caller's frozen
    /// manifest and readiness probe.
    pub embedding_space: EmbeddingSpaceIdentityV1,
    pub manifest_fingerprint: String,
    pub upstream_revision: String,
    pub license_spdx: String,
    pub network_source_hosts: Vec<String>,
    pub byte_budget: u64,
    pub destination_class: ModelDestinationClass,
    pub destination_fingerprint: String,
    /// Corpus census supplied by the caller for consent presentation.
    pub document_count: u64,
    /// Caller-computed reindex estimate, explicitly expressed in
    /// milliseconds. The planner never derives or adjusts it.
    pub estimated_reindex_duration_ms: u64,
    /// Caller-frozen issuance time copied into the exact authorization.
    pub issued_at_unix_seconds: u64,
    /// Caller-frozen exclusive expiry time copied into the exact
    /// authorization.
    pub expires_at_unix_seconds: u64,
    /// Caller-generated 128-bit lowercase-hex nonce copied into the exact
    /// authorization.
    pub nonce: String,
}

impl ModelAcquisitionTarget {
    fn authorization_for(
        &self,
        network: NetworkPolicy,
    ) -> Result<ModelAcquisitionAuthorization, RecoveryContractError> {
        let authorization = ModelAcquisitionAuthorization {
            schema_version: ModelAcquisitionAuthorizationSchemaVersion::V3,
            model_id: self.model_id.clone(),
            model_tier: self.model_tier,
            embedding_space: self.embedding_space.clone(),
            manifest_fingerprint: self.manifest_fingerprint.clone(),
            upstream_revision: self.upstream_revision.clone(),
            license_spdx: self.license_spdx.clone(),
            source: match network {
                NetworkPolicy::Allowed => ModelAcquisitionSource::Network {
                    source_hosts: self.network_source_hosts.clone(),
                },
                NetworkPolicy::Offline => ModelAcquisitionSource::LocalBundle,
            },
            byte_budget: self.byte_budget,
            destination_class: self.destination_class,
            destination_fingerprint: self.destination_fingerprint.clone(),
            document_count: self.document_count,
            estimated_reindex_duration_ms: self.estimated_reindex_duration_ms,
            issued_at_unix_seconds: self.issued_at_unix_seconds,
            expires_at_unix_seconds: self.expires_at_unix_seconds,
            nonce: self.nonce.clone(),
        };
        authorization.validate()?;
        Ok(authorization)
    }
}

fn validate_acquisition_authorization_window(
    issued_at_unix_seconds: u64,
    expires_at_unix_seconds: u64,
) -> Result<(), RecoveryContractError> {
    if expires_at_unix_seconds <= issued_at_unix_seconds {
        return Err(
            RecoveryContractError::InvalidAcquisitionAuthorizationWindow {
                issued_at_unix_seconds,
                expires_at_unix_seconds,
            },
        );
    }
    let lifetime_seconds = expires_at_unix_seconds - issued_at_unix_seconds;
    if lifetime_seconds > MAX_MODEL_ACQUISITION_AUTHORIZATION_LIFETIME_SECONDS {
        return Err(
            RecoveryContractError::AcquisitionAuthorizationLifetimeExceeded {
                lifetime_seconds,
                max_lifetime_seconds: MAX_MODEL_ACQUISITION_AUTHORIZATION_LIFETIME_SECONDS,
            },
        );
    }
    Ok(())
}

fn validate_acquisition_authorization_nonce(nonce: &str) -> Result<(), RecoveryContractError> {
    let valid_shape = nonce.len() == 32
        && nonce
            .bytes()
            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
    // ubs:ignore — this persisted acquisition nonce is public uniqueness evidence, not a bearer token.
    let nonzero = nonce.bytes().any(|byte| byte != b'0');
    if !valid_shape || !nonzero {
        return Err(RecoveryContractError::InvalidAcquisitionAuthorizationNonce);
    }
    Ok(())
}

fn validate_scope_text(field: &'static str, value: &str) -> Result<(), RecoveryContractError> {
    if value.trim().is_empty() || value.chars().any(char::is_control) {
        return Err(RecoveryContractError::InvalidAcquisitionScopeField { field });
    }
    Ok(())
}

fn validate_network_source_host(host: &str) -> Result<(), RecoveryContractError> {
    let invalid = || RecoveryContractError::InvalidNetworkSourceHost;
    if host.is_empty()
        || host.chars().any(|character| {
            character.is_whitespace()
                || character.is_control()
                || matches!(character, '@' | '/' | '?' | '#' | '\\')
        })
        || host.contains("://")
    {
        return Err(invalid());
    }

    if let Some(bracketed) = host.strip_prefix('[') {
        let Some(closing_bracket) = bracketed.find(']') else {
            return Err(invalid());
        };
        let address = &bracketed[..closing_bracket];
        let suffix = &bracketed[closing_bracket + 1..];
        address
            .parse::<std::net::Ipv6Addr>()
            .map_err(|_| invalid())?;
        if !suffix.is_empty() {
            let port = suffix.strip_prefix(':').ok_or_else(invalid)?;
            validate_network_source_port(port)?;
        }
        return Ok(());
    }

    if host.contains(['[', ']']) || host.bytes().filter(|byte| *byte == b':').count() > 1 {
        return Err(invalid());
    }
    let (address, port) = match host.rsplit_once(':') {
        Some((address, port)) => (address, Some(port)),
        None => (host, None),
    };
    if let Some(port) = port {
        validate_network_source_port(port)?;
    }
    if address.parse::<std::net::Ipv4Addr>().is_ok() {
        return Ok(());
    }
    if address
        .bytes()
        .all(|byte| byte.is_ascii_digit() || byte == b'.')
        || address.len() > 253
        || address.ends_with('.')
    {
        return Err(invalid());
    }
    for label in address.split('.') {
        if label.is_empty()
            || label.len() > 63
            || !label
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
            || !label
                .as_bytes()
                .first()
                .is_some_and(u8::is_ascii_alphanumeric)
            || !label
                .as_bytes()
                .last()
                .is_some_and(u8::is_ascii_alphanumeric)
        {
            return Err(invalid());
        }
    }
    Ok(())
}

fn validate_network_source_port(port: &str) -> Result<(), RecoveryContractError> {
    if port.is_empty() || !port.bytes().all(|byte| byte.is_ascii_digit()) {
        return Err(RecoveryContractError::InvalidNetworkSourceHost);
    }
    let parsed = port
        .parse::<u16>()
        .map_err(|_| RecoveryContractError::InvalidNetworkSourceHost)?;
    if parsed == 0 {
        return Err(RecoveryContractError::InvalidNetworkSourceHost);
    }
    Ok(())
}

/// Typed validation failure for a recovery request or response contract.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RecoveryContractError {
    #[error("request mode {mode:?} cannot request topology {topology:?}")]
    InvalidRequestTopology {
        mode: RequestMode,
        topology: RetrievalTopology,
    },
    #[error("hash-control request mode and readiness must be selected together")]
    HashControlModeReadinessMismatch,
    #[error("acquisition scope field `{field}` is empty or contains control characters")]
    InvalidAcquisitionScopeField { field: &'static str },
    #[error("model acquisition space identity is invalid: {reason}")]
    InvalidAcquisitionSpaceIdentity { reason: String },
    #[error("model acquisition requires a semantic embedding space")]
    NonSemanticAcquisitionSpace,
    #[error("acquisition identity field `{field}` conflicts with the complete space identity")]
    InconsistentAcquisitionIdentity { field: &'static str },
    #[error("readiness tier {tier} cannot satisfy requested topology {requested_topology:?}")]
    UnavailableTierTopologyMismatch {
        tier: ModelTier,
        requested_topology: RetrievalTopology,
    },
    #[error("acquisition target tier {target_tier} does not match readiness tier {readiness_tier}")]
    AcquisitionTargetTierMismatch {
        readiness_tier: ModelTier,
        target_tier: ModelTier,
    },
    #[error("model acquisition byte budget must be non-zero")]
    ZeroAcquisitionByteBudget,
    #[error(
        "model acquisition authorization window is invalid: issued_at={issued_at_unix_seconds}, \
         expires_at={expires_at_unix_seconds}"
    )]
    InvalidAcquisitionAuthorizationWindow {
        issued_at_unix_seconds: u64,
        expires_at_unix_seconds: u64,
    },
    #[error(
        "model acquisition authorization lifetime {lifetime_seconds}s exceeds the \
         {max_lifetime_seconds}s maximum"
    )]
    AcquisitionAuthorizationLifetimeExceeded {
        lifetime_seconds: u64,
        max_lifetime_seconds: u64,
    },
    #[error(
        "model acquisition authorization nonce must be a nonzero 128-bit value encoded as \
         exactly 32 lowercase hexadecimal characters"
    )]
    InvalidAcquisitionAuthorizationNonce,
    #[error(
        "model acquisition authorization is not yet valid: issued_at={issued_at_unix_seconds}, \
         evaluated_at={evaluation_time_unix_seconds}"
    )]
    AcquisitionAuthorizationNotYetValid {
        issued_at_unix_seconds: u64,
        evaluation_time_unix_seconds: u64,
    },
    #[error(
        "model acquisition authorization expired: expires_at={expires_at_unix_seconds}, \
         evaluated_at={evaluation_time_unix_seconds}"
    )]
    AcquisitionAuthorizationExpired {
        expires_at_unix_seconds: u64,
        evaluation_time_unix_seconds: u64,
    },
    #[error("model acquisition requires an exact supplied authorization before execution")]
    MissingAcquisitionAuthorization,
    #[error("model acquisition authorization was supplied when no exact acquisition requires it")]
    SurplusAcquisitionAuthorization,
    #[error("model acquisition authorization field `{field}` does not match the required scope")]
    MismatchedAcquisitionAuthorization { field: &'static str },
    #[error("network model acquisition requires at least one credential-free source host")]
    MissingNetworkSourceHosts,
    #[error(
        "network model acquisition source host must be a credential-free DNS name, IPv4 address, \
         or bracketed IPv6 address with an optional non-zero port"
    )]
    InvalidNetworkSourceHost,
    #[error("coverage_ppm {coverage_ppm} is outside the valid range for {topology:?}")]
    InvalidCoverage {
        topology: RetrievalTopology,
        coverage_ppm: u32,
    },
    #[error("requested topology {requested:?} cannot realize as {realized:?}")]
    IncompatibleResponseTopology {
        requested: RetrievalTopology,
        realized: RetrievalTopology,
    },
    #[error("non-semantic topology {topology:?} cannot admit {admitted} semantic scores")]
    NonSemanticScoresAdmitted {
        topology: RetrievalTopology,
        admitted: u64,
    },
    #[error("lexical-only response requires exactly one degradation reason code")]
    MissingDegradationReason,
    #[error("non-lexical response cannot carry a degradation reason code")]
    UnexpectedDegradationReason,
    #[error("recovery plan field `{field}` is inconsistent with the typed decision")]
    InconsistentRecoveryPlan { field: &'static str },
}

/// Whether retrying the original request can succeed, and under what
/// condition.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Retryability {
    /// The lane is usable; no recovery action is needed.
    NotNeeded,
    /// Retry after executing the recommended action.
    AfterAction,
    /// The current request itself produced no signal; retry only after
    /// changing its zero-k, filter, or vector input.
    AfterRequestChange,
    /// The recommended action cannot run under the current policy; the
    /// listed prerequisites must be granted first.
    BlockedByPolicy,
    /// The recommended action has no executable implementation in the
    /// current runtime. A listed capability must land before retrying.
    BlockedByCapability,
}

/// One truthful next action.
///
/// The four booleans are independent schema-mandated facts about the
/// action (bd-vmv7's field list), not an encoded state machine, so a
/// bitflag or enum representation would obscure the serialized contract.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RecoveryAction {
    /// Stable action code, append-only within a schema version.
    code: String,
    /// Human-readable explanation of what the action does and why.
    explanation: String,
    /// Command as an argv array. Placeholder tokens ([`ARG_INDEX_DIR`],
    /// [`ARG_SOURCE_DIR`]) are substituted by integrators; the pure
    /// planner never handles real paths.
    argv: Vec<String>,
    /// The action needs network access (model downloads).
    network_required: bool,
    /// The action needs explicit human consent (it replaces existing
    /// artifacts).
    consent_required: bool,
    /// The pre-existing data this action is intended to repair survives. For
    /// index recovery this means user documents and index contents; for model
    /// recovery it includes the cached model artifact itself. Reacquisition
    /// is therefore `false` even though corpus and index data remain intact.
    preserves_old_data: bool,
    /// The action replaces or rewrites existing artifacts.
    potentially_destructive: bool,
    /// Stable codes of conditions that must hold before the action can
    /// run (policy grants).
    prerequisites: Vec<String>,
    /// Stable code of the state expected after the action succeeds. Never
    /// `recovery.state.ready` for acquisition actions: readiness
    /// additionally requires the load self-test and a compatible
    /// non-empty index.
    expected_postcondition: String,
    /// Exact acquisition authorization this action requires. `None` for
    /// non-acquisition actions and when the caller failed to bind a frozen
    /// model target (which blocks the plan through a prerequisite).
    required_authorization: Option<ModelAcquisitionAuthorization>,
}

impl RecoveryAction {
    /// Stable action code.
    #[must_use]
    pub fn code(&self) -> &str {
        &self.code
    }

    /// Human-readable reason and effect.
    #[must_use]
    pub fn explanation(&self) -> &str {
        &self.explanation
    }

    /// Parser-executable argv, or an empty slice when prerequisites make the
    /// action unavailable.
    #[must_use]
    pub fn argv(&self) -> &[String] {
        &self.argv
    }

    /// Whether execution requires network access.
    #[must_use]
    pub const fn network_required(&self) -> bool {
        self.network_required
    }

    /// Whether execution requires explicit consent.
    #[must_use]
    pub const fn consent_required(&self) -> bool {
        self.consent_required
    }

    /// Whether the pre-existing data this action is intended to repair
    /// survives.
    #[must_use]
    pub const fn preserves_old_data(&self) -> bool {
        self.preserves_old_data
    }

    /// Whether the action rewrites or replaces artifacts.
    #[must_use]
    pub const fn potentially_destructive(&self) -> bool {
        self.potentially_destructive
    }

    /// Stable prerequisite codes that currently block execution.
    #[must_use]
    pub fn prerequisites(&self) -> &[String] {
        &self.prerequisites
    }

    /// Stable postcondition code expected after successful execution.
    #[must_use]
    pub fn expected_postcondition(&self) -> &str {
        &self.expected_postcondition
    }

    /// Exact scoped authorization required for acquisition.
    #[must_use]
    pub const fn required_authorization(&self) -> Option<&ModelAcquisitionAuthorization> {
        self.required_authorization.as_ref()
    }

    /// Render the argv for a POSIX shell, quoting every argument that
    /// contains characters beyond `[A-Za-z0-9_./:=-]` and the placeholder
    /// tokens (which are documentation, not shell input).
    #[must_use]
    pub fn shell_command(&self) -> String {
        self.argv
            .iter()
            .map(|arg| shell_quote(arg))
            .collect::<Vec<_>>()
            .join(" ")
    }
}

// This raw shape mirrors the same independent schema-mandated facts as
// RecoveryAction; collapsing them would make wire validation less explicit.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
struct RecoveryActionWire {
    code: String,
    explanation: String,
    argv: Vec<String>,
    network_required: bool,
    consent_required: bool,
    preserves_old_data: bool,
    potentially_destructive: bool,
    prerequisites: Vec<String>,
    expected_postcondition: String,
    #[serde(default)]
    required_authorization: WireField<Option<ModelAcquisitionAuthorization>>,
}

fn shell_quote(arg: &str) -> String {
    let safe = !arg.is_empty()
        && arg.chars().all(|c| {
            c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '/' | ':' | '=' | '-' | '<' | '>')
        });
    if safe {
        arg.to_owned()
    } else {
        // POSIX single-quote escaping: close, escaped quote, reopen.
        format!("'{}'", arg.replace('\'', "'\\''"))
    }
}

/// Truthful semantic contribution metadata for one response.
///
/// This contract is reusable by product output schemas after query
/// execution. The planner initializes `admitted_semantic_scores` to zero;
/// a search path must replace it with the actual admitted count before
/// emitting a completed semantic response. Non-semantic realized topologies
/// are permanently constrained to zero. The trusted type is Serialize-only:
/// wire data inside an [`UntrustedRecoveryPlan`] is decoded into a private raw
/// shape and compared field-for-field with a freshly planned contract.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct SemanticResponseContract {
    requested_topology: RetrievalTopology,
    realized_topology: RetrievalTopology,
    coverage_ppm: u32,
    admitted_semantic_scores: u64,
    /// Present exactly for a lexical-only hybrid degradation.
    degradation_reason_code: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
struct SemanticResponseContractWire {
    requested_topology: RetrievalTopology,
    realized_topology: RetrievalTopology,
    coverage_ppm: u32,
    admitted_semantic_scores: u64,
    #[serde(default)]
    degradation_reason_code: WireField<Option<String>>,
}

impl SemanticResponseContract {
    /// Construct and validate one response contract.
    ///
    /// # Errors
    ///
    /// Rejects impossible requested/realized topology pairs, out-of-range
    /// coverage, semantic-score admission by lexical/hash lanes, and
    /// missing or spurious degradation reasons.
    pub fn new(
        requested_topology: RetrievalTopology,
        realized_topology: RetrievalTopology,
        coverage_ppm: u32,
        admitted_semantic_scores: u64,
        degradation_reason_code: Option<String>,
    ) -> Result<Self, RecoveryContractError> {
        let contract = Self {
            requested_topology,
            realized_topology,
            coverage_ppm,
            admitted_semantic_scores,
            degradation_reason_code,
        };
        contract.validate()?;
        Ok(contract)
    }

    /// Retrieval topology the caller requested.
    #[must_use]
    pub const fn requested_topology(&self) -> RetrievalTopology {
        self.requested_topology
    }

    /// Retrieval topology the response actually realizes.
    #[must_use]
    pub const fn realized_topology(&self) -> RetrievalTopology {
        self.realized_topology
    }

    /// Semantic document coverage in parts per million.
    #[must_use]
    pub const fn coverage_ppm(&self) -> u32 {
        self.coverage_ppm
    }

    /// Number of semantic scores admitted into the response.
    #[must_use]
    pub const fn admitted_semantic_scores(&self) -> u64 {
        self.admitted_semantic_scores
    }

    /// Typed degradation reason for lexical-only hybrid fallback.
    #[must_use]
    pub fn degradation_reason_code(&self) -> Option<&str> {
        self.degradation_reason_code.as_deref()
    }

    /// Replace the planning-boundary zero with the count admitted by a
    /// completed response, re-validating non-semantic invariants.
    ///
    /// # Errors
    ///
    /// Returns [`RecoveryContractError::NonSemanticScoresAdmitted`] if a
    /// lexical/hash response attempts to claim semantic contribution.
    pub fn with_admitted_semantic_scores(
        mut self,
        admitted_semantic_scores: u64,
    ) -> Result<Self, RecoveryContractError> {
        self.admitted_semantic_scores = admitted_semantic_scores;
        self.validate()?;
        Ok(self)
    }

    fn validate(&self) -> Result<(), RecoveryContractError> {
        let topology_compatible =
            retrieval_topology_fits_request(self.requested_topology, self.realized_topology);
        if !topology_compatible {
            return Err(RecoveryContractError::IncompatibleResponseTopology {
                requested: self.requested_topology,
                realized: self.realized_topology,
            });
        }

        let coverage_valid = match self.realized_topology {
            RetrievalTopology::LexicalOnly | RetrievalTopology::HashControl => {
                self.coverage_ppm == 0
            }
            RetrievalTopology::FastOnly
            | RetrievalTopology::QualityOnly
            // ubs:ignore — coverage is a public retrieval-plan fact, not security material.
            | RetrievalTopology::FullProgressive => self.coverage_ppm == COMPLETE_COVERAGE_PPM,
            RetrievalTopology::PartialQuality { coverage_ppm } => {
                coverage_ppm == self.coverage_ppm
                    && (1..COMPLETE_COVERAGE_PPM).contains(&coverage_ppm)
            }
        };
        if !coverage_valid {
            return Err(RecoveryContractError::InvalidCoverage {
                topology: self.realized_topology,
                coverage_ppm: self.coverage_ppm,
            });
        }

        if !self.realized_topology.is_semantic() && self.admitted_semantic_scores != 0 {
            return Err(RecoveryContractError::NonSemanticScoresAdmitted {
                topology: self.realized_topology,
                admitted: self.admitted_semantic_scores,
            });
        }

        match (
            self.requested_topology,
            self.realized_topology,
            self.degradation_reason_code.as_deref(),
        ) {
            (RetrievalTopology::LexicalOnly, RetrievalTopology::LexicalOnly, None) => Ok(()),
            (RetrievalTopology::LexicalOnly, RetrievalTopology::LexicalOnly, Some(_)) => {
                Err(RecoveryContractError::UnexpectedDegradationReason)
            }
            (_, RetrievalTopology::LexicalOnly, Some(code)) if !code.trim().is_empty() => Ok(()),
            (_, RetrievalTopology::LexicalOnly, _) => {
                Err(RecoveryContractError::MissingDegradationReason)
            }
            (_, _, None) => Ok(()),
            (_, _, Some(_)) => Err(RecoveryContractError::UnexpectedDegradationReason),
        }
    }
}

/// The full plan: current state, verdict for the requested mode, and the
/// truthful next action.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct RecoveryPlan {
    /// [`RECOVERY_PLAN_SCHEMA_VERSION`].
    schema_version: RecoveryPlanSchemaVersion,
    /// The readiness state the plan was computed from.
    state: SemanticReadiness,
    /// Stable code for `state` (denormalized for consumers that do not
    /// decode the enum).
    state_code: String,
    /// Producer trust classification derived from `state`.
    provenance: SemanticProvenance,
    /// The mode the caller requested.
    mode: RequestMode,
    /// Exact retrieval topology the caller requested.
    requested_topology: RetrievalTopology,
    /// The policy the plan was computed under.
    policy: RecoveryPolicy,
    /// Whether semantic results can be served right now.
    semantic_available: bool,
    /// Whether retrying can succeed, and under what condition.
    retryability: Retryability,
    /// The truthful next action; `None` when the state needs none (ready,
    /// or the emptiness was request-scoped).
    action: Option<RecoveryAction>,
    /// Response shape allowed by this decision. `None` means the explicit
    /// request fails closed and no response may be emitted.
    response_contract: Option<SemanticResponseContract>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
struct RecoveryPlanWire {
    schema_version: RecoveryPlanSchemaVersion,
    state: SemanticReadiness,
    state_code: String,
    provenance: SemanticProvenance,
    mode: RequestMode,
    requested_topology: RetrievalTopology,
    policy: RecoveryPolicy,
    semantic_available: bool,
    retryability: Retryability,
    #[serde(default)]
    action: WireField<Option<RecoveryActionWire>>,
    #[serde(default)]
    response_contract: WireField<Option<SemanticResponseContractWire>>,
}

impl RecoveryPlanWire {
    fn validate_required_option_presence(&self) -> Result<(), &'static str> {
        let action = self
            .action
            .required_option_ref()
            .map_err(|()| "missing required field action")?;
        let response = self
            .response_contract
            .required_option_ref()
            .map_err(|()| "missing required field response_contract")?;
        if let Some(action) = action {
            action
                .required_authorization
                .required_option_ref()
                .map_err(|()| "missing required field action.required_authorization")?;
        }
        if let Some(response) = response {
            response
                .degradation_reason_code
                .required_option_ref()
                .map_err(|()| "missing required field response_contract.degradation_reason_code")?;
        }
        Ok(())
    }
}

/// Opaque, non-executable recovery-plan payload decoded from an untrusted
/// transport.
///
/// No action or argv accessor exists on this type. The only promotion path is
/// [`Self::validate_against`], which compares every payload field with a new
/// plan derived exclusively from a [`TrustedRecoveryContext`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UntrustedRecoveryPlan {
    wire: RecoveryPlanWire,
}

impl<'de> Deserialize<'de> for UntrustedRecoveryPlan {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = RecoveryPlanWire::deserialize(deserializer)?;
        wire.validate_required_option_presence()
            .map_err(serde::de::Error::custom)?;
        Ok(Self { wire })
    }
}

/// Independently sourced inputs that may promote one untrusted payload to a
/// trusted, executable [`RecoveryPlan`].
///
/// Every value must come from the current readiness probe, caller request,
/// environment policy, or frozen manifest. Never populate this context from
/// the payload being validated.
#[derive(Debug, Clone, Copy)]
pub struct TrustedRecoveryContext<'a> {
    state: &'a SemanticReadiness,
    request: RecoveryRequest,
    policy: &'a RecoveryPolicy,
    acquisition_target: Option<&'a ModelAcquisitionTarget>,
    evaluation_time_unix_seconds: u64,
}

impl<'a> TrustedRecoveryContext<'a> {
    /// Bind authoritative runtime inputs for untrusted-plan validation.
    #[must_use]
    pub const fn new(
        state: &'a SemanticReadiness,
        request: RecoveryRequest,
        policy: &'a RecoveryPolicy,
        acquisition_target: Option<&'a ModelAcquisitionTarget>,
        evaluation_time_unix_seconds: u64,
    ) -> Self {
        Self {
            state,
            request,
            policy,
            acquisition_target,
            evaluation_time_unix_seconds,
        }
    }
}

impl UntrustedRecoveryPlan {
    /// Compare every payload field with a fresh plan derived exclusively from
    /// trusted inputs.
    ///
    /// # Errors
    ///
    /// Returns [`RecoveryContractError::InconsistentRecoveryPlan`] for any
    /// payload substitution, including a coherent multi-field forgery.
    /// Trusted-context planning and target-validation errors are preserved.
    pub fn validate_against(
        self,
        trusted: TrustedRecoveryContext<'_>,
    ) -> Result<RecoveryPlan, RecoveryContractError> {
        let canonical = plan(trusted)?;
        validate_wire_against_canonical(&self.wire, &canonical)?;
        Ok(canonical)
    }
}

impl RecoveryPlan {
    /// Wire schema version.
    #[must_use]
    pub const fn schema_version(&self) -> RecoveryPlanSchemaVersion {
        self.schema_version
    }

    /// Readiness state used by the planner.
    #[must_use]
    pub const fn state(&self) -> &SemanticReadiness {
        &self.state
    }

    /// Stable code derived from [`Self::state`].
    #[must_use]
    pub fn state_code(&self) -> &str {
        &self.state_code
    }

    /// Producer provenance derived from readiness.
    #[must_use]
    pub const fn provenance(&self) -> SemanticProvenance {
        self.provenance
    }

    /// Requested mode.
    #[must_use]
    pub const fn mode(&self) -> RequestMode {
        self.mode
    }

    /// Requested retrieval topology.
    #[must_use]
    pub const fn requested_topology(&self) -> RetrievalTopology {
        self.requested_topology
    }

    /// Trusted policy used to construct the plan.
    #[must_use]
    pub const fn policy(&self) -> &RecoveryPolicy {
        &self.policy
    }

    /// Whether semantic results are currently admissible.
    #[must_use]
    pub const fn semantic_available(&self) -> bool {
        self.semantic_available
    }

    /// Retry verdict derived by the planner.
    #[must_use]
    pub const fn retryability(&self) -> Retryability {
        self.retryability
    }

    /// Canonical next action, when one exists.
    #[must_use]
    pub const fn action(&self) -> Option<&RecoveryAction> {
        self.action.as_ref()
    }

    /// Canonical response-admission contract, when a response is allowed.
    #[must_use]
    pub const fn response_contract(&self) -> Option<&SemanticResponseContract> {
        self.response_contract.as_ref()
    }

    /// Revalidate acquisition authorization immediately before execution.
    ///
    /// Planning and untrusted-wire promotion validate against the trusted time
    /// supplied for those operations. They do not mint a timeless capability:
    /// an executor must call this method again at the acquisition boundary
    /// using independently trusted current time. An interactive plan created
    /// before consent cannot execute: the caller must re-plan with the freshly
    /// granted exact authorization in [`RecoveryPolicy::acquisition_authorization`].
    ///
    /// # Errors
    ///
    /// Returns an authorization structural, scope-binding, not-yet-valid, or
    /// expiry error when the action is no longer executable at
    /// `evaluation_time_unix_seconds`.
    pub fn validate_for_execution_at(
        &self,
        evaluation_time_unix_seconds: u64,
    ) -> Result<(), RecoveryContractError> {
        validate_execution_authorization_binding(
            self.action
                .as_ref()
                .and_then(RecoveryAction::required_authorization),
            self.policy.acquisition_authorization.as_ref(),
            evaluation_time_unix_seconds,
        )
    }
}

fn inconsistent(field: &'static str) -> RecoveryContractError {
    RecoveryContractError::InconsistentRecoveryPlan { field }
}

fn validate_wire_against_canonical(
    wire: &RecoveryPlanWire,
    canonical: &RecoveryPlan,
) -> Result<(), RecoveryContractError> {
    // ubs:ignore — schema versions are public recovery-wire facts, not authenticators.
    if wire.schema_version != canonical.schema_version {
        return Err(inconsistent("schema_version"));
    }
    // ubs:ignore — readiness state is public recovery-wire data, not secret material.
    if wire.state != canonical.state {
        return Err(inconsistent("state"));
    }
    // ubs:ignore — state codes are public recovery-wire data, not authenticators.
    if wire.state_code != canonical.state_code {
        return Err(inconsistent("state_code"));
    }
    // ubs:ignore — provenance is public recovery-wire evidence, not an authenticator.
    if wire.provenance != canonical.provenance {
        return Err(inconsistent("provenance"));
    }
    // ubs:ignore — mode is a public recovery-wire fact, not security material.
    if wire.mode != canonical.mode {
        return Err(inconsistent("mode"));
    }
    // ubs:ignore — topology is public recovery-wire data, not an authenticator.
    if wire.requested_topology != canonical.requested_topology {
        return Err(inconsistent("requested_topology"));
    }
    // ubs:ignore — policy is public recovery-wire configuration, not an authenticator.
    if wire.policy != canonical.policy {
        return Err(inconsistent("policy"));
    }
    // ubs:ignore — availability is a public recovery-wire fact, not secret material.
    if wire.semantic_available != canonical.semantic_available {
        return Err(inconsistent("semantic_available"));
    }
    // ubs:ignore — retryability is a public recovery-wire fact, not an authenticator.
    if wire.retryability != canonical.retryability {
        return Err(inconsistent("retryability"));
    }
    let wire_action = wire
        .action
        .required_option_ref()
        .map_err(|()| inconsistent("action"))?;
    validate_action_wire(wire_action, canonical.action.as_ref())?;
    let wire_response = wire
        .response_contract
        .required_option_ref()
        .map_err(|()| inconsistent("response_contract"))?;
    validate_response_wire(wire_response, canonical.response_contract.as_ref())?;
    Ok(())
}

fn validate_action_wire(
    wire: Option<&RecoveryActionWire>,
    canonical: Option<&RecoveryAction>,
) -> Result<(), RecoveryContractError> {
    let (Some(wire), Some(canonical)) = (wire, canonical) else {
        return if wire.is_none() && canonical.is_none() {
            Ok(())
        } else {
            Err(inconsistent("action"))
        };
    };
    // ubs:ignore — action codes are public recovery-wire facts, not authenticators.
    if wire.code != canonical.code {
        return Err(inconsistent("action.code"));
    }
    // ubs:ignore — explanations are public operator guidance, not secret material.
    if wire.explanation != canonical.explanation {
        return Err(inconsistent("action.explanation"));
    }
    // ubs:ignore — argv is public recovery-action evidence, not an authenticator.
    if wire.argv != canonical.argv {
        return Err(inconsistent("action.argv"));
    }
    // ubs:ignore — network requirement is public recovery-action metadata.
    if wire.network_required != canonical.network_required {
        return Err(inconsistent("action.network_required"));
    }
    // ubs:ignore — consent requirement is public recovery-action metadata.
    if wire.consent_required != canonical.consent_required {
        return Err(inconsistent("action.consent_required"));
    }
    // ubs:ignore — preservation is public recovery-action metadata, not an authenticator.
    if wire.preserves_old_data != canonical.preserves_old_data {
        return Err(inconsistent("action.preserves_old_data"));
    }
    // ubs:ignore — destructive intent is public recovery-action metadata, not a secret.
    if wire.potentially_destructive != canonical.potentially_destructive {
        return Err(inconsistent("action.potentially_destructive"));
    }
    // ubs:ignore — prerequisites are public recovery-action facts, not authenticators.
    if wire.prerequisites != canonical.prerequisites {
        return Err(inconsistent("action.prerequisites"));
    }
    // ubs:ignore — postconditions are public recovery-action facts, not authenticators.
    if wire.expected_postcondition != canonical.expected_postcondition {
        return Err(inconsistent("action.expected_postcondition"));
    }
    let wire_authorization = wire
        .required_authorization
        .required_option_ref()
        .map_err(|()| inconsistent("action.required_authorization"))?;
    // ubs:ignore — this is a public frozen authorization contract, not a credential.
    if wire_authorization != canonical.required_authorization.as_ref() {
        return Err(inconsistent("action.required_authorization"));
    }
    Ok(())
}

fn validate_response_wire(
    wire: Option<&SemanticResponseContractWire>,
    canonical: Option<&SemanticResponseContract>,
) -> Result<(), RecoveryContractError> {
    let (Some(wire), Some(canonical)) = (wire, canonical) else {
        return if wire.is_none() && canonical.is_none() {
            Ok(())
        } else {
            Err(inconsistent("response_contract"))
        };
    };
    // ubs:ignore — requested topology is public response-contract metadata.
    if wire.requested_topology != canonical.requested_topology {
        return Err(inconsistent("response_contract.requested_topology"));
    }
    // ubs:ignore — realized topology is public response-contract metadata.
    if wire.realized_topology != canonical.realized_topology {
        return Err(inconsistent("response_contract.realized_topology"));
    }
    // ubs:ignore — coverage is public response-contract evidence, not a secret.
    if wire.coverage_ppm != canonical.coverage_ppm {
        return Err(inconsistent("response_contract.coverage_ppm"));
    }
    // ubs:ignore — score admission is public response-contract evidence.
    if wire.admitted_semantic_scores != canonical.admitted_semantic_scores {
        return Err(inconsistent("response_contract.admitted_semantic_scores"));
    }
    let wire_degradation_reason = wire
        .degradation_reason_code
        .required_option_ref()
        .map_err(|()| inconsistent("response_contract.degradation_reason_code"))?;
    // ubs:ignore — degradation reason codes are public operator evidence.
    if wire_degradation_reason != canonical.degradation_reason_code.as_ref() {
        return Err(inconsistent("response_contract.degradation_reason_code"));
    }
    Ok(())
}

fn mismatched_authorization_field(
    required: &ModelAcquisitionAuthorization,
    supplied: &ModelAcquisitionAuthorization,
) -> Option<&'static str> {
    // ubs:ignore — model IDs are public frozen acquisition facts, not credentials.
    if required.model_id != supplied.model_id {
        Some("model_id")
    // ubs:ignore — model tiers are public frozen acquisition facts.
    } else if required.model_tier != supplied.model_tier {
        Some("model_tier")
    // ubs:ignore — upstream revisions are public provenance, not secrets.
    } else if required.upstream_revision != supplied.upstream_revision {
        Some("upstream_revision")
    // ubs:ignore — embedding-space identities are public compatibility facts.
    } else if required.embedding_space != supplied.embedding_space {
        Some("embedding_space")
    // ubs:ignore — manifest fingerprints are public integrity evidence, not secrets.
    } else if required.manifest_fingerprint != supplied.manifest_fingerprint {
        Some("manifest_fingerprint")
    // ubs:ignore — license identifiers are public provenance facts.
    } else if required.license_spdx != supplied.license_spdx {
        Some("license_spdx")
    // ubs:ignore — model sources are public provenance facts, not credentials.
    } else if required.source != supplied.source {
        Some("source")
    // ubs:ignore — byte budgets are public acquisition-policy facts.
    } else if required.byte_budget != supplied.byte_budget {
        Some("byte_budget")
    // ubs:ignore — destination classes are public storage-policy facts.
    } else if required.destination_class != supplied.destination_class {
        Some("destination_class")
    // ubs:ignore — destination fingerprints are public integrity evidence, not secrets.
    } else if required.destination_fingerprint != supplied.destination_fingerprint {
        Some("destination_fingerprint")
    // ubs:ignore — document counts are public corpus-binding facts.
    } else if required.document_count != supplied.document_count {
        Some("document_count")
    // ubs:ignore — duration estimates are public planning facts.
    } else if required.estimated_reindex_duration_ms != supplied.estimated_reindex_duration_ms {
        Some("estimated_reindex_duration_ms")
    // ubs:ignore — issue times are public authorization-contract facts.
    } else if required.issued_at_unix_seconds != supplied.issued_at_unix_seconds {
        Some("issued_at_unix_seconds")
    // ubs:ignore — expiry times are public authorization-contract facts.
    } else if required.expires_at_unix_seconds != supplied.expires_at_unix_seconds {
        Some("expires_at_unix_seconds")
    // ubs:ignore — this persisted nonce is public replay-binding evidence, not a secret.
    } else if required.nonce != supplied.nonce {
        Some("nonce")
    } else {
        None
    }
}

fn validate_authorization_binding(
    required: Option<&ModelAcquisitionAuthorization>,
    supplied: Option<&ModelAcquisitionAuthorization>,
    evaluation_time_unix_seconds: u64,
) -> Result<(), RecoveryContractError> {
    match (required, supplied) {
        (None, None) => Ok(()),
        (None, Some(_)) => Err(RecoveryContractError::SurplusAcquisitionAuthorization),
        (Some(required), None) => required.validate_at(evaluation_time_unix_seconds),
        (Some(required), Some(supplied)) => {
            required.validate_at(evaluation_time_unix_seconds)?;
            supplied.validate_at(evaluation_time_unix_seconds)?;
            if let Some(field) = mismatched_authorization_field(required, supplied) {
                return Err(RecoveryContractError::MismatchedAcquisitionAuthorization { field });
            }
            Ok(())
        }
    }
}

fn validate_execution_authorization_binding(
    required: Option<&ModelAcquisitionAuthorization>,
    supplied: Option<&ModelAcquisitionAuthorization>,
    evaluation_time_unix_seconds: u64,
) -> Result<(), RecoveryContractError> {
    match (required, supplied) {
        (None, None) => Ok(()),
        (None, Some(_)) => Err(RecoveryContractError::SurplusAcquisitionAuthorization),
        (Some(_), None) => Err(RecoveryContractError::MissingAcquisitionAuthorization),
        (Some(required), Some(supplied)) => {
            required.validate_at(evaluation_time_unix_seconds)?;
            supplied.validate_at(evaluation_time_unix_seconds)?;
            if let Some(field) = mismatched_authorization_field(required, supplied) {
                return Err(RecoveryContractError::MismatchedAcquisitionAuthorization { field });
            }
            Ok(())
        }
    }
}

/// Compute the truthful plan for a readiness state under a request and
/// policy. Pure and deterministic: identical inputs yield identical plans.
///
/// # Errors
///
/// Rejects ambiguous request topology, invalid partial coverage, hash
/// requests without hash-control readiness, and malformed acquisition
/// targets before returning executable recovery metadata. Trusted evaluation
/// time is mandatory and never read from the serialized plan or ambient
/// process state.
pub fn plan(trusted: TrustedRecoveryContext<'_>) -> Result<RecoveryPlan, RecoveryContractError> {
    let TrustedRecoveryContext {
        state,
        request,
        policy,
        acquisition_target,
        evaluation_time_unix_seconds,
    } = trusted;
    let state = state.clone();
    let policy = policy.clone();
    let request = request.validate()?;
    if let Some(authorization) = &policy.acquisition_authorization {
        authorization.validate()?;
    }
    validate_hash_mode_state(request.mode, &state)?;
    validate_readiness(&state)?;
    validate_acquisition_tier(&state, request.requested_topology, acquisition_target)?;

    let action = action_for(
        &state,
        request.requested_topology,
        policy.network,
        acquisition_target,
    )?;
    validate_authorization_binding(
        action
            .as_ref()
            .and_then(RecoveryAction::required_authorization),
        policy.acquisition_authorization.as_ref(),
        evaluation_time_unix_seconds,
    )?;
    let (action, retryability) = match action {
        None => (
            None,
            if state.semantic_available()
                || matches!(
                    (&state, request.mode),
                    (SemanticReadiness::HashControl, RequestMode::HashControl)
                )
            {
                Retryability::NotNeeded
            } else {
                Retryability::AfterRequestChange
            },
        ),
        Some(mut action) => {
            let network_blocked =
                action.network_required && matches!(policy.network, NetworkPolicy::Offline);
            if network_blocked {
                push_prerequisite(&mut action, "recovery.policy.allow_network");
            }
            let authorization_satisfied =
                action
                    .required_authorization
                    .as_ref()
                    .is_some_and(|required| {
                        // ubs:ignore — this public policy contract is not an authenticator.
                        policy.acquisition_authorization.as_ref() == Some(required)
                    });
            let binding_missing = matches!(
                action.code.as_str(),
                "recovery.action.acquire_model" | "recovery.action.reacquire_model"
            ) && action.required_authorization.is_none();
            if binding_missing {
                push_prerequisite(&mut action, "recovery.policy.bind_model");
            }
            let consent_blocked = action.consent_required
                && matches!(policy.interaction, InteractionPolicy::NonInteractive)
                && !authorization_satisfied;
            if consent_blocked {
                push_prerequisite(&mut action, "recovery.policy.grant_consent");
            }
            let capability_blocked = action
                .prerequisites
                .iter()
                .any(|code| code.starts_with("recovery.capability."));
            let retryability = if capability_blocked {
                Retryability::BlockedByCapability
            } else if network_blocked
                || binding_missing
                || consent_blocked
                || !action.prerequisites.is_empty()
            {
                Retryability::BlockedByPolicy
            } else {
                Retryability::AfterAction
            };
            (Some(action), retryability)
        }
    };

    let semantic_available = state.semantic_available();
    let response_contract = response_contract_for(&state, request)?;
    let state_code = state.state_code().to_owned();
    let provenance = state.provenance();

    Ok(RecoveryPlan {
        schema_version: RecoveryPlanSchemaVersion::V4,
        state,
        state_code,
        provenance,
        mode: request.mode,
        requested_topology: request.requested_topology,
        policy,
        semantic_available,
        retryability,
        action,
        response_contract,
    })
}

fn validate_hash_mode_state(
    mode: RequestMode,
    state: &SemanticReadiness,
) -> Result<(), RecoveryContractError> {
    let hash_request = matches!(mode, RequestMode::HashControl);
    let hash_state = matches!(state, SemanticReadiness::HashControl);
    if hash_request == hash_state {
        Ok(())
    } else {
        Err(RecoveryContractError::HashControlModeReadinessMismatch)
    }
}

fn validate_readiness(state: &SemanticReadiness) -> Result<(), RecoveryContractError> {
    if let SemanticReadiness::PartialQualityCoverage { coverage_ppm, .. } = state
        && !(1..COMPLETE_COVERAGE_PPM).contains(coverage_ppm)
    {
        return Err(RecoveryContractError::InvalidCoverage {
            topology: RetrievalTopology::PartialQuality {
                coverage_ppm: *coverage_ppm,
            },
            coverage_ppm: *coverage_ppm,
        });
    }
    Ok(())
}

fn validate_acquisition_tier(
    state: &SemanticReadiness,
    requested_topology: RetrievalTopology,
    acquisition_target: Option<&ModelAcquisitionTarget>,
) -> Result<(), RecoveryContractError> {
    let readiness_tier = match state {
        SemanticReadiness::ModelMissing { tier } | SemanticReadiness::ModelUnloadable { tier } => {
            *tier
        }
        _ => return Ok(()),
    };
    let topology_matches = match requested_topology {
        // ubs:ignore — model tiers are public recovery-routing facts, not secrets.
        RetrievalTopology::FastOnly => readiness_tier == ModelTier::Fast,
        // ubs:ignore — model tiers are public recovery-routing facts, not secrets.
        RetrievalTopology::QualityOnly => readiness_tier == ModelTier::Quality,
        RetrievalTopology::FullProgressive => true,
        RetrievalTopology::LexicalOnly
        | RetrievalTopology::PartialQuality { .. }
        | RetrievalTopology::HashControl => false,
    };
    if !topology_matches {
        return Err(RecoveryContractError::UnavailableTierTopologyMismatch {
            tier: readiness_tier,
            requested_topology,
        });
    }
    if let Some(target) = acquisition_target
        // ubs:ignore — model tiers are public recovery-routing facts, not secrets.
        && target.model_tier != readiness_tier
    {
        return Err(RecoveryContractError::AcquisitionTargetTierMismatch {
            readiness_tier,
            target_tier: target.model_tier,
        });
    }
    Ok(())
}

fn response_contract_for(
    state: &SemanticReadiness,
    request: RecoveryRequest,
) -> Result<Option<SemanticResponseContract>, RecoveryContractError> {
    if matches!(request.mode, RequestMode::HashControl) {
        return SemanticResponseContract::new(
            RetrievalTopology::HashControl,
            RetrievalTopology::HashControl,
            0,
            0,
            None,
        )
        .map(Some);
    }

    if state.semantic_available() {
        let (realized_topology, coverage_ppm) = match (state, request.requested_topology) {
            (
                SemanticReadiness::PartialQualityCoverage { coverage_ppm, .. },
                RetrievalTopology::QualityOnly | RetrievalTopology::FullProgressive,
            ) => (
                RetrievalTopology::PartialQuality {
                    coverage_ppm: *coverage_ppm,
                },
                *coverage_ppm,
            ),
            _ => (request.requested_topology, COMPLETE_COVERAGE_PPM),
        };
        return SemanticResponseContract::new(
            request.requested_topology,
            realized_topology,
            coverage_ppm,
            0,
            None,
        )
        .map(Some);
    }

    if matches!(request.mode, RequestMode::Hybrid) {
        return SemanticResponseContract::new(
            request.requested_topology,
            RetrievalTopology::LexicalOnly,
            0,
            0,
            Some(state.state_code().to_owned()),
        )
        .map(Some);
    }

    Ok(None)
}

fn push_prerequisite(action: &mut RecoveryAction, code: &str) {
    // ubs:ignore — prerequisite codes are public recovery facts, not authenticators.
    if !action.prerequisites.iter().any(|existing| existing == code) {
        action.prerequisites.push(code.to_owned());
    }
}

// The parameters mirror RecoveryAction's schema-mandated boolean fields
// one-to-one; an intermediate flags type would only restate the struct.
#[allow(clippy::fn_params_excessive_bools)]
fn simple_action(
    code: &str,
    explanation: &str,
    argv: &[&str],
    network_required: bool,
    consent_required: bool,
    preserves_old_data: bool,
    potentially_destructive: bool,
    expected_postcondition: &str,
) -> RecoveryAction {
    RecoveryAction {
        code: code.to_owned(),
        explanation: explanation.to_owned(),
        argv: argv.iter().map(|&a| a.to_owned()).collect(),
        network_required,
        consent_required,
        preserves_old_data,
        potentially_destructive,
        prerequisites: Vec::new(),
        expected_postcondition: expected_postcondition.to_owned(),
        required_authorization: None,
    }
}

fn block_unbound_semantic_index_action(
    mut action: RecoveryAction,
    requested_topology: RetrievalTopology,
    quality_capability: &str,
) -> RecoveryAction {
    action.argv.clear();
    let capability = if matches!(requested_topology, RetrievalTopology::FastOnly) {
        "recovery.capability.execute_bound_semantic_index"
    } else {
        quality_capability
    };
    push_prerequisite(&mut action, capability);
    action
}

/// The exhaustive state → action table. No wildcard arm: adding a
/// readiness state without planning for it is a compile error.
fn action_for(
    state: &SemanticReadiness,
    requested_topology: RetrievalTopology,
    network: NetworkPolicy,
    acquisition_target: Option<&ModelAcquisitionTarget>,
) -> Result<Option<RecoveryAction>, RecoveryContractError> {
    match state {
        SemanticReadiness::Ready { .. } | SemanticReadiness::HashControl => Ok(None),
        SemanticReadiness::ModelMissing { .. } => {
            model_acquisition_action(false, network, acquisition_target).map(Some)
        }
        SemanticReadiness::ModelUnloadable { .. } => {
            model_acquisition_action(true, network, acquisition_target).map(Some)
        }
        SemanticReadiness::IndexAbsent => Ok(Some(block_unbound_semantic_index_action(
            simple_action(
                "recovery.action.build_index",
                "A verified model is present but no vector index exists. Current generic fsfs \
                 indexing can still fall through to a non-semantic producer, so recovery needs \
                 an executor bound to the attested semantic space and requested topology.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.index_built",
            ),
            requested_topology,
            "recovery.capability.build_quality_tier",
        ))),
        SemanticReadiness::IdentityMismatch => Ok(Some(block_unbound_semantic_index_action(
            simple_action(
                "recovery.action.reindex_full",
                "The index was built in a different embedding space than the configured model. \
                 Rebuild only if the identity change is intentional, through an executor bound \
                 to the attested semantic space and requested topology; the existing index is \
                 replaced.",
                &[],
                false,
                true,
                false,
                true,
                "recovery.post.index_rebuilt",
            ),
            requested_topology,
            "recovery.capability.reindex_quality_tier",
        ))),
        SemanticReadiness::DaemonMismatch => {
            let mut action = simple_action(
                "recovery.action.restart_daemon",
                "The embedding daemon serves a different space than the local configuration, \
                 but fsfs currently has no parser-executable restart operation. A bound daemon \
                 lifecycle capability must land before recovery can run.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.daemon_aligned",
            );
            push_prerequisite(&mut action, "recovery.capability.restart_daemon");
            Ok(Some(action))
        }
        SemanticReadiness::IndexEmpty(reason) => Ok(plan_for_empty(*reason, requested_topology)),
        SemanticReadiness::ManifestUnsafe => Ok(Some(block_unbound_semantic_index_action(
            simple_action(
                "recovery.action.reindex_full",
                "The manifest failed safety validation and its artifacts must not be trusted; \
                 rebuild from source content only through an executor bound to the attested \
                 semantic space and requested topology.",
                &[],
                false,
                true,
                false,
                true,
                "recovery.post.index_rebuilt",
            ),
            requested_topology,
            "recovery.capability.reindex_quality_tier",
        ))),
        SemanticReadiness::AnnStale => {
            let mut action = simple_action(
                "recovery.action.rebuild_ann",
                "The ANN sidecar belongs to an older index generation, but generic indexing \
                 does not bind the exact ANN generation to rebuild. Exact search remains \
                 correct while the dedicated generation-aware capability is unavailable.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.ann_rebuilt",
            );
            push_prerequisite(&mut action, "recovery.capability.rebuild_ann_generation");
            Ok(Some(action))
        }
        SemanticReadiness::GenerationIncomplete => Ok(Some(block_unbound_semantic_index_action(
            simple_action(
                "recovery.action.resume_index",
                "An index generation was interrupted before publication. Completing it requires \
                 an executor bound to the attested semantic space, topology, and generation; \
                 published data remains untouched.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.generation_completed",
            ),
            requested_topology,
            "recovery.capability.resume_quality_generation",
        ))),
        SemanticReadiness::PartialQualityCoverage { .. }
            if matches!(requested_topology, RetrievalTopology::FastOnly) =>
        {
            Ok(None)
        }
        SemanticReadiness::PartialQualityCoverage { .. } => {
            let mut action = simple_action(
                "recovery.action.backfill_quality",
                "Some records lack quality-tier embeddings, but generic indexing does not \
                 express a quality-only backfill. Search remains available while the dedicated \
                 tier-aware capability is unavailable.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.coverage_completed",
            );
            push_prerequisite(&mut action, "recovery.capability.backfill_quality_tier");
            Ok(Some(action))
        }
        SemanticReadiness::RemoteUnverified => {
            let mut action = simple_action(
                "recovery.action.provide_attestation",
                "Explicit remote intent cannot be admitted because its producer space is not \
                 attested. Supply a pinned producer attester through the caller-owned \
                 configuration boundary; there is no safe generic command that can invent \
                 this trust root.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.remote_attested",
            );
            push_prerequisite(&mut action, "recovery.policy.provide_attestation");
            Ok(Some(action))
        }
    }
}

fn model_acquisition_action(
    reacquire: bool,
    network: NetworkPolicy,
    acquisition_target: Option<&ModelAcquisitionTarget>,
) -> Result<RecoveryAction, RecoveryContractError> {
    let code = if reacquire {
        "recovery.action.reacquire_model"
    } else {
        "recovery.action.acquire_model"
    };
    let required_authorization = acquisition_target
        .map(|target| target.authorization_for(network))
        .transpose()?;
    let explanation = match (network, reacquire) {
        (NetworkPolicy::Allowed, false) => {
            "The configured semantic model must be acquired under the exact frozen \
             authorization, but current fsfs download syntax cannot bind every authorized \
             identity, byte-budget, destination, corpus, and reindex field to execution. This \
             action is deliberately non-executable until a bound executor exists."
        }
        (NetworkPolicy::Allowed, true) => {
            "The cached model failed verification or load self-test, but current fsfs download \
             syntax cannot bind the complete frozen re-acquisition authorization to execution. \
             This action is deliberately non-executable until a bound executor exists; index \
             data is untouched."
        }
        (NetworkPolicy::Offline, false) => {
            "A complete local-bundle import is required, but the current fsfs parser has no \
             offline importer. This action is deliberately non-executable until that capability \
             exists; no network access is permitted."
        }
        (NetworkPolicy::Offline, true) => {
            "Replacing the unloadable cache from a complete local bundle requires an importer \
             that the current fsfs parser does not provide. This action is deliberately \
             non-executable until that capability exists; index data is untouched."
        }
    };
    let mut action = simple_action(
        code,
        explanation,
        &[],
        matches!(network, NetworkPolicy::Allowed),
        true,
        !reacquire,
        reacquire,
        "recovery.post.model_acquired_unverified",
    );
    action.required_authorization = required_authorization;
    match network {
        NetworkPolicy::Allowed => push_prerequisite(
            &mut action,
            "recovery.capability.execute_bound_model_acquisition",
        ),
        NetworkPolicy::Offline => {
            push_prerequisite(&mut action, "recovery.capability.import_model_bundle");
        }
    }
    Ok(action)
}

/// Empty-index planning follows the zero-signal classification: benign
/// state emptiness wants ingestion, availability failures want rebuilds,
/// the ANN anomaly wants a sidecar rebuild, and request-scoped reasons
/// need no system action at all.
fn plan_for_empty(
    reason: ZeroSignalReason,
    requested_topology: RetrievalTopology,
) -> Option<RecoveryAction> {
    match reason {
        ZeroSignalReason::NewlyCreatedEmpty
        | ZeroSignalReason::AllTombstoned
        | ZeroSignalReason::WalOnlyNoLiveRecords => Some(block_unbound_semantic_index_action(
            simple_action(
                "recovery.action.ingest_content",
                "The index holds no live records. Populate it only through an executor bound to \
                 the attested semantic space and requested topology.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.index_populated",
            ),
            requested_topology,
            "recovery.capability.ingest_quality_tier",
        )),
        ZeroSignalReason::NoUsableVectors => Some(block_unbound_semantic_index_action(
            simple_action(
                "recovery.action.reindex_full",
                "Live records exist but none of their stored vectors is usable (zero-norm or \
                 corrupt); rebuild only through an executor bound to the attested semantic space \
                 and requested topology.",
                &[],
                false,
                true,
                false,
                true,
                "recovery.post.index_rebuilt",
            ),
            requested_topology,
            "recovery.capability.reindex_quality_tier",
        )),
        ZeroSignalReason::AnnReturnedEmptyDespiteUsableVectors => {
            let mut action = simple_action(
                "recovery.action.rebuild_ann",
                "The ANN graph returned no candidates although usable live vectors exist, but \
                 generic indexing does not bind the exact ANN generation to rebuild. The vector \
                 index remains untouched.",
                &[],
                false,
                false,
                true,
                false,
                "recovery.post.ann_rebuilt",
            );
            push_prerequisite(&mut action, "recovery.capability.rebuild_ann_generation");
            Some(action)
        }
        ZeroSignalReason::CallerRequestedZeroK
        | ZeroSignalReason::FilterEliminatedAll
        | ZeroSignalReason::NonFiniteQuery
        | ZeroSignalReason::ZeroNormQuery => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::decision_plane::ReasonCode;
    use crate::generation::{
        EMBEDDING_SPACE_IDENTITY_SCHEMA_V1, EmbeddingArtifactIdentityV1, EmbeddingIdentityBundleV1,
    };

    const TEST_NOW_UNIX_SECONDS: u64 = 2_000_000_000;
    const TEST_AUTHORIZATION_ISSUED_AT_UNIX_SECONDS: u64 = TEST_NOW_UNIX_SECONDS - 60;
    const TEST_AUTHORIZATION_EXPIRES_AT_UNIX_SECONDS: u64 = TEST_NOW_UNIX_SECONDS + 600;
    const TEST_AUTHORIZATION_NONCE: &str = "0123456789abcdef0123456789abcdef";

    fn semantic_space() -> EmbeddingSpaceIdentityV1 {
        EmbeddingSpaceIdentityV1 {
            schema_version: EMBEDDING_SPACE_IDENTITY_SCHEMA_V1,
            logical_model_id: "fixture-semantic-model".to_owned(),
            immutable_revision: "revision-0123456789abcdef".to_owned(),
            kind: EmbeddingSpaceKindV1::Semantic,
            artifact_manifest_fingerprint: "a".repeat(64),
            artifacts: vec![EmbeddingArtifactIdentityV1 {
                role: "weights".to_owned(),
                sha256: "c".repeat(64),
                size: 42_000_000,
            }],
            tokenizer_fingerprint: "d".repeat(64),
            vocabulary_fingerprint: "e".repeat(64),
            model_config_fingerprint: "f".repeat(64),
            model_preprocessing: "nfc-v1".to_owned(),
            sequence_policy: "truncate-256-v1".to_owned(),
            query_instruction: String::new(),
            document_instruction: String::new(),
            pooling: "mean-v1".to_owned(),
            output_normalization: "l2-v1".to_owned(),
            dimension: 384,
            input_contract_fingerprint: "1".repeat(64),
            hash_control: None,
            projection: None,
        }
    }

    fn target_for(model_tier: ModelTier) -> ModelAcquisitionTarget {
        ModelAcquisitionTarget {
            model_id: "fixture-semantic-model".to_owned(),
            model_tier,
            embedding_space: semantic_space(),
            manifest_fingerprint: "a".repeat(64),
            upstream_revision: "revision-0123456789abcdef".to_owned(),
            license_spdx: "Apache-2.0".to_owned(),
            network_source_hosts: vec!["models.example.test".to_owned()],
            byte_budget: 42_000_000,
            destination_class: ModelDestinationClass::ManagedCache,
            destination_fingerprint: "b".repeat(64),
            document_count: 12_345,
            estimated_reindex_duration_ms: 98_765,
            issued_at_unix_seconds: TEST_AUTHORIZATION_ISSUED_AT_UNIX_SECONDS,
            expires_at_unix_seconds: TEST_AUTHORIZATION_EXPIRES_AT_UNIX_SECONDS,
            nonce: TEST_AUTHORIZATION_NONCE.to_owned(),
        }
    }

    fn target() -> ModelAcquisitionTarget {
        target_for(ModelTier::Quality)
    }

    const fn missing(tier: ModelTier) -> SemanticReadiness {
        SemanticReadiness::ModelMissing { tier }
    }

    const fn unloadable(tier: ModelTier) -> SemanticReadiness {
        SemanticReadiness::ModelUnloadable { tier }
    }

    const fn explicit(requested_topology: RetrievalTopology) -> RecoveryRequest {
        RecoveryRequest {
            mode: RequestMode::ExplicitSemantic,
            requested_topology,
        }
    }

    const fn hybrid(requested_topology: RetrievalTopology) -> RecoveryRequest {
        RecoveryRequest {
            mode: RequestMode::Hybrid,
            requested_topology,
        }
    }

    const fn hash_control() -> RecoveryRequest {
        RecoveryRequest {
            mode: RequestMode::HashControl,
            requested_topology: RetrievalTopology::HashControl,
        }
    }

    fn semantic_requests() -> [RecoveryRequest; 6] {
        [
            explicit(RetrievalTopology::FastOnly),
            explicit(RetrievalTopology::QualityOnly),
            explicit(RetrievalTopology::FullProgressive),
            hybrid(RetrievalTopology::FastOnly),
            hybrid(RetrievalTopology::QualityOnly),
            hybrid(RetrievalTopology::FullProgressive),
        ]
    }

    fn representative_states() -> Vec<SemanticReadiness> {
        vec![
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Remote,
            },
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Daemon,
            },
            missing(ModelTier::Quality),
            unloadable(ModelTier::Quality),
            SemanticReadiness::IndexAbsent,
            SemanticReadiness::IdentityMismatch,
            SemanticReadiness::DaemonMismatch,
            SemanticReadiness::IndexEmpty(ZeroSignalReason::NewlyCreatedEmpty),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::AllTombstoned),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::WalOnlyNoLiveRecords),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::CallerRequestedZeroK),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::NoUsableVectors),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::AnnReturnedEmptyDespiteUsableVectors),
            SemanticReadiness::ManifestUnsafe,
            SemanticReadiness::AnnStale,
            SemanticReadiness::GenerationIncomplete,
            SemanticReadiness::PartialQualityCoverage {
                provenance: VerifiedSemanticProvenance::Local,
                coverage_ppm: 750_000,
            },
            SemanticReadiness::PartialQualityCoverage {
                provenance: VerifiedSemanticProvenance::Remote,
                coverage_ppm: 500_000,
            },
            SemanticReadiness::RemoteUnverified,
            SemanticReadiness::HashControl,
        ]
    }

    fn unready_states() -> Vec<SemanticReadiness> {
        representative_states()
            .into_iter()
            .filter(|state| {
                !state.semantic_available() && !matches!(state, SemanticReadiness::HashControl)
            })
            .collect()
    }

    fn all_policies() -> Vec<RecoveryPolicy> {
        let mut out = Vec::new();
        for interaction in [
            InteractionPolicy::Interactive,
            InteractionPolicy::NonInteractive,
        ] {
            for network in [NetworkPolicy::Allowed, NetworkPolicy::Offline] {
                out.push(RecoveryPolicy {
                    interaction,
                    network,
                    acquisition_authorization: None,
                });
            }
        }
        out
    }

    fn permissive() -> RecoveryPolicy {
        RecoveryPolicy {
            interaction: InteractionPolicy::Interactive,
            network: NetworkPolicy::Allowed,
            acquisition_authorization: None,
        }
    }

    // These test builders deliberately own state and policy so call sites can
    // pass temporary fixtures without introducing local bindings solely for
    // borrow lifetimes.
    #[allow(clippy::needless_pass_by_value)]
    fn plan(
        state: SemanticReadiness,
        request: RecoveryRequest,
        policy: RecoveryPolicy,
        acquisition_target: Option<&ModelAcquisitionTarget>,
    ) -> Result<RecoveryPlan, RecoveryContractError> {
        super::plan(TrustedRecoveryContext::new(
            &state,
            request,
            &policy,
            acquisition_target,
            TEST_NOW_UNIX_SECONDS,
        ))
    }

    #[allow(clippy::needless_pass_by_value)]
    fn planned(
        state: SemanticReadiness,
        request: RecoveryRequest,
        policy: RecoveryPolicy,
    ) -> RecoveryPlan {
        plan(state, request, policy, Some(&target())).expect("valid recovery plan")
    }

    fn tier_for_request(request: RecoveryRequest) -> ModelTier {
        match request.requested_topology {
            RetrievalTopology::FastOnly => ModelTier::Fast,
            RetrievalTopology::QualityOnly | RetrievalTopology::FullProgressive => {
                ModelTier::Quality
            }
            other @ (RetrievalTopology::LexicalOnly
            | RetrievalTopology::PartialQuality { .. }
            | RetrievalTopology::HashControl) => {
                assert!(
                    matches!(
                        other,
                        RetrievalTopology::FastOnly
                            | RetrievalTopology::QualityOnly
                            | RetrievalTopology::FullProgressive
                    ),
                    "semantic recovery helper received a non-semantic topology: {other:?}"
                );
                ModelTier::Quality
            }
        }
    }

    fn state_for_request(state: &SemanticReadiness, request: RecoveryRequest) -> SemanticReadiness {
        match state {
            SemanticReadiness::ModelMissing { .. } => missing(tier_for_request(request)),
            SemanticReadiness::ModelUnloadable { .. } => unloadable(tier_for_request(request)),
            _ => state.clone(),
        }
    }

    fn decode_and_validate(
        value: serde_json::Value,
        state: &SemanticReadiness,
        request: RecoveryRequest,
        policy: &RecoveryPolicy,
        acquisition_target: Option<&ModelAcquisitionTarget>,
    ) -> Result<RecoveryPlan, String> {
        let untrusted: UntrustedRecoveryPlan =
            serde_json::from_value(value).map_err(|error| error.to_string())?;
        untrusted
            .validate_against(TrustedRecoveryContext::new(
                state,
                request,
                policy,
                acquisition_target,
                TEST_NOW_UNIX_SECONDS,
            ))
            .map_err(|error| error.to_string())
    }

    #[test]
    fn every_stable_code_is_valid_and_unique() {
        let mut codes = Vec::new();
        let states = representative_states();
        for state in &states {
            codes.push(state.state_code().to_owned());
            if !matches!(state, SemanticReadiness::HashControl) {
                for request in semantic_requests() {
                    for policy in all_policies() {
                        let tier = tier_for_request(request);
                        let state = state_for_request(state, request);
                        let plan = plan(state, request, policy, Some(&target_for(tier)))
                            .expect("representative plan");
                        if let Some(action) = plan.action {
                            codes.push(action.code.clone());
                            codes.push(action.expected_postcondition.clone());
                            codes.extend(action.prerequisites);
                        }
                    }
                }
            }
        }
        let hash_plan = planned(SemanticReadiness::HashControl, hash_control(), permissive());
        codes.push(hash_plan.state_code);
        let unbound = plan(
            missing(ModelTier::Fast),
            explicit(RetrievalTopology::FastOnly),
            permissive(),
            None,
        )
        .expect("unbound acquisition still returns a blocked plan");
        codes.extend(unbound.action.expect("model action").prerequisites);
        codes.push("recovery.policy.allow_network".to_owned());
        for code in &codes {
            assert!(
                ReasonCode::new(code.as_str()).is_valid(),
                "invalid stable code format: {code}"
            );
        }
        // Distinct states never share a code with distinct actions.
        let state_codes: std::collections::HashSet<_> =
            states.iter().map(|s| s.state_code()).collect();
        assert_eq!(state_codes.len(), 13, "one code per state variant");

        let emitted: std::collections::HashSet<_> = codes.iter().map(String::as_str).collect();
        let v1_codes = [
            "recovery.state.ready",
            "recovery.state.model_missing",
            "recovery.state.model_unloadable",
            "recovery.state.index_absent",
            "recovery.state.identity_mismatch",
            "recovery.state.daemon_mismatch",
            "recovery.state.index_empty",
            "recovery.state.manifest_unsafe",
            "recovery.state.ann_stale",
            "recovery.state.generation_incomplete",
            "recovery.state.partial_quality_coverage",
            "recovery.action.acquire_model",
            "recovery.action.reacquire_model",
            "recovery.action.build_index",
            "recovery.action.reindex_full",
            "recovery.action.restart_daemon",
            "recovery.action.ingest_content",
            "recovery.action.rebuild_ann",
            "recovery.action.resume_index",
            "recovery.action.backfill_quality",
            "recovery.post.model_acquired_unverified",
            "recovery.post.index_built",
            "recovery.post.index_rebuilt",
            "recovery.post.daemon_aligned",
            "recovery.post.index_populated",
            "recovery.post.ann_rebuilt",
            "recovery.post.generation_completed",
            "recovery.post.coverage_completed",
            "recovery.policy.allow_network",
            "recovery.policy.grant_consent",
        ];
        for old_code in v1_codes {
            assert!(
                emitted.contains(old_code),
                "v1 code disappeared: {old_code}"
            );
        }
        for appended in [
            "recovery.state.remote_unverified",
            "recovery.state.hash_control",
            "recovery.action.provide_attestation",
            "recovery.post.remote_attested",
            "recovery.policy.provide_attestation",
            "recovery.policy.bind_model",
            "recovery.capability.backfill_quality_tier",
            "recovery.capability.build_quality_tier",
            "recovery.capability.execute_bound_model_acquisition",
            "recovery.capability.execute_bound_semantic_index",
            "recovery.capability.ingest_quality_tier",
            "recovery.capability.import_model_bundle",
            "recovery.capability.rebuild_ann_generation",
            "recovery.capability.reindex_quality_tier",
            "recovery.capability.restart_daemon",
            "recovery.capability.resume_quality_generation",
        ] {
            assert!(
                emitted.contains(appended),
                "appended code absent: {appended}"
            );
        }
    }

    #[test]
    fn explicit_semantic_fails_closed_for_every_unready_state() {
        for state in unready_states() {
            let plan = planned(
                state.clone(),
                explicit(RetrievalTopology::FullProgressive),
                permissive(),
            );
            assert!(!plan.semantic_available);
            assert!(
                plan.response_contract.is_none(),
                "explicit semantic never degrades to lexical: {state:?}"
            );
        }
    }

    #[test]
    fn hybrid_degrades_with_metadata_exactly_when_unavailable() {
        for state in unready_states() {
            let plan = planned(
                state.clone(),
                hybrid(RetrievalTopology::FullProgressive),
                permissive(),
            );
            let response = plan
                .response_contract
                .expect("unavailable hybrid must carry response contract");
            assert_eq!(
                response.requested_topology(),
                RetrievalTopology::FullProgressive
            );
            assert_eq!(response.realized_topology(), RetrievalTopology::LexicalOnly);
            assert_eq!(response.coverage_ppm(), 0);
            assert_eq!(response.admitted_semantic_scores(), 0);
            assert_eq!(response.degradation_reason_code(), Some(state.state_code()));
        }
    }

    #[test]
    fn acquisition_never_claims_readiness() {
        for state in [missing(ModelTier::Quality), unloadable(ModelTier::Quality)] {
            let reacquire = matches!(state, SemanticReadiness::ModelUnloadable { .. });
            let plan = planned(
                state,
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
            );
            assert_eq!(plan.retryability, Retryability::BlockedByCapability);
            let action = plan.action.expect("acquisition state has an action");
            assert_eq!(
                action.expected_postcondition,
                "recovery.post.model_acquired_unverified"
            );
            assert_ne!(action.expected_postcondition, "recovery.state.ready");
            assert!(action.network_required);
            assert!(action.consent_required);
            assert_eq!(action.preserves_old_data, !reacquire);
            assert_eq!(action.potentially_destructive, reacquire);
            assert_eq!(
                action.code,
                if reacquire {
                    "recovery.action.reacquire_model"
                } else {
                    "recovery.action.acquire_model"
                }
            );
            assert!(
                action.argv.is_empty(),
                "partial download syntax must not masquerade as exact bound authorization"
            );
            assert_eq!(
                action.prerequisites,
                ["recovery.capability.execute_bound_model_acquisition"]
            );
            let authorization = action
                .required_authorization
                .expect("acquisition binds exact authorization");
            assert_eq!(authorization.model_id, "fixture-semantic-model");
            assert_eq!(authorization.model_tier, ModelTier::Quality);
            assert_eq!(authorization.embedding_space, semantic_space());
            assert_eq!(authorization.manifest_fingerprint, "a".repeat(64));
            assert_eq!(authorization.upstream_revision, "revision-0123456789abcdef");
            assert_eq!(authorization.license_spdx, "Apache-2.0");
            assert_eq!(authorization.byte_budget, 42_000_000);
            assert_eq!(
                authorization.destination_class,
                ModelDestinationClass::ManagedCache
            );
            assert_eq!(authorization.destination_fingerprint, "b".repeat(64));
            assert_eq!(authorization.document_count, 12_345);
            assert_eq!(authorization.estimated_reindex_duration_ms, 98_765);
            assert_eq!(
                authorization.issued_at_unix_seconds,
                TEST_AUTHORIZATION_ISSUED_AT_UNIX_SECONDS
            );
            assert_eq!(
                authorization.expires_at_unix_seconds,
                TEST_AUTHORIZATION_EXPIRES_AT_UNIX_SECONDS
            );
            assert_eq!(authorization.nonce, TEST_AUTHORIZATION_NONCE);
            assert!(matches!(
                authorization.source,
                ModelAcquisitionSource::Network { .. }
            ));
        }
    }

    #[test]
    fn offline_policy_reports_missing_import_capability_without_fictional_argv() {
        let policy = RecoveryPolicy {
            interaction: InteractionPolicy::Interactive,
            network: NetworkPolicy::Offline,
            acquisition_authorization: None,
        };
        for state in [missing(ModelTier::Quality), unloadable(ModelTier::Quality)] {
            let plan = planned(
                state,
                hybrid(RetrievalTopology::FullProgressive),
                policy.clone(),
            );
            assert_eq!(plan.retryability, Retryability::BlockedByCapability);
            let action = plan.action.expect("action still recommended");
            assert!(
                action.argv.is_empty(),
                "offline recovery must not publish argv that fsfs cannot parse"
            );
            assert!(!action.network_required);
            assert!(action.consent_required);
            assert_eq!(
                action.prerequisites,
                ["recovery.capability.import_model_bundle"]
            );
            assert!(matches!(
                action.required_authorization.expect("offline scope").source,
                ModelAcquisitionSource::LocalBundle
            ));
        }
    }

    #[test]
    fn planned_semantic_mutations_never_publish_unbound_argv() {
        for state in unready_states() {
            let full_recovery = planned(
                state.clone(),
                explicit(RetrievalTopology::FullProgressive),
                permissive(),
            );
            if let Some(action) = full_recovery.action {
                assert!(
                    action.argv.is_empty(),
                    "quality/full recovery must not claim generic indexing realizes the \
                     requested topology for {state:?}: {:?}",
                    action.argv
                );
            }

            let request = explicit(RetrievalTopology::FastOnly);
            let fast_state = state_for_request(&state, request);
            let fast_recovery = plan(
                fast_state,
                request,
                permissive(),
                Some(&target_for(ModelTier::Fast)),
            )
            .expect("valid fast-tier recovery plan");
            let Some(action) = fast_recovery.action else {
                continue;
            };
            assert!(
                action.argv.is_empty(),
                "fast-only recovery must not execute until semantic producer identity and \
                 generation are bound for {state:?}: {:?}",
                action.argv
            );
        }

        for state in [
            SemanticReadiness::IndexAbsent,
            SemanticReadiness::IdentityMismatch,
            SemanticReadiness::ManifestUnsafe,
            SemanticReadiness::GenerationIncomplete,
            SemanticReadiness::IndexEmpty(ZeroSignalReason::NewlyCreatedEmpty),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::NoUsableVectors),
        ] {
            let recovery = plan(
                state.clone(),
                explicit(RetrievalTopology::FastOnly),
                permissive(),
                Some(&target_for(ModelTier::Fast)),
            )
            .expect("fast-tier semantic mutation plan");
            let action = recovery.action.expect("semantic mutation action");
            assert!(action.argv.is_empty(), "{state:?}");
            assert!(
                action
                    .prerequisites
                    .contains(&"recovery.capability.execute_bound_semantic_index".to_owned()),
                "{state:?}"
            );
            assert_eq!(
                recovery.retryability,
                Retryability::BlockedByCapability,
                "{state:?}"
            );
        }

        let daemon = planned(
            SemanticReadiness::DaemonMismatch,
            explicit(RetrievalTopology::FullProgressive),
            permissive(),
        );
        let daemon_action = daemon.action.expect("daemon recovery");
        assert!(daemon_action.argv.is_empty());
        assert_eq!(
            daemon_action.prerequisites,
            ["recovery.capability.restart_daemon"]
        );
        assert_eq!(daemon.retryability, Retryability::BlockedByCapability);
    }

    #[test]
    fn noninteractive_policy_blocks_consent_actions_with_prerequisite() {
        let policy = RecoveryPolicy {
            interaction: InteractionPolicy::NonInteractive,
            network: NetworkPolicy::Allowed,
            acquisition_authorization: None,
        };
        for state in [
            SemanticReadiness::IdentityMismatch,
            SemanticReadiness::ManifestUnsafe,
            SemanticReadiness::IndexEmpty(ZeroSignalReason::NoUsableVectors),
        ] {
            let plan = planned(
                state.clone(),
                explicit(RetrievalTopology::FullProgressive),
                policy.clone(),
            );
            assert_eq!(
                plan.retryability,
                Retryability::BlockedByCapability,
                "{state:?}"
            );
            let action = plan.action.expect("destructive states have actions");
            assert!(action.consent_required);
            assert!(action.potentially_destructive);
            assert!(!action.preserves_old_data);
            assert!(
                action
                    .prerequisites
                    .contains(&"recovery.policy.grant_consent".to_owned())
            );
            assert!(
                action
                    .prerequisites
                    .contains(&"recovery.capability.reindex_quality_tier".to_owned())
            );
        }
    }

    #[test]
    fn request_scoped_emptiness_needs_no_system_action() {
        for reason in [
            ZeroSignalReason::CallerRequestedZeroK,
            ZeroSignalReason::FilterEliminatedAll,
            ZeroSignalReason::NonFiniteQuery,
            ZeroSignalReason::ZeroNormQuery,
        ] {
            let plan = planned(
                SemanticReadiness::IndexEmpty(reason),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
            );
            assert!(plan.action.is_none(), "{reason:?}");
            assert_eq!(plan.retryability, Retryability::AfterRequestChange);
            assert!(!plan.semantic_available);
        }
    }

    #[test]
    fn partial_coverage_is_available_with_a_backfill_action() {
        let plan = planned(
            SemanticReadiness::PartialQualityCoverage {
                provenance: VerifiedSemanticProvenance::Remote,
                coverage_ppm: 625_000,
            },
            hybrid(RetrievalTopology::FullProgressive),
            permissive(),
        );
        assert!(plan.semantic_available);
        assert_eq!(plan.provenance, SemanticProvenance::VerifiedRemote);
        let response = plan.response_contract.as_ref().expect("response contract");
        assert_eq!(
            response.realized_topology(),
            RetrievalTopology::PartialQuality {
                coverage_ppm: 625_000
            }
        );
        assert_eq!(response.coverage_ppm(), 625_000);
        assert_eq!(response.admitted_semantic_scores(), 0);
        assert!(response.degradation_reason_code().is_none());
        let action = plan.action.expect("backfill recommended");
        assert_eq!(action.code, "recovery.action.backfill_quality");
        assert!(action.preserves_old_data);
        // The lane serves partial results, but no current command can express
        // the required quality-only backfill.
        assert_eq!(plan.retryability, Retryability::BlockedByCapability);
        assert_eq!(
            action.prerequisites,
            ["recovery.capability.backfill_quality_tier"]
        );
    }

    #[test]
    fn partial_quality_coverage_only_backfills_topologies_that_request_quality() {
        let state = SemanticReadiness::PartialQualityCoverage {
            provenance: VerifiedSemanticProvenance::Remote,
            coverage_ppm: 625_000,
        };
        for mode in [RequestMode::ExplicitSemantic, RequestMode::Hybrid] {
            let fast = planned(
                state.clone(),
                RecoveryRequest {
                    mode,
                    requested_topology: RetrievalTopology::FastOnly,
                },
                permissive(),
            );
            assert!(fast.semantic_available);
            assert_eq!(fast.retryability, Retryability::NotNeeded);
            assert!(
                fast.action.is_none(),
                "complete fast-tier coverage needs no quality backfill"
            );
            let response = fast.response_contract.expect("fast response contract");
            assert_eq!(response.realized_topology(), RetrievalTopology::FastOnly);
            assert_eq!(response.coverage_ppm(), COMPLETE_COVERAGE_PPM);

            for requested_topology in [
                RetrievalTopology::QualityOnly,
                RetrievalTopology::FullProgressive,
            ] {
                let quality = planned(
                    state.clone(),
                    RecoveryRequest {
                        mode,
                        requested_topology,
                    },
                    permissive(),
                );
                assert!(quality.semantic_available);
                assert_eq!(quality.retryability, Retryability::BlockedByCapability);
                let action = quality.action.expect("quality request needs backfill");
                assert_eq!(action.code, "recovery.action.backfill_quality");
                assert!(action.argv.is_empty());
                assert_eq!(
                    action.prerequisites,
                    ["recovery.capability.backfill_quality_tier"]
                );
                let response = quality
                    .response_contract
                    .expect("quality response contract");
                assert_eq!(
                    response.realized_topology(),
                    RetrievalTopology::PartialQuality {
                        coverage_ppm: 625_000
                    }
                );
                assert_eq!(response.coverage_ppm(), 625_000);
            }
        }
    }

    #[test]
    fn request_topology_matrix_is_explicit_and_hash_isolated() {
        for request in semantic_requests().into_iter().chain([hash_control()]) {
            assert_eq!(request.validate(), Ok(request));
            let json = serde_json::to_string(&request).expect("serialize request");
            let decoded: RecoveryRequest =
                serde_json::from_str(&json).expect("deserialize valid request");
            assert_eq!(decoded, request);
        }

        let invalid = [
            explicit(RetrievalTopology::LexicalOnly),
            explicit(RetrievalTopology::HashControl),
            explicit(RetrievalTopology::PartialQuality {
                coverage_ppm: 500_000,
            }),
            hybrid(RetrievalTopology::LexicalOnly),
            hybrid(RetrievalTopology::HashControl),
            hybrid(RetrievalTopology::PartialQuality {
                coverage_ppm: 500_000,
            }),
            RecoveryRequest {
                mode: RequestMode::HashControl,
                requested_topology: RetrievalTopology::LexicalOnly,
            },
            RecoveryRequest {
                mode: RequestMode::HashControl,
                requested_topology: RetrievalTopology::FastOnly,
            },
            RecoveryRequest {
                mode: RequestMode::HashControl,
                requested_topology: RetrievalTopology::QualityOnly,
            },
            RecoveryRequest {
                mode: RequestMode::HashControl,
                requested_topology: RetrievalTopology::FullProgressive,
            },
            RecoveryRequest {
                mode: RequestMode::HashControl,
                requested_topology: RetrievalTopology::PartialQuality {
                    coverage_ppm: 500_000,
                },
            },
        ];
        for request in invalid {
            assert!(matches!(
                request.validate(),
                Err(RecoveryContractError::InvalidRequestTopology { .. })
            ));
            let json = serde_json::to_string(&request).expect("serialize invalid request");
            assert!(
                serde_json::from_str::<RecoveryRequest>(&json).is_err(),
                "serde must not bypass request validation: {request:?}"
            );
        }

        for state in [
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            missing(ModelTier::Quality),
            SemanticReadiness::RemoteUnverified,
        ] {
            assert_eq!(
                plan(state, hash_control(), permissive(), Some(&target())),
                Err(RecoveryContractError::HashControlModeReadinessMismatch)
            );
        }
        for request in semantic_requests() {
            assert_eq!(
                plan(
                    SemanticReadiness::HashControl,
                    request,
                    permissive(),
                    Some(&target()),
                ),
                Err(RecoveryContractError::HashControlModeReadinessMismatch)
            );
        }
    }

    #[test]
    fn provenance_matrix_never_promotes_unverified_or_hash_producers() {
        for (producer, expected) in [
            (
                VerifiedSemanticProvenance::Local,
                SemanticProvenance::VerifiedLocal,
            ),
            (
                VerifiedSemanticProvenance::Remote,
                SemanticProvenance::VerifiedRemote,
            ),
            (
                VerifiedSemanticProvenance::Daemon,
                SemanticProvenance::VerifiedDaemon,
            ),
        ] {
            let plan = planned(
                SemanticReadiness::Ready {
                    provenance: producer,
                },
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
            );
            assert!(plan.semantic_available);
            assert_eq!(plan.provenance, expected);
            assert_eq!(
                plan.response_contract
                    .expect("verified producer may respond")
                    .realized_topology(),
                RetrievalTopology::QualityOnly
            );
        }

        let remote = planned(
            SemanticReadiness::RemoteUnverified,
            explicit(RetrievalTopology::QualityOnly),
            permissive(),
        );
        assert_eq!(remote.provenance, SemanticProvenance::UnverifiedRemote);
        assert!(!remote.semantic_available);
        assert!(remote.response_contract.is_none());
        let action = remote.action.expect("attestation recovery");
        assert_eq!(action.code, "recovery.action.provide_attestation");
        assert!(action.argv.is_empty());
        assert_eq!(
            action.prerequisites,
            ["recovery.policy.provide_attestation"]
        );

        let hash = planned(SemanticReadiness::HashControl, hash_control(), permissive());
        assert_eq!(hash.provenance, SemanticProvenance::HashControl);
        assert!(!hash.semantic_available);
        assert_eq!(
            hash.response_contract
                .expect("explicit hash control response")
                .realized_topology(),
            RetrievalTopology::HashControl
        );
    }

    #[test]
    fn response_contract_accepts_only_truthful_topology_and_coverage_pairs() {
        for (requested, realized, coverage) in [
            (
                RetrievalTopology::FastOnly,
                RetrievalTopology::FastOnly,
                COMPLETE_COVERAGE_PPM,
            ),
            (
                RetrievalTopology::QualityOnly,
                RetrievalTopology::QualityOnly,
                COMPLETE_COVERAGE_PPM,
            ),
            (
                RetrievalTopology::FullProgressive,
                RetrievalTopology::FullProgressive,
                COMPLETE_COVERAGE_PPM,
            ),
            (
                RetrievalTopology::FullProgressive,
                RetrievalTopology::FastOnly,
                COMPLETE_COVERAGE_PPM,
            ),
            (
                RetrievalTopology::FullProgressive,
                RetrievalTopology::QualityOnly,
                COMPLETE_COVERAGE_PPM,
            ),
            (
                RetrievalTopology::QualityOnly,
                RetrievalTopology::PartialQuality {
                    coverage_ppm: 250_000,
                },
                250_000,
            ),
            (
                RetrievalTopology::FullProgressive,
                RetrievalTopology::PartialQuality {
                    coverage_ppm: 750_000,
                },
                750_000,
            ),
        ] {
            let contract = SemanticResponseContract::new(requested, realized, coverage, 7, None)
                .expect("truthful semantic response");
            assert_eq!(contract.admitted_semantic_scores(), 7);
            let json = serde_json::to_string(&contract).expect("serialize response");
            assert!(
                serde_json::from_str::<SemanticResponseContractWire>(&json).is_ok(),
                "wire shape remains decodable only into the private raw type"
            );
        }

        for requested in [
            RetrievalTopology::FastOnly,
            RetrievalTopology::QualityOnly,
            RetrievalTopology::FullProgressive,
        ] {
            SemanticResponseContract::new(
                requested,
                RetrievalTopology::LexicalOnly,
                0,
                0,
                Some("recovery.state.model_missing".to_owned()),
            )
            .expect("typed lexical degradation");
        }
        SemanticResponseContract::new(
            RetrievalTopology::HashControl,
            RetrievalTopology::HashControl,
            0,
            0,
            None,
        )
        .expect("explicit hash control");
    }

    #[test]
    fn response_contract_rejects_silent_or_impossible_contribution_claims() {
        assert_eq!(
            SemanticResponseContract::new(
                RetrievalTopology::LexicalOnly,
                RetrievalTopology::LexicalOnly,
                0,
                0,
                Some("recovery.state.model_missing".to_owned()),
            ),
            Err(RecoveryContractError::UnexpectedDegradationReason)
        );
        SemanticResponseContract::new(
            RetrievalTopology::LexicalOnly,
            RetrievalTopology::LexicalOnly,
            0,
            0,
            None,
        )
        .expect("an explicitly lexical request is not a degradation");
        assert!(matches!(
            SemanticResponseContract::new(
                RetrievalTopology::PartialQuality {
                    coverage_ppm: 500_000,
                },
                RetrievalTopology::LexicalOnly,
                0,
                0,
                Some("recovery.state.model_missing".to_owned()),
            ),
            Err(RecoveryContractError::IncompatibleResponseTopology { .. })
        ));
        for (requested, realized) in [
            (RetrievalTopology::FastOnly, RetrievalTopology::QualityOnly),
            (
                RetrievalTopology::QualityOnly,
                RetrievalTopology::FullProgressive,
            ),
            (
                RetrievalTopology::HashControl,
                RetrievalTopology::LexicalOnly,
            ),
        ] {
            assert!(matches!(
                SemanticResponseContract::new(requested, realized, COMPLETE_COVERAGE_PPM, 0, None,),
                Err(RecoveryContractError::IncompatibleResponseTopology { .. })
            ));
        }

        for (realized, coverage) in [
            (RetrievalTopology::FastOnly, 0),
            (RetrievalTopology::QualityOnly, COMPLETE_COVERAGE_PPM - 1),
            (
                RetrievalTopology::FullProgressive,
                COMPLETE_COVERAGE_PPM + 1,
            ),
            (RetrievalTopology::LexicalOnly, 1),
            (RetrievalTopology::HashControl, 1),
            (RetrievalTopology::PartialQuality { coverage_ppm: 0 }, 0),
            (
                RetrievalTopology::PartialQuality {
                    coverage_ppm: COMPLETE_COVERAGE_PPM,
                },
                COMPLETE_COVERAGE_PPM,
            ),
            (
                RetrievalTopology::PartialQuality {
                    coverage_ppm: 250_000,
                },
                500_000,
            ),
        ] {
            let requested = match realized {
                RetrievalTopology::HashControl => RetrievalTopology::HashControl,
                RetrievalTopology::LexicalOnly | RetrievalTopology::FastOnly => {
                    RetrievalTopology::FastOnly
                }
                RetrievalTopology::QualityOnly | RetrievalTopology::PartialQuality { .. } => {
                    RetrievalTopology::QualityOnly
                }
                RetrievalTopology::FullProgressive => RetrievalTopology::FullProgressive,
            };
            let reason = matches!(realized, RetrievalTopology::LexicalOnly)
                .then(|| "recovery.state.model_missing".to_owned());
            assert!(matches!(
                SemanticResponseContract::new(requested, realized, coverage, 0, reason),
                Err(RecoveryContractError::InvalidCoverage { .. })
            ));
        }

        for topology in [
            RetrievalTopology::LexicalOnly,
            RetrievalTopology::HashControl,
        ] {
            let requested = if matches!(topology, RetrievalTopology::HashControl) {
                RetrievalTopology::HashControl
            } else {
                RetrievalTopology::FastOnly
            };
            let reason = matches!(topology, RetrievalTopology::LexicalOnly)
                .then(|| "recovery.state.model_missing".to_owned());
            assert!(matches!(
                SemanticResponseContract::new(requested, topology, 0, 1, reason),
                Err(RecoveryContractError::NonSemanticScoresAdmitted { .. })
            ));
        }

        assert_eq!(
            SemanticResponseContract::new(
                RetrievalTopology::FastOnly,
                RetrievalTopology::LexicalOnly,
                0,
                0,
                None,
            ),
            Err(RecoveryContractError::MissingDegradationReason)
        );
        assert_eq!(
            SemanticResponseContract::new(
                RetrievalTopology::FastOnly,
                RetrievalTopology::FastOnly,
                COMPLETE_COVERAGE_PPM,
                1,
                Some("recovery.state.model_missing".to_owned()),
            ),
            Err(RecoveryContractError::UnexpectedDegradationReason)
        );
    }

    #[test]
    fn noninteractive_acquisition_requires_exact_scoped_authorization() {
        for network in [NetworkPolicy::Allowed, NetworkPolicy::Offline] {
            let required = planned(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                RecoveryPolicy {
                    interaction: InteractionPolicy::Interactive,
                    network,
                    acquisition_authorization: None,
                },
            )
            .action
            .expect("acquisition action")
            .required_authorization
            .expect("scoped authorization");

            let exact = planned(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                RecoveryPolicy {
                    interaction: InteractionPolicy::NonInteractive,
                    network,
                    acquisition_authorization: Some(required.clone()),
                },
            );
            let exact_action = exact.action.expect("acquisition action");
            assert_eq!(exact.retryability, Retryability::BlockedByCapability);
            assert_eq!(
                exact_action.prerequisites,
                [match network {
                    NetworkPolicy::Allowed => {
                        "recovery.capability.execute_bound_model_acquisition"
                    }
                    NetworkPolicy::Offline => "recovery.capability.import_model_bundle",
                }]
            );

            let mut mismatches = Vec::new();
            let mut authorization = required.clone();
            authorization.model_id.push_str("-different");
            authorization.embedding_space.logical_model_id = authorization.model_id.clone();
            mismatches.push(("model_id", authorization));
            let mut authorization = required.clone();
            authorization.model_tier = match required.model_tier {
                ModelTier::Fast => ModelTier::Quality,
                ModelTier::Quality => ModelTier::Fast,
            };
            mismatches.push(("model_tier", authorization));
            let mut authorization = required.clone();
            authorization.embedding_space.dimension += 1;
            mismatches.push(("embedding_space", authorization));
            let mut authorization = required.clone();
            authorization.manifest_fingerprint = "c".repeat(64);
            mismatches.push(("manifest_fingerprint", authorization));
            let mut authorization = required.clone();
            authorization.upstream_revision.push_str("-different");
            authorization.embedding_space.immutable_revision =
                authorization.upstream_revision.clone();
            mismatches.push(("upstream_revision", authorization));
            let mut authorization = required.clone();
            authorization.license_spdx = "MIT".to_owned();
            mismatches.push(("license_spdx", authorization));
            let mut authorization = required.clone();
            authorization.source = match network {
                NetworkPolicy::Allowed => ModelAcquisitionSource::LocalBundle,
                NetworkPolicy::Offline => ModelAcquisitionSource::Network {
                    source_hosts: vec!["models.example.test".to_owned()],
                },
            };
            mismatches.push(("source", authorization));
            let mut authorization = required.clone();
            authorization.byte_budget += 1;
            mismatches.push(("byte_budget", authorization));
            let mut authorization = required.clone();
            authorization.destination_class = ModelDestinationClass::ExplicitDirectory;
            mismatches.push(("destination_class", authorization));
            let mut authorization = required.clone();
            authorization.destination_fingerprint = "d".repeat(64);
            mismatches.push(("destination_fingerprint", authorization));
            let mut authorization = required.clone();
            authorization.document_count += 1;
            mismatches.push(("document_count", authorization));
            let mut authorization = required.clone();
            authorization.estimated_reindex_duration_ms += 1;
            mismatches.push(("estimated_reindex_duration_ms", authorization));
            let mut authorization = required.clone();
            authorization.issued_at_unix_seconds -= 1;
            mismatches.push(("issued_at_unix_seconds", authorization));
            let mut authorization = required.clone();
            authorization.expires_at_unix_seconds += 1;
            mismatches.push(("expires_at_unix_seconds", authorization));
            let mut authorization = required.clone();
            authorization.nonce = "fedcba9876543210fedcba9876543210".to_owned();
            mismatches.push(("nonce", authorization));

            for (field, authorization) in mismatches {
                let result = plan(
                    missing(ModelTier::Quality),
                    explicit(RetrievalTopology::QualityOnly),
                    RecoveryPolicy {
                        interaction: InteractionPolicy::NonInteractive,
                        network,
                        acquisition_authorization: Some(authorization),
                    },
                    Some(&target()),
                );
                assert_eq!(
                    result,
                    Err(RecoveryContractError::MismatchedAcquisitionAuthorization { field }),
                    "scope mismatch must fail closed for {field}"
                );
            }
        }
    }

    #[test]
    fn acquisition_authorization_enforces_window_and_nonce_boundaries() {
        let authorization = target()
            .authorization_for(NetworkPolicy::Allowed)
            .expect("valid authorization fixture");

        for (issued_at_unix_seconds, expires_at_unix_seconds) in [(100, 100), (101, 100)] {
            let mut invalid = authorization.clone();
            invalid.issued_at_unix_seconds = issued_at_unix_seconds;
            invalid.expires_at_unix_seconds = expires_at_unix_seconds;
            assert_eq!(
                invalid.validate(),
                Err(
                    RecoveryContractError::InvalidAcquisitionAuthorizationWindow {
                        issued_at_unix_seconds,
                        expires_at_unix_seconds,
                    }
                )
            );
        }

        let mut maximum_lifetime = authorization.clone();
        maximum_lifetime.issued_at_unix_seconds = 1_000;
        maximum_lifetime.expires_at_unix_seconds =
            1_000 + MAX_MODEL_ACQUISITION_AUTHORIZATION_LIFETIME_SECONDS;
        maximum_lifetime
            .validate()
            .expect("the maximum authorization lifetime is inclusive");

        let mut excessive_lifetime = maximum_lifetime.clone();
        excessive_lifetime.expires_at_unix_seconds =
            excessive_lifetime.expires_at_unix_seconds.saturating_add(1);
        assert_eq!(
            excessive_lifetime.validate(),
            Err(
                RecoveryContractError::AcquisitionAuthorizationLifetimeExceeded {
                    lifetime_seconds: MAX_MODEL_ACQUISITION_AUTHORIZATION_LIFETIME_SECONDS + 1,
                    max_lifetime_seconds: MAX_MODEL_ACQUISITION_AUTHORIZATION_LIFETIME_SECONDS,
                }
            )
        );

        for nonce in [
            "0123456789abcdef0123456789abcde",
            "0123456789abcdef0123456789abcdef0",
            "0123456789ABCDEF0123456789ABCDEF",
            "0123456789abcdef0123456789abcdeg",
            "00000000000000000000000000000000",
        ] {
            let mut invalid = authorization.clone();
            invalid.nonce = nonce.to_owned();
            assert_eq!(
                invalid.validate(),
                Err(RecoveryContractError::InvalidAcquisitionAuthorizationNonce),
                "invalid nonce unexpectedly admitted: {nonce}"
            );
        }

        for nonce in [
            "00000000000000000000000000000001",
            "ffffffffffffffffffffffffffffffff",
        ] {
            let mut valid = authorization.clone();
            valid.nonce = nonce.to_owned();
            let result = valid.validate();
            assert!(result.is_ok(), "valid nonce {nonce} rejected: {result:?}");
        }
    }

    #[test]
    fn acquisition_authorization_uses_trusted_time_and_exclusive_expiry() {
        let authorization = target()
            .authorization_for(NetworkPolicy::Allowed)
            .expect("valid authorization fixture");
        let before_issuance = authorization.issued_at_unix_seconds.saturating_sub(1);

        assert_eq!(
            authorization.validate_at(before_issuance),
            Err(RecoveryContractError::AcquisitionAuthorizationNotYetValid {
                issued_at_unix_seconds: authorization.issued_at_unix_seconds,
                evaluation_time_unix_seconds: before_issuance,
            })
        );
        authorization
            .validate_at(authorization.issued_at_unix_seconds)
            .expect("authorization is valid at its inclusive issuance boundary");
        authorization
            .validate_at(authorization.expires_at_unix_seconds - 1)
            .expect("authorization is valid immediately before expiry");
        assert_eq!(
            authorization.validate_at(authorization.expires_at_unix_seconds),
            Err(RecoveryContractError::AcquisitionAuthorizationExpired {
                expires_at_unix_seconds: authorization.expires_at_unix_seconds,
                evaluation_time_unix_seconds: authorization.expires_at_unix_seconds,
            })
        );
    }

    #[test]
    fn authorization_binding_rejects_surplus_and_stale_scopes() {
        let required = target()
            .authorization_for(NetworkPolicy::Allowed)
            .expect("valid authorization fixture");
        assert_eq!(
            validate_authorization_binding(None, Some(&required), TEST_NOW_UNIX_SECONDS),
            Err(RecoveryContractError::SurplusAcquisitionAuthorization)
        );

        assert_eq!(
            validate_authorization_binding(Some(&required), None, required.expires_at_unix_seconds,),
            Err(RecoveryContractError::AcquisitionAuthorizationExpired {
                expires_at_unix_seconds: required.expires_at_unix_seconds,
                evaluation_time_unix_seconds: required.expires_at_unix_seconds,
            })
        );

        let mut stale_supplied = required.clone();
        stale_supplied.expires_at_unix_seconds = TEST_NOW_UNIX_SECONDS;
        assert_eq!(
            validate_authorization_binding(
                Some(&required),
                Some(&stale_supplied),
                TEST_NOW_UNIX_SECONDS,
            ),
            Err(RecoveryContractError::AcquisitionAuthorizationExpired {
                expires_at_unix_seconds: TEST_NOW_UNIX_SECONDS,
                evaluation_time_unix_seconds: TEST_NOW_UNIX_SECONDS,
            })
        );
    }

    #[test]
    fn planner_rejects_surplus_authorization_when_no_action_requires_it() {
        let surplus = target()
            .authorization_for(NetworkPolicy::Allowed)
            .expect("valid authorization fixture");
        let result = plan(
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            explicit(RetrievalTopology::FastOnly),
            RecoveryPolicy {
                interaction: InteractionPolicy::NonInteractive,
                network: NetworkPolicy::Allowed,
                acquisition_authorization: Some(surplus),
            },
            None,
        );
        assert_eq!(
            result,
            Err(RecoveryContractError::SurplusAcquisitionAuthorization)
        );
    }

    #[test]
    fn promotion_and_execution_each_recheck_authorization_expiry() {
        let state = missing(ModelTier::Quality);
        let request = explicit(RetrievalTopology::QualityOnly);
        let acquisition_target = target();
        let presentation_policy = RecoveryPolicy {
            interaction: InteractionPolicy::Interactive,
            network: NetworkPolicy::Allowed,
            acquisition_authorization: None,
        };
        let presentation_plan = super::plan(TrustedRecoveryContext::new(
            &state,
            request,
            &presentation_policy,
            Some(&acquisition_target),
            acquisition_target.expires_at_unix_seconds - 1,
        ))
        .expect("interactive presentation plan before authorization");
        assert_eq!(
            presentation_plan
                .validate_for_execution_at(acquisition_target.expires_at_unix_seconds - 1),
            Err(RecoveryContractError::MissingAcquisitionAuthorization),
            "a required but ungranted authorization must never pass the execution gate"
        );

        let exact_authorization = acquisition_target
            .authorization_for(NetworkPolicy::Allowed)
            .expect("exact authorization");
        let policy = RecoveryPolicy {
            interaction: InteractionPolicy::NonInteractive,
            network: NetworkPolicy::Allowed,
            acquisition_authorization: Some(exact_authorization),
        };
        let canonical = super::plan(TrustedRecoveryContext::new(
            &state,
            request,
            &policy,
            Some(&acquisition_target),
            TEST_NOW_UNIX_SECONDS,
        ))
        .expect("serialize a currently valid recovery plan");
        let serialized = serde_json::to_value(canonical).expect("serialize recovery plan");
        let promoted = serde_json::from_value::<UntrustedRecoveryPlan>(serialized.clone())
            .expect("decode untrusted recovery plan")
            .validate_against(TrustedRecoveryContext::new(
                &state,
                request,
                &policy,
                Some(&acquisition_target),
                acquisition_target.expires_at_unix_seconds - 1,
            ))
            .expect("promotion succeeds immediately before expiry");
        promoted
            .validate_for_execution_at(acquisition_target.expires_at_unix_seconds - 1)
            .expect("exact supplied authorization executes immediately before expiry");
        assert_eq!(
            promoted.validate_for_execution_at(acquisition_target.expires_at_unix_seconds),
            Err(RecoveryContractError::AcquisitionAuthorizationExpired {
                expires_at_unix_seconds: acquisition_target.expires_at_unix_seconds,
                evaluation_time_unix_seconds: acquisition_target.expires_at_unix_seconds,
            }),
            "a previously promoted plan is not a timeless execution capability"
        );

        let untrusted: UntrustedRecoveryPlan =
            serde_json::from_value(serialized).expect("decode second untrusted recovery plan");
        assert_eq!(
            untrusted.validate_against(TrustedRecoveryContext::new(
                &state,
                request,
                &policy,
                Some(&acquisition_target),
                acquisition_target.expires_at_unix_seconds,
            )),
            Err(RecoveryContractError::AcquisitionAuthorizationExpired {
                expires_at_unix_seconds: acquisition_target.expires_at_unix_seconds,
                evaluation_time_unix_seconds: acquisition_target.expires_at_unix_seconds,
            })
        );
    }

    #[test]
    fn planner_rejects_programmatically_constructed_invalid_policy_authorization() {
        let mut invalid = target()
            .authorization_for(NetworkPolicy::Allowed)
            .expect("valid authorization fixture");
        invalid.byte_budget = 0;
        let result = plan(
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            explicit(RetrievalTopology::FastOnly),
            RecoveryPolicy {
                interaction: InteractionPolicy::NonInteractive,
                network: NetworkPolicy::Allowed,
                acquisition_authorization: Some(invalid),
            },
            None,
        );
        assert_eq!(
            result,
            Err(RecoveryContractError::ZeroAcquisitionByteBudget),
            "planner must not serialize invalid authorization even when the ready action ignores it"
        );
    }

    #[test]
    fn acquisition_target_must_be_bound_and_well_formed() {
        let unbound = plan(
            missing(ModelTier::Fast),
            explicit(RetrievalTopology::FastOnly),
            permissive(),
            None,
        )
        .expect("missing binding yields a non-executable plan");
        assert_eq!(unbound.retryability, Retryability::BlockedByCapability);
        let action = unbound.action.expect("acquisition action");
        assert!(action.required_authorization.is_none());
        assert!(
            action.argv.is_empty(),
            "an unbound target cannot name an exact model and must not be executable"
        );
        assert_eq!(
            action.prerequisites,
            [
                "recovery.capability.execute_bound_model_acquisition",
                "recovery.policy.bind_model",
            ]
        );

        let mut malformed = target();
        malformed.model_id = " ".to_owned();
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::InvalidAcquisitionScopeField { field: "model_id" })
        ));

        let mut malformed = target();
        malformed.manifest_fingerprint = " ".to_owned();
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::InvalidAcquisitionScopeField {
                field: "manifest_fingerprint"
            })
        ));

        let mut malformed = target();
        malformed.upstream_revision = "revision\ninjected".to_owned();
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::InvalidAcquisitionScopeField {
                field: "upstream_revision"
            })
        ));

        let mut malformed = target();
        malformed.license_spdx.clear();
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::InvalidAcquisitionScopeField {
                field: "license_spdx"
            })
        ));

        let mut malformed = target();
        malformed.destination_fingerprint.clear();
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::InvalidAcquisitionScopeField {
                field: "destination_fingerprint"
            })
        ));

        let mut malformed = target();
        malformed.byte_budget = 0;
        assert_eq!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::ZeroAcquisitionByteBudget)
        );

        let mut missing_host = target();
        missing_host.network_source_hosts.clear();
        assert_eq!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&missing_host),
            ),
            Err(RecoveryContractError::MissingNetworkSourceHosts)
        );
        let offline = plan(
            missing(ModelTier::Quality),
            explicit(RetrievalTopology::QualityOnly),
            RecoveryPolicy {
                interaction: InteractionPolicy::Interactive,
                network: NetworkPolicy::Offline,
                acquisition_authorization: None,
            },
            Some(&missing_host),
        )
        .expect("local bundle does not depend on network hosts");
        assert!(matches!(
            offline
                .action
                .expect("offline action")
                .required_authorization
                .expect("offline authorization")
                .source,
            ModelAcquisitionSource::LocalBundle
        ));
    }

    #[test]
    fn acquisition_tier_and_embedding_space_are_anchored_to_trusted_inputs() {
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::FastOnly),
                permissive(),
                Some(&target_for(ModelTier::Quality)),
            ),
            Err(RecoveryContractError::UnavailableTierTopologyMismatch {
                tier: ModelTier::Quality,
                ..
            })
        ));
        assert!(matches!(
            plan(
                missing(ModelTier::Fast),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&target_for(ModelTier::Fast)),
            ),
            Err(RecoveryContractError::UnavailableTierTopologyMismatch {
                tier: ModelTier::Fast,
                ..
            })
        ));
        assert_eq!(
            plan(
                missing(ModelTier::Fast),
                explicit(RetrievalTopology::FullProgressive),
                permissive(),
                Some(&target_for(ModelTier::Quality)),
            ),
            Err(RecoveryContractError::AcquisitionTargetTierMismatch {
                readiness_tier: ModelTier::Fast,
                target_tier: ModelTier::Quality,
            })
        );
        plan(
            missing(ModelTier::Fast),
            explicit(RetrievalTopology::FullProgressive),
            permissive(),
            Some(&target_for(ModelTier::Fast)),
        )
        .expect("full progressive may recover the exact unavailable fast tier");
        plan(
            missing(ModelTier::Quality),
            explicit(RetrievalTopology::FullProgressive),
            permissive(),
            Some(&target_for(ModelTier::Quality)),
        )
        .expect("full progressive may recover the exact unavailable quality tier");

        let mut malformed = target();
        malformed.embedding_space.dimension = 0;
        assert!(matches!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&malformed),
            ),
            Err(RecoveryContractError::InvalidAcquisitionSpaceIdentity { .. })
        ));

        let mut hash_target = target();
        hash_target.embedding_space =
            EmbeddingIdentityBundleV1::explicit_test_model("hash-control", 384).space;
        hash_target.model_id = hash_target.embedding_space.logical_model_id.clone();
        hash_target.upstream_revision = hash_target.embedding_space.immutable_revision.clone();
        assert_eq!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&hash_target),
            ),
            Err(RecoveryContractError::NonSemanticAcquisitionSpace)
        );

        let mut inconsistent = target();
        inconsistent.model_id = "other-semantic-model".to_owned();
        assert_eq!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&inconsistent),
            ),
            Err(RecoveryContractError::InconsistentAcquisitionIdentity { field: "model_id" })
        );

        let mut inconsistent = target();
        inconsistent.upstream_revision = "different-immutable-revision".to_owned();
        assert_eq!(
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&inconsistent),
            ),
            Err(RecoveryContractError::InconsistentAcquisitionIdentity {
                field: "upstream_revision"
            })
        );
    }

    #[test]
    fn network_source_hosts_are_path_free_credential_free_authorities() {
        for host in [
            "models.example.test",
            "MODELS.EXAMPLE.TEST:443",
            "localhost",
            "127.0.0.1",
            "127.0.0.1:8443",
            "[2001:db8::1]",
            "[2001:db8::1]:443",
        ] {
            let mut valid = target();
            valid.network_source_hosts = vec![host.to_owned()];
            plan(
                missing(ModelTier::Quality),
                explicit(RetrievalTopology::QualityOnly),
                permissive(),
                Some(&valid),
            )
            .expect("credential-free host authority is valid");
        }

        for host in [
            "",
            " ",
            "https://models.example.test",
            "user:secret@models.example.test",
            "models.example.test/path",
            "models.example.test?variant=quality",
            "models.example.test#fragment",
            "models.example.test\\path",
            "models .example.test",
            "models.example.test\n",
            "models_example.test",
            "-models.example.test",
            "models-.example.test",
            "models..example.test",
            "models.example.test.",
            "999.999.999.999",
            "models.example.test:",
            "models.example.test:0",
            "models.example.test:+443",
            "models.example.test:65536",
            "models.example.test:https",
            "2001:db8::1",
            "[2001:db8::1",
            "[2001:db8::1]suffix",
            "[2001:db8::1]:0",
            "[2001:db8::1]:65536",
            "[not-ipv6]",
        ] {
            let mut malformed = target();
            malformed.network_source_hosts = vec![host.to_owned()];
            assert_eq!(
                plan(
                    missing(ModelTier::Quality),
                    explicit(RetrievalTopology::QualityOnly),
                    permissive(),
                    Some(&malformed),
                ),
                Err(RecoveryContractError::InvalidNetworkSourceHost),
                "unexpectedly accepted source host {host:?}"
            );
        }
    }

    #[test]
    fn invalid_partial_readiness_never_enters_a_plan() {
        for coverage_ppm in [0, COMPLETE_COVERAGE_PPM, COMPLETE_COVERAGE_PPM + 1] {
            assert!(matches!(
                plan(
                    SemanticReadiness::PartialQualityCoverage {
                        provenance: VerifiedSemanticProvenance::Local,
                        coverage_ppm,
                    },
                    explicit(RetrievalTopology::QualityOnly),
                    permissive(),
                    Some(&target()),
                ),
                Err(RecoveryContractError::InvalidCoverage { .. })
            ));
        }
    }

    #[test]
    fn serde_rejects_unknown_versions_fields_and_mismatched_scopes() {
        let state = missing(ModelTier::Quality);
        let request = hybrid(RetrievalTopology::FullProgressive);
        let policy = permissive();
        let acquisition_target = target();
        let canonical = plan(
            state.clone(),
            request,
            policy.clone(),
            Some(&acquisition_target),
        )
        .expect("canonical plan");
        let plan_json = serde_json::to_value(canonical).expect("serialize plan");
        let rejects = |value| {
            decode_and_validate(value, &state, request, &policy, Some(&acquisition_target)).is_err()
        };

        for legacy_version in [
            "frankensearch.recovery_plan.v1",
            "frankensearch.recovery_plan.v2",
            "frankensearch.recovery_plan.v3",
        ] {
            let mut changed = plan_json.clone();
            changed["schema_version"] = serde_json::Value::String(legacy_version.to_owned());
            assert!(
                rejects(changed),
                "legacy plan schema unexpectedly decoded: {legacy_version}"
            );
        }

        let mut changed = plan_json.clone();
        changed["unknown_contract_field"] = serde_json::Value::Bool(true);
        assert!(rejects(changed));

        let mut changed = plan_json.clone();
        changed["state_code"] = serde_json::Value::String("recovery.state.ready".to_owned());
        assert!(rejects(changed));

        let mut changed = plan_json.clone();
        changed["provenance"] = serde_json::Value::String("verified_local".to_owned());
        assert!(rejects(changed));

        let mut changed = plan_json.clone();
        changed["semantic_available"] = serde_json::Value::Bool(true);
        assert!(rejects(changed));

        let mut changed = plan_json.clone();
        changed["retryability"] = serde_json::Value::String("not_needed".to_owned());
        assert!(rejects(changed));

        let action_mutations = [
            ("code", serde_json::json!("recovery.action.reacquire_model")),
            ("explanation", serde_json::json!("trust the payload")),
            (
                "argv",
                serde_json::json!(["fsfs", "download-models", "--model", "different-model"]),
            ),
            ("network_required", serde_json::json!(false)),
            ("consent_required", serde_json::json!(false)),
            ("preserves_old_data", serde_json::json!(false)),
            ("potentially_destructive", serde_json::json!(true)),
            (
                "prerequisites",
                serde_json::json!(["recovery.policy.allow_network"]),
            ),
            (
                "expected_postcondition",
                serde_json::json!("recovery.state.ready"),
            ),
        ];
        for (field, value) in action_mutations {
            let mut changed = plan_json.clone();
            changed["action"][field] = value;
            assert!(rejects(changed), "trusted wire action field {field}");
        }

        let mut changed = plan_json.clone();
        changed["action"]["required_authorization"]["byte_budget"] =
            serde_json::Value::from(42_000_001_u64);
        assert!(rejects(changed), "trusted wire authorization substitution");

        let response_mutations = [
            (
                "requested_topology",
                serde_json::json!({"topology": "quality_only"}),
            ),
            (
                "realized_topology",
                serde_json::json!({"topology": "fast_only"}),
            ),
            ("coverage_ppm", serde_json::json!(1)),
            ("admitted_semantic_scores", serde_json::json!(1)),
            (
                "degradation_reason_code",
                serde_json::json!("recovery.state.model_unloadable"),
            ),
        ];
        for (field, value) in response_mutations {
            let mut changed = plan_json.clone();
            changed["response_contract"][field] = value;
            assert!(rejects(changed), "trusted wire response field {field}");
        }

        let authorization = plan_json["action"]["required_authorization"].clone();
        for legacy_version in [
            "frankensearch.model_acquisition_authorization.v1",
            "frankensearch.model_acquisition_authorization.v2",
        ] {
            let mut changed = authorization.clone();
            changed["schema_version"] = serde_json::Value::String(legacy_version.to_owned());
            assert!(
                serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err(),
                "legacy authorization schema unexpectedly decoded: {legacy_version}"
            );
        }

        let mut changed = authorization.clone();
        changed["model_id"] = serde_json::Value::String(" ".to_owned());
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        let mut changed = authorization.clone();
        changed["model_tier"] = serde_json::Value::String("Quality".to_owned());
        assert!(
            serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err(),
            "v4 recovery authorization must not inherit ModelTier's Rust casing"
        );

        for required_field in [
            "model_id",
            "model_tier",
            "embedding_space",
            "document_count",
            "estimated_reindex_duration_ms",
            "issued_at_unix_seconds",
            "expires_at_unix_seconds",
            "nonce",
        ] {
            let mut changed = authorization.clone();
            changed
                .as_object_mut()
                .expect("authorization JSON object")
                .remove(required_field);
            assert!(
                serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err(),
                "missing required consent field unexpectedly decoded: {required_field}"
            );
        }

        for (field, invalid_value) in [
            ("issued_at_unix_seconds", serde_json::json!("now")),
            ("expires_at_unix_seconds", serde_json::Value::Null),
            ("nonce", serde_json::json!(123_u64)),
        ] {
            let mut changed = authorization.clone();
            changed[field] = invalid_value;
            assert!(
                serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err(),
                "wrongly typed authorization field unexpectedly decoded: {field}"
            );
        }

        let mut changed = authorization.clone();
        changed["source"]["kind"] = serde_json::Value::String("ambient".to_owned());
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        let mut changed = authorization.clone();
        changed["destination_class"] = serde_json::Value::String("unbounded_path".to_owned());
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        let mut changed = authorization.clone();
        changed["byte_budget"] = serde_json::Value::from(0);
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        let mut changed = authorization.clone();
        changed["embedding_space"]["dimension"] = serde_json::Value::from(0);
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        let mut changed = authorization.clone();
        changed["embedding_space"]["logical_model_id"] =
            serde_json::Value::String("different-model".to_owned());
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        for host in [
            "https://models.example.test",
            "user:secret@models.example.test",
            "models.example.test/path",
            "models.example.test?variant=quality",
            "models.example.test#fragment",
            "models example.test",
            "models.example.test:0",
            "models.example.test:+443",
            "2001:db8::1",
            "[not-ipv6]",
        ] {
            let mut changed = authorization.clone();
            changed["source"]["source_hosts"] = serde_json::json!([host]);
            assert!(
                serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err(),
                "serde unexpectedly accepted source host {host:?}"
            );
        }

        let mut changed = authorization;
        changed["manifest_fingerprint"] = serde_json::Value::String(" ".to_owned());
        assert!(serde_json::from_value::<ModelAcquisitionAuthorization>(changed).is_err());

        let mut changed = plan_json.clone();
        changed["action"]["argv"] =
            serde_json::json!(["fsfs", "download-models", "--model", "different-model"]);
        assert!(rejects(changed), "argv must remain bound to trusted target");

        let mut changed = plan_json;
        changed["action"]["required_authorization"]["source"] = serde_json::json!({
            "kind": "local_bundle",
            "source_hosts": ["must-not-be-ignored.example.test"]
        });
        assert!(rejects(changed));
    }

    #[test]
    fn untrusted_wire_rejects_unknown_fields_at_every_nested_object_boundary() {
        let state = missing(ModelTier::Quality);
        let request = hybrid(RetrievalTopology::FullProgressive);
        let policy = permissive();
        let acquisition_target = target();
        let canonical = plan(state, request, policy, Some(&acquisition_target))
            .expect("canonical nested-wire fixture");
        let plan_json = serde_json::to_value(canonical).expect("serialize nested-wire fixture");
        let rejects_plan = |value| serde_json::from_value::<UntrustedRecoveryPlan>(value).is_err();

        let mut changed = plan_json.clone();
        changed["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "plan envelope");

        let mut changed = plan_json.clone();
        changed["state"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "readiness envelope");

        let mut changed = plan_json.clone();
        changed["state"]["detail"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "readiness detail");

        let mut changed = plan_json.clone();
        changed["requested_topology"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "requested topology");

        let mut changed = plan_json.clone();
        changed["policy"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "policy");

        let mut changed = plan_json.clone();
        changed["action"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "action");

        let mut changed = plan_json.clone();
        changed["action"]["required_authorization"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "acquisition authorization");

        let mut changed = plan_json.clone();
        changed["action"]["required_authorization"]["embedding_space"]["unexpected"] =
            serde_json::json!(true);
        assert!(rejects_plan(changed), "embedding-space identity");

        let mut changed = plan_json.clone();
        changed["action"]["required_authorization"]["embedding_space"]["artifacts"][0]["unexpected"] =
            serde_json::json!(true);
        assert!(rejects_plan(changed), "embedding artifact identity");

        let mut changed = plan_json.clone();
        changed["action"]["required_authorization"]["source"]["unexpected"] =
            serde_json::json!(true);
        assert!(rejects_plan(changed), "acquisition source");

        let mut changed = plan_json.clone();
        changed["response_contract"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "response contract");

        let mut changed = plan_json.clone();
        changed["response_contract"]["requested_topology"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "response requested topology");

        let mut changed = plan_json;
        changed["response_contract"]["realized_topology"]["unexpected"] = serde_json::json!(true);
        assert!(rejects_plan(changed), "response realized topology");

        for state_json in [
            serde_json::json!({
                "state": "ready",
                "detail": {"provenance": "local", "unexpected": true}
            }),
            serde_json::json!({
                "state": "model_missing",
                "detail": {"tier": "fast", "unexpected": true}
            }),
            serde_json::json!({
                "state": "model_unloadable",
                "detail": {"tier": "quality", "unexpected": true}
            }),
            serde_json::json!({
                "state": "partial_quality_coverage",
                "detail": {
                    "provenance": "daemon",
                    "coverage_ppm": 625_000,
                    "unexpected": true
                }
            }),
        ] {
            assert!(
                serde_json::from_value::<SemanticReadiness>(state_json).is_err(),
                "object-valued readiness detail discarded an unknown field"
            );
        }

        assert!(
            serde_json::from_value::<SemanticReadiness>(serde_json::json!({
                "state": "index_absent",
                "unexpected": true
            }))
            .is_err(),
            "unit readiness envelope discarded an unknown field"
        );

        assert!(
            serde_json::from_value::<SemanticReadiness>(serde_json::json!({
                "state": "model_missing",
                "detail": {"tier": "Quality"}
            }))
            .is_err(),
            "v3 readiness tier must use the recovery-local lowercase spelling"
        );

        assert!(
            serde_json::from_value::<RecoveryRequest>(serde_json::json!({
                "mode": "hybrid",
                "requested_topology": {
                    "topology": "partial_quality",
                    "coverage_ppm": 625_000,
                    "unexpected": true
                }
            }))
            .is_err(),
            "structured topology discarded an unknown field"
        );

        for invalid_topology in [
            serde_json::json!({"topology": "fast_only", "coverage_ppm": 625_000}),
            serde_json::json!({"topology": "partial_quality"}),
            serde_json::json!({"topology": "partial_quality", "coverage_ppm": null}),
        ] {
            assert!(
                serde_json::from_value::<RecoveryRequest>(serde_json::json!({
                    "mode": "hybrid",
                    "requested_topology": invalid_topology
                }))
                .is_err(),
                "topology-specific field presence was not enforced"
            );
        }
    }

    #[test]
    fn tagged_wire_envelopes_enforce_variant_specific_fields() {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct TopologyHarness {
            value: RetrievalTopology,
        }

        for expected in [
            RetrievalTopology::LexicalOnly,
            RetrievalTopology::HashControl,
            RetrievalTopology::FastOnly,
            RetrievalTopology::QualityOnly,
            RetrievalTopology::FullProgressive,
        ] {
            let topology_json = serde_json::to_value(expected).expect("serialize topology");
            let decoded: TopologyHarness =
                serde_json::from_value(serde_json::json!({"value": topology_json.clone()}))
                    .expect("decode exact unit topology");
            assert_eq!(decoded.value, expected);

            let mut unknown = topology_json.clone();
            unknown["unexpected"] = serde_json::json!(true);
            assert!(
                serde_json::from_value::<TopologyHarness>(serde_json::json!({"value": unknown}))
                    .is_err(),
                "unit topology accepted an unknown field: {expected:?}"
            );

            let mut forbidden = topology_json;
            forbidden["coverage_ppm"] = serde_json::json!(625_000);
            assert!(
                serde_json::from_value::<TopologyHarness>(serde_json::json!({"value": forbidden}))
                    .is_err(),
                "unit topology accepted partial-only coverage: {expected:?}"
            );
            for forbidden_value in [serde_json::Value::Null, serde_json::json!({})] {
                let mut forbidden = serde_json::to_value(expected).expect("serialize topology");
                forbidden["coverage_ppm"] = forbidden_value;
                assert!(
                    serde_json::from_value::<TopologyHarness>(
                        serde_json::json!({"value": forbidden})
                    )
                    .is_err(),
                    "unit topology accepted null or structured coverage: {expected:?}"
                );
            }
        }

        let partial = RetrievalTopology::PartialQuality {
            coverage_ppm: 625_000,
        };
        let partial_json = serde_json::to_value(partial).expect("serialize partial topology");
        let decoded: TopologyHarness =
            serde_json::from_value(serde_json::json!({"value": partial_json.clone()}))
                .expect("decode exact partial topology");
        assert_eq!(decoded.value, partial);
        for invalid in [
            serde_json::json!({"topology": "partial_quality"}),
            serde_json::json!({"topology": "partial_quality", "coverage_ppm": null}),
            serde_json::json!({
                "topology": "partial_quality",
                "coverage_ppm": 625_000,
                "unexpected": true
            }),
            serde_json::json!({}),
            serde_json::json!({"topology": null}),
        ] {
            assert!(
                serde_json::from_value::<TopologyHarness>(serde_json::json!({"value": invalid}))
                    .is_err(),
                "topology envelope accepted a missing, null, or forbidden field"
            );
        }

        let unit_states = [
            SemanticReadiness::IndexAbsent,
            SemanticReadiness::IdentityMismatch,
            SemanticReadiness::DaemonMismatch,
            SemanticReadiness::ManifestUnsafe,
            SemanticReadiness::AnnStale,
            SemanticReadiness::GenerationIncomplete,
            SemanticReadiness::RemoteUnverified,
            SemanticReadiness::HashControl,
        ];
        for expected in unit_states {
            let state_json = serde_json::to_value(&expected).expect("serialize unit readiness");
            assert_eq!(
                serde_json::from_value::<SemanticReadiness>(state_json.clone())
                    .expect("decode exact unit readiness"),
                expected
            );

            let mut unknown = state_json.clone();
            unknown["unexpected"] = serde_json::json!(true);
            assert!(
                serde_json::from_value::<SemanticReadiness>(unknown).is_err(),
                "unit readiness accepted an unknown field: {expected:?}"
            );

            for forbidden_detail in [
                serde_json::json!({}),
                serde_json::json!("caller_requested_zero_k"),
                serde_json::json!({"tier": "fast"}),
            ] {
                let mut forbidden = state_json.clone();
                forbidden["detail"] = forbidden_detail;
                assert!(
                    serde_json::from_value::<SemanticReadiness>(forbidden).is_err(),
                    "unit readiness accepted scalar or structured detail: {expected:?}"
                );
            }

            let mut null_detail = state_json;
            null_detail["detail"] = serde_json::Value::Null;
            assert!(
                serde_json::from_value::<SemanticReadiness>(null_detail).is_err(),
                "unit readiness accepted null detail: {expected:?}"
            );
        }

        for expected in [
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            missing(ModelTier::Fast),
            unloadable(ModelTier::Quality),
            SemanticReadiness::IndexEmpty(ZeroSignalReason::CallerRequestedZeroK),
            SemanticReadiness::PartialQualityCoverage {
                provenance: VerifiedSemanticProvenance::Daemon,
                coverage_ppm: 625_000,
            },
        ] {
            let state_json = serde_json::to_value(&expected).expect("serialize detailed readiness");
            assert_eq!(
                serde_json::from_value::<SemanticReadiness>(state_json.clone())
                    .expect("decode exact detailed readiness"),
                expected
            );

            let mut missing_detail = state_json.clone();
            missing_detail
                .as_object_mut()
                .expect("readiness object")
                .remove("detail");
            assert!(
                serde_json::from_value::<SemanticReadiness>(missing_detail).is_err(),
                "detailed readiness accepted missing detail: {expected:?}"
            );

            let mut null_detail = state_json.clone();
            null_detail["detail"] = serde_json::Value::Null;
            assert!(
                serde_json::from_value::<SemanticReadiness>(null_detail).is_err(),
                "detailed readiness accepted null detail: {expected:?}"
            );

            let mut forbidden_detail = state_json.clone();
            if let Some(detail) = forbidden_detail["detail"].as_object_mut() {
                detail.insert("unexpected".to_owned(), serde_json::json!(true));
            } else {
                forbidden_detail["detail"] = serde_json::json!({"unexpected": true});
            }
            assert!(
                serde_json::from_value::<SemanticReadiness>(forbidden_detail).is_err(),
                "detailed readiness discarded a forbidden detail field: {expected:?}"
            );

            let mut unknown = state_json;
            unknown["unexpected"] = serde_json::json!(true);
            assert!(
                serde_json::from_value::<SemanticReadiness>(unknown).is_err(),
                "detailed readiness accepted an unknown envelope field: {expected:?}"
            );
        }
        assert!(serde_json::from_value::<SemanticReadiness>(serde_json::json!({})).is_err());
        assert!(
            serde_json::from_value::<SemanticReadiness>(serde_json::json!({"state": null}))
                .is_err()
        );
        for cross_variant in [
            serde_json::json!({
                "state": "ready",
                "detail": {"tier": "fast"}
            }),
            serde_json::json!({
                "state": "model_missing",
                "detail": {"provenance": "local"}
            }),
            serde_json::json!({
                "state": "model_unloadable",
                "detail": {"provenance": "daemon", "coverage_ppm": 625_000}
            }),
            serde_json::json!({
                "state": "index_empty",
                "detail": {"provenance": "local", "coverage_ppm": 625_000}
            }),
            serde_json::json!({
                "state": "partial_quality_coverage",
                "detail": "caller_requested_zero_k"
            }),
        ] {
            assert!(
                serde_json::from_value::<SemanticReadiness>(cross_variant).is_err(),
                "readiness tag accepted another variant's otherwise-valid detail"
            );
        }

        let local_bundle = serde_json::to_value(ModelAcquisitionSource::LocalBundle)
            .expect("serialize local bundle");
        assert_eq!(
            serde_json::from_value::<ModelAcquisitionSource>(local_bundle.clone())
                .expect("decode exact local bundle"),
            ModelAcquisitionSource::LocalBundle
        );
        for invalid in [
            serde_json::json!({"kind": "local_bundle", "unexpected": true}),
            serde_json::json!({"kind": "local_bundle", "source_hosts": []}),
            serde_json::json!({
                "kind": "local_bundle",
                "source_hosts": ["models.example.test"]
            }),
            serde_json::json!({"kind": "local_bundle", "source_hosts": null}),
            serde_json::json!({}),
            serde_json::json!({"kind": null}),
        ] {
            assert!(
                serde_json::from_value::<ModelAcquisitionSource>(invalid).is_err(),
                "local-bundle source accepted a missing, null, or forbidden field"
            );
        }

        let network = ModelAcquisitionSource::Network {
            source_hosts: vec!["models.example.test".to_owned()],
        };
        let network_json = serde_json::to_value(&network).expect("serialize network source");
        assert_eq!(
            serde_json::from_value::<ModelAcquisitionSource>(network_json.clone())
                .expect("decode exact network source"),
            network
        );
        for invalid in [
            serde_json::json!({"kind": "network"}),
            serde_json::json!({"kind": "network", "source_hosts": null}),
            serde_json::json!({
                "kind": "network",
                "source_hosts": ["models.example.test"],
                "unexpected": true
            }),
        ] {
            assert!(
                serde_json::from_value::<ModelAcquisitionSource>(invalid).is_err(),
                "network source accepted a missing, null, or forbidden field"
            );
        }
    }

    #[test]
    fn recovery_v4_requires_every_canonical_null_field_to_be_present() {
        let ready = planned(
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            explicit(RetrievalTopology::FastOnly),
            permissive(),
        );
        let ready_json = serde_json::to_value(ready).expect("serialize ready plan");
        assert!(ready_json["policy"]["acquisition_authorization"].is_null());
        assert!(ready_json["action"].is_null());
        assert!(ready_json["response_contract"]["degradation_reason_code"].is_null());
        serde_json::from_value::<UntrustedRecoveryPlan>(ready_json.clone())
            .expect("explicit canonical nulls decode");

        let mut missing = ready_json.clone();
        missing["policy"]
            .as_object_mut()
            .expect("policy object")
            .remove("acquisition_authorization");
        assert!(
            serde_json::from_value::<UntrustedRecoveryPlan>(missing).is_err(),
            "missing policy.acquisition_authorization was treated as explicit null"
        );

        let mut missing = ready_json.clone();
        missing
            .as_object_mut()
            .expect("plan object")
            .remove("action");
        assert!(
            serde_json::from_value::<UntrustedRecoveryPlan>(missing).is_err(),
            "missing plan.action was treated as explicit null"
        );

        let mut missing = ready_json;
        missing["response_contract"]
            .as_object_mut()
            .expect("response object")
            .remove("degradation_reason_code");
        assert!(
            serde_json::from_value::<UntrustedRecoveryPlan>(missing).is_err(),
            "missing response.degradation_reason_code was treated as explicit null"
        );

        let unavailable = planned(
            SemanticReadiness::IndexAbsent,
            explicit(RetrievalTopology::FastOnly),
            permissive(),
        );
        let unavailable_json =
            serde_json::to_value(unavailable).expect("serialize unavailable plan");
        assert!(unavailable_json["action"]["required_authorization"].is_null());
        assert!(unavailable_json["response_contract"].is_null());
        serde_json::from_value::<UntrustedRecoveryPlan>(unavailable_json.clone())
            .expect("explicit action/response nulls decode");

        let mut missing = unavailable_json.clone();
        missing["action"]
            .as_object_mut()
            .expect("action object")
            .remove("required_authorization");
        assert!(
            serde_json::from_value::<UntrustedRecoveryPlan>(missing).is_err(),
            "missing action.required_authorization was treated as explicit null"
        );

        let mut missing = unavailable_json;
        missing
            .as_object_mut()
            .expect("plan object")
            .remove("response_contract");
        assert!(
            serde_json::from_value::<UntrustedRecoveryPlan>(missing).is_err(),
            "missing plan.response_contract was treated as explicit null"
        );
    }

    #[test]
    fn trusted_context_rejects_coherent_plan_and_target_substitution() {
        let state = missing(ModelTier::Quality);
        let request = hybrid(RetrievalTopology::FullProgressive);
        let policy = permissive();
        let acquisition_target = target();

        let ready_forgery = plan(
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            request,
            policy.clone(),
            Some(&acquisition_target),
        )
        .expect("internally coherent ready plan");
        assert!(
            decode_and_validate(
                serde_json::to_value(ready_forgery).expect("serialize forgery"),
                &state,
                request,
                &policy,
                Some(&acquisition_target),
            )
            .is_err(),
            "a coherent state, response, and retryability forgery must not replace probe state"
        );

        let request_forgery = plan(
            state.clone(),
            hybrid(RetrievalTopology::QualityOnly),
            policy.clone(),
            Some(&acquisition_target),
        )
        .expect("internally coherent alternate-request plan");
        assert!(
            decode_and_validate(
                serde_json::to_value(request_forgery).expect("serialize forgery"),
                &state,
                request,
                &policy,
                Some(&acquisition_target),
            )
            .is_err(),
            "a coherent topology and response forgery must not replace the caller request"
        );

        let offline_policy = RecoveryPolicy {
            interaction: InteractionPolicy::Interactive,
            network: NetworkPolicy::Offline,
            acquisition_authorization: None,
        };
        let policy_forgery = plan(
            state.clone(),
            request,
            offline_policy,
            Some(&acquisition_target),
        )
        .expect("internally coherent alternate-policy plan");
        assert!(
            decode_and_validate(
                serde_json::to_value(policy_forgery).expect("serialize forgery"),
                &state,
                request,
                &policy,
                Some(&acquisition_target),
            )
            .is_err(),
            "wire policy must not grant or remove execution capabilities"
        );

        let trusted_coverage = SemanticReadiness::PartialQualityCoverage {
            provenance: VerifiedSemanticProvenance::Local,
            coverage_ppm: 625_000,
        };
        let forged_coverage = SemanticReadiness::PartialQualityCoverage {
            provenance: VerifiedSemanticProvenance::Local,
            coverage_ppm: 700_000,
        };
        let coverage_forgery = plan(forged_coverage, request, policy.clone(), None)
            .expect("internally coherent alternate-coverage plan");
        assert!(
            decode_and_validate(
                serde_json::to_value(coverage_forgery).expect("serialize forgery"),
                &trusted_coverage,
                request,
                &policy,
                None,
            )
            .is_err(),
            "matching state and response coverage substitutions must not replace the census"
        );

        let mut alternate_target = target();
        alternate_target.model_id = "alternate-semantic-model".to_owned();
        alternate_target.embedding_space.logical_model_id = alternate_target.model_id.clone();
        alternate_target.upstream_revision = "alternate-immutable-revision".to_owned();
        alternate_target.embedding_space.immutable_revision =
            alternate_target.upstream_revision.clone();
        let target_forgery = plan(
            state.clone(),
            request,
            policy.clone(),
            Some(&alternate_target),
        )
        .expect("internally coherent alternate-target plan");
        assert!(
            decode_and_validate(
                serde_json::to_value(target_forgery).expect("serialize forgery"),
                &state,
                request,
                &policy,
                Some(&acquisition_target),
            )
            .is_err(),
            "a self-consistent action and authorization cannot substitute another frozen target"
        );
    }

    #[test]
    fn shell_rendering_quotes_unsafe_arguments() {
        let action = RecoveryAction {
            code: "recovery.action.build_index".to_owned(),
            explanation: String::new(),
            argv: vec![
                "fsfs".to_owned(),
                "index".to_owned(),
                "--index-dir".to_owned(),
                "/data/My Projects/it's here".to_owned(),
                ARG_SOURCE_DIR.to_owned(),
            ],
            network_required: false,
            consent_required: false,
            preserves_old_data: true,
            potentially_destructive: false,
            prerequisites: Vec::new(),
            expected_postcondition: "recovery.post.index_built".to_owned(),
            required_authorization: None,
        };
        assert_eq!(
            action.shell_command(),
            "fsfs index --index-dir '/data/My Projects/it'\\''s here' <source-dir>"
        );
    }

    #[test]
    fn serialization_roundtrips_and_locks_schema_version() {
        for state in representative_states() {
            if matches!(state, SemanticReadiness::HashControl) {
                continue;
            }
            for request in semantic_requests() {
                for policy in all_policies() {
                    let tier = tier_for_request(request);
                    let state = state_for_request(&state, request);
                    let acquisition_target = target_for(tier);
                    let original = plan(
                        state.clone(),
                        request,
                        policy.clone(),
                        Some(&acquisition_target),
                    )
                    .expect("valid representative plan");
                    let json = serde_json::to_value(&original).expect("serialize plan");
                    assert_eq!(
                        json["schema_version"],
                        serde_json::Value::String(RECOVERY_PLAN_SCHEMA_VERSION.to_owned())
                    );
                    let decoded = decode_and_validate(
                        json,
                        &state,
                        request,
                        &policy,
                        Some(&acquisition_target),
                    )
                    .expect("validate untrusted plan against authoritative context");
                    assert_eq!(decoded, original);
                }
            }
        }
        let hash = planned(SemanticReadiness::HashControl, hash_control(), permissive());
        let json = serde_json::to_value(&hash).expect("serialize hash plan");
        let decoded = decode_and_validate(
            json,
            &SemanticReadiness::HashControl,
            hash_control(),
            &permissive(),
            None,
        )
        .expect("validate hash plan");
        assert_eq!(decoded, hash);
    }

    #[test]
    fn golden_plan_json_for_model_missing_offline_hybrid() {
        let plan = planned(
            missing(ModelTier::Quality),
            hybrid(RetrievalTopology::FullProgressive),
            RecoveryPolicy {
                interaction: InteractionPolicy::NonInteractive,
                network: NetworkPolicy::Offline,
                acquisition_authorization: None,
            },
        );
        let json = serde_json::to_value(&plan).expect("serialize plan");
        assert_eq!(json["schema_version"], "frankensearch.recovery_plan.v4");
        assert_eq!(json["state"]["state"], "model_missing");
        assert_eq!(json["state"]["detail"]["tier"], "quality");
        assert_eq!(json["state_code"], "recovery.state.model_missing");
        assert_eq!(json["provenance"], "unavailable");
        assert_eq!(json["mode"], "hybrid");
        assert_eq!(json["requested_topology"]["topology"], "full_progressive");
        assert_eq!(json["policy"]["interaction"], "non_interactive");
        assert_eq!(json["policy"]["network"], "offline");
        assert!(json["policy"]["acquisition_authorization"].is_null());
        assert_eq!(json["semantic_available"], false);
        assert_eq!(json["retryability"], "blocked_by_capability");
        assert_eq!(json["action"]["code"], "recovery.action.acquire_model");
        assert_eq!(json["action"]["argv"], serde_json::json!([]));
        assert_eq!(json["action"]["network_required"], false);
        assert_eq!(json["action"]["consent_required"], true);
        assert_eq!(
            json["action"]["prerequisites"][0],
            "recovery.capability.import_model_bundle"
        );
        assert_eq!(
            json["action"]["prerequisites"][1],
            "recovery.policy.grant_consent"
        );
        assert_eq!(
            json["action"]["required_authorization"]["schema_version"],
            "frankensearch.model_acquisition_authorization.v3"
        );
        assert_eq!(
            json["action"]["required_authorization"]["model_id"],
            "fixture-semantic-model"
        );
        assert_eq!(
            json["action"]["required_authorization"]["model_tier"],
            "quality"
        );
        assert_eq!(
            json["action"]["required_authorization"]["embedding_space"]["logical_model_id"],
            "fixture-semantic-model"
        );
        assert_eq!(
            json["action"]["required_authorization"]["embedding_space"]["dimension"],
            384
        );
        assert_eq!(
            json["action"]["required_authorization"]["source"]["kind"],
            "local_bundle"
        );
        assert_eq!(
            json["action"]["required_authorization"]["byte_budget"],
            42_000_000
        );
        assert_eq!(
            json["action"]["required_authorization"]["document_count"],
            12_345
        );
        assert_eq!(
            json["action"]["required_authorization"]["estimated_reindex_duration_ms"],
            98_765
        );
        assert_eq!(
            json["action"]["required_authorization"]["issued_at_unix_seconds"],
            TEST_AUTHORIZATION_ISSUED_AT_UNIX_SECONDS
        );
        assert_eq!(
            json["action"]["required_authorization"]["expires_at_unix_seconds"],
            TEST_AUTHORIZATION_EXPIRES_AT_UNIX_SECONDS
        );
        assert_eq!(
            json["action"]["required_authorization"]["nonce"],
            TEST_AUTHORIZATION_NONCE
        );
        assert_eq!(
            json["response_contract"]["requested_topology"]["topology"],
            "full_progressive"
        );
        assert_eq!(
            json["response_contract"]["realized_topology"]["topology"],
            "lexical_only"
        );
        assert_eq!(json["response_contract"]["coverage_ppm"], 0);
        assert_eq!(json["response_contract"]["admitted_semantic_scores"], 0);
        assert_eq!(
            json["response_contract"]["degradation_reason_code"],
            "recovery.state.model_missing"
        );
    }

    #[test]
    fn golden_transition_table_is_stable() {
        // One compact row per unique state code and semantic mode under the
        // permissive policy, plus the explicit hash-control row.
        let states = vec![
            SemanticReadiness::Ready {
                provenance: VerifiedSemanticProvenance::Local,
            },
            missing(ModelTier::Quality),
            unloadable(ModelTier::Quality),
            SemanticReadiness::IndexAbsent,
            SemanticReadiness::IdentityMismatch,
            SemanticReadiness::DaemonMismatch,
            SemanticReadiness::IndexEmpty(ZeroSignalReason::NewlyCreatedEmpty),
            SemanticReadiness::ManifestUnsafe,
            SemanticReadiness::AnnStale,
            SemanticReadiness::GenerationIncomplete,
            SemanticReadiness::PartialQualityCoverage {
                provenance: VerifiedSemanticProvenance::Local,
                coverage_ppm: 750_000,
            },
            SemanticReadiness::RemoteUnverified,
        ];
        let mut rows = Vec::new();
        for state in &states {
            for request in [
                explicit(RetrievalTopology::FullProgressive),
                hybrid(RetrievalTopology::FullProgressive),
            ] {
                let plan = planned(state.clone(), request, permissive());
                let mode_tag = match request.mode {
                    RequestMode::ExplicitSemantic => "semantic",
                    RequestMode::Hybrid => "hybrid",
                    RequestMode::HashControl => unreachable!("semantic request array"),
                };
                let action_tag = plan.action.as_ref().map_or_else(
                    || "none,false,false".to_owned(),
                    |a| format!("{},{},{}", a.code, a.network_required, a.consent_required),
                );
                let retry_tag = match plan.retryability {
                    Retryability::NotNeeded => "not_needed",
                    Retryability::AfterAction => "after_action",
                    Retryability::AfterRequestChange => "after_request_change",
                    Retryability::BlockedByPolicy => "blocked",
                    Retryability::BlockedByCapability => "capability_blocked",
                };
                let (realized, coverage) = plan
                    .response_contract
                    .as_ref()
                    .map_or(("none", 0), |response| {
                        (response.realized_topology().code(), response.coverage_ppm())
                    });
                rows.push(format!(
                    "{}|{} => {},{},{},{}",
                    plan.state_code, mode_tag, action_tag, retry_tag, realized, coverage
                ));
            }
        }
        let hash = planned(SemanticReadiness::HashControl, hash_control(), permissive());
        let hash_response = hash.response_contract.expect("hash response");
        rows.push(format!(
            "{}|hash_control => none,false,false,not_needed,{},{}",
            hash.state_code,
            hash_response.realized_topology().code(),
            hash_response.coverage_ppm()
        ));
        let expected: Vec<&str> = vec![
            "recovery.state.ready|semantic => none,false,false,not_needed,full_progressive,1000000",
            "recovery.state.ready|hybrid => none,false,false,not_needed,full_progressive,1000000",
            "recovery.state.model_missing|semantic => recovery.action.acquire_model,true,true,capability_blocked,none,0",
            "recovery.state.model_missing|hybrid => recovery.action.acquire_model,true,true,capability_blocked,lexical_only,0",
            "recovery.state.model_unloadable|semantic => recovery.action.reacquire_model,true,true,capability_blocked,none,0",
            "recovery.state.model_unloadable|hybrid => recovery.action.reacquire_model,true,true,capability_blocked,lexical_only,0",
            "recovery.state.index_absent|semantic => recovery.action.build_index,false,false,capability_blocked,none,0",
            "recovery.state.index_absent|hybrid => recovery.action.build_index,false,false,capability_blocked,lexical_only,0",
            "recovery.state.identity_mismatch|semantic => recovery.action.reindex_full,false,true,capability_blocked,none,0",
            "recovery.state.identity_mismatch|hybrid => recovery.action.reindex_full,false,true,capability_blocked,lexical_only,0",
            "recovery.state.daemon_mismatch|semantic => recovery.action.restart_daemon,false,false,capability_blocked,none,0",
            "recovery.state.daemon_mismatch|hybrid => recovery.action.restart_daemon,false,false,capability_blocked,lexical_only,0",
            "recovery.state.index_empty|semantic => recovery.action.ingest_content,false,false,capability_blocked,none,0",
            "recovery.state.index_empty|hybrid => recovery.action.ingest_content,false,false,capability_blocked,lexical_only,0",
            "recovery.state.manifest_unsafe|semantic => recovery.action.reindex_full,false,true,capability_blocked,none,0",
            "recovery.state.manifest_unsafe|hybrid => recovery.action.reindex_full,false,true,capability_blocked,lexical_only,0",
            "recovery.state.ann_stale|semantic => recovery.action.rebuild_ann,false,false,capability_blocked,none,0",
            "recovery.state.ann_stale|hybrid => recovery.action.rebuild_ann,false,false,capability_blocked,lexical_only,0",
            "recovery.state.generation_incomplete|semantic => recovery.action.resume_index,false,false,capability_blocked,none,0",
            "recovery.state.generation_incomplete|hybrid => recovery.action.resume_index,false,false,capability_blocked,lexical_only,0",
            "recovery.state.partial_quality_coverage|semantic => recovery.action.backfill_quality,false,false,capability_blocked,partial_quality,750000",
            "recovery.state.partial_quality_coverage|hybrid => recovery.action.backfill_quality,false,false,capability_blocked,partial_quality,750000",
            "recovery.state.remote_unverified|semantic => recovery.action.provide_attestation,false,false,blocked,none,0",
            "recovery.state.remote_unverified|hybrid => recovery.action.provide_attestation,false,false,blocked,lexical_only,0",
            "recovery.state.hash_control|hash_control => none,false,false,not_needed,hash_control,0",
        ];
        assert_eq!(
            rows, expected,
            "transition table changed: contract review required"
        );
    }
}