subc-control 0.15.0

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
//! 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::path::PathBuf;

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

pub use subc_protocol::RouteCloseReason;

macro_rules! open_string_enum {
    (
        $(#[$meta:meta])*
        $name:ident {
            $( $variant:ident => $wire_name:literal ),+ $(,)?
        }
    ) => {
        $(#[$meta])*
        #[derive(Debug, Clone, PartialEq, Eq)]
        pub enum $name {
            $( $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),
                })
            }
        }
    };
}

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

/// 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 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 CATALOG_LIST: &str = "catalog.list";
    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_RELOAD: &str = "supervisor.reload";
    pub const SUPERVISOR_RESCAN: &str = "supervisor.rescan";
    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";
}

/// 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 {
    #[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>>,
        /// Opaque admission facts supplied by the configured carrier module.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        admission_facts: Option<serde_json::Value>,
    },
    #[serde(rename = "route.poll")]
    RoutePoll {
        route_channel: u16,
        route_epoch: u32,
        kind: PollKind,
    },
    #[serde(rename = "supervisor.list")]
    SupervisorList {},
    #[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 — the wedge-bounce
        /// escape, where a stuck in-flight request would never settle anyway.
        /// Additive; older daemons that predate this field reject unknown
        /// fields on channel-0 requests, so senders must omit it unless asked
        /// for (the CLI only sends it when a flag is passed).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        drain_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,
    },
    /// 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 = "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>,
    },
    #[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,
    },
    #[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(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,
    },
}

/// 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,
        reason: RouteCloseReason,
    },
    #[serde(rename = "route.closed")]
    RouteClosed {
        module_id: String,
        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 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,
}

/// 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 {
    #[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,
}

/// 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>,
    #[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,
    },
    /// 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",
        UnsupportedPlatform => "unsupported_platform",
        RunningExecutableUnreadable => "running_executable_unreadable",
        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,
    },
    /// 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 = "method", rename_all = "snake_case")]
enum RunningImageEvidenceWire {
    LinuxProcSha256 { digest: String },
    MacosSpawnInode { device: u64, inode: u64 },
}

#[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 = "kind", rename_all = "snake_case")]
enum StderrTailEntryWire {
    Line {
        text: String,
        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
        truncated: bool,
    },
    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 })
        }
        _ => 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<'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 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::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!(),
                }
            }
            _ => 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 } => StderrTailEntryWire::Line {
                text: text.clone(),
                truncated: *truncated,
            }
            .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 } => Ok(Self::Line { text, truncated }),
                _ => 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",
    }
}

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

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CatalogEntry {
    pub module_id: String,
    /// Whether the registered module currently accepts new route binds.
    ///
    /// Older daemons omit this field and are interpreted as ready.
    #[serde(default = "default_true")]
    pub ready: bool,
    /// 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>,
    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>>,
}

#[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>,
}

/// 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.
    None,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SupervisorEntry {
    pub module_id: String,
    pub state: String,
    pub enabled: 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,
    pub health: SupervisorHealthStatus,
    /// 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>,
    /// 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>,
}

#[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 {
    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 {
            target: RouteTarget::ToolProvider {
                module_id: "aft".to_string(),
            },
            identity: BindIdentity::new("/tmp/project", "opencode", "session-1"),
            consumer_identity: None,
            consumer_capabilities: None,
            admission_facts: 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());
    }

    #[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,
            admission_facts,
            ..
        } = decoded
        else {
            panic!("decoded wrong request variant");
        };
        assert_eq!(consumer_identity, None);
        assert_eq!(consumer_capabilities, 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::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"),
        ] {
            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 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"})
        );
    }

    #[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 }
        );
    }
}