subc-control 0.40.1

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

#![forbid(unsafe_code)]

use std::{collections::BTreeMap, path::PathBuf};

use serde::{
    de::{Error as _, MapAccess, SeqAccess, Visitor},
    ser::SerializeMap,
    Deserialize, Deserializer, Serialize, Serializer,
};
use subc_protocol::{
    manifest::{
        CapabilityDeclarations, EventDeclaration, ManifestProvenance, OperationDelivery,
        OperationPayload, ProviderRole, RichUiDescriptor, SelfSignalDeclaration,
    },
    scope::ScopeSelector,
    session::HealthStatus,
    BindIdentity, RouteTarget,
};

pub use subc_protocol::claim::{
    Claim, ClaimMintReply, ClaimMintRequest, ClaimPresentReply, ClaimPresentRequest, ClaimPurpose,
    ClaimRateLimitedDetail,
};
pub use subc_protocol::peer::CallerOrigin as CatalogOrigin;
pub use subc_protocol::RouteCloseReason;
use subc_protocol::{peer::MAX_ATTESTATION_INTEGER, provider_declarations::ProviderDeclarations};

mod activity;
pub use activity::*;

mod scope_served_by;
pub use scope_served_by::*;

macro_rules! open_string_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $( $(#[$variant_meta:meta])* $variant:ident => $wire_name:literal ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq)]
        pub enum $name {
            $( $(#[$variant_meta])* $variant, )+
            Unknown(String),
        }

        impl $name {
            fn wire_name(&self) -> &str {
                match self {
                    $( Self::$variant => $wire_name, )+
                    Self::Unknown(value) => value,
                }
            }
        }

        impl Serialize for $name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(self.wire_name())
            }
        }

        impl<'de> Deserialize<'de> for $name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let value = String::deserialize(deserializer)?;
                Ok(match value.as_str() {
                    $( $wire_name => Self::$variant, )+
                    _ => Self::Unknown(value),
                })
            }
        }
    };
}

mod rescan_checked;
pub use rescan_checked::*;

mod app_open;
pub use app_open::*;

mod connection_describe;
pub use connection_describe::*;

mod subtree;
pub use subtree::*;
mod tree;
pub use tree::*;

/// Daemon-spawned consumer identity presented on route.open.
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ConsumerIdentity {
    pub module_id: String,
    pub launch_nonce: String,
}

// Hand-written so the launch nonce is never printed. The nonce is the credential
// that attributes a connection to a supervised module, and a derived Debug would
// write it into any log line or panic message that formats this value. Same
// reasoning as ConnectionInfo's Debug in subc-transport.
impl std::fmt::Debug for ConsumerIdentity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ConsumerIdentity")
            .field("module_id", &self.module_id)
            .field(
                "launch_nonce",
                &format_args!("<{} bytes redacted>", self.launch_nonce.len()),
            )
            .finish()
    }
}

/// Reserved dotted operation prefixes for the v0.4 control vocabulary.
///
/// `scheduler.` and `watch.` were reserved here from v0.4 until 2026-08-10 and
/// were removed deliberately rather than left as placeholders: neither was ever
/// implemented, and both capabilities are now owned elsewhere by ruling --
/// scheduled tasks belong to the session runtime (prefrontal) because the
/// daemon is state-free routing, and external-event watching belongs to the
/// connectors module (plexus). A reserved name for something that will never be
/// built here reads as a roadmap commitment to anyone surveying the protocol,
/// and it recruited exactly that misunderstanding from an outside contributor.
pub mod config;

pub mod ops {
    pub const SERVER: &str = "server.";
    pub const CATALOG: &str = "catalog.";
    pub const ROUTE: &str = "route.";
    pub const SUPERVISOR: &str = "supervisor.";
    pub const CONFIG: &str = "config.";

    pub const SERVER_DESCRIBE: &str = "server.describe";
    pub const DAEMON_SHUTDOWN_INTENT: &str = "daemon.shutdown_intent";
    pub const CATALOG_LIST: &str = "catalog.list";
    pub const CATALOG_WATCH: &str = "catalog.watch";
    pub const ROUTE_OPEN: &str = "route.open";
    pub const ROUTE_POLL: &str = "route.poll";
    pub const ROUTE_CLOSING: &str = "route.closing";
    pub const ROUTE_CLOSED: &str = "route.closed";
    pub const SUPERVISOR_LIST: &str = "supervisor.list";
    pub const SUPERVISOR_RESTART: &str = "supervisor.restart";
    pub const SUPERVISOR_SWAP: &str = "supervisor.swap";
    pub const SUPERVISOR_RELOAD: &str = "supervisor.reload";
    pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
    pub const SUPERVISOR_RESCAN_CHECKED: &str = "supervisor.rescan_checked";
    pub const SUPERVISOR_RELEASE_RESERVED: &str = "supervisor.release_reserved";
    pub const SUPERVISOR_SET_ENABLED: &str = "supervisor.set_enabled";
    pub const SUPERVISOR_HEALTH_PROBE: &str = "supervisor.health_probe";
    pub const SUPERVISOR_HEALTH: &str = "supervisor.health";
    pub const SUPERVISOR_STDERR_TAIL: &str = "supervisor.stderr_tail";
    pub const SUPERVISOR_TERMINALS: &str = "supervisor.terminals";
    pub const SUPERVISOR_ROUTES: &str = "supervisor.routes";
    pub const SUPERVISOR_PROVENANCE: &str = "supervisor.provenance";
    pub const SUPERVISOR_SPAWN_SNAPSHOT: &str = "supervisor.spawn_snapshot";
    pub const SUPERVISOR_SPAWN_SUBSCRIBE: &str = "supervisor.spawn_subscribe";
    pub const ACTIVITY_RECORD: &str = "activity.record";
    pub const ACTIVITY_QUERY: &str = "activity.query";
    pub const ACTIVITY_SUBSCRIBE: &str = "activity.subscribe";
    pub const APP_OPEN: &str = "app.open";
    pub const CONNECTION_DESCRIBE: &str = "connection.describe";
}

/// Client-originated channel-0 control RPC body.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "op")]
// RouteOpen carries the complete route metadata, while several control operations
// are markers; retain the direct public wire shape instead of boxing its fields.
#[allow(clippy::large_enum_variant)]
pub enum ClientControlRequest {
    /// Announce a planned daemon restart. Other values, including an absent
    /// intent, are refused by the daemon with `invalid_params`.
    #[serde(rename = "daemon.shutdown_intent")]
    DaemonShutdownIntent {
        #[serde(default)]
        intent: serde_json::Value,
    },
    #[serde(rename = "server.describe")]
    ServerDescribe {},
    #[serde(rename = "catalog.list")]
    CatalogList {
        /// Absent lists every registered module; present narrows to one. A
        /// narrowed list for an unregistered id is an empty list rather than an
        /// error, so absent and unregistered are distinguishable only by which
        /// question you asked.
        #[serde(default)]
        module_id: Option<String>,
    },
    #[serde(rename = "route.open")]
    RouteOpen {
        target: RouteTarget,
        identity: BindIdentity,
        /// The consumer's claim to a supervised launch, which the daemon verifies
        /// against its live spawn nonces before stamping a principal.
        ///
        /// Absent is a legitimate shape, not an omission: a direct key-holder has
        /// no launch nonce to present, and the daemon stamps `Direct`. So absence
        /// means NO CLAIM WAS MADE, never that a claim was refused — a refused
        /// claim is an error frame and the route never opens. A provider deciding
        /// what to trust reads the stamped principal on the bind, not this.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        consumer_identity: Option<ConsumerIdentity>,
        /// Consumer-declared reverse-request capabilities for the route. This is
        /// an unverified declaration, not a privilege grant; if a consumer
        /// over-declares, providers may still send reverse requests that later
        /// time out or deny. Providers must treat an absent field as no
        /// reverse-request capability. The vocabulary is open strings; known MCP
        /// method-family values today are "elicitation", "sampling", and
        /// "roots".
        #[serde(default, skip_serializing_if = "Option::is_none")]
        consumer_capabilities: Option<Vec<String>>,
        /// The versions of provider roles this consumer speaks on the route,
        /// role name to version (`{"tool-provider": "v1"}`). Like
        /// `consumer_capabilities` it is an unverified declaration that grants
        /// nothing: the daemon checks its shape
        /// (`subc_protocol::session::validate_role_versions`), refuses a
        /// malformed one as `invalid_request` naming `role_versions`, and
        /// copies it unchanged onto the module's bind. An empty map means the
        /// same as an absent one. Send it only to a daemon advertising
        /// `route-role-versions/v1`: an older daemon drops unknown fields, so
        /// the provider would never see it.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        role_versions: Option<BTreeMap<String, String>>,
        /// Opt into immediate, never-forwarded `route_busy` refusals instead of
        /// waiting for request credits. This field is daemon-only and is never
        /// copied into the module's bind.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        busy_refusals: Option<bool>,
        /// Opaque admission facts supplied by the configured carrier module.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        admission_facts: Option<serde_json::Value>,
        /// The scope to open the route under. The daemon admits the open only
        /// when the opener (its attested principal, never anything in this
        /// body) is the scope's owner or a listed carrier, and stamps the
        /// scope on the module's bind. Send it only to a daemon advertising
        /// `scopes/v1`: an older daemon drops unknown fields and would open an
        /// unscoped route.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        scope: Option<ScopeSelector>,
    },
    #[serde(rename = "route.poll")]
    RoutePoll {
        route_channel: u16,
        route_epoch: u32,
        kind: PollKind,
    },
    #[serde(rename = "supervisor.list")]
    SupervisorList {},
    /// Read the live supervised processes and the event cursor atomically.
    #[serde(rename = "supervisor.spawn_snapshot")]
    SupervisorSpawnSnapshot {},
    /// Replay spawn events after `since`, then remain open for live events.
    ///
    /// The cursor is one value copied from a snapshot or event. It includes the
    /// daemon incarnation so a restarted daemon rejects an earlier instance's
    /// sequence instead of treating it as a position in the current stream.
    ///
    /// Refusals and terminal errors, as `Error` frames on the request's corr:
    /// - `spawn_cursor_incarnation_mismatch` (detail `current_daemon_incarnation`):
    ///   `since` names another daemon incarnation.
    /// - `spawn_cursor_too_old` (detail `oldest_retained_cursor`): `since`
    ///   predates the retained event ring.
    /// - `spawn_subscriber_lagged` (detail `first_undelivered_cursor`): the open
    ///   stream fell too far behind and the daemon dropped it. It arrives after
    ///   every event that was already queued and ends the stream; resubscribe
    ///   with `since` set to the last cursor received.
    #[serde(rename = "supervisor.spawn_subscribe")]
    SupervisorSpawnSubscribe {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        since: Option<SpawnCursor>,
    },
    #[serde(rename = "supervisor.restart")]
    SupervisorRestart {
        module_id: String,
        /// Optional per-restart override of the module's drain budget, in ms.
        /// Absent: the module's configured `drain_timeout_ms` (or the daemon
        /// default) applies. `0` tears down without waiting: use it to restart a
        /// wedged module whose stuck in-flight request would never settle, so
        /// waiting for a drain would be pointless.
        /// Additive; older daemons silently ignore this field and use their
        /// configured/default drain budget, even when the sender requests `0`.
        /// Senders that require the override must use a daemon version that
        /// supports it (the CLI only sends it when a flag is passed).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        drain_timeout_ms: Option<u64>,
    },
    /// Blue/green restart: start a replacement beside the running process, keep
    /// routing to the running one until the replacement declares itself ready,
    /// then move new routes over and drain the old process.
    ///
    /// Refused before anything is spawned unless the module's daemon config
    /// declares `overlap: "safe"`: two processes on one single-writer store is
    /// a data hazard, so the default is exclusive. Answered once the swap has
    /// either cut over (the old process is still draining) or failed; a failure
    /// leaves the old process serving and undrained, and names the arm in
    /// `ErrorBody.detail`.
    ///
    /// A new op rather than a flag on `supervisor.restart`: a daemon that
    /// predates swap rejects an unknown op, whereas an unknown field could be
    /// dropped and turned into a plain restart.
    #[serde(rename = "supervisor.swap")]
    SupervisorSwap {
        module_id: String,
        /// How long the replacement may take to register and declare itself
        /// ready before the swap is abandoned. Absent: the daemon default.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ready_timeout_ms: Option<u64>,
    },
    #[serde(rename = "supervisor.reload")]
    SupervisorReload { module_id: String },
    #[serde(rename = "supervisor.rescan")]
    SupervisorRescan {
        /// Compute the reconciliation and return it WITHOUT applying it.
        ///
        /// Rescan retires any supervised module absent from the config, which
        /// stops live processes. Both halves of that decision are inspectable in
        /// advance -- the config is a file, the running set is `supervisor.list`
        /// -- but nothing reconstructs the diff for the operator, so it is read
        /// from the result table AFTER the retires have happened.
        ///
        /// A preview must be computed daemon-side rather than by a client, because
        /// a client would have to locate the daemon's config itself: two rules
        /// selecting one subject, agreeing until someone runs a daemon with a
        /// non-default config. A preview that can describe a different file than
        /// the operation reads is worse than none, because it is believed.
        ///
        /// Defaults to false so an existing client sending `{}` still executes,
        /// and is OMITTED when false so the bytes an existing client sends are
        /// unchanged. Serialising `preview:false` would have altered the request's
        /// wire form for every caller that never asked for a preview -- caught by
        /// the golden fixture, which is the whole reason that pin exists.
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        preview: bool,
    },
    /// A rescan whose preview is computed on configuration text the caller
    /// supplies, and whose apply runs only if the daemon still matches that
    /// preview. Served by daemons advertising
    /// [`RESCAN_CANDIDATE_PREVIEW_CAPABILITY`].
    ///
    /// Exactly two forms are accepted; any other combination is refused
    /// `invalid_control_body`:
    /// - `preview: true` with `candidate`: parse and validate the candidate
    ///   (at most [`RESCAN_CANDIDATE_MAX_BYTES`]) with the loader the daemon
    ///   uses for its file, compare it with the staged module specs, and
    ///   report what applying it would do. Nothing is written or applied.
    ///   The reply carries the `expect` an apply must send.
    /// - `preview: false` with `expect`: refuse
    ///   [`CONFIG_CHANGED_SINCE_PREVIEW`] when the daemon's config file no
    ///   longer hashes to `expect.config_sha256` or the staged generation has
    ///   moved; otherwise apply the file exactly as `supervisor.rescan` does.
    ///
    /// Both reply with `supervisor.rescan`'s result shape.
    ///
    /// A new op rather than fields on `supervisor.rescan`: a daemon that
    /// predates it refuses the unknown op, whereas unknown fields would be
    /// dropped and the preview would describe the file on disk instead of the
    /// candidate.
    #[serde(rename = "supervisor.rescan_checked")]
    SupervisorRescanChecked {
        preview: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        candidate: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expect: Option<RescanExpect>,
    },
    /// Retire the retained exact-id reservation after its configuration entry has
    /// been removed. This is intentionally separate from rescan so deleting
    /// configuration never silently opens a protected module id to registration.
    #[serde(rename = "supervisor.release_reserved")]
    SupervisorReleaseReserved { module_id: String },
    #[serde(rename = "supervisor.set_enabled")]
    SupervisorSetEnabled { module_id: String, enabled: bool },
    #[serde(rename = "supervisor.health_probe")]
    SupervisorHealthProbe { module_id: String },
    #[serde(rename = "supervisor.health")]
    SupervisorHealth {},
    /// Enumerate the routes currently served by one supervised module, or every
    /// module when omitted.
    ///
    /// This privileged census is control-plane-only. It is deliberately not an
    /// MCP facade or agent-tool operation: callers holding the daemon control
    /// connection may inspect live route ownership, while agent-facing modules
    /// must not be able to address that surface at all.
    ///
    /// The daemon answers from its forwarding table under a read lock and never
    /// consults a module. That makes the read safe during a drain, when a module
    /// cannot be queried without recreating the hang/restart hazard that route
    /// status reads avoid.
    #[serde(rename = "supervisor.routes")]
    SupervisorRoutes {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<String>,
    },
    /// Report source-tagged provenance for supervised modules, optionally narrowed
    /// to one module.
    #[serde(rename = "supervisor.provenance")]
    SupervisorProvenance {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        module_id: Option<String>,
    },
    /// Retained stderr for one module.
    ///
    /// A separate op rather than a field on `supervisor.list`: the tail is
    /// kilobytes per module and `list` renders every module, so carrying it in
    /// the snapshot would charge every status read for a payload almost no
    /// caller wants. Caps ride on the REQUEST so a caller wanting twenty lines
    /// and one wanting the whole ring need no separate fields anywhere.
    #[serde(rename = "supervisor.stderr_tail")]
    SupervisorStderrTail {
        module_id: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_lines: Option<u32>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max_bytes: Option<u32>,
    },
    /// Retained terminal exits for one module.
    ///
    /// This stays separate from `supervisor.list`: a history grows with every
    /// incident, while the list is a current-state read most callers issue often.
    ///
    /// The read MUST stay off the supervisor command channel — it reads the
    /// module's shared ring directly. This is a requirement, not an
    /// optimisation: when the supervision task itself dies, every
    /// command-channel op returns `CommandClosed`, and that is precisely the
    /// moment an operator needs the exit history most. A history reachable only
    /// through the machinery whose death you are diagnosing is unreachable when
    /// it matters. Proven failure mode, not a hypothetical.
    #[serde(rename = "supervisor.terminals")]
    SupervisorTerminals { module_id: String },
}

/// subc's channel-0 response body for client control RPCs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "op")]
pub enum ClientControlResponse {
    #[serde(rename = "daemon.shutdown_intent")]
    DaemonShutdownIntent { intent: String, expires_at_ms: u64 },
    #[serde(rename = "server.describe")]
    ServerDescribe {
        protocol_ver: u8,
        subc_ops: Vec<String>,
        capabilities: Vec<String>,
        connected_clients: u64,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        counters: Option<serde_json::Value>,
        /// Git commit the daemon was built from, or "unavailable" when the
        /// build could not read it. The crate version cannot discriminate a
        /// skewed daemon/CLI pair (it moves per release, not per commit), so
        /// this is the identity a consumer compares against its own embedded
        /// commit to detect that it is talking to an older build than it was
        /// compiled with. Absent from daemons predating the field.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        build_git_sha: Option<String>,
        /// sha256 of the workspace Cargo.lock at build time, or "unavailable".
        /// Answers "which dependency set" where the commit answers "which
        /// source"; a commit match with a digest mismatch means a rebuild
        /// against edited dependencies. Absent from daemons predating the
        /// field.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        build_lock_digest: Option<String>,
        /// Daemon-evaluated capability requirements. Present when the configured
        /// fleet has declarations to evaluate, so operators can inspect an absent
        /// required capability without parsing daemon logs.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        capability_requirements: Vec<CapabilityRequirementStatus>,
        /// The daemon's machine id (`subc_protocol::MachineId`), the same value
        /// every module receives on `HELLO_ACK`. A name for this machine, never
        /// an authority: nothing may grant trust because two parties report the
        /// same value. Absent from daemons predating the field.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        machine_id: Option<String>,
        /// The configuration file the daemon reads and `supervisor.rescan`
        /// rescans, exactly as the daemon names it: never canonicalized, so a
        /// symlinked file is reported as the link. Sent only when that path is
        /// absolute; a relative one (no home variable set, or a relative
        /// `XDG_CONFIG_HOME`) depends on the daemon's working directory and
        /// would name a different file for the reader. Absent from daemons
        /// predating the field and from daemons started without a reloadable
        /// config file.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        config_path: Option<PathBuf>,
    },
    #[serde(rename = "catalog.list")]
    CatalogList {
        generation: u64,
        modules: Vec<CatalogEntry>,
        subc_ops: Vec<String>,
    },
    #[serde(rename = "route.open")]
    RouteOpen {
        route_channel: u16,
        route_epoch: u32,
        /// Total request credits, present only when busy refusals were enabled.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        request_window: Option<usize>,
        /// Watch credits on an opted-in module-managed route.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        watch_window: Option<usize>,
    },
    #[serde(rename = "route.poll")]
    RoutePoll {
        route_channel: u16,
        route_epoch: u32,
        status: Option<String>,
        live: Option<bool>,
    },
    #[serde(rename = "supervisor.list")]
    SupervisorList {
        generation: u64,
        modules: Vec<SupervisorEntry>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        daemon: Option<DaemonResources>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_commands: Option<Vec<AgentCommandResources>>,
    },
    #[serde(rename = "supervisor.spawn_snapshot")]
    SupervisorSpawnSnapshot {
        #[serde(flatten)]
        snapshot: SpawnSnapshot,
    },
    #[serde(rename = "supervisor.ack")]
    SupervisorAck { module_id: String, applied: bool },
    #[serde(rename = "supervisor.rescan")]
    SupervisorRescan {
        #[serde(flatten)]
        result: SupervisorRescanResult,
    },
    #[serde(rename = "supervisor.health_probe")]
    SupervisorHealthProbe {
        module_id: String,
        status: HealthStatus,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detail: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        metrics: Option<serde_json::Value>,
    },
    #[serde(rename = "supervisor.health")]
    SupervisorHealth {
        generation: u64,
        modules: Vec<SupervisorHealthEntry>,
    },
    #[serde(rename = "supervisor.routes")]
    SupervisorRoutes { modules: Vec<SupervisorRouteModule> },
    #[serde(rename = "supervisor.provenance")]
    SupervisorProvenance {
        daemon: SupervisorDaemonProvenance,
        modules: Vec<SupervisorModuleProvenance>,
    },
    #[serde(rename = "supervisor.stderr_tail")]
    SupervisorStderrTail {
        module_id: String,
        #[serde(flatten)]
        tail: StderrTail,
    },
    #[serde(rename = "supervisor.terminals")]
    SupervisorTerminals {
        module_id: String,
        #[serde(flatten)]
        terminals: TerminalHistory,
    },
}

/// Capability required before sending `accepts_close_reasons` on `route.open`.
pub const ROUTE_CLOSE_REASONS_CAPABILITY: &str = "route-close-reasons/v1";

/// Optional request keys kept outside the exhaustive `RouteOpen` variant so
/// existing construction sites and destructures remain source-compatible.
/// SDKs send these keys only after observing [`ROUTE_CLOSE_REASONS_CAPABILITY`].
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RouteOpenRequestExt {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accepts_close_reasons: Option<Vec<String>>,
}

impl RouteOpenRequestExt {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_accepts_close_reasons(mut self, reasons: Option<Vec<String>>) -> Self {
        self.accepts_close_reasons = reasons;
        self
    }

    /// Read the companion keys from the same JSON body as the existing request.
    pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
        require_route_open_object(body)?;
        serde_json::from_value(body.clone())
    }

    /// Write companion keys into an existing request body, replacing stale keys.
    /// Empty companions omit their keys rather than writing `null`.
    pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
        write_route_open_ext(body, self, &["accepts_close_reasons"])
    }
}

/// Optional reply keys kept beside, rather than inside, the exhaustive
/// `RouteOpen` variant so existing emitters and readers need no source changes.
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct RouteOpenReplyExt {
    /// An absent or incomplete target establishes no marked spawn.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_route_open_target"
    )]
    pub target: Option<RouteOpenTarget>,
}

impl RouteOpenReplyExt {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_target(mut self, target: Option<RouteOpenTarget>) -> Self {
        self.target = target;
        self
    }

    /// Read target facts from the same JSON body as the existing reply.
    pub fn read_from(body: &serde_json::Value) -> serde_json::Result<Self> {
        require_route_open_object(body)?;
        serde_json::from_value(body.clone())
    }

    /// Write target facts into an existing reply body, replacing a stale target.
    /// An empty companion removes the key rather than writing `null`.
    pub fn write_to(&self, body: &mut serde_json::Value) -> serde_json::Result<()> {
        write_route_open_ext(body, self, &["target"])
    }
}

fn require_route_open_object(body: &serde_json::Value) -> serde_json::Result<()> {
    if body.is_object()
        && body.get("op").and_then(serde_json::Value::as_str) == Some(ops::ROUTE_OPEN)
    {
        Ok(())
    } else {
        Err(serde_json::Error::custom(
            "expected a route.open body object",
        ))
    }
}

fn write_route_open_ext(
    body: &mut serde_json::Value,
    ext: &impl Serialize,
    keys: &[&str],
) -> serde_json::Result<()> {
    require_route_open_object(body)?;
    let serde_json::Value::Object(fields) = serde_json::to_value(ext)? else {
        unreachable!("route.open companions serialize as objects");
    };
    let object = body.as_object_mut().expect("validated route.open object");
    for key in keys {
        object.remove(*key);
    }
    object.extend(fields);
    Ok(())
}

/// A target kind unknown to this reader never establishes a supervised spawn.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RouteOpenTargetKind {
    Spawn,
    Prefix,
    Unsupervised,
    #[serde(other)]
    Unknown,
}

/// Daemon-attested target facts. Spawn-only keys are ignored for all other kinds,
/// which are always unmarked. Incomplete targets decode as absent in the reply.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct RouteOpenTarget {
    pub incarnation: String,
    pub kind: RouteOpenTargetKind,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub spawn: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority_epoch: Option<u64>,
    pub first_party: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approved_declarations_digest: Option<String>,
}

impl RouteOpenTarget {
    /// Construct target facts using the same validation and per-kind rules as
    /// the wire reader, including the cross-language integer bound.
    pub fn new(
        incarnation: impl Into<String>,
        kind: RouteOpenTargetKind,
        spawn: Option<u64>,
        authority_epoch: Option<u64>,
        first_party: bool,
        approved_declarations_digest: Option<String>,
    ) -> serde_json::Result<Self> {
        serde_json::from_value(serde_json::json!({
            "incarnation": incarnation.into(), "kind": kind,
            "spawn": spawn, "authority_epoch": authority_epoch,
            "first_party": first_party,
            "approved_declarations_digest": approved_declarations_digest,
        }))
    }
}

impl<'de> Deserialize<'de> for RouteOpenTarget {
    fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
        decode_route_open_target(serde_json::Value::deserialize(decoder)?)
            .map_err(D::Error::custom)?
            .ok_or_else(|| D::Error::custom("incomplete route.open target"))
    }
}

fn deserialize_route_open_target<'de, D: Deserializer<'de>>(
    decoder: D,
) -> Result<Option<RouteOpenTarget>, D::Error> {
    decode_route_open_target(serde_json::Value::deserialize(decoder)?).map_err(D::Error::custom)
}

fn decode_route_open_target(
    mut value: serde_json::Value,
) -> serde_json::Result<Option<RouteOpenTarget>> {
    if value.is_null() {
        return Ok(None);
    }
    let object = value
        .as_object_mut()
        .ok_or_else(|| serde_json::Error::custom("expected target object"))?;
    let is_spawn = object.get("kind").and_then(serde_json::Value::as_str) == Some("spawn");
    if is_spawn {
        // Validate even an incomplete spawn: rounding must not alias identities.
        for field in ["spawn", "authority_epoch"] {
            if let Some(integer) = object.get(field) {
                deserialize_optional_attestation_integer(integer)?;
            }
        }
    } else {
        for field in ["spawn", "authority_epoch", "approved_declarations_digest"] {
            object.remove(field);
        }
    }
    if ["incarnation", "kind", "first_party"]
        .iter()
        .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null))
        || (is_spawn
            && ["spawn", "authority_epoch", "approved_declarations_digest"]
                .iter()
                .any(|key| object.get(*key).is_none_or(serde_json::Value::is_null)))
    {
        return Ok(None);
    }
    #[derive(Deserialize)]
    struct Wire {
        incarnation: String,
        kind: RouteOpenTargetKind,
        spawn: Option<u64>,
        authority_epoch: Option<u64>,
        first_party: bool,
        approved_declarations_digest: Option<String>,
    }
    let wire: Wire = serde_json::from_value(value)?;
    Ok(Some(RouteOpenTarget {
        incarnation: wire.incarnation,
        kind: wire.kind,
        spawn: wire.spawn,
        authority_epoch: wire.authority_epoch,
        first_party: is_spawn && wire.first_party,
        approved_declarations_digest: wire.approved_declarations_digest,
    }))
}

fn deserialize_optional_attestation_integer<'de, D: Deserializer<'de>>(
    decoder: D,
) -> Result<Option<u64>, D::Error> {
    let value = Option::<u64>::deserialize(decoder)?;
    if value.is_some_and(|integer| integer > MAX_ATTESTATION_INTEGER) {
        return Err(D::Error::custom("attestation integer exceeds 2^53-1"));
    }
    Ok(value)
}

/// Channel-0 subscription request, framed like `activity.subscribe`. It stays
/// outside the exhaustive control enums; defining it does not advertise the op.
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
#[serde(tag = "op", rename = "catalog.watch")]
pub struct CatalogWatchRequest {}

impl CatalogWatchRequest {
    pub const OP: &'static str = ops::CATALOG_WATCH;

    pub fn new() -> Self {
        Self {}
    }
}

/// One channel-0 subscription response on the request's correlation id, with
/// RESPONSE and MORE set, like `activity.subscribe`. There is no separate ACK:
/// the first push carries the current generation, then advances may coalesce.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "op", rename = "catalog.watch")]
pub struct CatalogWatchResponse {
    pub generation: u64,
}

impl CatalogWatchResponse {
    pub const OP: &'static str = ops::CATALOG_WATCH;

    pub fn new(generation: u64) -> Self {
        Self { generation }
    }
}

impl<'de> Deserialize<'de> for CatalogWatchRequest {
    fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(tag = "op")]
        enum Wire {
            #[serde(rename = "catalog.watch")]
            Body {},
        }
        let Wire::Body {} = Wire::deserialize(decoder)?;
        Ok(Self::new())
    }
}

impl<'de> Deserialize<'de> for CatalogWatchResponse {
    fn deserialize<D: Deserializer<'de>>(decoder: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        #[serde(tag = "op")]
        enum Wire {
            #[serde(rename = "catalog.watch")]
            Body { generation: u64 },
        }
        let Wire::Body { generation } = Wire::deserialize(decoder)?;
        Ok(Self::new(generation))
    }
}

/// Daemon-originated channel-0 control push body.
///
/// A module cannot originate these pushes: subc creates them from its own
/// forwarding state and enqueues them directly to client connection sinks.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "op")]
pub enum ClientControlPush {
    #[serde(rename = "route.closing")]
    RouteClosing {
        module_id: String,
        /// Channel numbers identifying affected routes on this client's connection.
        /// Channels used by other clients or by the provider are not included.
        #[serde(default)]
        channels: Vec<u16>,
        reason: RouteCloseReason,
    },
    #[serde(rename = "route.closed")]
    RouteClosed {
        module_id: String,
        /// Channel numbers identifying affected routes on this client's connection.
        /// Channels used by other clients or by the provider are not included.
        #[serde(default)]
        channels: Vec<u16>,
        reason: RouteCloseReason,
        /// The exact result of the forwarding-quiescence wait for live routes.
        drained: bool,
        /// Pending route.bind relays forced down before that wait. They are not
        /// covered by `drained`, even when live routes quiesced.
        abandoned: u32,
        /// Subscription credits captured and excluded from this drain's wire predicate.
        #[serde(default)]
        excluded_subscriptions: u32,
        /// Whether subc will leave this module down until operator action.
        ///
        /// The claim covers daemon-owned recovery only. `None` is accepted only
        /// from daemons that predate this field; every current daemon emission is
        /// `Some`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        terminal: Option<bool>,
    },
}

/// A daemon-incarnation-scoped position in the supervised spawn event stream.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpawnCursor {
    pub daemon_incarnation: String,
    pub seq: u64,
}

/// One process present in an atomic supervisor spawn snapshot.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LiveSpawn {
    pub module_id: String,
    /// Names one launch of this module: unique and increasing per module
    /// within one daemon run (one `daemon_incarnation`). The daemon assigns it when the launch
    /// starts, before the process is running, and it is the `spawn` a caller
    /// or target attestation names. A launch that never runs keeps its number,
    /// so successive generations may skip.
    pub spawn_generation: u64,
    pub pid: u32,
    pub spawned_at_ms: u64,
}

/// Atomic live-process census and the cursor at which it was observed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpawnSnapshot {
    pub cursor: SpawnCursor,
    /// Maximum retained event count for this daemon.
    pub ring_bound: u64,
    pub live: Vec<LiveSpawn>,
}

/// Fact observed by the supervisor when a child process starts or exits.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SpawnEventKind {
    Spawned,
    Exited,
}

/// One retained or live spawn event.
///
/// Exit events intentionally carry no disposition or reason because exit
/// classification is recorded separately; credential consumers revoke on every
/// exit regardless of the cause.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SpawnEvent {
    pub cursor: SpawnCursor,
    pub kind: SpawnEventKind,
    pub module_id: String,
    /// The launch's generation; see [`LiveSpawn::spawn_generation`].
    pub spawn_generation: u64,
    pub pid: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_signal: Option<i32>,
}

/// A module's retained stderr, oldest entry first.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct StderrTail {
    pub capture: StderrCaptureState,
    pub entries: Vec<StderrTailEntry>,
    /// Lines not present above: evicted by the ring, or held back by this
    /// request's own caps.
    ///
    /// Non-zero means the first entry is not the first line the module wrote. A
    /// reader hunting a cause needs that, or an absent explanation reads as a
    /// module that never gave one.
    ///
    /// Zero is skipped so the common complete-tail case stays compact.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub dropped_lines: u64,
}

/// Live routes served by one module.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupervisorRouteModule {
    pub module_id: String,
    pub routes: Vec<SupervisorRoute>,
}

/// One live consumer route in a [`SupervisorRouteModule`].
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupervisorRoute {
    pub consumer: SupervisorRouteConsumer,
    /// Milliseconds since the daemon bound this route.
    pub age_ms: u64,
    /// True once the endpoint began draining. Draining routes remain visible so
    /// a census does not misreport an already-closing route as live.
    pub draining: bool,
    /// WHY the endpoint is draining — the same reason vocabulary the
    /// route.closing push carries — present exactly when `draining` is true.
    /// Additive: older daemons omit it, and a census consumer must treat a
    /// draining route without a reason as draining-for-an-unstated-reason,
    /// never as not-draining.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_reason: Option<RouteCloseReason>,
}

/// Source-tagged provenance for one supervised module.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupervisorModuleProvenance {
    pub module_id: String,
    pub module_declared: ModuleDeclaredProvenance,
    pub daemon_observed: SupervisorObservedProcess,
}

/// Optional entry keys kept outside the exhaustive provenance struct so older
/// construction sites and destructures remain source-compatible.
#[non_exhaustive]
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct SupervisorModuleProvenanceExt {
    /// The running spawn's registration path. Absence makes no claim about it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registration: Option<RegistrationMethod>,
    /// Durable configured channel support, including stopped and disabled modules:
    /// `declared`, `undeclared`, or `not_applicable` for protocol-none children.
    /// Absence means unknown; future strings are retained unchanged.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registration_declaration: Option<String>,
}

impl SupervisorModuleProvenanceExt {
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn with_registration(mut self, registration: Option<RegistrationMethod>) -> Self {
        self.registration = registration;
        self
    }

    /// Read from a single module entry, not the enclosing provenance reply.
    pub fn read_from(entry: &serde_json::Value) -> serde_json::Result<Self> {
        if !entry.is_object() {
            return Err(serde_json::Error::custom(
                "expected a module provenance entry object",
            ));
        }
        serde_json::from_value(entry.clone())
    }

    /// Replace companion keys in a single module entry. Absent observations
    /// remove stale keys rather than writing `null`.
    pub fn write_to(&self, entry: &mut serde_json::Value) -> serde_json::Result<()> {
        let object = entry.as_object_mut().ok_or_else(|| {
            serde_json::Error::custom("expected a module provenance entry object")
        })?;
        object.remove("registration");
        if let Some(method) = &self.registration {
            object.insert("registration".into(), serde_json::to_value(method)?);
        }
        object.remove("registration_declaration");
        if let Some(declaration) = &self.registration_declaration {
            object.insert(
                "registration_declaration".into(),
                declaration.clone().into(),
            );
        }
        Ok(())
    }
}

/// How a running supervised spawn registered. Unknown future methods confer
/// neither channel registration nor nonce registration.
#[non_exhaustive]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum RegistrationMethod {
    Channel,
    Nonce,
    #[serde(other)]
    Unknown,
}

/// Admission refused because a gated module lacks channel support. This reason
/// spends no restart budget; restarting cannot repair a missing declaration.
pub const REGISTRATION_CHANNEL_UNSUPPORTED: &str = "registration_channel_unsupported";

/// A module's declared build metadata, if its HELLO manifest carried it.
#[derive(Debug, Clone, PartialEq)]
pub enum ModuleDeclaredProvenance {
    Reported {
        build: ManifestProvenance,
    },
    Unverifiable,
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

/// Process facts observed by the daemon for a supervised module.
///
/// Build claims remain under `module_declared`; mixing them here would imply the
/// daemon independently observed module-provided metadata.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupervisorObservedProcess {
    /// The daemon's Windows delivery record for this process: `pipe` after the
    /// process whose PID was returned by spawn has read all nonce bytes; `env`
    /// when that delivery was not completed and SUBC_LAUNCH_NONCE was offered.
    /// This is returned under `daemon_observed.launch_nonce_source` by
    /// `supervisor.provenance`, and is absent when the daemon cannot report it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_nonce_source: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spawned_at_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spawned_from: Option<PathBuf>,
    pub running_image: RunningImageAgreement,
}

/// Independent comparisons of configured path, launch spec and running image at list time.
/// An absent verdict means the daemon predates this field, not agreement.
///
/// Use [`PendingReloadVerdict::new`] rather than an external struct literal:
///
/// ```compile_fail,E0639
/// use subc_control::{PendingReloadVerdict, ReloadPathAgreement, RunningImageAgreement,
///     RunningImageUnavailableReason};
/// let verdict = PendingReloadVerdict {
///     path: ReloadPathAgreement::Match,
///     image: RunningImageAgreement::Unavailable {
///         reason: RunningImageUnavailableReason::NotRunning,
///     },
///     spec: None,
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[non_exhaustive]
pub struct PendingReloadVerdict {
    pub path: ReloadPathAgreement,
    pub image: RunningImageAgreement,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spec: Option<LaunchSpecAgreement>,
}

impl PendingReloadVerdict {
    /// Create the path and image comparisons without a launch-spec verdict.
    #[must_use]
    pub fn new(path: ReloadPathAgreement, image: RunningImageAgreement) -> Self {
        Self {
            path,
            image,
            spec: None,
        }
    }

    /// Set or clear the comparison of launch specifications.
    #[must_use]
    pub fn with_spec(mut self, spec: Option<LaunchSpecAgreement>) -> Self {
        self.spec = spec;
        self
    }
}

#[cfg(test)]
mod launch_spec_wire_tests {
    use super::*;

    #[test]
    fn older_daemon_omission_is_not_reported_and_unknown_status_round_trips() {
        let old = r#"{"path":{"status":"match"},"image":{"status":"unavailable","reason":"not_running"}}"#;
        let parsed: PendingReloadVerdict = serde_json::from_str(old).unwrap();
        assert_eq!(parsed.spec, None);
        assert_eq!(serde_json::to_string(&parsed).unwrap(), old);
        let future = r#"{"status":"future_spec","detail":{"z":1,"a":2}}"#;
        let parsed: LaunchSpecAgreement = serde_json::from_str(future).unwrap();
        assert!(
            matches!(parsed, LaunchSpecAgreement::Unknown { ref tag, .. } if tag == "future_spec")
        );
        assert_eq!(serde_json::to_string(&parsed).unwrap(), future);
        let unavailable = LaunchSpecAgreement::Unavailable {
            reason: LaunchSpecUnavailableReason::SpawnedSpecUnavailable,
        };
        let encoded = serde_json::to_string(&unavailable).unwrap();
        assert_eq!(
            encoded,
            r#"{"status":"unavailable","reason":"spawned_spec_unavailable"}"#
        );
        assert_eq!(
            serde_json::from_str::<LaunchSpecAgreement>(&encoded).unwrap(),
            unavailable
        );
    }
}

/// Comparison of the configured launch inputs with the inputs recorded at spawn.
/// No digest or configured env values are sent to clients.
#[derive(Debug, Clone, PartialEq)]
pub enum LaunchSpecAgreement {
    Match,
    Mismatch,
    Unavailable {
        reason: LaunchSpecUnavailableReason,
    },
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

open_string_enum! {
    LaunchSpecUnavailableReason {
        NotRunning => "not_running",
        SpawnedSpecUnavailable => "spawned_spec_unavailable",
    }
}

/// Whether the running process was spawned from the currently configured program.
#[derive(Debug, Clone, PartialEq)]
pub enum ReloadPathAgreement {
    Match,
    Mismatch {
        configured: PathBuf,
        spawned_from: PathBuf,
    },
    Unavailable {
        reason: ReloadPathUnavailableReason,
    },
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

open_string_enum! {
    /// Why configured and spawned paths cannot be compared.
    ReloadPathUnavailableReason {
        NotRunning => "not_running",
        SpawnedPathUnavailable => "spawned_path_unavailable",
    }
}

/// Daemon provenance paired with its runtime process observation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupervisorDaemonProvenance {
    pub daemon_build: DaemonBuildProvenance,
    pub daemon_observed: DaemonObservedProcess,
}

/// Build metadata embedded in the daemon binary.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DaemonBuildProvenance {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build_git_sha: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build_lock_digest: Option<String>,
}

/// Runtime process facts observed for the daemon itself.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DaemonObservedProcess {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    /// Wall time derived from suspend-inclusive elapsed time at each read. Clock
    /// correction can move it by the size of a clock step, and even without a
    /// step it may vary by about a second between reads. Do not equality-compare
    /// it. Use raw process start ticks for stable identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at_ms: Option<u64>,
    pub running_image: RunningImageAgreement,
}

/// Whether the executable currently running agrees with the spawned image.
#[derive(Debug, Clone, PartialEq)]
pub enum RunningImageAgreement {
    Match {
        evidence: RunningImageEvidence,
    },
    Mismatch {
        running: RunningImageEvidence,
        disk: RunningImageEvidence,
    },
    Unavailable {
        reason: RunningImageUnavailableReason,
    },
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

/// Platform-specific evidence used to compare a running image with its spawn path.
#[derive(Debug, Clone, PartialEq)]
pub enum RunningImageEvidence {
    LinuxProcSha256 {
        digest: String,
    },
    MacosSpawnInode {
        device: u64,
        inode: u64,
    },
    /// The spawn-time Windows file object, not verified executable content.
    WindowsSpawnFileId {
        volume_serial_number: u64,
        file_id: [u8; 16],
    },
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

open_string_enum! {
    /// Reasons why an executable identity could not be observed.
    RunningImageUnavailableReason {
        NotRunning => "not_running",
        NotYetMeasured => "not_yet_measured",
        UnsupportedPlatform => "unsupported_platform",
        RunningExecutableUnreadable => "running_executable_unreadable",
        RunningExecutablePermissionDenied => "running_executable_permission_denied",
        ProcessHidden => "process_hidden",
        SpawnedPathUnreadable => "spawned_path_unreadable",
        HashFailed => "hash_failed",
        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
    }
}

/// The identity tier the daemon can honestly report for a route consumer.
///
/// A caller that proved a live daemon-issued launch nonce is named `reserved`.
/// A direct key-holder has no such attestation, so it is reported as `direct`
/// with its connection counter instead of an invented module name.
#[derive(Debug, Clone, PartialEq)]
pub enum SupervisorRouteConsumer {
    Reserved {
        module_id: String,
    },
    Direct {
        connection_id: u64,
    },
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

/// Whether stderr is being captured for a module, and if not, why not.
///
/// A typed state rather than an empty-tail convention. "The module printed
/// nothing before dying" and "nobody was capturing" send an operator in opposite
/// directions, and rendering them alike is the defect this op exists to fix --
/// the same shape as a `detail -` that means both no-detail and never-probed.
#[derive(Debug, Clone, PartialEq)]
pub enum StderrCaptureState {
    /// A reader is attached, or was attached and saw clean EOF. An empty
    /// `entries` under this state means the module genuinely wrote nothing.
    Captured,
    /// Retained entries are valid, but the stderr reader ended before clean EOF.
    Incomplete { reason: String },
    /// No reader was attached. `entries` says nothing about what the module wrote.
    NotCaptured { reason: String },
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

#[derive(Debug, Clone, PartialEq)]
pub enum StderrTailEntry {
    Line {
        text: String,
        /// The line was cut at the per-line cap and `text` is a prefix.
        ///
        /// Carried as a field rather than left to a marker in `text` so a
        /// consumer can branch on it without string matching.
        truncated: bool,
        /// Wall-clock Unix milliseconds at which the daemon read this line off
        /// the module's pipe. `None` from a daemon that predates the field; a
        /// reader must then show no time rather than make one up.
        at_ms: Option<u64>,
    },
    /// The supervisor spawned a new process. Entries after this came from it.
    ///
    /// In-band because position is the information: which side of the restart a
    /// line falls on is unanswerable from a count.
    ProcessStart,
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum ModuleDeclaredProvenanceWire {
    Reported { build: ManifestProvenance },
    Unverifiable,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum RunningImageAgreementWire {
    Match {
        evidence: RunningImageEvidence,
    },
    Mismatch {
        running: RunningImageEvidence,
        disk: RunningImageEvidence,
    },
    Unavailable {
        reason: RunningImageUnavailableReason,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum ReloadPathAgreementWire {
    Match,
    Mismatch {
        configured: PathBuf,
        spawned_from: PathBuf,
    },
    Unavailable {
        reason: ReloadPathUnavailableReason,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum LaunchSpecAgreementWire {
    Match,
    Mismatch,
    Unavailable { reason: LaunchSpecUnavailableReason },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "method", rename_all = "snake_case")]
enum RunningImageEvidenceWire {
    LinuxProcSha256 {
        digest: String,
    },
    MacosSpawnInode {
        device: u64,
        inode: u64,
    },
    WindowsSpawnFileId {
        volume_serial_number: u64,
        file_id: [u8; 16],
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum SupervisorRouteConsumerWire {
    Reserved { module_id: String },
    Direct { connection_id: u64 },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
enum StderrCaptureStateWire {
    Captured,
    Incomplete { reason: String },
    NotCaptured { reason: String },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status", rename_all = "snake_case")]
enum ChildResourceUsageWire {
    Measured(ChildResourceReading),
    Unavailable {
        reason: ChildResourceUnavailableReason,
    },
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum StderrTailEntryWire {
    Line {
        text: String,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        truncated: bool,
        // Omitted when absent so a reply without it is byte-identical to what
        // an older daemon sends. Older decoders ignore the member when present.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        at_ms: Option<u64>,
    },
    ProcessStart,
}

/// JSON values whose object members retain wire order at every depth.
#[derive(Debug, Clone, PartialEq)]
pub enum OrderedJsonValue {
    Null,
    Bool(bool),
    Number(serde_json::Number),
    String(String),
    Array(Vec<Self>),
    Object(OrderedJsonObject),
}

/// Ordered JSON members retained for an unknown tagged value.
#[derive(Debug, Clone, PartialEq)]
pub struct OrderedJsonObject(Vec<(String, OrderedJsonValue)>);

impl OrderedJsonObject {
    /// Returns the members in the order they appeared on the wire.
    pub fn as_entries(&self) -> &[(String, OrderedJsonValue)] {
        &self.0
    }

    fn into_value(self) -> serde_json::Value {
        serde_json::Value::Object(
            self.0
                .into_iter()
                .map(|(key, value)| (key, value.into_value()))
                .collect(),
        )
    }
}

impl OrderedJsonValue {
    fn into_value(self) -> serde_json::Value {
        match self {
            Self::Null => serde_json::Value::Null,
            Self::Bool(value) => serde_json::Value::Bool(value),
            Self::Number(value) => serde_json::Value::Number(value),
            Self::String(value) => serde_json::Value::String(value),
            Self::Array(values) => {
                serde_json::Value::Array(values.into_iter().map(Self::into_value).collect())
            }
            Self::Object(value) => value.into_value(),
        }
    }
}

impl Serialize for OrderedJsonValue {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Null => serializer.serialize_unit(),
            Self::Bool(value) => serializer.serialize_bool(*value),
            Self::Number(value) => value.serialize(serializer),
            Self::String(value) => serializer.serialize_str(value),
            Self::Array(values) => values.serialize(serializer),
            Self::Object(value) => value.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for OrderedJsonValue {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OrderedValueVisitor;

        impl<'de> Visitor<'de> for OrderedValueVisitor {
            type Value = OrderedJsonValue;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("a JSON value with ordered object members")
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::Null)
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::Null)
            }

            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
            where
                D: Deserializer<'de>,
            {
                OrderedJsonValue::deserialize(deserializer)
            }

            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::Bool(value))
            }

            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::Number(value.into()))
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::Number(value.into()))
            }

            fn visit_f64<E>(self, value: f64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                serde_json::Number::from_f64(value)
                    .map(OrderedJsonValue::Number)
                    .ok_or_else(|| E::custom("non-finite JSON number"))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::String(value.to_owned()))
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(OrderedJsonValue::String(value))
            }

            fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut values = Vec::new();
                while let Some(value) = sequence.next_element()? {
                    values.push(value);
                }
                Ok(OrderedJsonValue::Array(values))
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut entries = Vec::new();
                while let Some((key, value)) = map.next_entry()? {
                    entries.push((key, value));
                }
                Ok(OrderedJsonValue::Object(OrderedJsonObject(entries)))
            }
        }

        deserializer.deserialize_any(OrderedValueVisitor)
    }
}

impl Serialize for OrderedJsonObject {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut map = serializer.serialize_map(Some(self.0.len()))?;
        for (key, value) in &self.0 {
            map.serialize_entry(key, value)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for OrderedJsonObject {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct OrderedObjectVisitor;

        impl<'de> Visitor<'de> for OrderedObjectVisitor {
            type Value = OrderedJsonObject;

            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str("an object with ordered JSON members")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut entries = Vec::new();
                while let Some((key, value)) = map.next_entry()? {
                    entries.push((key, value));
                }
                Ok(OrderedJsonObject(entries))
            }
        }

        deserializer.deserialize_map(OrderedObjectVisitor)
    }
}

fn read_tagged<'de, D>(
    deserializer: D,
    field: &'static str,
) -> Result<(String, OrderedJsonObject), D::Error>
where
    D: Deserializer<'de>,
{
    let body = OrderedJsonObject::deserialize(deserializer)?;
    let mut tag = None;
    for (key, value) in body.as_entries() {
        if key != field {
            continue;
        }
        if tag.is_some() {
            return Err(D::Error::custom(format!(
                "tagged object has duplicate `{field}` field"
            )));
        }
        let OrderedJsonValue::String(value) = value else {
            return Err(D::Error::custom(format!(
                "tagged object has no string `{field}` field"
            )));
        };
        tag = Some(value);
    }
    let Some(tag) = tag else {
        return Err(D::Error::custom(format!(
            "tagged object has no string `{field}` field"
        )));
    };
    Ok((tag.to_string(), body))
}

fn read_ordered_tagged(
    value: OrderedJsonValue,
    field: &'static str,
) -> Result<(String, OrderedJsonObject), String> {
    let OrderedJsonValue::Object(body) = value else {
        return Err(format!("expected tagged object with `{field}` field"));
    };
    let mut tag = None;
    for (key, value) in body.as_entries() {
        if key != field {
            continue;
        }
        if tag.is_some() {
            return Err(format!("tagged object has duplicate `{field}` field"));
        }
        let OrderedJsonValue::String(value) = value else {
            return Err(format!("tagged object has no string `{field}` field"));
        };
        tag = Some(value);
    }
    let Some(tag) = tag else {
        return Err(format!("tagged object has no string `{field}` field"));
    };
    Ok((tag.to_string(), body))
}

fn ordered_field<'a>(body: &'a OrderedJsonObject, field: &str) -> Option<&'a OrderedJsonValue> {
    body.as_entries()
        .iter()
        .find_map(|(key, value)| (key == field).then_some(value))
}

fn ordered_string(body: &OrderedJsonObject, field: &str) -> Result<String, String> {
    match ordered_field(body, field) {
        Some(OrderedJsonValue::String(value)) => Ok(value.clone()),
        Some(_) => Err(format!("tagged object field `{field}` is not a string")),
        None => Err(format!("tagged object has no `{field}` field")),
    }
}

fn decode_running_image_evidence(value: OrderedJsonValue) -> Result<RunningImageEvidence, String> {
    let (tag, body) = read_ordered_tagged(value, "method")?;
    match tag.as_str() {
        "linux_proc_sha256" => Ok(RunningImageEvidence::LinuxProcSha256 {
            digest: ordered_string(&body, "digest")?,
        }),
        "macos_spawn_inode" => {
            let device = ordered_field(&body, "device")
                .and_then(|value| match value {
                    OrderedJsonValue::Number(number) => number.as_u64(),
                    _ => None,
                })
                .ok_or_else(|| "tagged object has no unsigned `device` field".to_string())?;
            let inode = ordered_field(&body, "inode")
                .and_then(|value| match value {
                    OrderedJsonValue::Number(number) => number.as_u64(),
                    _ => None,
                })
                .ok_or_else(|| "tagged object has no unsigned `inode` field".to_string())?;
            Ok(RunningImageEvidence::MacosSpawnInode { device, inode })
        }
        "windows_spawn_file_id" => {
            let wire: RunningImageEvidenceWire = serde_json::from_value(
                serde_json::to_value(&body).map_err(|error| error.to_string())?,
            )
            .map_err(|error| error.to_string())?;
            match wire {
                RunningImageEvidenceWire::WindowsSpawnFileId {
                    volume_serial_number,
                    file_id,
                } => Ok(RunningImageEvidence::WindowsSpawnFileId {
                    volume_serial_number,
                    file_id,
                }),
                _ => unreachable!(),
            }
        }
        _ => Ok(RunningImageEvidence::Unknown { tag, body }),
    }
}

impl Serialize for ModuleDeclaredProvenance {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Reported { build } => ModuleDeclaredProvenanceWire::Reported {
                build: build.clone(),
            }
            .serialize(serializer),
            Self::Unverifiable => ModuleDeclaredProvenanceWire::Unverifiable.serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for ModuleDeclaredProvenance {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let (tag, value) = read_tagged(deserializer, "status")?;
        match tag.as_str() {
            "reported" => match serde_json::from_value(value.into_value())
                .map_err(D::Error::custom)?
            {
                ModuleDeclaredProvenanceWire::Reported { build } => Ok(Self::Reported { build }),
                ModuleDeclaredProvenanceWire::Unverifiable => unreachable!(),
            },
            "unverifiable" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    ModuleDeclaredProvenanceWire::Unverifiable => Ok(Self::Unverifiable),
                    ModuleDeclaredProvenanceWire::Reported { .. } => unreachable!(),
                }
            }
            _ => Ok(Self::Unknown { tag, body: value }),
        }
    }
}

impl Serialize for RunningImageAgreement {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Match { evidence } => RunningImageAgreementWire::Match {
                evidence: evidence.clone(),
            }
            .serialize(serializer),
            Self::Mismatch { running, disk } => RunningImageAgreementWire::Mismatch {
                running: running.clone(),
                disk: disk.clone(),
            }
            .serialize(serializer),
            Self::Unavailable { reason } => RunningImageAgreementWire::Unavailable {
                reason: reason.clone(),
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl Serialize for ReloadPathAgreement {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Match => ReloadPathAgreementWire::Match.serialize(serializer),
            Self::Mismatch {
                configured,
                spawned_from,
            } => ReloadPathAgreementWire::Mismatch {
                configured: configured.clone(),
                spawned_from: spawned_from.clone(),
            }
            .serialize(serializer),
            Self::Unavailable { reason } => ReloadPathAgreementWire::Unavailable {
                reason: reason.clone(),
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl Serialize for LaunchSpecAgreement {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Match => LaunchSpecAgreementWire::Match.serialize(serializer),
            Self::Mismatch => LaunchSpecAgreementWire::Mismatch.serialize(serializer),
            Self::Unavailable { reason } => LaunchSpecAgreementWire::Unavailable {
                reason: reason.clone(),
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for LaunchSpecAgreement {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let (tag, body) = read_tagged(deserializer, "status")?;
        match tag.as_str() {
            "match" => Ok(Self::Match),
            "mismatch" => Ok(Self::Mismatch),
            "unavailable" => match serde_json::from_value(body.into_value())
                .map_err(D::Error::custom)?
            {
                LaunchSpecAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
                _ => unreachable!(),
            },
            _ => Ok(Self::Unknown { tag, body }),
        }
    }
}

impl<'de> Deserialize<'de> for ReloadPathAgreement {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let (tag, body) = read_tagged(deserializer, "status")?;
        match tag.as_str() {
            "match" => Ok(Self::Match),
            "mismatch" => {
                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
                    ReloadPathAgreementWire::Mismatch {
                        configured,
                        spawned_from,
                    } => Ok(Self::Mismatch {
                        configured,
                        spawned_from,
                    }),
                    _ => unreachable!(),
                }
            }
            "unavailable" => match serde_json::from_value(body.into_value())
                .map_err(D::Error::custom)?
            {
                ReloadPathAgreementWire::Unavailable { reason } => Ok(Self::Unavailable { reason }),
                _ => unreachable!(),
            },
            _ => Ok(Self::Unknown { tag, body }),
        }
    }
}

impl<'de> Deserialize<'de> for RunningImageAgreement {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let (tag, value) = read_tagged(deserializer, "status")?;
        match tag.as_str() {
            "match" => Ok(Self::Match {
                evidence: decode_running_image_evidence(
                    ordered_field(&value, "evidence")
                        .cloned()
                        .ok_or_else(|| D::Error::custom("tagged object has no `evidence` field"))?,
                )
                .map_err(D::Error::custom)?,
            }),
            "mismatch" => Ok(Self::Mismatch {
                running: decode_running_image_evidence(
                    ordered_field(&value, "running")
                        .cloned()
                        .ok_or_else(|| D::Error::custom("tagged object has no `running` field"))?,
                )
                .map_err(D::Error::custom)?,
                disk: decode_running_image_evidence(
                    ordered_field(&value, "disk")
                        .cloned()
                        .ok_or_else(|| D::Error::custom("tagged object has no `disk` field"))?,
                )
                .map_err(D::Error::custom)?,
            }),
            "unavailable" => Ok(Self::Unavailable {
                reason: serde_json::from_value(
                    ordered_field(&value, "reason")
                        .cloned()
                        .ok_or_else(|| D::Error::custom("tagged object has no `reason` field"))?
                        .into_value(),
                )
                .map_err(D::Error::custom)?,
            }),
            _ => Ok(Self::Unknown { tag, body: value }),
        }
    }
}

impl Serialize for ChildResourceUsage {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Measured(reading) => {
                ChildResourceUsageWire::Measured(reading.clone()).serialize(serializer)
            }
            Self::Unavailable { reason } => ChildResourceUsageWire::Unavailable {
                reason: reason.clone(),
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for ChildResourceUsage {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let (tag, body) = read_tagged(deserializer, "status")?;
        match tag.as_str() {
            "measured" | "unavailable" => {
                match serde_json::from_value(body.into_value()).map_err(D::Error::custom)? {
                    ChildResourceUsageWire::Measured(reading) => Ok(Self::Measured(reading)),
                    ChildResourceUsageWire::Unavailable { reason } => {
                        Ok(Self::Unavailable { reason })
                    }
                }
            }
            _ => Ok(Self::Unknown { tag, body }),
        }
    }
}

impl Serialize for RunningImageEvidence {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::LinuxProcSha256 { digest } => RunningImageEvidenceWire::LinuxProcSha256 {
                digest: digest.clone(),
            }
            .serialize(serializer),
            Self::MacosSpawnInode { device, inode } => RunningImageEvidenceWire::MacosSpawnInode {
                device: *device,
                inode: *inode,
            }
            .serialize(serializer),
            Self::WindowsSpawnFileId {
                volume_serial_number,
                file_id,
            } => RunningImageEvidenceWire::WindowsSpawnFileId {
                volume_serial_number: *volume_serial_number,
                file_id: *file_id,
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for RunningImageEvidence {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let (tag, value) = read_tagged(deserializer, "method")?;
        match tag.as_str() {
            "linux_proc_sha256" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    RunningImageEvidenceWire::LinuxProcSha256 { digest } => {
                        Ok(Self::LinuxProcSha256 { digest })
                    }
                    _ => unreachable!(),
                }
            }
            "macos_spawn_inode" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    RunningImageEvidenceWire::MacosSpawnInode { device, inode } => {
                        Ok(Self::MacosSpawnInode { device, inode })
                    }
                    _ => unreachable!(),
                }
            }
            "windows_spawn_file_id" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    RunningImageEvidenceWire::WindowsSpawnFileId {
                        volume_serial_number,
                        file_id,
                    } => Ok(Self::WindowsSpawnFileId {
                        volume_serial_number,
                        file_id,
                    }),
                    _ => unreachable!(),
                }
            }
            _ => Ok(Self::Unknown { tag, body: value }),
        }
    }
}

impl Serialize for SupervisorRouteConsumer {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Reserved { module_id } => SupervisorRouteConsumerWire::Reserved {
                module_id: module_id.clone(),
            }
            .serialize(serializer),
            Self::Direct { connection_id } => SupervisorRouteConsumerWire::Direct {
                connection_id: *connection_id,
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for SupervisorRouteConsumer {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let (tag, value) = read_tagged(deserializer, "kind")?;
        match tag.as_str() {
            "reserved" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    SupervisorRouteConsumerWire::Reserved { module_id } => {
                        Ok(Self::Reserved { module_id })
                    }
                    _ => unreachable!(),
                }
            }
            "direct" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    SupervisorRouteConsumerWire::Direct { connection_id } => {
                        Ok(Self::Direct { connection_id })
                    }
                    _ => unreachable!(),
                }
            }
            _ => Ok(Self::Unknown { tag, body: value }),
        }
    }
}

impl Serialize for StderrCaptureState {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Captured => StderrCaptureStateWire::Captured.serialize(serializer),
            Self::Incomplete { reason } => StderrCaptureStateWire::Incomplete {
                reason: reason.clone(),
            }
            .serialize(serializer),
            Self::NotCaptured { reason } => StderrCaptureStateWire::NotCaptured {
                reason: reason.clone(),
            }
            .serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for StderrCaptureState {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let (tag, value) = read_tagged(deserializer, "state")?;
        match tag.as_str() {
            "captured" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    StderrCaptureStateWire::Captured => Ok(Self::Captured),
                    _ => unreachable!(),
                }
            }
            "incomplete" => match serde_json::from_value(value.into_value())
                .map_err(D::Error::custom)?
            {
                StderrCaptureStateWire::Incomplete { reason } => Ok(Self::Incomplete { reason }),
                _ => unreachable!(),
            },
            "not_captured" => match serde_json::from_value(value.into_value())
                .map_err(D::Error::custom)?
            {
                StderrCaptureStateWire::NotCaptured { reason } => Ok(Self::NotCaptured { reason }),
                _ => unreachable!(),
            },
            _ => Ok(Self::Unknown { tag, body: value }),
        }
    }
}

impl Serialize for StderrTailEntry {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Line {
                text,
                truncated,
                at_ms,
            } => StderrTailEntryWire::Line {
                text: text.clone(),
                truncated: *truncated,
                at_ms: *at_ms,
            }
            .serialize(serializer),
            Self::ProcessStart => StderrTailEntryWire::ProcessStart.serialize(serializer),
            Self::Unknown { body, .. } => body.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for StderrTailEntry {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let (tag, value) = read_tagged(deserializer, "kind")?;
        match tag.as_str() {
            "line" => match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                StderrTailEntryWire::Line {
                    text,
                    truncated,
                    at_ms,
                } => Ok(Self::Line {
                    text,
                    truncated,
                    at_ms,
                }),
                _ => unreachable!(),
            },
            "process_start" => {
                match serde_json::from_value(value.into_value()).map_err(D::Error::custom)? {
                    StderrTailEntryWire::ProcessStart => Ok(Self::ProcessStart),
                    _ => unreachable!(),
                }
            }
            _ => Ok(Self::Unknown { tag, body: value }),
        }
    }
}

fn is_zero_u64(value: &u64) -> bool {
    *value == 0
}

fn default_true() -> bool {
    true
}

/// Bounded terminal history for one module, oldest retained record first.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TerminalHistory {
    /// Unix milliseconds at the current daemon's start; entries may predate it.
    pub daemon_started_at_ms: u64,
    pub entries: Vec<TerminalEntry>,
    /// Exits evicted by the current daemon's ring, possibly recovered from its
    /// journal. Not a count of missing exits: expired journal totals are unknown.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub dropped: u64,
    /// Unparseable or incomplete lines across the shared journal, including
    /// lines whose module cannot be determined. Zero on older daemons.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub journal_skipped_lines: u64,
    /// Files that could not be read completely, excluding absent generations.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub journal_read_errors: u64,
    /// Failed journal appends across all modules in the current daemon.
    #[serde(default, skip_serializing_if = "is_zero_u64")]
    pub journal_write_failures: u64,
}

/// One terminal child exit and the supervisor action it selected.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct TerminalEntry {
    /// Opaque identity of the daemon that observed this exit; absent on older
    /// daemons. Different tokens mean different lifetimes, not chronological order.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub daemon_incarnation: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_code: Option<i32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_signal: Option<i32>,
    pub at_ms: u64,
    pub disposition: TerminalDisposition,
    /// Supervisor classification of this exit. Absent on daemons that predate
    /// the field; unknown future kinds remain readable instead of failing the
    /// enclosing terminal record.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub exit_kind: Option<TerminalExitKind>,
    /// Why the supervisor chose this disposition, when the disposition alone
    /// does not say. A `failed` record carries the exhausted crash budget here
    /// (`crash budget exhausted: max_restarts=3 within window_secs=600`), which
    /// is the difference between an operator seeing "it failed" and seeing which
    /// limit stopped it. Prose for humans: render it, never parse it. Absent for
    /// ordinary dispositions and on daemons predating the field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disposition_detail: Option<String>,
}

/// Exit classification carried by supervisor history and census records.
///
/// This is an open string enum so future daemon variants degrade to a readable
/// unknown kind rather than making a consumer discard the enclosing record.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TerminalExitKind {
    Clean,
    Crash,
    DeliberateSeverance,
    Unknown(String),
}

impl TerminalExitKind {
    fn wire_name(&self) -> &str {
        match self {
            Self::Clean => "clean",
            Self::Crash => "crash",
            Self::DeliberateSeverance => "deliberate_severance",
            Self::Unknown(value) => value,
        }
    }
}

impl Serialize for TerminalExitKind {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.wire_name())
    }
}

impl<'de> Deserialize<'de> for TerminalExitKind {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(match value.as_str() {
            "clean" => Self::Clean,
            "crash" => Self::Crash,
            "deliberate_severance" => Self::DeliberateSeverance,
            _ => Self::Unknown(value),
        })
    }
}

open_string_enum! {
    /// The supervisor disposition selected after observing a terminal exit.
    TerminalDisposition {
        Stopped => "stopped",
        Disabled => "disabled",
        Failed => "failed",
        Restarting => "restarting",
        /// The child exited after the daemon had begun its own announced
        /// shutdown, whatever its exit code or signal. Such an exit is not
        /// a crash and is never followed by a respawn. Readers that predate
        /// this value decode it as `Unknown("daemon_shutdown")`.
        DaemonShutdown => "daemon_shutdown",
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum PollKind {
    Status,
    Liveness,
}

/// A registered module's catalog projection.
///
/// Use [`CatalogEntry::new`] and its `with_*` methods to construct entries so
/// future fields do not require changes to callers.
/// Struct literals and functional record updates are not supported outside this crate:
///
/// ```compile_fail,E0639
/// use subc_control::CatalogEntry;
/// let entry = CatalogEntry::new("provider", vec![], vec![]);
/// let entry = CatalogEntry { ready: false, ..entry };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[non_exhaustive]
pub struct CatalogEntry {
    pub module_id: String,
    /// Module-declared human-readable name. Apps fall back to `module_id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Whether the registered module currently accepts new route binds.
    ///
    /// This is the module's EFFECTIVE readiness: its own declared readiness
    /// AND every one of its `need: required` capabilities having a registered
    /// provider. It is exactly the condition `route.open` checks, so a caller
    /// reading `false` here will be refused with `module_warming`; `not_ready`
    /// says why.
    ///
    /// Older daemons omit this field and are interpreted as ready. Daemons that
    /// predate `not_ready` report declared readiness only.
    #[serde(default = "default_true")]
    pub ready: bool,
    /// Why `ready` is false, in the same shape `route.open` puts in the
    /// `detail` of its `module_warming` refusal. Absent when the module is
    /// ready, and absent from daemons that predate the field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub not_ready: Option<NotReadyReason>,
    /// The registered module's self-declared build version, projected from its
    /// manifest so a consumer can tell WHICH BUILD of a module it is talking
    /// to at connect time.
    ///
    /// Without this, a client compiled against a module's current source reads
    /// a contract that is true of the repository and false of the running
    /// process -- the types match, the JSON decodes, and the meaning has
    /// changed. That failure carries no error to notice; the version in the
    /// catalog turns a semantic skew into a log line at connect instead of a
    /// wrong sentence on a user's screen.
    ///
    /// Optional on the wire only because entries serialized by older daemons
    /// lack it: absent means "daemon predates the field", never "module has
    /// no version" (the manifest field is required at registration).
    ///
    /// The reading is ARMED BY OBSERVATION, not by this documentation: until
    /// a consumer has seen at least one populated entry from the daemon it is
    /// connected to, an all-None catalog is indistinguishable from an old
    /// daemon, and a client shipping the documented reading against it would
    /// hold a guarantee it does not have.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub module_version: Option<String>,
    /// Build provenance mirrored from the registered module's manifest.
    /// Absent when the module did not declare it or the daemon predates the field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<ManifestProvenance>,
    pub roles: Vec<ProviderRole>,
    pub control_ops: Vec<String>,
    /// Static capability declarations from the registering module's manifest.
    ///
    /// Optional on the wire so consumers connected to a daemon that predates the
    /// capability grammar retain their existing catalog decoding behavior.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<CapabilityDeclarations>,
    /// Self-signal declarations mirrored verbatim from the registering module's
    /// manifest. The daemon relays these declarations without interpreting them.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub self_signals: Option<Vec<SelfSignalDeclaration>>,
    /// Event declarations mirrored verbatim from the registering module's manifest.
    /// Absent when the manifest omits `events`; an empty array records an affirmative
    /// declaration that the module publishes no events.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<EventDeclaration>>,
    /// Open delivery hints mirrored from the module manifest. Empty means unary;
    /// only `"watch"` on a declared management query is subscribable.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub operation_delivery: BTreeMap<String, OperationDelivery>,
    /// Raw request payload limits mirrored from the module manifest by operation
    /// name. Empty maps preserve catalog bytes from before payload declarations.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub operation_payload: BTreeMap<String, OperationPayload>,
    /// Management operations the module serves to a flow-scoped call, mirrored
    /// unchanged from its manifest. Absent means the module did not say, so a
    /// reader treats the answer as unknown rather than as "none"; an empty list
    /// admits no operation under a flow scope. Absence preserves catalog bytes
    /// from before the field. The daemon relays it and never enforces it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub flow_operations: Option<Vec<String>>,
    /// Deferred-operation declarations mirrored from the registered manifest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operation_deferral: Option<BTreeMap<String, bool>>,
    /// Management operations the module guards with `operator.confirm`,
    /// mirrored unchanged from its manifest. Absent means the module did not
    /// say (or declared an invalid list, which the daemon dropped), so a reader
    /// treats the answer as unknown. Absence preserves catalog bytes from before
    /// the field. The daemon relays it and refuses nothing on its basis.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirm_operations: Option<Vec<String>>,
    /// Rich-UI descriptor mirrored verbatim from the registering manifest.
    /// The daemon does not fetch or interpret the manifest described here.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rich_ui: Option<RichUiDescriptor>,
    /// Opaque per-role objects mirrored unchanged from the registered manifest.
    /// Each role owns its schema; the daemon validates only keys, shape and size.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
    /// True when HELLO is bound to its configured spawn through a registration
    /// channel (gated or ungated), a prefix claim, or the legacy launch-nonce
    /// check for an ungated reserved module or swap candidate. The historical
    /// field name does not imply that a channel registration presented a nonce.
    #[serde(default, skip_serializing_if = "is_false")]
    pub nonce_verified: bool,
    /// Active-spawn discovery facts, never an authorization source. Older
    /// daemons omit these fields; absence confers no first-party mark.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub incarnation: Option<String>,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_optional_attestation_integer"
    )]
    pub spawn: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_party: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<CatalogOrigin>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_declarations_digest: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approved_declarations_digest: Option<String>,
    /// Whole declaration sets appear only on a filtered catalog read. Provider
    /// objects retain unknown keys; requested entries are not approval evidence.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub approved_declarations: Option<ProviderDeclarations>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requested_declarations: Option<ProviderDeclarations>,
}

impl CatalogEntry {
    /// Sets the optional module-declared display name.
    #[must_use]
    pub fn with_display_name(mut self, display_name: Option<String>) -> Self {
        self.display_name = display_name;
        self
    }

    /// Construct an entry with its required fields and wire-compatible defaults.
    #[must_use]
    pub fn new(
        module_id: impl Into<String>,
        roles: Vec<ProviderRole>,
        control_ops: Vec<String>,
    ) -> Self {
        Self {
            module_id: module_id.into(),
            ready: default_true(),
            display_name: None,
            not_ready: None,
            module_version: None,
            provenance: None,
            roles,
            control_ops,
            capabilities: None,
            self_signals: None,
            events: None,
            operation_delivery: BTreeMap::new(),
            operation_payload: BTreeMap::new(),
            flow_operations: None,
            operation_deferral: None,
            confirm_operations: None,
            rich_ui: None,
            role_declarations: BTreeMap::new(),
            nonce_verified: false,
            incarnation: None,
            spawn: None,
            first_party: None,
            origin: None,
            requested_declarations_digest: None,
            approved_declarations_digest: None,
            approved_declarations: None,
            requested_declarations: None,
        }
    }

    /// Set raw request payload limits mirrored from the registered manifest.
    #[must_use]
    pub fn with_operation_payload(
        mut self,
        operation_payload: BTreeMap<String, OperationPayload>,
    ) -> Self {
        self.operation_payload = operation_payload;
        self
    }

    /// Set or clear the flow-scoped operation list mirrored from the registered
    /// manifest. `None` is omitted from the wire.
    #[must_use]
    pub fn with_flow_operations(mut self, flow_operations: Option<Vec<String>>) -> Self {
        self.flow_operations = flow_operations;
        self
    }

    /// Set deferred-operation declarations mirrored from the manifest.
    #[must_use]
    pub fn with_operation_deferral(mut self, operations: Option<BTreeMap<String, bool>>) -> Self {
        self.operation_deferral = operations;
        self
    }

    /// Set or clear the confirm-guarded operation list mirrored from the
    /// registered manifest. `None` is omitted from the wire.
    #[must_use]
    pub fn with_confirm_operations(mut self, confirm_operations: Option<Vec<String>>) -> Self {
        self.confirm_operations = confirm_operations;
        self
    }

    /// Set the module's effective readiness.
    #[must_use]
    pub fn with_ready(mut self, ready: bool) -> Self {
        self.ready = ready;
        self
    }

    /// Set or clear the reason the module is not ready.
    #[must_use]
    pub fn with_not_ready(mut self, not_ready: Option<NotReadyReason>) -> Self {
        self.not_ready = not_ready;
        self
    }

    /// Set or clear the module's self-declared version.
    #[must_use]
    pub fn with_module_version(mut self, module_version: Option<String>) -> Self {
        self.module_version = module_version;
        self
    }

    /// Set or clear the build provenance mirrored from the registered manifest.
    #[must_use]
    pub fn with_provenance(mut self, provenance: Option<ManifestProvenance>) -> Self {
        self.provenance = provenance;
        self
    }

    /// Set or clear the module's static capability declarations.
    #[must_use]
    pub fn with_capabilities(mut self, capabilities: Option<CapabilityDeclarations>) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Set or clear the module's self-signal declarations.
    #[must_use]
    pub fn with_self_signals(mut self, self_signals: Option<Vec<SelfSignalDeclaration>>) -> Self {
        self.self_signals = self_signals;
        self
    }

    /// Set or clear the event declarations mirrored from the module manifest.
    #[must_use]
    pub fn with_events(mut self, events: Option<Vec<EventDeclaration>>) -> Self {
        self.events = events;
        self
    }

    /// Set delivery hints mirrored from the module manifest.
    /// Serialization omits this field when the stored map is empty.
    #[must_use]
    pub fn with_operation_delivery(
        mut self,
        operation_delivery: BTreeMap<String, OperationDelivery>,
    ) -> Self {
        self.operation_delivery = operation_delivery;
        self
    }

    /// Set the descriptor mirrored from the module's HELLO manifest.
    #[must_use]
    pub fn with_rich_ui(mut self, rich_ui: Option<RichUiDescriptor>) -> Self {
        self.rich_ui = rich_ui;
        self
    }

    /// Set opaque per-role declarations mirrored from the registered manifest.
    #[must_use]
    pub fn with_role_declarations(
        mut self,
        role_declarations: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
    ) -> Self {
        self.role_declarations = role_declarations;
        self
    }

    /// Record HELLO's verified spawn or prefix binding; see `nonce_verified`.
    #[must_use]
    pub fn with_nonce_verified(mut self, nonce_verified: bool) -> Self {
        self.nonce_verified = nonce_verified;
        self
    }
}

fn is_false(value: &bool) -> bool {
    !value
}

/// Why a registered module is not accepting new route binds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct NotReadyReason {
    /// `declared_not_ready` when the module itself said it is not ready, or
    /// `required_capability_unprovided` when a capability it declares
    /// `need: required` has no registered provider. Open vocabulary: a newer
    /// daemon may add reasons.
    pub reason: String,
    /// For `required_capability_unprovided`, the lexicographically first
    /// required capability that has no registered provider.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capability: Option<String>,
}

impl NotReadyReason {
    pub const DECLARED_NOT_READY: &'static str = "declared_not_ready";
    pub const REQUIRED_CAPABILITY_UNPROVIDED: &'static str = "required_capability_unprovided";
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CapabilityRequirementStatus {
    pub consumer: String,
    pub capability: String,
    pub need: String,
    pub verdict: String,
    pub episode_seq: u64,
    pub config_satisfiable: bool,
    pub runtime_available: bool,
    pub detail: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SupervisorRescanResult {
    pub added: Vec<String>,
    pub removed: Vec<String>,
    pub changed_pending_reload: Vec<String>,
    /// Modules whose enabled flag differs between config and running state.
    ///
    /// Rescan calls `set_enabled` for these, so omitting them made the preview
    /// describe two of the three mutation classes it performs. A module changing
    /// only its enabled flag landed in no bucket at all -- not added, removed or
    /// changed, and deliberately not counted as unchanged either -- so the sole
    /// evidence was that the buckets no longer summed to the configured module
    /// count. A preview is consulted precisely when someone is being careful,
    /// which is the worst place to under-report.
    ///
    /// Empty is skipped so consumers written against the older shape keep
    /// parsing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub enabled_changes: Vec<String>,
    pub unchanged: u32,
    /// True when this reconciliation was computed but NOT applied.
    ///
    /// Carried on the result rather than left to the caller's memory of what it
    /// asked for. A preview and an execution are otherwise byte-identical, so a
    /// reader who meets this output later -- in a log, a transcript, a pasted
    /// snippet -- cannot tell which one happened. Absent when false, so existing
    /// consumers see the shape they already parse.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub preview: bool,
    /// Config sections that changed but which rescan CANNOT apply, so the
    /// operator learns a daemon restart is required from the command they just
    /// ran rather than from the journal.
    ///
    /// The daemon has always detected this and logged a warning. A warning in a
    /// log is addressed to whoever is reading the log, and the person who just
    /// edited the config is by construction looking at the CLI instead: reported
    /// by an outside contributor after a module crash-looped through four
    /// respawns because a new top-level `storage` section was silently not
    /// applied, diagnosable only by journal archaeology.
    ///
    /// Names the SECTIONS rather than a boolean, because "something else
    /// changed" sends the operator back to diffing their own file -- which is
    /// the work the message exists to save.
    ///
    /// Empty is skipped, so consumers written against the older shape keep
    /// parsing.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub restart_required: Vec<String>,
    /// Required capabilities that a dry-run's resulting module set would leave
    /// unprovided. Rows are human-readable because the preview is an operator
    /// explanation, not a second manifest schema.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capability_warnings: Vec<String>,
    /// What applying the previewed candidate would do to each module, in
    /// module id order. Filled only by a `supervisor.rescan_checked` preview;
    /// a module whose launch spec, health policy and enabled flag all stay as
    /// staged has no entry, and neither has a disabled module that is added
    /// or removed. Empty is skipped, so `supervisor.rescan` replies keep their
    /// shape.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub module_actions: Vec<RescanModuleAction>,
    /// Modules whose running process still uses launch inputs from an earlier
    /// rescan: their staged spec waits for a restart that this candidate
    /// does not cause. Filled only by a `supervisor.rescan_checked` preview.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub earlier_pending: Vec<String>,
    /// The value an apply of this preview must send. Present only on a
    /// `supervisor.rescan_checked` preview.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expect: Option<RescanExpect>,
}

/// Which wire protocol a supervised module speaks to subc, as DECLARED in
/// daemon config. Never inferred from observed behaviour.
///
/// The distinction this exists to keep is between a module that should have
/// registered and has not yet, and one that never will. A `Subc` module that has
/// not registered is a subc module that is LATE -- it may be booting, it may be
/// wedged, and the supervisor's health probing and restart escalation are the
/// right response. A `None` module is a third-party process (the NATS server is
/// the first) that subc launches, supervises, and stops, and that is all: it
/// speaks no subc wire at all, so treating its silence as a fault would restart
/// a perfectly healthy process forever.
///
/// Inferring the difference from "has not registered within N seconds" would
/// collapse exactly the two cases that must stay apart, which is why this is a
/// declaration.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ModuleProtocol {
    /// The module registers over channel 0, answers `health.check`, and can
    /// serve routes. Every module predating this field is one of these, which is
    /// why it is the default.
    #[default]
    Subc,
    /// The module speaks no subc wire. It is supervised as a process only.
    ///
    /// A clean exit (status 0) that the daemon did not request is restarted as
    /// a crash, counting against the restart budget, instead of being recorded
    /// as a stop. Such a module is usually a stock program that exits 0 on
    /// SIGTERM, so a stray outside signal would otherwise leave it down for
    /// good; a subc-wire module re-raises SIGTERM instead, so this rule is not
    /// needed for it.
    None,
}

/// A supervised module's current state and process observations.
///
/// Use [`SupervisorEntry::new`] and its `with_*` methods to construct entries so
/// future fields do not require changes to callers.
/// Struct literals and functional record updates are not supported outside this crate:
///
/// ```compile_fail,E0639
/// use subc_control::{SupervisorEntry, SupervisorHealthStatus};
/// let entry = SupervisorEntry::new("provider", "running", true, true, SupervisorHealthStatus::Unknown);
/// let entry = SupervisorEntry { resources: None, ..entry };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[non_exhaustive]
pub struct SupervisorEntry {
    /// Script content approved for the installed runner, when configured.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script: Option<ScriptModuleStatus>,
    /// A hidden previous instance blocks only this module's next spawn. This
    /// PID is not the supervised child and must not be presented as its identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub waiting_for_previous_pid: Option<u32>,
    pub module_id: String,
    pub state: String,
    /// Why admission was refused. This is an open string: readers must not
    /// match exhaustively. `registration_channel_unsupported` means the gated
    /// module lacks its support declaration, not a crash to restart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admission_refused: Option<String>,
    /// Estimated Unix milliseconds of the next retry after restart-budget
    /// exhaustion. Recomputed from the daemon's monotonic remaining delay on
    /// each read; on macOS the countdown pauses during sleep. Absent otherwise.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_retry_at_ms: Option<u64>,
    pub enabled: bool,
    /// The enabled value in the daemon's loaded configuration, not a stored
    /// drift flag. Absent when there is no configured entry or on older daemons.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub configured_enabled: Option<bool>,
    /// Whether this module is serving.
    ///
    /// For a `Subc` module: enabled, running, process alive, AND registered.
    /// For a `None` module the registration term is dropped, because a module
    /// that speaks no subc wire never registers and the daemon cannot assert
    /// more than "the process it launched is alive". READ IT WITH `protocol`:
    /// `live: true` means something weaker for a `None` module, and a renderer
    /// that prints it as a bare boolean for one is claiming more than the daemon
    /// knows.
    pub live: bool,
    /// The module's declared wire protocol. Absent on daemons predating the
    /// field, where every module was a subc module, so the default is exactly
    /// what those daemons meant.
    #[serde(default)]
    pub protocol: ModuleProtocol,
    /// Retained for one release for older status consumers: false on Unix, true
    /// on Windows. Non-wire modules receive no nonce on either platform.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_nonce_env: Option<bool>,
    /// The daemon's Windows per-spawn delivery result: `pipe` after the spawned
    /// process read all bytes, otherwise `env` for the offered environment copy.
    /// Returned in `supervisor.list`, independently of the source the module
    /// declares in `manifest.provenance.launch_nonce_source` when registering.
    /// Processes that do not speak the wire protocol and stopped modules omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launch_nonce_source: Option<String>,
    pub health: SupervisorHealthStatus,
    /// Computed from the stored launch spec and observed process at list time;
    /// None means an older daemon did not report this comparison.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending_reload: Option<PendingReloadVerdict>,
    /// When the daemon last collected this module's health, as unix
    /// milliseconds. Absent means NEVER PROBED (a module inside its first probe
    /// window, whose `health` is therefore `Unknown` rather than good), not
    /// probed-long-ago. An old value and an absent one call for opposite
    /// readings, so do not render them alike.
    #[serde(default)]
    pub last_probe_ms: Option<u64>,
    /// Exit code of the module's most recent process exit, if the process has
    /// exited at least once. Survives respawn so a now-`running` module still
    /// reports what killed its previous incarnation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_exit_code: Option<i32>,
    /// Terminating signal of the module's most recent process exit (Unix), if
    /// any. `Some(9)` = SIGKILL (OOM/jetsam/kill-on-drop), `Some(6)` = SIGABRT
    /// (often a panic-abort). Survives respawn.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_exit_signal: Option<i32>,
    /// Unix milliseconds when the most recent child exit was observed. Present
    /// even when the terminal ring is not queried, so existing list readers can
    /// order their latest observed exit against events they already received.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_exit_ms: Option<u64>,
    /// Classification of the most recent child exit. Absent on daemons that
    /// predate exit-kind reporting.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_exit_kind: Option<TerminalExitKind>,
    /// Replacement processes spawned for this module so far, against the budget
    /// that disables it.
    ///
    /// THIS IS THE COUNTER THAT ENDS A MODULE, and it is not the one beside it.
    /// `SupervisorHealthEntry::consecutive_failures` returns to zero on any
    /// successful probe, so a module can miss probes all day and read zero; this
    /// one only decreases when an operator restarts, reloads, or re-enables the
    /// module. Reaching the budget moves it to `Failed` and it stays there until
    /// somebody intervenes.
    ///
    /// So a module one restart from being disabled is indistinguishable from a
    /// freshly booted one unless this pair is read. Both are reported together
    /// because the count alone does not say how close it is.
    ///
    /// Absent from daemons predating the field, which is why it is optional
    /// rather than defaulted to zero: zero would assert a full budget.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_count: Option<u32>,
    /// Replacement processes this module is allowed before it is disabled. See
    /// `restart_count`; absent on daemons predating the field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_restarts: Option<u32>,
    /// Replacement processes spawned over this module's entire supervisor lifetime.
    /// Unlike `restart_count`, this value is never reset by an operator action.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lifetime_restarts: Option<u32>,
    /// Successful child spawns in this daemon incarnation. Zero means the
    /// module has not successfully spawned; every successful spawn increments
    /// the value exactly once.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub spawn_generation: Option<u64>,
    /// The span `restart_count` is counted over, in seconds. The crash budget is
    /// a RATE, not a lifetime total: `restart_count` counts only the restarts
    /// inside the last `restart_window_secs`, and older ones no longer hold a
    /// slot. Without this field a reader cannot tell "2 of 3 crashes, ever" from
    /// "2 of 3 crashes in the last ten minutes", and those two call for opposite
    /// reactions.
    ///
    /// Absent on daemons predating the windowed budget, where the count really
    /// was a lifetime total.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_window_secs: Option<u64>,
    /// Effective drain budget for this module, in milliseconds. This is the
    /// resolved policy the running supervisor uses, not a config-file reread.
    /// Absent on older daemons.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drain_timeout_ms: Option<u64>,
    /// Effective base delay before a crash restart, in milliseconds. Absent on
    /// older daemons.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_backoff_ms: Option<u64>,
    /// Effective maximum delay before a crash restart, in milliseconds. Absent
    /// on older daemons.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restart_max_backoff_ms: Option<u64>,
    /// Memory and cumulative CPU time of the module's process, read when this
    /// list was answered. Report only: the daemon keeps no history and acts on
    /// none of it.
    ///
    /// It describes the one process the supervisor spawned (its `pid`), not
    /// processes that one has started in turn, so a module that forks workers
    /// reports only its own share.
    ///
    /// Absent means the daemon predates the field. A daemon that has the field
    /// but could not read the process (not running, unsupported platform, read
    /// failed) says so with `Unavailable` and a reason, so neither case can be
    /// mistaken for a process using nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resources: Option<ChildResourceUsage>,
    /// Cumulative CPU and current memory including child processes, when known.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tree: Option<TreeReading>,
    /// Why this reporting daemon has no tree reading for this response.
    /// `not_yet_measured` means this launch has no measurement; `unreadable`
    /// and `launch_changed` can accompany a retained, older tree. `not_running`
    /// marks a stopped module. Future reasons remain valid open-set strings.
    /// Absence alone does not establish tree support.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tree_unavailable: Option<String>,
    /// CPU used across the wall-clock interval covered by retained samples.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cpu_last_hour: Option<CpuLastHour>,
}

impl SupervisorEntry {
    #[must_use]
    pub fn with_script(mut self, script: Option<ScriptModuleStatus>) -> Self {
        self.script = script;
        self
    }
    /// Set the estimated time of a failed module's next automatic retry.
    #[must_use]
    pub fn with_next_retry_at_ms(mut self, next_retry_at_ms: Option<u64>) -> Self {
        self.next_retry_at_ms = next_retry_at_ms;
        self
    }

    /// Construct an entry with its required fields and wire-compatible defaults.
    #[must_use]
    pub fn new(
        module_id: impl Into<String>,
        state: impl Into<String>,
        enabled: bool,
        live: bool,
        health: SupervisorHealthStatus,
    ) -> Self {
        Self {
            module_id: module_id.into(),
            script: None,
            state: state.into(),
            admission_refused: None,
            next_retry_at_ms: None,
            waiting_for_previous_pid: None,
            enabled,
            configured_enabled: None,
            live,
            protocol: ModuleProtocol::default(),
            launch_nonce_env: None,
            launch_nonce_source: None,
            health,
            pending_reload: None,
            last_probe_ms: None,
            last_exit_code: None,
            last_exit_signal: None,
            last_exit_ms: None,
            last_exit_kind: None,
            restart_count: None,
            max_restarts: None,
            lifetime_restarts: None,
            spawn_generation: None,
            restart_window_secs: None,
            drain_timeout_ms: None,
            restart_backoff_ms: None,
            restart_max_backoff_ms: None,
            resources: None,
            tree: None,
            tree_unavailable: None,
            cpu_last_hour: None,
        }
    }

    /// Set or clear the daemon's admission refusal reason.
    #[must_use]
    pub fn with_admission_refused(mut self, reason: Option<String>) -> Self {
        self.admission_refused = reason;
        self
    }

    /// Set the module's declared wire protocol.
    #[must_use]
    pub fn with_protocol(mut self, protocol: ModuleProtocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// Attach the enabled value from the daemon's loaded configuration.
    #[must_use]
    pub fn with_configured_enabled(mut self, configured_enabled: Option<bool>) -> Self {
        self.configured_enabled = configured_enabled;
        self
    }

    /// Set or clear the launch nonce environment indicator.
    #[must_use]
    pub fn with_launch_nonce_env(mut self, launch_nonce_env: Option<bool>) -> Self {
        self.launch_nonce_env = launch_nonce_env;
        self
    }

    pub fn with_launch_nonce_source(mut self, source: Option<String>) -> Self {
        self.launch_nonce_source = source;
        self
    }

    #[must_use]
    pub fn with_waiting_for_previous_pid(mut self, pid: Option<u32>) -> Self {
        self.waiting_for_previous_pid = pid;
        self
    }

    /// Set or clear the comparison between the launch spec and observed process.
    #[must_use]
    pub fn with_pending_reload(mut self, pending_reload: Option<PendingReloadVerdict>) -> Self {
        self.pending_reload = pending_reload;
        self
    }

    /// Set or clear the last health collection timestamp.
    #[must_use]
    pub fn with_last_probe_ms(mut self, last_probe_ms: Option<u64>) -> Self {
        self.last_probe_ms = last_probe_ms;
        self
    }

    /// Set or clear the most recent process exit code.
    #[must_use]
    pub fn with_last_exit_code(mut self, last_exit_code: Option<i32>) -> Self {
        self.last_exit_code = last_exit_code;
        self
    }

    /// Set or clear the most recent process exit signal.
    #[must_use]
    pub fn with_last_exit_signal(mut self, last_exit_signal: Option<i32>) -> Self {
        self.last_exit_signal = last_exit_signal;
        self
    }

    /// Set or clear the most recent process exit timestamp.
    #[must_use]
    pub fn with_last_exit_ms(mut self, last_exit_ms: Option<u64>) -> Self {
        self.last_exit_ms = last_exit_ms;
        self
    }

    /// Set or clear the most recent process exit classification.
    #[must_use]
    pub fn with_last_exit_kind(mut self, last_exit_kind: Option<TerminalExitKind>) -> Self {
        self.last_exit_kind = last_exit_kind;
        self
    }

    /// Set or clear the restart count for the current crash budget.
    #[must_use]
    pub fn with_restart_count(mut self, restart_count: Option<u32>) -> Self {
        self.restart_count = restart_count;
        self
    }

    /// Set or clear the maximum restarts allowed by the crash budget.
    #[must_use]
    pub fn with_max_restarts(mut self, max_restarts: Option<u32>) -> Self {
        self.max_restarts = max_restarts;
        self
    }

    /// Set or clear the lifetime restart count.
    #[must_use]
    pub fn with_lifetime_restarts(mut self, lifetime_restarts: Option<u32>) -> Self {
        self.lifetime_restarts = lifetime_restarts;
        self
    }

    /// Set or clear the successful spawn count for this daemon incarnation.
    #[must_use]
    pub fn with_spawn_generation(mut self, spawn_generation: Option<u64>) -> Self {
        self.spawn_generation = spawn_generation;
        self
    }

    /// Set or clear the time window of the crash budget.
    #[must_use]
    pub fn with_restart_window_secs(mut self, restart_window_secs: Option<u64>) -> Self {
        self.restart_window_secs = restart_window_secs;
        self
    }

    /// Set or clear the effective drain budget in milliseconds.
    #[must_use]
    pub fn with_drain_timeout_ms(mut self, drain_timeout_ms: Option<u64>) -> Self {
        self.drain_timeout_ms = drain_timeout_ms;
        self
    }

    /// Set or clear the effective base restart delay in milliseconds.
    #[must_use]
    pub fn with_restart_backoff_ms(mut self, restart_backoff_ms: Option<u64>) -> Self {
        self.restart_backoff_ms = restart_backoff_ms;
        self
    }

    /// Set or clear the effective maximum restart delay in milliseconds.
    #[must_use]
    pub fn with_restart_max_backoff_ms(mut self, restart_max_backoff_ms: Option<u64>) -> Self {
        self.restart_max_backoff_ms = restart_max_backoff_ms;
        self
    }

    /// Set or clear the observed resource usage of the supervised process.
    #[must_use]
    pub fn with_resources(mut self, resources: Option<ChildResourceUsage>) -> Self {
        self.resources = resources;
        self
    }

    /// Attach a report-only reading covering the module's process container.
    #[must_use]
    pub fn with_tree(mut self, tree: Option<TreeReading>) -> Self {
        self.tree = tree;
        self
    }

    /// Explain an absent tree reading without manufacturing numeric counters.
    #[must_use]
    pub fn with_tree_unavailable(mut self, reason: Option<String>) -> Self {
        self.tree_unavailable = reason;
        self
    }
}

/// Content identity is separate from the runner executable's identity.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ScriptModuleStatus {
    pub runtime: String,
    pub bun_version: Option<String>,
    pub path: PathBuf,
    pub sha256: Option<String>,
    pub size: Option<u64>,
    pub needs_review: bool,
}

#[cfg(test)]
mod script_status_tests {
    use super::*;

    #[test]
    fn script_status_roundtrips_and_old_supervisor_entries_remain_readable() {
        let old = SupervisorEntry::new(
            "example",
            "running",
            true,
            true,
            SupervisorHealthStatus::Unknown,
        );
        let value = serde_json::to_value(&old).unwrap();
        assert!(value.get("script").is_none());
        assert!(serde_json::from_value::<SupervisorEntry>(value)
            .unwrap()
            .script
            .is_none());
        let current = old.with_script(Some(ScriptModuleStatus {
            runtime: "bun".into(),
            bun_version: None,
            path: "bundle.js".into(),
            sha256: Some("ab".repeat(32)),
            size: Some(3),
            needs_review: true,
        }));
        let decoded: SupervisorEntry =
            serde_json::from_slice(&serde_json::to_vec(&current).unwrap()).unwrap();
        assert_eq!(decoded, current);
    }
}

/// A module process's memory and CPU time as read at list time, or why none
/// could be read.
#[derive(Debug, Clone, PartialEq)]
pub enum ChildResourceUsage {
    Measured(ChildResourceReading),
    Unavailable {
        reason: ChildResourceUnavailableReason,
    },
    /// Future discriminator. `body` retains the complete ordered object; `tag`
    /// is its decoded discriminator projection.
    Unknown {
        tag: String,
        body: OrderedJsonObject,
    },
}

/// One reading of a module process's memory and CPU time.
/// Use [`ChildResourceReading::new`] and its builders so future fields stay additive.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChildResourceReading {
    /// Memory in bytes, measured as `memory_kind` says. The figures differ
    /// by platform and are not comparable across kinds.
    pub memory_bytes: u64,
    pub memory_kind: ChildMemoryKind,
    /// Bytes swapped out, where the platform reports it per process (Linux).
    /// Absent means not reported, not zero.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub swap_bytes: Option<u64>,
    /// CPU time spent in user mode since the process started, in
    /// milliseconds. Cumulative, not a rate: a percentage needs two readings
    /// and the elapsed time between them.
    pub cpu_user_ms: u64,
    /// CPU time spent in the kernel on the process's behalf since it started,
    /// in milliseconds.
    pub cpu_system_ms: u64,
}

impl ChildResourceReading {
    /// Create a process reading without optional swap accounting.
    #[must_use]
    pub fn new(
        memory_bytes: u64,
        memory_kind: ChildMemoryKind,
        cpu_user_ms: u64,
        cpu_system_ms: u64,
    ) -> Self {
        Self {
            memory_bytes,
            memory_kind,
            cpu_user_ms,
            cpu_system_ms,
            swap_bytes: None,
        }
    }

    /// Set or clear swap bytes where the platform can measure them.
    #[must_use]
    pub fn with_swap_bytes(mut self, swap_bytes: Option<u64>) -> Self {
        self.swap_bytes = swap_bytes;
        self
    }
}

open_string_enum! {
    /// What `ChildResourceReading::memory_bytes` measures.
    ChildMemoryKind {
        /// macOS `phys_footprint`: memory the kernel charges to the process,
        /// the figure jetsam acts on. Unlike resident size it does not count
        /// pages an allocator has already released with `MADV_FREE`.
        PhysFootprint => "phys_footprint",
        /// Linux `VmRSS`: pages resident in RAM, shared file-backed pages
        /// included and swapped-out pages excluded.
        ResidentSet => "resident_set",
        /// Windows `WorkingSetSize`: resident pageable memory, including shared
        /// pages, not Unix RSS or private committed bytes.
        WindowsWorkingSet => "windows_working_set",
    }
}

open_string_enum! {
    /// Why a module process's resources could not be read.
    ChildResourceUnavailableReason {
        /// The module has no running process.
        NotRunning => "not_running",
        /// The daemon's platform has no per-process source.
        UnsupportedPlatform => "unsupported_platform",
        /// The process could not be read, typically because it exited while
        /// the list was being answered.
        Unreadable => "unreadable",
        /// The pid no longer names the process the supervisor spawned, so a
        /// reading would describe some other process.
        ProcessIdentityUnconfirmed => "process_identity_unconfirmed",
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SupervisorHealthStatus {
    Ok,
    Degraded,
    Failing,
    Unresponsive,
    Unknown,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SupervisorHealthEntry {
    pub module_id: String,
    pub status: SupervisorHealthStatus,
    /// The module's own human-readable note on its state. Absent means the
    /// module said nothing, which is the ordinary shape for a healthy module and
    /// is NOT a claim that nothing is wrong. Never parse it: it is prose the
    /// module may reword freely, and `status` plus `metrics` are the machine
    /// surface.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
    /// The module's own metrics object, relayed opaquely. Absent means the module
    /// published none on this probe — either it reports no metrics at all, or the
    /// probe did not reach it — so absence cannot distinguish "nothing to report"
    /// from "nobody asked". Read `last_probe_ms` to tell those apart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metrics: Option<serde_json::Value>,
    pub consecutive_failures: u32,
    /// Number of recurring health replies received after their daemon deadline.
    /// Each increment is evidence that the module remained alive despite a miss.
    #[serde(default)]
    pub late_answer_count: u64,
    /// End-to-end latency of the newest late reply, measured from probe start.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_late_answer_latency_ms: Option<u64>,
    /// The escalation the supervisor last took for this module (report, restart,
    /// alert). Absent means NO ACTION HAS EVER BEEN TAKEN, not that the last one
    /// succeeded — a module that has never misbehaved and one whose action record
    /// predates a daemon restart both present as absent.
    #[serde(default)]
    pub last_action: Option<String>,
    /// When `last_action` was taken, as unix milliseconds. Absent exactly when
    /// `last_action` is absent; the pair moves together.
    #[serde(default)]
    pub last_action_ms: Option<u64>,
    /// When the daemon last collected this entry, as unix milliseconds.
    ///
    /// `supervisor.health` answers from the supervisor's STORED record rather
    /// than probing, so every field above describes some moment in the past and
    /// nothing here said which. That matters most right after a restart, where
    /// the surface is used to confirm a deploy: a record collected before the
    /// restart reports the OLD process, reads as a failed deploy, and invites a
    /// redeploy of something that was already correct.
    ///
    /// `None` means never probed — distinct from probed-long-ago, and the reader
    /// must not collapse them. Absent on modules that advertise no health
    /// capability, which is why it is optional rather than defaulted to zero.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_probe_ms: Option<u64>,
}

#[cfg(test)]
mod tests {
    #[test]
    fn configured_enabled_omission_preserves_exact_old_list_bytes() {
        let entry = r#"{"module_id":"provider","state":"running","enabled":true,"live":true,"protocol":"subc","health":"unknown","last_probe_ms":null}"#;
        let decoded: SupervisorEntry = serde_json::from_str(entry).unwrap();
        assert_eq!(decoded.configured_enabled, None);
        assert_eq!(serde_json::to_string(&decoded).unwrap(), entry);
    }

    #[test]
    fn configured_enabled_values_round_trip_in_list() {
        for enabled in [false, true] {
            let entry = SupervisorEntry::new(
                "provider",
                "running",
                true,
                true,
                SupervisorHealthStatus::Unknown,
            )
            .with_configured_enabled(Some(enabled));
            let entry_json = serde_json::to_value(&entry).unwrap();
            assert_eq!(entry_json["configured_enabled"], enabled);
            assert_eq!(
                serde_json::from_value::<SupervisorEntry>(entry_json).unwrap(),
                entry
            );
        }
    }

    #[test]
    fn windows_running_image_evidence_round_trips_all_sixteen_id_bytes() {
        let evidence = super::RunningImageEvidence::WindowsSpawnFileId {
            volume_serial_number: u64::MAX,
            file_id: [
                0, 1, 2, 3, 4, 5, 6, 7, 128, 129, 130, 131, 252, 253, 254, 255,
            ],
        };
        let agreement = super::RunningImageAgreement::Match { evidence };
        let encoded = serde_json::to_string(&agreement).unwrap();
        assert!(encoded.contains("windows_spawn_file_id"));
        assert_eq!(
            serde_json::from_str::<super::RunningImageAgreement>(&encoded).unwrap(),
            agreement
        );
    }

    #[test]
    fn unix_running_image_evidence_keeps_original_wire_bytes() {
        assert_eq!(
            serde_json::to_string(&super::RunningImageEvidence::MacosSpawnInode {
                device: 7,
                inode: 11
            })
            .unwrap(),
            "{\"method\":\"macos_spawn_inode\",\"device\":7,\"inode\":11}"
        );
        assert_eq!(
            serde_json::to_string(&super::RunningImageEvidence::LinuxProcSha256 {
                digest: "abc".to_owned()
            })
            .unwrap(),
            "{\"method\":\"linux_proc_sha256\",\"digest\":\"abc\"}"
        );
    }
    use super::*;
    use subc_protocol::{BindIdentity, RouteTarget};

    #[test]
    fn legacy_terminal_decoder_ignores_deliberate_severance_kind() {
        let entry = TerminalEntry {
            daemon_incarnation: Some("daemon-before-restart".into()),
            exit_code: Some(1),
            exit_signal: None,
            at_ms: 1_700_000_000_123,
            disposition: TerminalDisposition::Restarting,
            exit_kind: Some(TerminalExitKind::DeliberateSeverance),
            disposition_detail: None,
        };
        let wire = serde_json::to_string(&entry).expect("terminal entry serializes");
        assert_eq!(
            serde_json::from_str::<serde_json::Value>(&wire).expect("terminal entry is JSON")
                ["exit_kind"],
            "deliberate_severance"
        );

        #[derive(serde::Deserialize)]
        struct LegacyTerminalEntry {
            exit_code: Option<i32>,
            exit_signal: Option<i32>,
            at_ms: u64,
            disposition: TerminalDisposition,
        }

        let decoded: LegacyTerminalEntry =
            serde_json::from_str(&wire).expect("legacy decoder keeps the terminal record");
        assert_eq!(decoded.exit_code, Some(1));
        assert_eq!(decoded.exit_signal, None);
        assert_eq!(decoded.at_ms, 1_700_000_000_123);
        assert_eq!(decoded.disposition, TerminalDisposition::Restarting);

        let future_wire = wire.replace("deliberate_severance", "future_exit_kind");
        let future: TerminalEntry =
            serde_json::from_str(&future_wire).expect("new decoder keeps a future terminal kind");
        assert_eq!(
            future.exit_kind,
            Some(TerminalExitKind::Unknown("future_exit_kind".to_string()))
        );
    }

    #[test]
    fn terminal_incarnation_is_optional_for_older_daemons() {
        let entry: TerminalEntry = serde_json::from_value(serde_json::json!({
            "at_ms": 123,
            "disposition": "stopped"
        }))
        .unwrap();
        let encoded = serde_json::to_value(&entry).unwrap();
        assert_eq!(
            (entry.daemon_incarnation, encoded.get("daemon_incarnation")),
            (None, None)
        );
    }

    #[test]
    fn route_poll_uses_kind_field() {
        let body = serde_json::to_value(ClientControlRequest::RoutePoll {
            route_channel: 7,
            route_epoch: 11,
            kind: PollKind::Status,
        })
        .unwrap();

        assert_eq!(body["op"], "route.poll");
        assert_eq!(body["route_epoch"], 11);
        assert_eq!(body["kind"], "status");
        assert!(body.get("op").is_some());
    }

    #[test]
    fn route_open_is_internally_tagged() {
        let request = ClientControlRequest::RouteOpen {
            busy_refusals: None,
            target: RouteTarget::ToolProvider {
                module_id: "aft".to_string(),
            },
            identity: BindIdentity::new("opencode", "session-1"),
            consumer_identity: None,
            consumer_capabilities: None,
            role_versions: None,
            admission_facts: None,
            scope: None,
        };

        let body = serde_json::to_value(request).unwrap();
        assert_eq!(body["op"], "route.open");
        assert_eq!(body["target"]["kind"], "tool_provider");
        assert!(body.get("consumer_identity").is_none());
        assert!(body.get("consumer_capabilities").is_none());
        assert!(body.get("role_versions").is_none());
    }

    #[test]
    fn route_open_without_optional_fields_still_decodes() {
        let body = serde_json::json!({
            "op": "route.open",
            "target": { "kind": "tool_provider", "module_id": "aft" },
            "identity": {
                "project_root": "/tmp/project",
                "harness": "opencode",
                "session": "session-1"
            }
        });

        let decoded: ClientControlRequest = serde_json::from_value(body).unwrap();
        let ClientControlRequest::RouteOpen {
            consumer_identity,
            consumer_capabilities,
            role_versions,
            admission_facts,
            ..
        } = decoded
        else {
            panic!("decoded wrong request variant");
        };
        assert_eq!(consumer_identity, None);
        assert_eq!(consumer_capabilities, None);
        assert_eq!(role_versions, None);
        assert_eq!(admission_facts, None);
    }

    #[test]
    fn new_route_closed_decoder_defaults_fields_absent_from_old_daemon() {
        let old_wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0}"#;
        let decoded: ClientControlPush = serde_json::from_str(old_wire).unwrap();
        match decoded {
            ClientControlPush::RouteClosed {
                excluded_subscriptions,
                terminal,
                ..
            } => {
                assert_eq!(excluded_subscriptions, 0);
                assert_eq!(terminal, None);
            }
            other => panic!("unexpected push: {other:?}"),
        }
        assert!(!serde_json::to_string(&decoded)
            .unwrap()
            .contains("terminal"));
    }

    #[test]
    fn old_route_closed_decoder_ignores_new_terminal_field() {
        #[derive(serde::Deserialize)]
        #[serde(tag = "op")]
        enum LegacyClientControlPush {
            #[serde(rename = "route.closed")]
            RouteClosed {
                module_id: String,
                reason: RouteCloseReason,
                drained: bool,
                abandoned: u32,
            },
        }

        let wire = r#"{"op":"route.closed","module_id":"aft-tools","reason":"crash","drained":false,"abandoned":0,"excluded_subscriptions":3,"terminal":true}"#;
        let decoded: LegacyClientControlPush = serde_json::from_str(wire).unwrap();
        match decoded {
            LegacyClientControlPush::RouteClosed {
                module_id,
                reason,
                drained,
                abandoned,
            } => {
                assert_eq!(module_id, "aft-tools");
                assert_eq!(reason, RouteCloseReason::Crash);
                assert!(!drained);
                assert_eq!(abandoned, 0);
            }
        }
    }

    #[test]
    fn supervisor_routes_is_a_control_plane_request() {
        let body = serde_json::json!({
            "op": "supervisor.routes",
            "module_id": "aft"
        });

        let request: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
        assert_eq!(serde_json::to_value(request).unwrap(), body);
    }

    #[test]
    fn diagnostic_string_enums_retain_unknown_wire_values() {
        let reason: RunningImageUnavailableReason =
            serde_json::from_str("\"future_reason\"").unwrap();
        let disposition: TerminalDisposition =
            serde_json::from_str("\"future_disposition\"").unwrap();

        assert_eq!(
            reason,
            RunningImageUnavailableReason::Unknown("future_reason".to_string())
        );
        assert_eq!(
            disposition,
            TerminalDisposition::Unknown("future_disposition".to_string())
        );
    }

    #[test]
    fn diagnostic_string_enums_preserve_existing_wire_names() {
        let names = [
            (RunningImageUnavailableReason::NotRunning, "not_running"),
            (
                RunningImageUnavailableReason::UnsupportedPlatform,
                "unsupported_platform",
            ),
            (
                RunningImageUnavailableReason::RunningExecutableUnreadable,
                "running_executable_unreadable",
            ),
            (
                RunningImageUnavailableReason::RunningExecutablePermissionDenied,
                "running_executable_permission_denied",
            ),
            (
                RunningImageUnavailableReason::ProcessHidden,
                "process_hidden",
            ),
            (
                RunningImageUnavailableReason::SpawnedPathUnreadable,
                "spawned_path_unreadable",
            ),
            (RunningImageUnavailableReason::HashFailed, "hash_failed"),
            (
                RunningImageUnavailableReason::ProcessIdentityUnconfirmed,
                "process_identity_unconfirmed",
            ),
        ];
        for (value, expected) in names {
            let wire = serde_json::to_string(&value).unwrap();
            assert_eq!(wire, format!("\"{expected}\""));
            let decoded: RunningImageUnavailableReason = serde_json::from_str(&wire).unwrap();
            assert_eq!(decoded, value);
        }

        for (value, expected) in [
            (TerminalDisposition::Stopped, "stopped"),
            (TerminalDisposition::Disabled, "disabled"),
            (TerminalDisposition::Failed, "failed"),
            (TerminalDisposition::Restarting, "restarting"),
            (TerminalDisposition::DaemonShutdown, "daemon_shutdown"),
        ] {
            let wire = serde_json::to_string(&value).unwrap();
            assert_eq!(wire, format!("\"{expected}\""));
            let decoded: TerminalDisposition = serde_json::from_str(&wire).unwrap();
            assert_eq!(decoded, value);
        }
    }

    #[test]
    fn supervisor_waiting_previous_pid_is_optional_and_round_trips() {
        let entry = SupervisorEntry::new(
            "waiting-module",
            "starting",
            true,
            false,
            SupervisorHealthStatus::Unknown,
        );
        let old_wire = serde_json::to_value(&entry).unwrap();
        assert!(old_wire.get("waiting_for_previous_pid").is_none());
        let decoded: SupervisorEntry = serde_json::from_value(old_wire).unwrap();
        assert_eq!(decoded.waiting_for_previous_pid, None);
        let entry = entry.with_waiting_for_previous_pid(Some(42));
        let wire = serde_json::to_value(&entry).unwrap();
        assert_eq!(wire["waiting_for_previous_pid"], 42);
        let decoded: SupervisorEntry = serde_json::from_value(wire).unwrap();
        assert_eq!(decoded.waiting_for_previous_pid, Some(42));
    }

    #[test]
    fn diagnostic_string_enums_reject_non_string_bodies() {
        assert!(serde_json::from_str::<RunningImageUnavailableReason>("42").is_err());
        assert!(serde_json::from_str::<TerminalDisposition>("{\"value\":\"failed\"}").is_err());
    }

    #[test]
    fn unknown_provenance_reason_does_not_discard_healthy_siblings() {
        let body = serde_json::json!({
            "op": "supervisor.provenance",
            "daemon": {
                "daemon_build": {},
                "daemon_observed": {
                    "running_image": {
                        "status": "unavailable",
                        "reason": "not_running"
                    }
                }
            },
            "modules": [
                {
                    "module_id": "future",
                    "module_declared": { "status": "unverifiable" },
                    "daemon_observed": {
                        "running_image": {
                            "status": "unavailable",
                            "reason": "future_reason"
                        }
                    }
                },
                {
                    "module_id": "healthy-a",
                    "module_declared": { "status": "unverifiable" },
                    "daemon_observed": {
                        "running_image": {
                            "status": "match",
                            "evidence": {
                                "method": "linux_proc_sha256",
                                "digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
                            }
                        }
                    }
                },
                {
                    "module_id": "healthy-b",
                    "module_declared": { "status": "unverifiable" },
                    "daemon_observed": {
                        "running_image": {
                            "status": "unavailable",
                            "reason": "unsupported_platform"
                        }
                    }
                }
            ]
        });

        let decoded: ClientControlResponse = serde_json::from_value(body).unwrap();
        let ClientControlResponse::SupervisorProvenance { modules, .. } = decoded else {
            panic!("decoded wrong response variant");
        };
        assert_eq!(modules.len(), 3);
        assert_eq!(modules[0].module_id, "future");
        assert_eq!(
            modules[0].daemon_observed.running_image,
            RunningImageAgreement::Unavailable {
                reason: RunningImageUnavailableReason::Unknown("future_reason".to_string())
            }
        );
        assert_eq!(modules[1].module_id, "healthy-a");
        assert_eq!(modules[2].module_id, "healthy-b");
    }

    #[test]
    fn tagged_unknown_values_retain_tag_and_body() {
        macro_rules! assert_unknown_round_trip {
            ($ty:ident, $field:literal, $value:expr) => {
                let value = $value;
                let wire = serde_json::to_string(&value).unwrap();
                let decoded: $ty = serde_json::from_str(&wire).unwrap();
                match decoded {
                    $ty::Unknown { tag, body } => {
                        assert_eq!(tag, value[$field].as_str().unwrap());
                        assert_eq!(serde_json::to_value(&body).unwrap(), value);
                    }
                    _ => panic!("decoded known variant"),
                }
            };
        }

        assert_unknown_round_trip!(
            ModuleDeclaredProvenance,
            "status",
            serde_json::json!({"status": "future", "build": {"version": 7}})
        );
        assert_unknown_round_trip!(
            RunningImageAgreement,
            "status",
            serde_json::json!({"status": "future", "evidence": {"digest": "abc"}})
        );
        assert_unknown_round_trip!(
            RunningImageEvidence,
            "method",
            serde_json::json!({"method": "future", "digest": "abc"})
        );
        assert_unknown_round_trip!(
            SupervisorRouteConsumer,
            "kind",
            serde_json::json!({"kind": "future", "module_id": "m"})
        );
        assert_unknown_round_trip!(
            StderrCaptureState,
            "state",
            serde_json::json!({"state": "future", "reason": "because"})
        );
        assert_unknown_round_trip!(
            StderrTailEntry,
            "kind",
            serde_json::json!({"kind": "future", "text": "line"})
        );
        assert_unknown_round_trip!(
            ChildResourceUsage,
            "status",
            serde_json::json!({"status": "future", "memory_bytes": 1})
        );
    }

    #[test]
    fn child_resource_usage_round_trips_both_known_states() {
        let measured = ChildResourceUsage::Measured(ChildResourceReading {
            memory_bytes: 0,
            memory_kind: ChildMemoryKind::ResidentSet,
            swap_bytes: Some(0),
            cpu_user_ms: 0,
            cpu_system_ms: 0,
        });
        let wire = serde_json::to_value(&measured).unwrap();
        assert_eq!(
            wire,
            serde_json::json!({
                "status": "measured",
                "memory_bytes": 0,
                "memory_kind": "resident_set",
                "swap_bytes": 0,
                "cpu_user_ms": 0,
                "cpu_system_ms": 0
            })
        );
        assert_eq!(
            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
            measured
        );

        let unavailable = ChildResourceUsage::Unavailable {
            reason: ChildResourceUnavailableReason::NotRunning,
        };
        let wire = serde_json::to_value(&unavailable).unwrap();
        assert_eq!(
            wire,
            serde_json::json!({"status": "unavailable", "reason": "not_running"})
        );
        assert_eq!(
            serde_json::from_value::<ChildResourceUsage>(wire).unwrap(),
            unavailable
        );
    }

    #[test]
    fn a_stderr_line_decodes_with_and_without_its_capture_time() {
        // A current daemon stamps each line; an older one sends no `at_ms`.
        // Both must decode, and the absent case must stay absent rather than
        // turn into a time nobody recorded.
        let stamped: StderrTailEntry = serde_json::from_str(
            r#"{"kind":"line","text":"boom","truncated":true,"at_ms":1789801440685}"#,
        )
        .unwrap();
        assert_eq!(
            stamped,
            StderrTailEntry::Line {
                text: "boom".to_string(),
                truncated: true,
                at_ms: Some(1_789_801_440_685),
            }
        );
        let unstamped: StderrTailEntry =
            serde_json::from_str(r#"{"kind":"line","text":"boom"}"#).unwrap();
        assert_eq!(
            unstamped,
            StderrTailEntry::Line {
                text: "boom".to_string(),
                truncated: false,
                at_ms: None,
            }
        );
        // Absent stays absent on the way out, so a reply without stamps is
        // exactly what an older daemon would have sent.
        assert_eq!(
            serde_json::to_string(&unstamped).unwrap(),
            r#"{"kind":"line","text":"boom"}"#
        );
        assert_eq!(
            serde_json::to_value(&stamped).unwrap()["at_ms"],
            serde_json::json!(1_789_801_440_685u64)
        );
    }

    #[test]
    fn tagged_unknown_values_round_trip_the_original_json() {
        let wire = r#"{"kind":"future_consumer","detail":{"z":1}}"#;
        let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
    }

    #[test]
    fn tagged_unknown_values_round_trip_trailing_tag() {
        let route_wire = r#"{"detail":{"z":1},"kind":"future_consumer"}"#;
        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);

        let stderr_wire = r#"{"reason":"because","state":"future_state"}"#;
        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
    }

    #[test]
    fn tagged_unknown_values_round_trip_middle_tag() {
        let route_wire = r#"{"a":1,"kind":"future_x","b":2}"#;
        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);

        let stderr_wire = r#"{"a":1,"state":"future_state","b":2}"#;
        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
    }

    #[test]
    fn tagged_unknown_values_round_trip_deep_payload() {
        let route_wire = r#"{"a":{"n":[1,2]},"kind":"future_x","zz":"s","b":null}"#;
        let route: SupervisorRouteConsumer = serde_json::from_str(route_wire).unwrap();
        assert_eq!(serde_json::to_string(&route).unwrap(), route_wire);

        let stderr_wire = r#"{"a":{"n":[1,2]},"state":"future_state","zz":"s","b":null}"#;
        let stderr: StderrCaptureState = serde_json::from_str(stderr_wire).unwrap();
        assert_eq!(serde_json::to_string(&stderr).unwrap(), stderr_wire);
    }

    #[test]
    fn tagged_unknown_values_reject_non_object_bodies() {
        for wire in ["42", r#""future""#, "[]"] {
            assert!(serde_json::from_str::<SupervisorRouteConsumer>(wire).is_err());
            assert!(serde_json::from_str::<StderrCaptureState>(wire).is_err());
        }
    }

    #[test]
    fn duplicate_discriminators_reject_without_panicking() {
        assert_eq!(
            serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"unverifiable"}"#)
                .unwrap(),
            ModuleDeclaredProvenance::Unverifiable
        );
        match serde_json::from_str::<ModuleDeclaredProvenance>(r#"{"status":"future_thing"}"#)
            .unwrap()
        {
            ModuleDeclaredProvenance::Unknown { tag, .. } => assert_eq!(tag, "future_thing"),
            _ => panic!("future discriminator decoded as a known variant"),
        }

        let wires = [
            r#"{"status":"reported","status":"unverifiable"}"#,
            r#"{"status":"unverifiable","status":"reported"}"#,
            r#"{"status":"reported","build":{},"status":"unverifiable"}"#,
            r#"{"status":"unverifiable","build":{},"status":"reported"}"#,
        ];

        for wire in wires {
            let result =
                std::panic::catch_unwind(|| serde_json::from_str::<ModuleDeclaredProvenance>(wire));
            assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
            assert!(
                result.unwrap().is_err(),
                "duplicate discriminator decoded: {wire}"
            );
        }

        let wire = r#"{"state":"captured","state":"incomplete","reason":"x"}"#;
        let result = std::panic::catch_unwind(|| serde_json::from_str::<StderrCaptureState>(wire));
        assert!(result.is_ok(), "duplicate discriminator panicked: {wire}");
        assert!(
            result.unwrap().is_err(),
            "duplicate discriminator decoded: {wire}"
        );
    }

    #[test]
    fn nested_unknown_values_round_trip_without_normalizing_member_order() {
        let known_wire =
            r#"{"status":"match","evidence":{"method":"linux_proc_sha256","digest":"abc"}}"#;
        let known: RunningImageAgreement = serde_json::from_str(known_wire).unwrap();
        assert_eq!(serde_json::to_string(&known).unwrap(), known_wire);

        for wire in [
            r#"{"kind":"future_x","detail":{"zeta":1,"alpha":2}}"#,
            r#"{"kind":"future_x","d":{"b":{"zz":1,"aa":2}}}"#,
        ] {
            let decoded: SupervisorRouteConsumer = serde_json::from_str(wire).unwrap();
            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
        }

        for wire in [
            r#"{"status":"match","evidence":{"method":"future_probe","zz":1,"aa":2}}"#,
            r#"{"status":"match","evidence":{"method":"future_probe","d":{"zz":1,"aa":2}}}"#,
        ] {
            let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
            assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
        }

        let wire = r#"{"status":"mismatch","running":{"detail":{"z":1},"method":"future_running"},"disk":{"method":"future_disk","detail":{"z":1}}}"#;
        let decoded: RunningImageAgreement = serde_json::from_str(wire).unwrap();
        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);

        let wire = r#"{"capture":{"state":"captured"},"entries":[{"detail":{"z":1,"a":2},"kind":"future_line"},{"kind":"future_restart","meta":{"b":{"zz":1,"aa":2}}}]}"#;
        let decoded: StderrTail = serde_json::from_str(wire).unwrap();
        assert_eq!(serde_json::to_string(&decoded).unwrap(), wire);
    }

    #[test]
    fn tagged_unknown_member_does_not_discard_known_siblings() {
        let body = serde_json::json!({
            "modules": [{
                "module_id": "target",
                "routes": [
                    {"consumer": {"kind": "future_consumer", "module_id": "m", "detail": {"retry": true}}, "age_ms": 0, "draining": false},
                    {"consumer": {"kind": "direct", "connection_id": 7}, "age_ms": 0, "draining": false}
                ]
            }]
        });
        let decoded: ClientControlResponse = serde_json::from_value(
            serde_json::json!({"op": "supervisor.routes", "modules": body["modules"]}),
        )
        .unwrap();
        let ClientControlResponse::SupervisorRoutes { modules } = decoded else {
            panic!("decoded wrong response variant");
        };
        assert_eq!(modules[0].routes.len(), 2);
        assert_eq!(
            modules[0].routes[1].consumer,
            SupervisorRouteConsumer::Direct { connection_id: 7 }
        );
    }
}

#[cfg(test)]
mod launch_nonce_redaction_tests {
    use super::*;

    const NONCE: &str = "nonce-f00dfeed1234abcd";

    fn identity() -> ConsumerIdentity {
        ConsumerIdentity {
            module_id: "wernicke".to_string(),
            launch_nonce: NONCE.to_string(),
        }
    }

    #[test]
    fn consumer_identity_debug_names_the_module_and_never_the_nonce() {
        let printed = format!("{:?}", identity());
        assert!(printed.contains("wernicke"), "{printed}");
        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
    }

    #[test]
    fn route_open_request_debug_never_prints_the_nonce() {
        let request = ClientControlRequest::RouteOpen {
            busy_refusals: None,
            target: subc_protocol::RouteTarget::ToolProvider {
                module_id: "broca".to_string(),
            },
            identity: subc_protocol::BindIdentity::new("test".to_string(), "session".to_string()),
            consumer_identity: Some(identity()),
            consumer_capabilities: None,
            role_versions: None,
            admission_facts: None,
            scope: None,
        };
        let printed = format!("{request:?}");
        assert!(!printed.contains(NONCE), "launch nonce printed: {printed}");
    }
}

#[cfg(test)]
mod reader_skew_tests {
    use super::*;
    use serde_json::{json, Value};

    fn catalog() -> Value {
        json!({"module_id": "provider", "roles": [], "control_ops": []})
    }

    fn reply() -> Value {
        json!({"op": "route.open", "route_channel": 7, "route_epoch": 11})
    }

    fn target() -> Value {
        json!({
            "incarnation": "daemon", "kind": "spawn", "spawn": 17,
            "authority_epoch": 23, "first_party": true,
            "approved_declarations_digest": "approved"
        })
    }

    fn request() -> Value {
        json!({
            "op": "route.open",
            "target": {"kind": "tool_provider", "module_id": "provider"},
            "identity": {"harness": "test", "session": "session-1"}
        })
    }

    #[test]
    fn reader_skew_catalog_optional_spawn_fields_and_legacy_omission() {
        let old: CatalogEntry = serde_json::from_value(catalog()).unwrap();
        let built = CatalogEntry::new("provider", vec![], vec![]);
        assert_eq!(old, built);
        assert_eq!(old.first_party, None);
        let old_bytes = serde_json::to_value(&old).unwrap();
        let additions = json!({
            "incarnation": "daemon", "spawn": 17, "first_party": false,
            "origin": "development", "requested_declarations_digest": "requested",
            "approved_declarations_digest": "approved"
        });
        let mut body = catalog();
        for (key, value) in additions.as_object().unwrap() {
            assert!(old_bytes.get(key).is_none(), "{key}");
            body[key] = value.clone();
        }
        let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
        let encoded = serde_json::to_value(&decoded).unwrap();
        for (key, value) in additions.as_object().unwrap() {
            assert_eq!(&encoded[key], value, "{key}");
        }
        assert_eq!(decoded.first_party, Some(false));
        assert_eq!(decoded.origin, Some(CatalogOrigin::Development));
    }

    #[test]
    fn reader_skew_catalog_filtered_declarations_keep_provider_owned_keys() {
        let mut body = catalog();
        body["requested_declarations"] = json!({"provider": {"future": {"scope": ["write"]}}});
        body["approved_declarations"] = json!({"provider": {"future": {"scope": ["read"]}}});
        let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
        let encoded = serde_json::to_value(decoded).unwrap();
        for key in ["requested_declarations", "approved_declarations"] {
            assert_eq!(encoded[key], body[key]);
        }
        let unfiltered: CatalogEntry = serde_json::from_value(catalog()).unwrap();
        assert_eq!(unfiltered.approved_declarations, None);
        assert_eq!(unfiltered.requested_declarations, None);
    }

    #[test]
    fn reader_skew_catalog_unknown_origin_is_other() {
        let mut body = catalog();
        body["origin"] = json!("future-origin");
        let decoded: CatalogEntry = serde_json::from_value(body).unwrap();
        assert_eq!(decoded.origin, Some(CatalogOrigin::Other));
    }

    #[test]
    fn reader_skew_catalog_spawn_refuses_unsafe_integers() {
        let mut body = catalog();
        body["spawn"] = json!(9_007_199_254_740_991_u64);
        let decoded: CatalogEntry = serde_json::from_value(body.clone()).unwrap();
        assert_eq!(decoded.spawn, Some(9_007_199_254_740_991));
        for invalid in [
            json!(9_007_199_254_740_992_u64),
            json!(-1),
            json!(1.5),
            json!("17"),
        ] {
            body["spawn"] = invalid;
            assert!(serde_json::from_value::<CatalogEntry>(body.clone()).is_err());
        }
    }

    #[test]
    fn reader_skew_catalog_watch_request_uses_subscription_op() {
        let body = json!({"op": "catalog.watch"});
        let request: CatalogWatchRequest = serde_json::from_value(body.clone()).unwrap();
        assert_eq!(request, CatalogWatchRequest::new());
        assert_eq!(serde_json::to_value(request).unwrap(), body);
        assert_eq!(CatalogWatchRequest::OP, "catalog.watch");
        for invalid in [json!({}), json!({"op": "activity.subscribe"})] {
            assert!(serde_json::from_value::<CatalogWatchRequest>(invalid).is_err());
        }
    }

    #[test]
    fn reader_skew_catalog_watch_push_carries_generation_without_ack() {
        for generation in [0, 19, 42] {
            let body = json!({"op": "catalog.watch", "generation": generation});
            let push: CatalogWatchResponse = serde_json::from_value(body.clone()).unwrap();
            assert_eq!(push, CatalogWatchResponse::new(generation));
            assert_eq!(serde_json::to_value(push).unwrap(), body);
        }
        assert_eq!(CatalogWatchResponse::OP, "catalog.watch");
        for invalid in [
            json!({"op": "catalog.watch"}),
            json!({"op": "activity.subscribe", "generation": 1}),
        ] {
            assert!(serde_json::from_value::<CatalogWatchResponse>(invalid).is_err());
        }
    }

    #[test]
    fn reader_skew_route_open_reply_helpers_preserve_existing_decoder() {
        let mut body = reply();
        let legacy: ClientControlResponse = serde_json::from_value(body.clone()).unwrap();
        let empty = RouteOpenReplyExt::read_from(&body).unwrap();
        assert_eq!(empty, RouteOpenReplyExt::new());
        empty.write_to(&mut body).unwrap();
        assert_eq!(body, reply());
        body["target"] = target();
        let decoded = RouteOpenReplyExt::read_from(&body).unwrap();
        assert_eq!(
            decoded.target.as_ref().unwrap().kind,
            RouteOpenTargetKind::Spawn
        );
        let mut encoded = reply();
        RouteOpenReplyExt::new()
            .with_target(decoded.target)
            .write_to(&mut encoded)
            .unwrap();
        assert_eq!(encoded, body);
        assert_eq!(
            serde_json::from_value::<ClientControlResponse>(encoded.clone()).unwrap(),
            legacy
        );
        RouteOpenReplyExt::new().write_to(&mut encoded).unwrap();
        assert_eq!(encoded, reply());
    }

    #[test]
    fn reader_skew_route_open_incomplete_target_is_unmarked() {
        let mut body = reply();
        body["target"] = target();
        assert!(RouteOpenReplyExt::read_from(&body)
            .unwrap()
            .target
            .is_some());
        for key in [
            "incarnation",
            "kind",
            "spawn",
            "authority_epoch",
            "first_party",
            "approved_declarations_digest",
        ] {
            let mut incomplete = body.clone();
            incomplete["target"].as_object_mut().unwrap().remove(key);
            assert_eq!(
                RouteOpenReplyExt::read_from(&incomplete).unwrap().target,
                None,
                "{key}"
            );
        }
        body["target"] = Value::Null;
        assert_eq!(RouteOpenReplyExt::read_from(&body).unwrap().target, None);
    }

    #[test]
    fn reader_skew_route_open_non_spawn_kinds_ignore_spawn_authority() {
        for (kind, expected) in [
            ("prefix", RouteOpenTargetKind::Prefix),
            ("unsupervised", RouteOpenTargetKind::Unsupervised),
        ] {
            let mut body = reply();
            body["target"] = target();
            body["target"]["kind"] = json!(kind);
            // Spawn-only keys are not parsed, even when a future kind reuses them.
            body["target"]["spawn"] = json!("not-a-spawn");
            body["target"]["authority_epoch"] = json!(9_007_199_254_740_992_u64);
            body["target"]["approved_declarations_digest"] = json!(["not-a-digest"]);
            let ext = RouteOpenReplyExt::read_from(&body).unwrap();
            let target = ext.target.as_ref().unwrap();
            assert_eq!(target.kind, expected);
            assert_eq!(target.spawn, None);
            assert_eq!(target.authority_epoch, None);
            assert_eq!(target.approved_declarations_digest, None);
            assert!(!target.first_party);
            let mut encoded = reply();
            ext.write_to(&mut encoded).unwrap();
            for key in ["spawn", "authority_epoch", "approved_declarations_digest"] {
                assert!(encoded["target"].get(key).is_none());
            }
        }
    }

    #[test]
    fn reader_skew_route_open_unknown_kind_is_not_spawn() {
        let mut body = reply();
        body["target"] = target();
        body["target"]["kind"] = json!("future-kind");
        let ext = RouteOpenReplyExt::read_from(&body).unwrap();
        let target = ext.target.unwrap();
        assert_eq!(target.kind, RouteOpenTargetKind::Unknown);
        assert_eq!(target.spawn, None);
        assert_eq!(target.authority_epoch, None);
        assert_eq!(target.approved_declarations_digest, None);
        assert!(!target.first_party);
    }

    #[test]
    fn reader_skew_route_open_spawn_and_epoch_refuse_unsafe_integers() {
        for field in ["spawn", "authority_epoch"] {
            let mut body = reply();
            body["target"] = target();
            body["target"][field] = json!(9_007_199_254_740_991_u64);
            let ext = RouteOpenReplyExt::read_from(&body).unwrap();
            assert_eq!(
                serde_json::to_value(ext).unwrap()["target"][field],
                9_007_199_254_740_991_u64
            );
            for invalid in [
                json!(9_007_199_254_740_992_u64),
                json!(-1),
                json!(1.5),
                json!("17"),
            ] {
                body["target"][field] = invalid;
                assert!(RouteOpenReplyExt::read_from(&body).is_err(), "{field}");
                let mut incomplete = body.clone();
                incomplete["target"]
                    .as_object_mut()
                    .unwrap()
                    .remove("incarnation");
                assert!(
                    RouteOpenReplyExt::read_from(&incomplete).is_err(),
                    "{field}"
                );
            }
        }
    }

    #[test]
    fn reader_skew_route_open_request_helpers_preserve_existing_decoder() {
        let mut body = request();
        let legacy: ClientControlRequest = serde_json::from_value(body.clone()).unwrap();
        assert_eq!(
            RouteOpenRequestExt::read_from(&body).unwrap(),
            RouteOpenRequestExt::new()
        );
        RouteOpenRequestExt::new().write_to(&mut body).unwrap();
        assert_eq!(body, request());
        body["accepts_close_reasons"] = json!(["authority_changed", "future-reason"]);
        let decoded = RouteOpenRequestExt::read_from(&body).unwrap();
        assert_eq!(
            decoded.accepts_close_reasons,
            Some(vec!["authority_changed".into(), "future-reason".into()])
        );
        let mut encoded = request();
        RouteOpenRequestExt::new()
            .with_accepts_close_reasons(decoded.accepts_close_reasons)
            .write_to(&mut encoded)
            .unwrap();
        assert_eq!(encoded, body);
        assert_eq!(
            serde_json::from_value::<ClientControlRequest>(encoded.clone()).unwrap(),
            legacy
        );
        RouteOpenRequestExt::new().write_to(&mut encoded).unwrap();
        assert_eq!(encoded, request());
        assert_eq!(ROUTE_CLOSE_REASONS_CAPABILITY, "route-close-reasons/v1");
    }

    #[test]
    fn reader_skew_route_open_helpers_refuse_other_bodies() {
        for mut body in [json!({}), json!([]), json!({"op": "catalog.list"})] {
            assert!(RouteOpenRequestExt::read_from(&body).is_err());
            assert!(RouteOpenReplyExt::read_from(&body).is_err());
            assert!(RouteOpenRequestExt::new().write_to(&mut body).is_err());
            assert!(RouteOpenReplyExt::new().write_to(&mut body).is_err());
        }
    }

    #[test]
    fn reader_skew_route_open_target_constructor_validates_like_reader() {
        let spawn = RouteOpenTarget::new(
            "daemon",
            RouteOpenTargetKind::Spawn,
            Some(17),
            Some(23),
            true,
            Some("approved".into()),
        )
        .unwrap();
        assert_eq!(serde_json::to_value(spawn).unwrap(), target());
        for (spawn, epoch) in [(9_007_199_254_740_992, 23), (17, 9_007_199_254_740_992)] {
            assert!(RouteOpenTarget::new(
                "daemon",
                RouteOpenTargetKind::Spawn,
                Some(spawn),
                Some(epoch),
                true,
                Some("approved".into())
            )
            .is_err());
        }
    }
}

#[cfg(test)]
mod claim_wire_tests {
    use super::*;
    use serde_json::{json, Value};

    fn legacy_provenance() -> SupervisorModuleProvenance {
        SupervisorModuleProvenance {
            module_id: "worker".into(),
            module_declared: ModuleDeclaredProvenance::Unverifiable,
            daemon_observed: SupervisorObservedProcess {
                launch_nonce_source: None,
                pid: None,
                spawned_at_ms: None,
                spawned_from: None,
                running_image: RunningImageAgreement::Unavailable {
                    reason: RunningImageUnavailableReason::NotRunning,
                },
            },
        }
    }

    #[test]
    fn provenance_registration_companion_round_trip_preserves_legacy_entry() {
        let legacy = legacy_provenance();
        let original = serde_json::to_value(&legacy).unwrap();
        let absent = SupervisorModuleProvenanceExt::read_from(&original).unwrap();
        assert_eq!(absent.registration, None);
        let mut wire = original.clone();
        absent.write_to(&mut wire).unwrap();
        assert_eq!(wire, original);
        for (method, spelling) in [
            (RegistrationMethod::Channel, "channel"),
            (RegistrationMethod::Nonce, "nonce"),
        ] {
            let ext = SupervisorModuleProvenanceExt::new().with_registration(Some(method.clone()));
            ext.write_to(&mut wire).unwrap();
            assert_eq!(wire["registration"], spelling);
            assert_eq!(
                SupervisorModuleProvenanceExt::read_from(&wire).unwrap(),
                ext
            );
            let old_reader: SupervisorModuleProvenance =
                serde_json::from_value(wire.clone()).unwrap();
            assert_eq!(old_reader, legacy);
            assert_eq!(serde_json::to_value(old_reader).unwrap(), original);
        }
        absent.write_to(&mut wire).unwrap();
        assert_eq!(wire, original);
        for mut invalid in [Value::Null, json!([]), json!("entry")] {
            assert!(SupervisorModuleProvenanceExt::read_from(&invalid).is_err());
            assert!(absent.write_to(&mut invalid).is_err());
        }
    }

    #[test]
    fn provenance_unknown_registration_is_not_channel_or_nonce() {
        let mut wire = serde_json::to_value(legacy_provenance()).unwrap();
        wire["registration"] = json!("future_method");
        let ext = SupervisorModuleProvenanceExt::read_from(&wire).unwrap();
        assert_eq!(ext.registration, Some(RegistrationMethod::Unknown));
        assert_ne!(ext.registration, Some(RegistrationMethod::Channel));
        assert_ne!(ext.registration, Some(RegistrationMethod::Nonce));
        wire["registration"] = json!(false);
        assert!(SupervisorModuleProvenanceExt::read_from(&wire).is_err());
    }

    #[test]
    fn registration_declaration_golden_is_optional_open_and_source_compatible() {
        let original = serde_json::to_value(legacy_provenance()).unwrap();
        for declaration in ["declared", "undeclared", "not_applicable", "future_support"] {
            let mut golden = original.clone();
            golden["registration_declaration"] = json!(declaration);
            let extension = SupervisorModuleProvenanceExt::read_from(&golden).unwrap();
            assert_eq!(
                serde_json::to_value(&extension).unwrap(),
                json!({
                    "registration_declaration": declaration
                })
            );
            let mut written = original.clone();
            extension.write_to(&mut written).unwrap();
            assert_eq!(written, golden);
            assert_eq!(
                serde_json::from_value::<SupervisorModuleProvenance>(golden).unwrap(),
                legacy_provenance()
            );
            SupervisorModuleProvenanceExt::new()
                .write_to(&mut written)
                .unwrap();
            assert_eq!(written, original);
        }
    }

    #[test]
    fn admission_refusal_is_optional_and_open() {
        let entry = SupervisorEntry::new(
            "worker",
            "stopped",
            true,
            false,
            SupervisorHealthStatus::Unknown,
        );
        let original = serde_json::to_value(&entry).unwrap();
        assert!(original.get("admission_refused").is_none());
        let read: SupervisorEntry = serde_json::from_value(original.clone()).unwrap();
        assert_eq!(read.admission_refused, None);
        assert_eq!(serde_json::to_value(read).unwrap(), original);
        assert_eq!(
            REGISTRATION_CHANNEL_UNSUPPORTED,
            "registration_channel_unsupported"
        );
        for reason in [REGISTRATION_CHANNEL_UNSUPPORTED, "future_reason"] {
            let mut wire = original.clone();
            wire["admission_refused"] = json!(reason);
            let read: SupervisorEntry = serde_json::from_value(wire.clone()).unwrap();
            assert_eq!(read.admission_refused.as_deref(), Some(reason));
            assert_eq!(serde_json::to_value(read).unwrap(), wire);
            let built = entry.clone().with_admission_refused(Some(reason.into()));
            assert_eq!(serde_json::to_value(built).unwrap(), wire);
        }
    }
}