car-proto 0.54.0

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

pub mod approval_summary;
mod canonical;

pub use canonical::{canonical_json, canonical_sha256};

/// Wire protocol version for the daemon JSON-RPC protocol. Bump ONLY on a
/// backward-incompatible change to the request/response shapes or method
/// semantics (NOT on every release — this is independent of the package
/// semver). Client and server exchange this in the `server.handshake` RPC so
/// version drift FAILS LOUD with a clear error instead of silently
/// misbehaving or hanging.
pub const PROTOCOL_VERSION: u32 = 3;

/// Authenticated model-catalog content identity and snapshot reads.
pub const MODELS_CATALOG_IDENTITY_CAPABILITY: &str = "models.catalog-identity.v1";

/// Immutable model identity on every inference completion.
pub const INFER_MODEL_IDENTITY_CAPABILITY: &str = "infer.model-identity.v1";

/// Per-session cancellation of an active inference.
pub const INFER_CANCEL_CAPABILITY: &str = "infer.cancel.v1";

/// Relative deadline control for an active inference.
pub const INFER_DEADLINE_CAPABILITY: &str = "infer.deadline.v1";

/// Explicit bounded pagination for run list, replay, and live subscription.
pub const RUNS_PAGINATION_CAPABILITY: &str = "runs.pagination.v1";

/// Authenticated same-agent reclaim of an orphaned live run.
pub const RUNS_RESUME_CAPABILITY: &str = "runs.resume.v1";

/// Durable, authenticated cancellation of an active run.
pub const RUNS_CANCEL_CAPABILITY: &str = "runs.cancel.v1";

/// Runtime-observed state mutations returned by raw WebSocket tool callbacks.
pub const TOOLS_CALLBACK_STATE_CAPABILITY: &str = "tools.callback-state.v1";

/// Host-managed, schema-bound exact agent/tool approvals on WebSocket admission.
pub const AGENT_TOOL_OVERRIDES_CAPABILITY: &str = "permissions.agent-tool-overrides.v1";

/// In-app feedback (`feedback.compose_preview` / `submit` / `status` / `list`):
/// the consent-previewed, redacted bug-report handoff into Parslee's intake.
/// Optional — a client that does not negotiate it cannot spool reports or read
/// submission summaries on that connection (the daemon refuses with the
/// standard capability-mismatch error), mirroring every other gated surface.
pub const FEEDBACK_CAPABILITY: &str = "feedback.v1";

/// Capabilities implemented by this protocol version. Kept sorted so the
/// handshake response is deterministic across clients and platforms.
pub const SUPPORTED_CAPABILITIES: &[&str] = &[
    AGENT_TOOL_OVERRIDES_CAPABILITY,
    FEEDBACK_CAPABILITY,
    INFER_CANCEL_CAPABILITY,
    INFER_DEADLINE_CAPABILITY,
    INFER_MODEL_IDENTITY_CAPABILITY,
    MODELS_CATALOG_IDENTITY_CAPABILITY,
    RUNS_CANCEL_CAPABILITY,
    RUNS_PAGINATION_CAPABILITY,
    RUNS_RESUME_CAPABILITY,
    TOOLS_CALLBACK_STATE_CAPABILITY,
];

/// Capabilities every bundled v3 client requires from the daemon.
pub const REQUIRED_CLIENT_CAPABILITIES: &[&str] = &[
    INFER_MODEL_IDENTITY_CAPABILITY,
    MODELS_CATALOG_IDENTITY_CAPABILITY,
];

/// JSON-RPC application error returned when a handshake-gated method is called
/// before this WebSocket session has completed `server.handshake`.
///
/// `session.auth` is deliberately allowed before negotiation because an
/// auth-enabled daemon requires it as the connection's first frame.
pub const PROTOCOL_HANDSHAKE_REQUIRED_ERROR_CODE: i32 = -32005;

/// JSON-RPC application error returned when `server.handshake` receives a
/// client protocol version other than [`PROTOCOL_VERSION`].
pub const PROTOCOL_VERSION_MISMATCH_ERROR_CODE: i32 = -32006;

/// JSON-RPC application error returned when a client names an unsupported
/// mandatory capability during `server.handshake`.
pub const PROTOCOL_CAPABILITY_MISMATCH_ERROR_CODE: i32 = -32008;

/// JSON-RPC application error returned when an inference request's optimistic
/// model-catalog precondition does not match the snapshot bound by the daemon.
/// The request is rejected before any provider or local worker dispatch.
pub const CATALOG_PRECONDITION_MISMATCH_ERROR_CODE: i32 = -32009;
/// JSON-RPC application error returned when a globally reserved run id /
/// idempotency key belongs to another authenticated client.
pub const RUN_OWNERSHIP_CONFLICT_ERROR_CODE: i32 = -32010;
/// JSON-RPC application error returned when a durable run JSONL contains a
/// malformed newline-terminated record. Partial records are never returned.
pub const RUN_TRACE_CORRUPTION_ERROR_CODE: i32 = -32011;

/// Stable message prefix paired with
/// [`PROTOCOL_HANDSHAKE_REQUIRED_ERROR_CODE`]. Hosts may use the numeric code
/// for typed handling and surface this text as an actionable fallback.
pub const PROTOCOL_HANDSHAKE_REQUIRED_MESSAGE_PREFIX: &str = "protocol handshake required:";

/// Stable message prefix paired with [`PROTOCOL_VERSION_MISMATCH_ERROR_CODE`].
pub const PROTOCOL_VERSION_MISMATCH_MESSAGE_PREFIX: &str = "protocol version mismatch:";

/// Stable prefix paired with [`PROTOCOL_CAPABILITY_MISMATCH_ERROR_CODE`].
pub const PROTOCOL_CAPABILITY_MISMATCH_MESSAGE_PREFIX: &str = "protocol capability mismatch:";

/// Stable prefix paired with [`CATALOG_PRECONDITION_MISMATCH_ERROR_CODE`].
pub const CATALOG_PRECONDITION_MISMATCH_MESSAGE_PREFIX: &str = "catalog precondition mismatch:";
/// Stable prefix paired with [`RUN_OWNERSHIP_CONFLICT_ERROR_CODE`].
pub const RUN_OWNERSHIP_CONFLICT_MESSAGE_PREFIX: &str = "run ownership conflict:";
/// Stable prefix paired with [`RUN_TRACE_CORRUPTION_ERROR_CODE`].
pub const RUN_TRACE_CORRUPTION_MESSAGE_PREFIX: &str = "run trace corruption:";

/// Negotiate supported required/optional capabilities. Unsupported mandatory
/// entries are returned sorted and deduplicated; unsupported optional entries
/// are ignored. A successful result is also sorted and deduplicated.
pub fn negotiate_capabilities(
    required: &[String],
    optional: &[String],
) -> Result<Vec<String>, Vec<String>> {
    use std::collections::BTreeSet;

    let supported: BTreeSet<&str> = SUPPORTED_CAPABILITIES.iter().copied().collect();
    let missing: Vec<String> = required
        .iter()
        .filter(|capability| !supported.contains(capability.as_str()))
        .cloned()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect();
    if !missing.is_empty() {
        return Err(missing);
    }

    Ok(required
        .iter()
        .chain(optional)
        .filter(|capability| supported.contains(capability.as_str()))
        .cloned()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect())
}

/// JSON-RPC application error returned when something in FRONT of the model
/// declined the request's *content* — a managed gateway's content filter, a
/// provider's moderation layer — rather than the model answering or the call
/// crashing.
///
/// This is deliberately NOT `-32603 internal error`. A refusal is a
/// deterministic ruling on that content, not a fault, and collapsing the two
/// costs three different consumers (Parslee-ai/car#796):
///
/// - a **benchmark** can score a refusal as a refusal instead of counting it as
///   a crash — an adversarial-safety suite drives this path on purpose, and it
///   cannot measure anything if the blocked cases are indistinguishable from
///   broken ones;
/// - a **retry loop** stops instead of burning its budget re-sending a decision
///   that will never change;
/// - an **operator** can tell a content ruling from a misconfiguration.
///
/// The **numeric code is the contract.** [`CONTENT_REFUSED_MESSAGE_PREFIX`] is
/// the paired fallback for consumers that only ever see the message text.
pub const CONTENT_REFUSED_ERROR_CODE: i32 = -32007;

/// Stable message prefix paired with [`CONTENT_REFUSED_ERROR_CODE`]. Consumers
/// that only see the flattened message string (an FFI client rendering
/// `"{code} {message}"`, a log line) can match on this prefix; anything that can
/// read the JSON-RPC error object should match the code instead.
pub const CONTENT_REFUSED_MESSAGE_PREFIX: &str = "content refused:";

/// Typed terminal observation returned by `infer.cancel` and
/// `infer.deadline`. Confirmation is deliberately evidence-bearing: only an
/// exact backend acknowledgement may produce a `*_confirmed` variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum InferenceControlStatus {
    AlreadyTerminal,
    CancelledConfirmed,
    TerminationUnconfirmed,
    DeadlineExceededConfirmed,
    DeadlineExceededUnconfirmed,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct InferenceControlResponse {
    pub inference_id: String,
    pub status: InferenceControlStatus,
}

pub mod daemon;
pub use daemon::{method_accepts_host_authority, HOST_MANAGEMENT_METHODS};

/// Compute a deterministic, content-derived run id (EPIC B / B7).
///
/// `runs.start` already treats a caller-supplied `idempotency_key` as the
/// run id, so "same key → same run". This is the canonical way to *derive*
/// that key from the run's content, so two independent devices (or a
/// retried / replayed start) that issue the same logical run compute the
/// **same** id without coordinating — the prerequisite for the multi-device
/// idempotency keys and execution-lease fencing in B5.
///
/// The id is `run-<hex>` where `<hex>` is the first 32 hex chars of
/// `SHA-256(agent_id ‖ "\x1f" ‖ intent ‖ "\x1f" ‖ salt)`. `salt`
/// distinguishes otherwise-identical logical runs (e.g. a date bucket, a
/// scheduler occurrence id, or a user-supplied nonce); pass `""` when the
/// `(agent_id, intent)` pair alone identifies the run. Pure and stable
/// across builds/platforms — pass the result as `runs.start`'s
/// `idempotency_key`.
pub fn deterministic_run_id(agent_id: &str, intent: &str, salt: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(agent_id.as_bytes());
    hasher.update(b"\x1f");
    hasher.update(intent.as_bytes());
    hasher.update(b"\x1f");
    hasher.update(salt.as_bytes());
    let digest = hasher.finalize();
    let hex: String = digest.iter().take(16).map(|b| format!("{b:02x}")).collect();
    format!("run-{hex}")
}

#[cfg(test)]
mod run_id_tests {
    use super::deterministic_run_id;

    #[test]
    fn same_inputs_same_id() {
        let a = deterministic_run_id("agent-1", "summarize inbox", "2026-06-30");
        let b = deterministic_run_id("agent-1", "summarize inbox", "2026-06-30");
        assert_eq!(a, b, "deterministic: identical inputs → identical id");
        assert!(a.starts_with("run-"));
        assert_eq!(a.len(), 4 + 32);
    }

    #[test]
    fn distinct_inputs_distinct_ids() {
        let base = deterministic_run_id("agent-1", "intent", "s");
        assert_ne!(base, deterministic_run_id("agent-2", "intent", "s"));
        assert_ne!(base, deterministic_run_id("agent-1", "other", "s"));
        assert_ne!(base, deterministic_run_id("agent-1", "intent", "s2"));
    }

    #[test]
    fn no_field_separator_collision() {
        // The 0x1f separator prevents ("ab","c") colliding with ("a","bc").
        assert_ne!(
            deterministic_run_id("ab", "c", ""),
            deterministic_run_id("a", "bc", "")
        );
    }
}

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

    #[test]
    fn protocol_v3_advertises_catalog_and_inference_identity() {
        assert_eq!(PROTOCOL_VERSION, 3);
        assert!(SUPPORTED_CAPABILITIES.contains(&MODELS_CATALOG_IDENTITY_CAPABILITY));
        assert!(SUPPORTED_CAPABILITIES.contains(&INFER_MODEL_IDENTITY_CAPABILITY));
        assert!(SUPPORTED_CAPABILITIES.contains(&INFER_CANCEL_CAPABILITY));
        assert!(SUPPORTED_CAPABILITIES.contains(&INFER_DEADLINE_CAPABILITY));
        assert!(!REQUIRED_CLIENT_CAPABILITIES.contains(&INFER_CANCEL_CAPABILITY));
        assert!(!REQUIRED_CLIENT_CAPABILITIES.contains(&INFER_DEADLINE_CAPABILITY));
    }

    #[test]
    fn callback_state_is_an_optional_v3_capability() {
        assert!(SUPPORTED_CAPABILITIES.contains(&TOOLS_CALLBACK_STATE_CAPABILITY));
        assert!(!REQUIRED_CLIENT_CAPABILITIES.contains(&TOOLS_CALLBACK_STATE_CAPABILITY));
    }

    #[test]
    fn feedback_is_an_optional_v3_capability() {
        assert!(SUPPORTED_CAPABILITIES.contains(&FEEDBACK_CAPABILITY));
        assert!(!REQUIRED_CLIENT_CAPABILITIES.contains(&FEEDBACK_CAPABILITY));
    }

    #[test]
    fn exact_agent_tool_overrides_are_an_optional_v3_capability() {
        assert!(SUPPORTED_CAPABILITIES.contains(&AGENT_TOOL_OVERRIDES_CAPABILITY));
        assert!(!REQUIRED_CLIENT_CAPABILITIES.contains(&AGENT_TOOL_OVERRIDES_CAPABILITY));
    }

    #[test]
    fn run_resume_is_optional_strict_and_carries_no_caller_owner_identity() {
        assert!(SUPPORTED_CAPABILITIES.contains(&RUNS_RESUME_CAPABILITY));
        assert!(!REQUIRED_CLIENT_CAPABILITIES.contains(&RUNS_RESUME_CAPABILITY));
        let request: RunResumeRequest =
            serde_json::from_value(serde_json::json!({"run_id":"run-1"})).unwrap();
        assert_eq!(request.run_id, "run-1");
        assert_eq!(
            serde_json::to_value(&request).unwrap(),
            serde_json::json!({"run_id":"run-1"})
        );

        for caller_supplied_credential in [
            serde_json::json!({"run_id":"run-1", "agent_id":"caller-controlled"}),
            serde_json::json!({"run_id":"run-1", "client_id":"caller-controlled"}),
            serde_json::json!({"run_id":"run-1", "idempotency_key":"caller-controlled"}),
            serde_json::json!({"run_id":"run-1", "owner_token":"caller-controlled"}),
        ] {
            assert!(
                serde_json::from_value::<RunResumeRequest>(caller_supplied_credential).is_err()
            );
        }

        let response = RunResumeResponse {
            run_id: "run-1".into(),
            agent_id: "agent-1".into(),
            client_id: "client-new".into(),
            resumed_from_client_id: "client-old".into(),
        };
        assert_eq!(
            serde_json::to_value(response).unwrap(),
            serde_json::json!({
                "run_id":"run-1",
                "agent_id":"agent-1",
                "client_id":"client-new",
                "resumed_from_client_id":"client-old"
            })
        );
    }

    #[test]
    fn inference_control_statuses_have_stable_typed_wire_names() {
        let cases = [
            (InferenceControlStatus::AlreadyTerminal, "already_terminal"),
            (
                InferenceControlStatus::CancelledConfirmed,
                "cancelled_confirmed",
            ),
            (
                InferenceControlStatus::TerminationUnconfirmed,
                "termination_unconfirmed",
            ),
            (
                InferenceControlStatus::DeadlineExceededConfirmed,
                "deadline_exceeded_confirmed",
            ),
            (
                InferenceControlStatus::DeadlineExceededUnconfirmed,
                "deadline_exceeded_unconfirmed",
            ),
            (InferenceControlStatus::Unknown, "unknown"),
        ];
        for (status, expected) in cases {
            assert_eq!(serde_json::to_value(status).unwrap(), expected);
        }
    }

    #[test]
    fn unknown_mandatory_capability_fails_loud() {
        let error = negotiate_capabilities(
            &["future.mandatory.v1".to_string()],
            &[MODELS_CATALOG_IDENTITY_CAPABILITY.to_string()],
        )
        .expect_err("an unsupported mandatory capability must reject the handshake");

        assert_eq!(error, vec!["future.mandatory.v1"]);
    }

    #[test]
    fn negotiated_capabilities_are_sorted_deduplicated_and_optional_safe() {
        let negotiated = negotiate_capabilities(
            &[
                INFER_MODEL_IDENTITY_CAPABILITY.to_string(),
                MODELS_CATALOG_IDENTITY_CAPABILITY.to_string(),
                INFER_MODEL_IDENTITY_CAPABILITY.to_string(),
            ],
            &[
                "future.optional.v1".to_string(),
                MODELS_CATALOG_IDENTITY_CAPABILITY.to_string(),
            ],
        )
        .unwrap();

        assert_eq!(
            negotiated,
            vec![
                INFER_MODEL_IDENTITY_CAPABILITY.to_string(),
                MODELS_CATALOG_IDENTITY_CAPABILITY.to_string(),
            ]
        );
    }

    #[test]
    fn run_pagination_capability_is_negotiable() {
        let capability = "runs.pagination.v1".to_string();
        assert_eq!(
            negotiate_capabilities(std::slice::from_ref(&capability), &[]),
            Ok(vec![capability])
        );
    }

    #[test]
    fn run_page_requests_require_explicit_cursor_and_limit() {
        assert!(serde_json::from_value::<RunListRequest>(serde_json::json!({
            "agent_id": "agent-a"
        }))
        .is_err());
        assert!(
            serde_json::from_value::<RunGetTraceRequest>(serde_json::json!({
                "run_id": "run-a"
            }))
            .is_err()
        );
        assert!(
            serde_json::from_value::<RunSubscribeRequest>(serde_json::json!({
                "run_id": "run-a"
            }))
            .is_err()
        );
    }
}

use car_ir::ActionProposal;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;

/// Tool definition sent by client during registration.
///
/// Mirrors the caller-settable fields of `car_ir::ToolSchema` over the wire so
/// the validator, caching, and rate-limiting layers see the same values the
/// in-process engine does. `ToolSchema.source` is deliberately absent: the
/// runtime assigns `user_defined` to client registrations rather than trusting
/// a caller to claim `builtin`. New optional fields are added with serde defaults so
/// pre-v0.5.x clients (which only sent `name` / `description` /
/// `parameters`) still parse cleanly.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolDefinition {
    pub name: String,
    #[serde(default)]
    pub description: String,
    /// JSON Schema for parameters. Empty object = schemaless (legacy
    /// behavior — validator skips type checks).
    #[serde(default)]
    pub parameters: Value,
    /// JSON Schema for return value (optional).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub returns: Option<Value>,
    /// Marks the tool as safe to cache/retry.
    #[serde(default)]
    pub idempotent: bool,
    /// If set, results are cached with this TTL in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache_ttl_secs: Option<u64>,
    /// If set, rate-limited to this many calls per interval.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rate_limit: Option<ToolRateLimit>,
}

/// Mirror of `car_ir::ToolRateLimit` over the wire.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolRateLimit {
    pub max_calls: u32,
    pub interval_secs: f64,
}

// --- Client → Server requests ---

/// Initialize a session.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInitRequest {
    pub client_id: String,
    #[serde(default)]
    pub tools: Vec<ToolDefinition>,
    #[serde(default)]
    pub policies: Vec<PolicyDefinition>,
}

/// Policy definition from client.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyDefinition {
    pub name: String,
    pub rule: String, // deny_tool, deny_tool_param, require_state, etc.
    #[serde(default)]
    pub target: String,
    #[serde(default)]
    pub key: String,
    #[serde(default)]
    pub value: Value,
    #[serde(default)]
    pub pattern: String,
}

/// Submit a proposal for execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProposalSubmitRequest {
    pub proposal: ActionProposal,
}

/// Verify a proposal without executing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyRequest {
    pub proposal: ActionProposal,
    #[serde(default)]
    pub initial_state: HashMap<String, Value>,
}

// --- Server → Client callbacks ---

/// Server asks client to execute a tool.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExecuteRequest {
    pub action_id: String,
    pub tool: String,
    pub parameters: Value,
    #[serde(default)]
    pub timeout_ms: Option<u64>,
    #[serde(default)]
    pub attempt: u32,
    /// Daemon-side callback-routing id (the JSON-RPC `id` of this
    /// `tools.execute` request, e.g. `"cb-1"`), surfaced into the params so
    /// the host can key a per-call abort registry on it. When this call is
    /// reaped (the daemon's callback wait expires), the daemon emits a
    /// `tools.cancel` notification carrying the SAME `request_id` so the host
    /// kills the in-flight child instead of orphaning it (Parslee-ai/car#264).
    ///
    /// **Correlate by `request_id`, not `action_id`** — `action_id` is empty
    /// for legacy `execute()` callers and is not unique across concurrent or
    /// retried attempts. `#[serde(default)]` so pre-#264 hosts still parse the
    /// payload (they just won't get the cancel correlation key).
    #[serde(default)]
    pub request_id: String,
    /// The Runtime execution session this call belongs to, stamped by the
    /// **daemon** rather than assembled by the client (Parslee-ai/car#904).
    ///
    /// Correlation was previously the host's problem, and the conventions
    /// available for it are fragile in exactly the situation that needs them:
    /// `action_id` is client-authored and explicitly not unique across
    /// concurrent or retried attempts, and a submit-time map keyed on it
    /// inherits that. An agent keeping per-mission receipts had to thread
    /// identity through its own scheme, and the naive one (a process-global
    /// run id) lets a later mission's artifact inherit an earlier mission's
    /// receipts.
    ///
    /// The executor already had this value and threw it away — it reached
    /// `execute_with_action_in_session` as an unused `_session_id` parameter.
    /// Stamping it costs nothing and makes attribution server-side fact
    /// instead of client-side convention.
    ///
    /// `None` for callers with no session: the legacy `execute()` path, and
    /// in-process executors that never had one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
}

/// Fire-and-forget `tools.cancel` notification (Parslee-ai/car#264).
///
/// Emitted server → client when a `tools.execute` callback is reaped (the
/// daemon's per-call wait expired) so the host can abort the in-flight child
/// (e.g. a `claude -p` / `codex exec` driven by `drive_cli`) instead of leaving
/// it orphaned. A notification (no `id`, no response expected): the daemon has
/// already given up on the call and is not waiting on the host's acknowledgment.
///
/// Correlation is by `request_id` (the `tools.execute` routing id), NOT
/// `action_id` — see [`ToolExecuteRequest::request_id`].
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolCancelRequest {
    /// The reaped call's routing id — matches the `request_id` the host saw on
    /// the originating `tools.execute`.
    pub request_id: String,
    /// The originating proposal `Action.id`, for host-side logging/telemetry.
    /// May be empty (legacy `execute()` callers don't carry one).
    #[serde(default)]
    pub action_id: String,
    /// Why the call was cancelled — currently always a callback-timeout reason
    /// string. Advisory; the host should abort regardless of the reason.
    #[serde(default)]
    pub reason: String,
}

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

/// Client returns tool execution result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolExecuteResponse {
    pub action_id: String,
    #[serde(default)]
    pub output: Option<Value>,
    #[serde(default)]
    pub error: Option<String>,
    /// The callback explicitly classified this error as unrecoverable.
    ///
    /// Additive and false by default so responses from older clients retain
    /// their ordinary proposal-scoped failure behavior. This bit is execution
    /// evidence, not [`car_ir::FailureBehavior`] policy, and is never inferred
    /// from [`Self::error`] text.
    #[serde(default, skip_serializing_if = "is_false")]
    pub terminal: bool,
}

// --- Server → Client notifications ---

/// Execution event notification (streaming).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExecutionEvent {
    pub kind: String, // matches EventKind values
    #[serde(default)]
    pub action_id: Option<String>,
    #[serde(default)]
    pub proposal_id: Option<String>,
    #[serde(default)]
    pub data: HashMap<String, Value>,
}

// --- Host UI protocol ---

/// OS-host-visible agent status.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HostAgentStatus {
    Idle,
    Running,
    WaitingForApproval,
    Paused,
    Completed,
    Errored,
    Stopped,
}

/// Host-visible display hints for an agent.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct HostAgentDisplay {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub icon: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accent: Option<String>,
}

/// Agent entry visible to menu bar, tray, or terminal host clients.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostAgent {
    pub id: String,
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    pub status: HostAgentStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_task: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default)]
    pub display: HostAgentDisplay,
    pub updated_at: DateTime<Utc>,
    #[serde(default)]
    pub metadata: Value,
}

/// Request to register an agent with the OS host surface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterHostAgentRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    #[serde(default)]
    pub kind: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pid: Option<u32>,
    #[serde(default)]
    pub display: HostAgentDisplay,
    #[serde(default)]
    pub metadata: Value,
}

/// Request to update an agent's host-visible status.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetHostAgentStatusRequest {
    pub agent_id: String,
    pub status: HostAgentStatus,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub current_task: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
    #[serde(default)]
    pub payload: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum HostApprovalStatus {
    Pending,
    Resolved,
}

/// Approval request visible to the OS host surface.
///
/// `client_id` is the WS session that raised the approval. When
/// `Some(x)`, only session `x` may call `host.resolve_approval` on
/// it — added 2026-05 after a security audit found unrestricted
/// resolve let one client approve another's pending request. When
/// `None` the approval is system-raised (the high-risk-method
/// approval gate uses this so the local UI session can resolve
/// approvals raised by *other* sessions' dispatch attempts) and
/// any authenticated session may resolve it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostApprovalRequest {
    pub id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    pub action: String,
    pub details: Value,
    #[serde(default)]
    pub options: Vec<String>,
    pub status: HostApprovalStatus,
    pub created_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolved_at: Option<DateTime<Utc>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resolution: Option<String>,
}

/// Request to create an approval prompt in the host surface.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateHostApprovalRequest {
    /// The agent the approval is raised for.
    ///
    /// **Advisory from an agent-bound caller.** `host.request_approval` replaces
    /// this with the session's authenticated agent binding when the session has
    /// one, so an agent cannot attribute its request to another agent or leave
    /// it unattributed. A client with no binding — the operator surface holding
    /// the daemon-wide token — keeps what it sends, because raising an approval
    /// on an agent's behalf is exactly what those clients do.
    ///
    /// The stamped value is what the requester-vs-resolver comparison in
    /// `car_server_types::host::Resolver` reads, so its trustworthiness is the
    /// check's trustworthiness.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    pub action: String,
    #[serde(default)]
    pub details: Value,
    #[serde(default)]
    pub options: Vec<String>,
    /// When `true`, the approval is created as system-level: it has
    /// no `client_id` owner and any authenticated session may resolve
    /// it. This is the right mode for agent-requested approvals where
    /// "the user" (via CarHost or `car-host approve`) is the resolver,
    /// not the requesting agent itself. The previous default (always
    /// session-owned by the requester) locked the approval to the
    /// agent's WS connection, which broke as soon as the agent
    /// reconnected — the new session got a fresh client_id and could
    /// no longer resolve its own pending approval, AND CarHost (a
    /// different session) couldn't either.
    ///
    /// Defaults to `false` for backward compatibility: existing
    /// callers that don't set this field keep the strict per-session
    /// ownership semantics.
    #[serde(default)]
    pub system_level: bool,
}

/// Request to resolve an approval.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolveHostApprovalRequest {
    pub approval_id: String,
    pub resolution: String,
}

// --- iMessage approval-transport config surface (`messaging.*`) ---
//
// The host/local-auth-gated config channel for the iMessage approval
// transport (Unit 3). These are the ONLY allowlist/config-mutation path
// in the system; the daemon's WS handlers reject any caller that is not
// `session.is_host` or presenting the per-launch local auth token. An
// inbound iMessage carries neither, so it can never mutate config.

/// Result of `messaging.config.get` / `messaging.config.set` — the
/// current (or post-mutation) view of the transport config. The active
/// pairing code is intentionally NOT echoed here (it is surfaced only via
/// `messaging.pairing.status`, mirroring the local-UI-rooted invariant).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct MessagingConfigView {
    /// Which channel this view describes (stable string key: `"imessage"` /
    /// `"slack"`). Echoed so a per-channel round-trip can confirm WHICH channel
    /// the flags belong to. Defaults to `"imessage"` for the back-compat
    /// surface.
    #[serde(default = "default_channel_key")]
    pub channel: String,
    /// Master opt-in flag (default `false`).
    pub enabled: bool,
    /// Approver handles permitted to resolve approvals over this channel.
    pub allowlisted_handles: Vec<String>,
    /// Whether a pairing is currently in flight (a code has been minted
    /// and not yet consumed). The code value itself is not exposed here.
    pub pairing_active: bool,
}

/// Back-compat default for `MessagingConfigView::channel` — iMessage.
fn default_channel_key() -> String {
    "imessage".to_string()
}

/// Params for `messaging.config.set`. All fields optional — only the
/// supplied fields mutate (a `null`/absent field leaves that part of the
/// config unchanged). `add_handles` / `remove_handles` apply after
/// `allowlisted_handles` when both are present.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MessagingConfigSetRequest {
    /// Which channel this mutation targets (stable string key: `"imessage"` /
    /// `"slack"`). **Absent ⇒ iMessage** — back-compat for the #403 surface and
    /// bindings, which have no `channel` field. (The full FFI/doc parity for the
    /// explicit `channel` field — `.d.ts`/`.pyi`/websocket-protocol — lands in
    /// Unit 6; the server-side optional field is added here so the per-channel
    /// WS round-trip works. The wire value stays a plain string tagged by
    /// channel — no typed identity struct across FFI.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel: Option<String>,
    /// When present, set the master opt-in flag.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    /// When present, REPLACE the entire allowlist with these handles.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allowlisted_handles: Option<Vec<String>>,
    /// When present, add each handle to the allowlist (idempotent).
    #[serde(default)]
    pub add_handles: Vec<String>,
    /// When present, remove each handle from the allowlist (idempotent).
    #[serde(default)]
    pub remove_handles: Vec<String>,
    /// Slack bot token (`xoxb-`) to provision. When BOTH `bot_token` and
    /// `app_token` are present (Slack channel only), the daemon writes them to
    /// the OS keychain (MC-9) and persists only a keychain *reference* into the
    /// config — the bearer value never lands in `messaging.json` nor echoes back
    /// in the response. This is a host-gated, write-only provisioning input; an
    /// inbound message cannot reach this surface (MC-6). Absent ⇒ no token
    /// change (back-compat for the enable/allowlist-only callers).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bot_token: Option<String>,
    /// Slack app-level token (`xapp-`) to provision. See [`Self::bot_token`] —
    /// both must be present to trigger provisioning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub app_token: Option<String>,
    /// Slack post-channel id (`C0123…` / `D024…`) — the conversation the
    /// outbound approval prompt posts into (Slack channel only). Unlike the
    /// tokens this is CONFIGURATION, not a secret: the daemon persists it IN
    /// `messaging.json` (host-gated), never the keychain. Set on the same
    /// `messaging.config.set { channel: "slack", … }` call as the tokens.
    /// Absent ⇒ no post-channel change (back-compat).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub slack_channel: Option<String>,
}

/// Result of `messaging.pairing.start` — the freshly minted, high-entropy
/// pairing code to display ONLY in the local UI, plus the post-mint view.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MessagingPairingStartResponse {
    /// The minted pairing code. Shown only in local UI; the paired device
    /// texts it back to prove control of its handle.
    pub pairing_code: String,
    /// Post-mint config view (`pairing_active` is now `true`).
    pub config: MessagingConfigView,
}

/// Result of `messaging.pairing.status` — whether a pairing is in flight
/// and, when so, the active code (host/local-auth gated read only, so the
/// local UI can re-display the code after a reload).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MessagingPairingStatusResponse {
    /// Whether a pairing code is currently active.
    pub pairing_active: bool,
    /// The active pairing code, when one is in flight. Returned only over
    /// the host/local-auth-gated surface — never over any inbound channel.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pairing_code: Option<String>,
}

/// Result of `messaging.status` — the real runtime liveness of a channel's
/// approval transport, computed daemon-side (U2). The host UI renders a SINGLE
/// readiness state from this object rather than re-deriving "is it on" from
/// scattered permission widgets (the scatter that produced the confusing pane).
///
/// Readiness order (the pane resolves the FIRST failing condition):
/// `enabled` → `watcher_running` → `fda_readable` → `paired` → Ready.
/// `last_send_*` / `last_error` drive "last delivered" + a surfaced error.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct MessagingStatusView {
    /// Which channel this status describes (`"imessage"` / `"slack"`).
    #[serde(default = "default_channel_key")]
    pub channel: String,
    /// Master opt-in flag for this channel (condition 1).
    pub enabled: bool,
    /// Whether at least one handle is paired/allowlisted (condition 2).
    pub paired: bool,
    /// Whether this channel's watcher loop is currently spawned (condition 3 —
    /// the invisible-restart fix; `true` once U1 has spawned it).
    pub watcher_running: bool,
    /// Whether the daemon can read the Messages database (Full Disk Access —
    /// condition 4). Probed daemon-side (the daemon is the reader). For non-
    /// iMessage channels this is `true` (no chat.db dependency).
    pub fda_readable: bool,
    /// Unix-epoch milliseconds of the most recent recorded send (success OR
    /// failure). `None` until the first send. Drives "Last delivered: `<time>`".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_send_at_ms: Option<i64>,
    /// Whether the most recent recorded send succeeded. `None` until the first
    /// send; `Some(false)` for a hard error OR a soft `sent:false`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_send_ok: Option<bool>,
    /// The most recent send FAILURE reason (hard error or soft `sent:false`).
    /// `None` when the last send succeeded or none has happened. Surfaced in the
    /// pane so a swallowed failure becomes visible.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_error: Option<String>,
}

/// Result of `messaging.test_send` — the synchronous outcome of the on-demand
/// self-test (U4). `ok:true` means the labeled test message was delivered to
/// the paired handle; `ok:false` carries an actionable `error` (channel off, no
/// paired handle, Automation denied, recipient-not-found). The self-test mints
/// NO approval/pairing mapping and resolves nothing.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct MessagingTestSendResponse {
    /// Whether the test message was delivered.
    pub ok: bool,
    /// Actionable failure reason when `ok == false`; `None` on success.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Host event emitted to subscribed OS host clients.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostEvent {
    pub id: String,
    /// Monotonic daemon-local ordering token. A reconnect snapshot carries
    /// the sequence it observed, so a client can reconcile it PER
    /// CONVERSATION KEY: the snapshot's verdict stands for every key that no
    /// live event with a strictly larger sequence has already spoken for on
    /// that socket.
    #[serde(default)]
    pub sequence: u64,
    pub timestamp: DateTime<Utc>,
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    pub message: String,
    #[serde(default)]
    pub payload: Value,
}

/// One browser wait returned by `host.subscribe.pending_signins`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BrowserSignInSnapshot {
    pub conversation_id: String,
    pub standing_session: bool,
    pub message: String,
}

impl BrowserSignInSnapshot {
    pub fn new(conversation_id: Option<&str>, message: impl Into<String>) -> Self {
        Self {
            conversation_id: conversation_id.unwrap_or("").to_string(),
            standing_session: conversation_id.is_none(),
            message: message.into(),
        }
    }
}

/// User-owned device registered by a native host app.
///
/// This is deliberately status/capability metadata, not a raw remote-exec
/// surface. The daemon can tell the flagship assistant which personal devices
/// are present and what consumer-safe surfaces they advertise; individual
/// privacy-heavy capabilities still need dedicated, policy-gated RPCs.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HostDevice {
    pub id: String,
    pub name: String,
    pub platform: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default)]
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session_id: Option<String>,
    pub updated_at: DateTime<Utc>,
    #[serde(default)]
    pub metadata: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RegisterHostDeviceRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    pub name: String,
    pub platform: String,
    #[serde(default)]
    pub capabilities: Vec<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub metadata: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UpdateHostDeviceRequest {
    pub device_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub platform: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub status: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

/// Manifest-lock relationship for the daemon serving this WS.
/// Returned inside [`HostIdentity`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HostManifestRole {
    /// This daemon holds the exclusive `<manifest>.lock` — agents.*
    /// mutations route through here.
    Owner,
    /// Another `car-server` on the host owns the lock; this daemon
    /// runs in observe-only mode (Parslee-ai/car-releases#44).
    Observer,
    /// No manifest is configured at all — `HOME` unset or the
    /// embedder didn't install one.
    None,
}

/// Daemon-identifying metadata returned inside [`HostSnapshot`].
/// Lets multi-daemon hosts (`car-server install` plus an ad-hoc
/// eval daemon, etc.) tell which daemon they connected to and
/// whether THIS one owns the supervisor lock or is observe-only.
/// Closes the observability gap from Parslee-ai/car-releases#44.
///
/// Stable on the wire across the connection's lifetime — emitted
/// once on subscribe rather than as a periodic event because the
/// fields are immutable for the daemon's lifetime (the manifest
/// role flips only on daemon restart, which would close this WS
/// anyway).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostIdentity {
    /// `CARGO_PKG_VERSION` from the daemon binary at build time.
    pub version: String,
    /// `std::process::id()` of the daemon — operators correlating
    /// log lines + `ps`/`lsof` output need this.
    pub pid: u32,
    /// Absolute path to the lifecycle-agent manifest this daemon
    /// supervises (or observes). `None` when no manifest is
    /// configured (`HOME` unset; embedder didn't install one).
    /// Lossy-encoded on non-UTF-8 paths — operators on path
    /// layouts that round-trip through this field should normalize
    /// upstream.
    pub manifest_path: Option<String>,
    pub manifest_role: HostManifestRole,
    /// Parslee cloud account bound to this daemon, when the local user
    /// has completed `car auth login`. This is advisory identity for
    /// cloud-backed features; the local WS auth token still gates access
    /// to the daemon process.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parslee: Option<ParsleeIdentity>,
}

/// Parslee cloud identity associated with the local CAR user.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParsleeIdentity {
    pub account_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub email: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active_organization: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub organization_name: Option<String>,
}

/// Snapshot returned by `host.subscribe`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HostSnapshot {
    pub subscribed: bool,
    #[serde(default)]
    pub agents: Vec<HostAgent>,
    #[serde(default)]
    pub devices: Vec<HostDevice>,
    #[serde(default)]
    pub approvals: Vec<HostApprovalRequest>,
    #[serde(default)]
    pub events: Vec<HostEvent>,
    /// Authoritative browser waits at `event_sequence`. Clients replace
    /// local attention from this on reconnect unless they have already
    /// applied a live event with a larger sequence.
    #[serde(default)]
    pub pending_signins: Vec<BrowserSignInSnapshot>,
    #[serde(default)]
    pub event_sequence: u64,
    /// Daemon-identifying metadata — added 2026-05 to surface
    /// observe-only mode (Parslee-ai/car-releases#44) and let
    /// multi-daemon hosts tell which daemon they're talking to.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub identity: Option<HostIdentity>,
}

// --- Run lifecycle (agent run tracing, U1) ---
//
// A "run" is one `runs.start` / `runs.complete` bracket around an agent
// loop, identified by a durable `run_id` (a uuid) that is independent of
// the ephemeral, server-assigned WS `client_id`. U1 introduces only the
// run boundary + terminal-outcome carriers; the per-turn `RunTurn` /
// `CliOutcome` / `VerifierVerdict` model lands in U2.
//
// `RunStarted` and `RunEnded` are the two durable run records U1 emits.
// They serialize as tagged JSON (`{ "kind": "started", ... }` /
// `{ "kind": "ended", ... }`) so U2/U3 can extend the record set
// (adding a `Turn` variant) without breaking the on-wire shape.

/// How a run reached its terminal state.
///
/// `Outcome` carries the harness-reported `AgentOutcome` from
/// `runs.complete`. `Incomplete` is written daemon-side when a harness
/// disconnects without ever reporting an outcome (past the short grace
/// window) — R5. It is deliberately distinct from any `OutcomeStatus`
/// so the dashboard can render "the harness vanished" differently from
/// "the agent gave up".
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RunTermination {
    /// The harness called `runs.complete` with a terminal outcome.
    Outcome {
        /// Convenience copy of `outcome.status`, surfaced top-level so
        /// list views can render the terminal banner without parsing
        /// the full `AgentOutcome`.
        status: car_ir::OutcomeStatus,
        outcome: car_ir::AgentOutcome,
    },
    /// The connection dropped mid-run with no `runs.complete` — the
    /// daemon wrote this marker. No `AgentOutcome` is available.
    Incomplete,
    /// CAR confirmed that all controlled work stopped and durably committed
    /// the caller's body-free cancellation identity.
    Cancelled {
        cancellation: RunCancellationIdentity,
    },
}

/// Body-free identity durably bound into a cancelled terminal. The free-text
/// reason is deliberately represented only by its digest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunCancellationIdentity {
    pub receipt_version: u32,
    pub run_id: String,
    pub idempotency_key: String,
    pub reason_digest: String,
    pub principal: String,
    pub action_id: Option<String>,
    pub request_id: Option<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunCancellationStatus {
    CancelledConfirmed,
    AlreadyTerminal,
    TerminationUnconfirmed,
}

/// Strict `runs.cancel` request. Unknown fields are rejected to keep the
/// idempotency preimage closed and reviewable.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunCancelRequest {
    pub run_id: String,
    pub idempotency_key: String,
    pub reason: String,
}

/// Deterministic, body-free cancellation receipt.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunCancelResponse {
    pub receipt_version: u32,
    pub run_id: String,
    pub idempotency_key: String,
    pub reason_digest: String,
    pub principal: String,
    pub status: RunCancellationStatus,
    pub terminal_digest: Option<String>,
    pub action_id: Option<String>,
    pub request_id: Option<String>,
    pub receipt_digest: String,
}

/// First durable row for one cancellation key. It contains no reason/body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunCancellationRequested {
    pub receipt_version: u32,
    pub run_id: String,
    pub idempotency_key: String,
    pub reason_digest: String,
    pub principal: String,
    pub action_id: Option<String>,
    pub request_id: Option<String>,
}

/// A run began — recorded when `runs.start` mints the `run_id`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunStarted {
    pub run_id: String,
    /// WebSocket connection that authenticated and opened this run. Optional
    /// only for replay compatibility with pre-0.51 rows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    /// The owning agent. Resolved from `session.auth {agent_id}`,
    /// `CAR_AGENT_ID`, or (one-shot fallback) a deterministic id
    /// synthesized from the agent's name.
    pub agent_id: String,
    /// What the agent was asked to do (free text from the harness).
    pub intent: String,
    /// The outcome the agent is steering toward, when supplied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome_description: Option<String>,
    pub started_at: DateTime<Utc>,
}

/// A run reached a terminal state — recorded on `runs.complete` (with a
/// reported outcome) or on a mid-run disconnect (as `Incomplete`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunEnded {
    pub run_id: String,
    /// Must match `RunStarted.client_id` for CAR-owned 0.51+ writes. Optional
    /// only for replay compatibility with historical rows.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub client_id: Option<String>,
    pub agent_id: String,
    pub termination: RunTermination,
    /// Lowercase SHA-256 of the RFC 8785/JCS serialization of `termination`.
    /// This binds the terminal journal event, RPC acknowledgment, and durable
    /// row to one exact CAR run outcome; it is not an artifact/content digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completion_digest: Option<String>,
    pub ended_at: DateTime<Utc>,
}

// --- Per-turn run trace (agent run tracing, U2) ---
//
// A "turn" is one submitted proposal (no inference chain-of-thought
// capture). The recorder (`car-server-core/src/run_trace.rs`) joins the
// submitted proposal's `actions[i]` to the resulting `ActionResult`s by
// `action_id` and emits one `RunTurn` per action, tagged with the
// session's current `run_id`. The recorder is tool-agnostic — it always
// records `tool` / `parameters` / `output` — and applies a thin, optional
// classifier for Bulldozer's `drive_cli` / `check_outcome` tools to fill
// `cli_outcome` / `verifier_verdict`. Those return-shape field names
// (`output_tail` / `exit_code` / `timed_out` / `passed`) are the agent's
// contract, not the runtime's; the classifier keys on them.

/// How a CLI-driving action (e.g. Bulldozer's `drive_cli`) terminated.
///
/// `Exited { code }` is the normal case — the process ran and returned an
/// exit code. `Killed` is a signal death (the tool surfaced a `signal`
/// with no numeric `exit_code`). `Timeout` is the tool's own
/// `timed_out` flag. `KTD7`: this is one of the orthogonal, multi-valued
/// per-turn outcome fields — distinct from the run-level `OutcomeStatus`
/// — so a timed-out drive never gets mis-rendered as a run failure.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum CliOutcome {
    /// The process exited with a numeric code (0 = success).
    Exited { code: i64 },
    /// The process was killed by a signal (no numeric exit code).
    Killed,
    /// The tool reported `timed_out = true`.
    Timeout,
}

/// The verifier verdict for a turn — Bulldozer's `check_outcome` result.
///
/// "Verifier" here is the agent's `check_outcome` tool result (its
/// `passed` field), NOT the runtime's static `verifyProposal` gate. A
/// turn with `Fail` is the healthy re-prod case (drove another turn),
/// not a run failure — KTD7 / R11. `NotRun` covers a turn that never
/// reached the verifier (a `drive_cli`-only turn, a timeout, or a
/// policy-rejected action).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VerifierVerdict {
    /// `check_outcome` returned `passed = true`.
    Pass,
    /// `check_outcome` returned `passed = false` (healthy re-prod — amber).
    Fail,
    /// The verifier did not run for this turn.
    NotRun,
}

/// A policy rejection captured on a turn (R2 / R11). When an action is
/// `ActionStatus::Rejected`, the tool body never ran, so `cli_outcome`
/// is forced to `not-run` and the rejection is recorded here.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PolicyRejection {
    /// The rule that fired — the verbatim `ActionResult.error` string
    /// (e.g. `policy 'no-destructive': param 'prompt' matches 'rm -rf'`).
    pub rule: String,
    /// The blocked parameter name, best-effort extracted from the
    /// rejection reason (the `param '<name>'` token a `deny_tool_param`
    /// rejection carries). `None` when the reason has no param token.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub param: Option<String>,
}

/// One captured turn of a run — one action of one submitted proposal.
///
/// The recorder always fills `index` / `prompt` / `tool` / `parameters`
/// / `output` (tool-agnostic). `cli_outcome` / `verifier_verdict` /
/// `policy_rejected` are the thin Bulldozer classifier's enrichment and
/// are `None` / `NotRun` for any other tool. Multi-valued and orthogonal
/// to the run-level `OutcomeStatus` (KTD7).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RunTurn {
    /// 0-based position of this action within the run's ordered turn
    /// stream (monotonic across proposals in the run).
    pub index: usize,
    /// The exact submitted proposal that produced this turn. Missing only
    /// for legacy or externally narrated turns that did not supply identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub proposal_id: Option<String>,
    /// The exact submitted action that produced this turn. Missing only for
    /// legacy or externally narrated turns that did not supply identity.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_id: Option<String>,
    /// Exact lifecycle status returned for this action. Missing when no
    /// matching result exists or for legacy/external turns that omit it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_status: Option<car_ir::ActionStatus>,
    /// Exact executor-reported duration for this action, in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_duration_ms: Option<f64>,
    /// Exact executor result timestamp. This is a completion observation,
    /// not a synthesized start time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub action_completed_at: Option<DateTime<Utc>>,
    /// Exact predecessor action IDs from the executor's dependency graph.
    /// `Some([])` means a known root; `None` means dependency identity is
    /// unavailable (for example, a legacy journal entry).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub depends_on: Option<Vec<String>>,
    /// The submitted action's state-dependency keys, verbatim. `Some([])`
    /// is explicitly known-empty; `None` means legacy/unknown metadata.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub state_dependencies: Option<Vec<String>>,
    /// The prompt handed to the driven CLI — the action's `prompt`
    /// parameter when present (`drive_cli`). `None` for tools that take
    /// no `prompt`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub prompt: Option<String>,
    /// The tool name from the submitted action (`drive_cli`,
    /// `check_outcome`, or any other). `None` for non-`ToolCall` actions.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tool: Option<String>,
    /// The full action parameters as submitted — tool-agnostic capture so
    /// non-Bulldozer agents still get a usable trail.
    #[serde(default, skip_serializing_if = "Value::is_null")]
    pub parameters: Value,
    /// The tool's returned output value (the `ActionResult.output`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,
    /// The classified CLI outcome for a `drive_cli` turn; `None` for
    /// non-driving tools.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cli_outcome: Option<CliOutcome>,
    /// The verifier verdict — `Pass`/`Fail` from a `check_outcome` turn,
    /// `NotRun` otherwise.
    pub verifier_verdict: VerifierVerdict,
    /// A policy rejection, when this action was `Rejected`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub policy_rejected: Option<PolicyRejection>,
}

/// One durable run record. U1 ships `Started` / `Ended`; U2 adds the
/// per-turn `Turn` variant. Tagged on `record` so adding a variant is
/// forward-compatible on the wire.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "record", rename_all = "snake_case")]
pub enum RunRecord {
    Started(RunStarted),
    Ended(RunEnded),
    Turn(RunTurn),
    CancellationRequested(RunCancellationRequested),
    CancellationResult(RunCancelResponse),
}

/// `runs.start` request params.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunStartRequest {
    /// Owning agent id. Optional on the wire: when absent the daemon
    /// resolves from `session.auth {agent_id}`, then `CAR_AGENT_ID`,
    /// then falls back to a deterministic id synthesized from
    /// `agent_name`. With none of these available, `runs.start` is
    /// rejected.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_id: Option<String>,
    /// Agent display name — the one-shot fallback source for a
    /// deterministic `agent_id` when nothing else resolves.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub agent_name: Option<String>,
    pub intent: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome_description: Option<String>,
    /// Optional caller-supplied run id for a globally reserved,
    /// same-WebSocket idempotent start. An exact retry on the connection that
    /// owns the live nonterminal run returns that binding. A terminal run, a
    /// run owned by another connection, or any durable occurrence from a
    /// prior connection is not adopted: `runs.start` returns JSON-RPC
    /// `-32010` (`run ownership conflict:`). After an unacknowledged start and
    /// disconnect, CAR releases the key only when no `RunStarted` boundary
    /// reached durable storage; otherwise it reconciles one historical
    /// `Incomplete` occurrence and keeps the original key owned. Absent ⇒ the
    /// daemon mints a fresh random `run_id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
}

/// `runs.start` response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunStartResponse {
    pub run_id: String,
    pub agent_id: String,
    /// Server-assigned authenticated WebSocket identity persisted on every
    /// active lifecycle journal event and durable boundary row.
    pub client_id: String,
}

/// Strict `runs.resume` request. The caller supplies no owner identity or
/// secret: the daemon derives both from the authenticated WebSocket session.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RunResumeRequest {
    pub run_id: String,
}

/// `runs.resume` response naming the daemon-minted replacement socket and the
/// stale socket it atomically fenced.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RunResumeResponse {
    pub run_id: String,
    pub agent_id: String,
    pub client_id: String,
    pub resumed_from_client_id: String,
}

/// `runs.complete` request params.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunCompleteRequest {
    pub run_id: String,
    pub outcome: car_ir::AgentOutcome,
}

/// `runs.complete` response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunCompleteResponse {
    pub run_id: String,
    pub ok: bool,
    /// Same canonical terminal digest persisted in `RunEnded` and emitted in
    /// the terminal `run_completed` journal event.
    pub completion_digest: String,
}

/// `runs.record_turns` request params — a WS-only batch append of
/// client-narrated turns to a run the calling connection owns. The agent
/// builds full `RunTurn`s itself (out-of-pipeline capture: its work
/// happens inside its own subprocess, never through `proposal.submit`),
/// then pushes them here in batches. The daemon owns the turn `index`
/// (re-stamped under the `runs` lock — the client's `index` values are
/// ignored), the per-field/per-turn byte caps, the batch-size cap, and
/// the per-run turn ceiling; it appends through the same
/// `record_run_turns` path the proposal recorder uses, so persistence and
/// `runs.trace.event` fanout are identical. Turn content beyond size is
/// intentional pass-through — the daemon validates size and ownership,
/// never semantics.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunRecordTurnsRequest {
    pub run_id: String,
    /// The batch of turns to append, in order. Each is appended as a
    /// [`RunRecord::Turn`]. On the wire a turn may omit `index` (the daemon
    /// owns it — re-stamped under the `runs` lock; any sent value is
    /// ignored) and `verifier_verdict` (defaults to `NotRun`). Must be
    /// non-empty.
    pub turns: Vec<RunTurn>,
}

/// `runs.record_turns` response.
///
/// On a healthy append `ok` is `true`, `base_index` is the daemon-stamped
/// 0-based position of the FIRST turn in the batch, and `count` is the
/// number appended (the stamped indices are `base_index .. base_index +
/// count`). On a non-fatal rejection (`ok: false`) nothing is appended and
/// `dropped` carries the machine-readable reason the agent treats as
/// "stop sending for this run": `run_not_found` (no such run, or the
/// caller isn't entitled — uniform with the read path's not-found, never
/// an owner oracle), `run_terminal` (the run already reported / was swept
/// terminal), `run_turn_limit` (the per-run turn ceiling was reached), or
/// `turn_too_large` (a turn could not be bounded under the per-turn byte
/// cap even after its free-form fields were replaced — a misbehaving
/// client; the whole batch is dropped, never partially admitted).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunRecordTurnsResponse {
    pub run_id: String,
    /// 0-based index of the first appended turn. `0` when nothing was
    /// appended (`ok: false`).
    pub base_index: usize,
    /// Number of turns appended. `0` when `ok: false`.
    pub count: usize,
    pub ok: bool,
    /// The machine-readable drop reason when `ok` is `false`; omitted on a
    /// healthy append.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dropped: Option<String>,
}

// --- Live run-trace subscription (agent run tracing, U4) ---
//
// `runs.subscribe {run_id}` returns a snapshot of the run's turns so far
// plus a `cursor` (the count of records the snapshot covers), then the
// daemon pushes one `runs.trace.event` notification per record appended
// AFTER that cursor. The snapshot + the subscriber registration happen
// atomically under the same lock the recorder holds when it appends, so
// no record in the snapshot/register window is dropped (gap) or
// double-delivered (dup) — R7. The notification is WS-only (no FFI
// method); a CarHost re-issues `runs.subscribe {run_id}` after a
// reconnect and gap-fills via the cursor (R8). Authorization (R16):
// only the run's owning agent connection or the CarHost host-client may
// subscribe.

/// Coarse live status of a run for the subscribe snapshot and each
/// `runs.trace.event`. Distinct from the run-level `OutcomeStatus`
/// carried inside a terminal `RunTermination::Outcome` — this is the
/// "is the run still open?" signal the live client folds into its view.
/// Mirrors `RunStore::RunStatus` but lives in `car-proto` so the wire
/// shape doesn't depend on the server-core crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunLiveStatus {
    /// No terminal record yet — the run is still being written.
    InProgress,
    /// `runs.complete` reported a terminal `AgentOutcome`.
    Completed,
    /// The harness disconnected without reporting an outcome (R5).
    Incomplete,
    /// Cancellation was requested but CAR could not confirm controlled work
    /// stopped. The run is quarantined and remains nonterminal.
    CancellationPending,
    /// CAR durably confirmed cancellation.
    Cancelled,
}

/// `runs.subscribe` request params.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunSubscribeRequest {
    pub run_id: String,
    /// Zero-based turn cursor. Unlike `runs.get_trace`, lifecycle records do
    /// not advance this cursor.
    pub cursor: usize,
    /// Maximum turns returned by this catch-up page.
    pub limit: usize,
}

/// `runs.subscribe` response — one bounded catch-up page before the live
/// `runs.trace.event` stream starts.
///
/// `turns` contains ordered `RunTurn` records beginning at `cursor`.
/// A partial page has `subscribed = false` and a `next_cursor`; the client
/// must request each continuation. The page that reaches `live_cursor`
/// atomically registers the subscriber and returns `subscribed = true`, so
/// turns appended at the catch-up boundary cannot be skipped. The
/// `RunStarted` data is already conveyed by `agent_id` + the request's
/// `run_id`, and the terminal disposition by `status`, so this response
/// carries turns only. Every record in `turns` is a `RunRecord::Turn`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunSubscribeResponse {
    pub run_id: String,
    pub agent_id: String,
    /// Ordered `RunRecord::Turn` records beginning at `cursor`.
    pub turns: Vec<RunRecord>,
    /// Echo of the requested turn cursor.
    pub cursor: usize,
    /// Echo of the applied page limit.
    pub limit: usize,
    /// Present only while more catch-up turns remain. The client must request
    /// that cursor before it can become live-subscribed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<usize>,
    /// Exact turn-count boundary observed while this page was selected.
    pub live_cursor: usize,
    /// True only when the page reached `live_cursor` and registration happened
    /// atomically under the same run lock. Terminal traces use this as a
    /// caught-up marker but do not retain a future notification sink.
    pub subscribed: bool,
    pub status: RunLiveStatus,
}

/// `runs.unsubscribe` request params.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunUnsubscribeRequest {
    pub run_id: String,
}

/// `runs.unsubscribe` response.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunUnsubscribeResponse {
    pub run_id: String,
    /// `true` if a subscription for this `(connection, run_id)` existed
    /// and was removed; `false` if there was nothing to remove.
    pub removed: bool,
}

/// One `runs.trace.event` server → client notification (agent run
/// tracing, U4). Pushed to every `(host_client, run_id)` subscriber.
///
/// `record` is the appended `RunRecord`:
/// - `Turn` — emitted after `record_run_turns` appends it to the run's
///   in-memory buffer, under the same lock that holds the snapshot/
///   register window closed (the gap/dup-free contract). `cursor` is the
///   run's turn count immediately AFTER this turn was appended (1-based),
///   so a subscriber at turn-cursor `n` expects the next `Turn` event's
///   `cursor` to be `n + 1` — a mismatch means a gap (re-subscribe, R8).
/// - `Started` — emitted on `runs.start`; a lifecycle marker. `cursor`
///   carries the run's current turn count (0 at start) and does not
///   advance the turn stream.
/// - `Ended` — emitted on `runs.complete` / disconnect-`Incomplete`;
///   carries the final turn count in `cursor` and the terminal `status`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunTraceEvent {
    pub run_id: String,
    pub agent_id: String,
    pub record: RunRecord,
    /// The run's turn count after this record was processed. Advances by
    /// one per `Turn`; unchanged on `Started`/`Ended`.
    pub cursor: usize,
    pub status: RunLiveStatus,
}

// --- Replay read RPCs (agent run tracing, U5) ---
//
// `runs.list {agent_id}` and `runs.get_trace {run_id, cursor?}` are the
// WS-only replay reads CarHost uses to list an agent's runs and fetch a
// completed run's full trace. They read the disk store (`RunStore`), so
// they work after a daemon restart / `client_id` churn — `run_id` /
// `agent_id` are the durable keys. Both are authorization-gated (R16):
// `runs.list` authorizes the caller for `agent_id` first (the param is
// not a transparent key — an unentitled id is rejected, not enumerated);
// `runs.get_trace` resolves the run's owning `agent_id` from disk and
// authorizes against it.
//
// Only the *request* params are typed here. The responses are built
// inline in the handler (mirroring `agents.tail_log`'s `{ lines }` shape)
// because they carry the run-store's `RunSummary` type, which lives in
// `car-server-core` — `car-proto` must not depend on it. The exact JSON
// response shapes are documented in `docs/websocket-protocol.md` and
// asserted in `car-server-core/tests/run_trace_replay.rs`:
//
//   runs.list      → { agent_id, runs: [RunSummary] }   (newest-first)
//   runs.get_trace → { run_id, agent_id, records: [RunRecord], cursor }
//                    or { run_id, not_found: true } for an unknown run.
//
// `RunSummary` = { run_id, agent_id, intent, started_at, ended_at?,
// status, turn_count }; `RunRecord` is the tagged Started/Turn/Ended
// union defined above. The `cursor` echoes the request's `cursor` (0 when
// omitted) — the index `records` begins at, for paged fetches of large
// runs.

/// `runs.list` request params — list an agent's runs newest-first.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunListRequest {
    /// The agent whose runs to list. Authorization-gated (R16): the
    /// caller must own this agent (`session.auth {agent_id}`) or be the
    /// CarHost host-client. Not a transparent key — an unentitled id is
    /// rejected, never enumerated.
    pub agent_id: String,
    /// Opaque numeric keyset. `0` starts at the current newest row; a returned
    /// `next_cursor` resumes strictly after the prior page even if a new run is
    /// inserted at the head.
    pub cursor: usize,
    /// Maximum rows to return. Must be between 1 and the server hard maximum.
    pub limit: usize,
}

/// `runs.get_trace` request params — fetch one bounded page of a run's ordered trace.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunGetTraceRequest {
    /// The run to fetch. The owning `agent_id` is resolved from the disk
    /// store and the caller is authorized against it (R16).
    pub run_id: String,
    /// Optional start index into the run's ordered `RunRecord` stream —
    /// the first record returned. Omitted / `0` starts at the beginning;
    /// a non-zero cursor continues a large run from that offset. The
    /// response echoes the applied cursor.
    pub cursor: usize,
    /// Maximum records to return. Must be between 1 and the server hard maximum.
    pub limit: usize,
}

// --- Response types ---

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionInitResponse {
    pub session_id: String,
    pub tools_registered: usize,
    pub policies_registered: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyResponse {
    pub valid: bool,
    pub issues: Vec<VerifyIssueProto>,
    pub simulated_state: HashMap<String, Value>,
    /// Parallelizable execution batches (DAG levels), action IDs.
    /// Defaulted for backward-compatible deserialization of older
    /// daemons that omitted it.
    #[serde(default)]
    pub execution_levels: Vec<Vec<String>>,
    /// Undeclared write conflicts: (action1, action2, key).
    #[serde(default)]
    pub conflicts: Vec<(String, String, String)>,
    /// Evidence bundle: the verifier's declared scope — checks run,
    /// assumptions, untested regions, residual risks, coverage
    /// confidence (survey "Code as Agent Harness" §5.2.2). Carried as
    /// opaque JSON so car-proto stays decoupled from car-verify; shape
    /// mirrors `car_verify::VerificationEvidence`.
    #[serde(default)]
    pub evidence: Value,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifyIssueProto {
    pub action_id: String,
    pub severity: String,
    pub message: String,
    /// Which kind of check produced the finding: `"decision_procedure"` |
    /// `"heuristic"` | `"sampled"` — the string form of
    /// `car_verify::EvidenceTier`, carried as a `String` so car-proto stays
    /// decoupled from car-verify (same reason `evidence` is an opaque `Value`).
    ///
    /// Orthogonal to `severity`, which says how bad the finding would be rather
    /// than how it was derived. Defaulted so a newer client can still
    /// deserialize an older daemon's response, where it arrives empty.
    #[serde(default)]
    pub tier: String,
}

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

    #[test]
    fn tool_definition_roundtrip() {
        let td = ToolDefinition {
            name: "search".to_string(),
            description: "Search the web".to_string(),
            parameters: serde_json::json!({"type": "object", "properties": {"query": {"type": "string"}}}),
            returns: None,
            idempotent: false,
            cache_ttl_secs: None,
            rate_limit: None,
        };
        let json = serde_json::to_string(&td).unwrap();
        let rt: ToolDefinition = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.name, "search");
    }

    #[test]
    fn tool_definition_back_compat_pre_v05_clients() {
        // Pre-v0.5 clients only sent these three fields. The new
        // optional fields must default cleanly so the wire stays
        // backward-compatible.
        let legacy = r#"{"name":"read","description":"","parameters":{}}"#;
        let td: ToolDefinition = serde_json::from_str(legacy).unwrap();
        assert_eq!(td.name, "read");
        assert!(td.returns.is_none());
        assert!(!td.idempotent);
        assert!(td.cache_ttl_secs.is_none());
        assert!(td.rate_limit.is_none());
    }

    #[test]
    fn tool_execute_request_roundtrip() {
        let req = ToolExecuteRequest {
            action_id: "a1".to_string(),
            tool: "search".to_string(),
            parameters: serde_json::json!({"query": "rust"}),
            timeout_ms: Some(5000),
            attempt: 1,
            request_id: "cb-7".to_string(),
            session_id: Some("sess-7".to_string()),
        };
        let json = serde_json::to_string(&req).unwrap();
        let rt: ToolExecuteRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.tool, "search");
        assert_eq!(rt.timeout_ms, Some(5000));
        assert_eq!(rt.request_id, "cb-7");
        assert_eq!(rt.session_id.as_deref(), Some("sess-7"));
    }

    /// Parslee-ai/car#904 — the correlation field must be additive in both
    /// directions, because the daemon and the host upgrade independently.
    #[test]
    fn tool_execute_request_session_id_is_additive_both_ways() {
        // A pre-#904 daemon sends no `session_id`; a new host must still parse.
        let legacy =
            r#"{"action_id":"a1","tool":"x","parameters":{},"attempt":1,"request_id":"cb-1"}"#;
        let rt: ToolExecuteRequest = serde_json::from_str(legacy).unwrap();
        assert_eq!(rt.session_id, None);

        // A sessionless caller must not put a null on the wire: `execute()` and
        // in-process executors legitimately have no session, and emitting
        // `"session_id": null` would make every such payload differ from the
        // pre-#904 shape for no gain.
        let sessionless = ToolExecuteRequest {
            action_id: "a1".to_string(),
            tool: "x".to_string(),
            parameters: serde_json::json!({}),
            timeout_ms: None,
            attempt: 1,
            request_id: "cb-1".to_string(),
            session_id: None,
        };
        let json = serde_json::to_string(&sessionless).unwrap();
        assert!(
            !json.contains("session_id"),
            "a sessionless call must omit the key entirely, got: {json}"
        );
    }

    #[test]
    fn tool_execute_request_request_id_defaults_for_pre264_hosts() {
        // Pre-#264 payloads (no request_id) must still parse — the field
        // defaults to empty so an older host gets a usable callback, just
        // without the cancel correlation key.
        let legacy = r#"{"action_id":"a1","tool":"x","parameters":{},"attempt":1}"#;
        let rt: ToolExecuteRequest = serde_json::from_str(legacy).unwrap();
        assert_eq!(rt.request_id, "");
        assert_eq!(rt.tool, "x");
    }

    #[test]
    fn tool_cancel_request_roundtrip() {
        let c = ToolCancelRequest {
            request_id: "cb-3".to_string(),
            action_id: "a2".to_string(),
            reason: "tool 'drive_cli' callback timed out (185s)".to_string(),
        };
        let json = serde_json::to_string(&c).unwrap();
        let rt: ToolCancelRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.request_id, "cb-3");
        assert_eq!(rt.action_id, "a2");
        assert!(rt.reason.contains("timed out"));
        // action_id + reason default when omitted (only request_id required).
        let minimal: ToolCancelRequest = serde_json::from_str(r#"{"request_id":"cb-9"}"#).unwrap();
        assert_eq!(minimal.request_id, "cb-9");
        assert_eq!(minimal.action_id, "");
        assert_eq!(minimal.reason, "");
    }

    #[test]
    fn tool_execute_response_success() {
        let resp = ToolExecuteResponse {
            action_id: "a1".to_string(),
            output: Some(Value::from("results")),
            error: None,
            terminal: false,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("results"));
        assert!(!json.contains("terminal"));
    }

    #[test]
    fn tool_execute_response_error() {
        let resp = ToolExecuteResponse {
            action_id: "a1".to_string(),
            output: None,
            error: Some("timeout".to_string()),
            terminal: true,
        };
        let json = serde_json::to_string(&resp).unwrap();
        assert!(json.contains("timeout"));
        assert!(json.contains(r#""terminal":true"#));

        let legacy: ToolExecuteResponse =
            serde_json::from_str(r#"{"action_id":"a1","error":"legacy callback failure"}"#)
                .unwrap();
        assert!(!legacy.terminal);
    }

    #[test]
    fn session_init_request() {
        let req = SessionInitRequest {
            client_id: "client-1".to_string(),
            tools: vec![ToolDefinition {
                name: "read".to_string(),
                description: "Read file".to_string(),
                parameters: serde_json::json!({}),
                returns: None,
                idempotent: false,
                cache_ttl_secs: None,
                rate_limit: None,
            }],
            policies: vec![],
        };
        let json = serde_json::to_string(&req).unwrap();
        let rt: SessionInitRequest = serde_json::from_str(&json).unwrap();
        assert_eq!(rt.tools.len(), 1);
    }

    #[test]
    fn verify_request() {
        let req = VerifyRequest {
            proposal: ActionProposal {
                id: "p1".to_string(),
                source: "test".to_string(),
                actions: vec![],
                timestamp: chrono::Utc::now(),
                context: HashMap::new(),
            },
            initial_state: [("x".to_string(), Value::from(1))].into(),
        };
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("p1"));
    }

    #[test]
    fn run_start_request_resolves_optional_agent_id() {
        // The harness may omit agent_id (daemon resolves it) and may
        // supply agent_name as the one-shot fallback source.
        let wire = r#"{"intent":"ship the feature","agent_name":"Bulldozer"}"#;
        let req: RunStartRequest = serde_json::from_str(wire).unwrap();
        assert_eq!(req.intent, "ship the feature");
        assert_eq!(req.agent_id, None);
        assert_eq!(req.agent_name.as_deref(), Some("Bulldozer"));
        assert_eq!(req.outcome_description, None);
    }

    #[test]
    fn run_record_started_ended_roundtrip() {
        let started = RunRecord::Started(RunStarted {
            run_id: "run-1".to_string(),
            client_id: Some("client-1".to_string()),
            agent_id: "agent-1".to_string(),
            intent: "do the thing".to_string(),
            outcome_description: Some("the thing is done".to_string()),
            started_at: chrono::Utc::now(),
        });
        let json = serde_json::to_string(&started).unwrap();
        // Tagged on `record` so U2 can add a `Turn` variant without
        // breaking the wire.
        assert!(json.contains("\"record\":\"started\""));
        let rt: RunRecord = serde_json::from_str(&json).unwrap();
        match rt {
            RunRecord::Started(s) => assert_eq!(s.run_id, "run-1"),
            other => panic!("expected Started, got {other:?}"),
        }

        let ended = RunRecord::Ended(RunEnded {
            run_id: "run-1".to_string(),
            client_id: Some("client-1".to_string()),
            agent_id: "agent-1".to_string(),
            termination: RunTermination::Outcome {
                status: car_ir::OutcomeStatus::Success,
                outcome: car_ir::AgentOutcome::success("done"),
            },
            completion_digest: Some("abc123".to_string()),
            ended_at: chrono::Utc::now(),
        });
        let json = serde_json::to_string(&ended).unwrap();
        assert!(json.contains("\"record\":\"ended\""));
        assert!(json.contains("\"kind\":\"outcome\""));
        let rt: RunRecord = serde_json::from_str(&json).unwrap();
        match rt {
            RunRecord::Ended(e) => match e.termination {
                RunTermination::Outcome { status, .. } => {
                    assert_eq!(status, car_ir::OutcomeStatus::Success)
                }
                other => panic!("expected Outcome, got {other:?}"),
            },
            other => panic!("expected Ended, got {other:?}"),
        }
    }

    #[test]
    fn run_termination_incomplete_serializes_distinctly() {
        let term = RunTermination::Incomplete;
        let json = serde_json::to_string(&term).unwrap();
        assert_eq!(json, r#"{"kind":"incomplete"}"#);
    }

    #[test]
    fn historical_run_records_replay_without_client_binding_fields() {
        let started: RunRecord = serde_json::from_str(
            r#"{"record":"started","run_id":"old","agent_id":"agent","intent":"go","started_at":"2026-01-02T03:04:05Z"}"#,
        )
        .expect("historical started row");
        let ended: RunRecord = serde_json::from_str(
            r#"{"record":"ended","run_id":"old","agent_id":"agent","termination":{"kind":"incomplete"},"ended_at":"2026-01-02T03:05:05Z"}"#,
        )
        .expect("historical ended row");

        match started {
            RunRecord::Started(row) => assert!(row.client_id.is_none()),
            other => panic!("expected started, got {other:?}"),
        }
        match ended {
            RunRecord::Ended(row) => {
                assert!(row.client_id.is_none());
                assert!(row.completion_digest.is_none());
            }
            other => panic!("expected ended, got {other:?}"),
        }
    }

    #[test]
    fn cli_outcome_tagged_variants_roundtrip() {
        let exited = CliOutcome::Exited { code: 0 };
        let json = serde_json::to_string(&exited).unwrap();
        assert_eq!(json, r#"{"kind":"exited","code":0}"#);
        assert_eq!(serde_json::from_str::<CliOutcome>(&json).unwrap(), exited);

        assert_eq!(
            serde_json::to_string(&CliOutcome::Killed).unwrap(),
            r#"{"kind":"killed"}"#
        );
        assert_eq!(
            serde_json::to_string(&CliOutcome::Timeout).unwrap(),
            r#"{"kind":"timeout"}"#
        );
        assert_eq!(
            serde_json::from_str::<CliOutcome>(r#"{"kind":"timeout"}"#).unwrap(),
            CliOutcome::Timeout
        );
    }

    #[test]
    fn verifier_verdict_serializes_snake_case() {
        assert_eq!(
            serde_json::to_string(&VerifierVerdict::Pass).unwrap(),
            r#""pass""#
        );
        assert_eq!(
            serde_json::to_string(&VerifierVerdict::Fail).unwrap(),
            r#""fail""#
        );
        assert_eq!(
            serde_json::to_string(&VerifierVerdict::NotRun).unwrap(),
            r#""not_run""#
        );
        assert_eq!(
            serde_json::from_str::<VerifierVerdict>(r#""not_run""#).unwrap(),
            VerifierVerdict::NotRun
        );
    }

    #[test]
    fn policy_rejection_omits_none_param() {
        let pr = PolicyRejection {
            rule: "policy 'x': denied".to_string(),
            param: None,
        };
        let json = serde_json::to_string(&pr).unwrap();
        assert!(
            !json.contains("param"),
            "None param must be omitted: {json}"
        );
        let with_param = PolicyRejection {
            rule: "policy 'x': param 'prompt' matches 'rm -rf'".to_string(),
            param: Some("prompt".to_string()),
        };
        let json = serde_json::to_string(&with_param).unwrap();
        assert!(json.contains("\"param\":\"prompt\""));
        assert_eq!(
            serde_json::from_str::<PolicyRejection>(&json).unwrap(),
            with_param
        );
    }

    #[test]
    fn run_record_turn_variant_roundtrip() {
        // The `turn` variant must serialize under the same `record` tag as
        // Started/Ended so U3/U4 consume one ordered RunRecord stream.
        let turn = RunRecord::Turn(RunTurn {
            index: 0,
            proposal_id: None,
            action_id: None,
            action_status: None,
            action_duration_ms: None,
            action_completed_at: None,
            depends_on: None,
            state_dependencies: None,
            prompt: Some("make the test pass".to_string()),
            tool: Some("drive_cli".to_string()),
            parameters: serde_json::json!({ "cli": "claude", "prompt": "make the test pass" }),
            output: Some(serde_json::json!({ "exit_code": 0, "output_tail": "done" })),
            cli_outcome: Some(CliOutcome::Exited { code: 0 }),
            verifier_verdict: VerifierVerdict::NotRun,
            policy_rejected: None,
        });
        let json = serde_json::to_string(&turn).unwrap();
        assert!(
            json.contains("\"record\":\"turn\""),
            "turn must tag on `record`: {json}"
        );
        match serde_json::from_str::<RunRecord>(&json).unwrap() {
            RunRecord::Turn(t) => {
                assert_eq!(t.index, 0);
                assert_eq!(t.tool.as_deref(), Some("drive_cli"));
                assert_eq!(t.cli_outcome, Some(CliOutcome::Exited { code: 0 }));
                assert_eq!(t.verifier_verdict, VerifierVerdict::NotRun);
            }
            other => panic!("expected Turn, got {other:?}"),
        }
    }

    #[test]
    fn run_turn_minimal_omits_optional_fields() {
        // A generic, non-Bulldozer turn: no prompt, no cli/verifier
        // classification, no rejection — only the always-present fields
        // serialize plus the required verifier_verdict.
        let turn = RunTurn {
            index: 3,
            proposal_id: None,
            action_id: None,
            action_status: None,
            action_duration_ms: None,
            action_completed_at: None,
            depends_on: None,
            state_dependencies: None,
            prompt: None,
            tool: Some("search".to_string()),
            parameters: serde_json::json!({ "query": "rust" }),
            output: Some(Value::from("results")),
            cli_outcome: None,
            verifier_verdict: VerifierVerdict::NotRun,
            policy_rejected: None,
        };
        let json = serde_json::to_string(&turn).unwrap();
        assert!(!json.contains("prompt"));
        assert!(!json.contains("cli_outcome"));
        assert!(!json.contains("policy_rejected"));
        assert!(json.contains("\"verifier_verdict\":\"not_run\""));
        let rt: RunTurn = serde_json::from_str(&json).unwrap();
        assert_eq!(rt, turn);
    }

    #[test]
    fn run_live_status_roundtrip() {
        // snake_case wire form the live subscribe/event share with the
        // store's RunStatus.
        assert_eq!(
            serde_json::to_string(&RunLiveStatus::InProgress).unwrap(),
            "\"in_progress\""
        );
        assert_eq!(
            serde_json::from_str::<RunLiveStatus>("\"completed\"").unwrap(),
            RunLiveStatus::Completed
        );
        assert_eq!(
            serde_json::from_str::<RunLiveStatus>("\"incomplete\"").unwrap(),
            RunLiveStatus::Incomplete
        );
    }

    #[test]
    fn run_trace_event_wraps_record_and_cursor() {
        // The live notification carries the appended record plus the
        // post-append turn cursor and the run's live status.
        let ev = RunTraceEvent {
            run_id: "run-1".to_string(),
            agent_id: "agent-a".to_string(),
            record: RunRecord::Turn(RunTurn {
                index: 4,
                proposal_id: None,
                action_id: None,
                action_status: None,
                action_duration_ms: None,
                action_completed_at: None,
                depends_on: None,
                state_dependencies: None,
                prompt: Some("fix it".to_string()),
                tool: Some("drive_cli".to_string()),
                parameters: serde_json::json!({ "prompt": "fix it" }),
                output: Some(serde_json::json!({ "exit_code": 0 })),
                cli_outcome: Some(CliOutcome::Exited { code: 0 }),
                verifier_verdict: VerifierVerdict::NotRun,
                policy_rejected: None,
            }),
            cursor: 5,
            status: RunLiveStatus::InProgress,
        };
        let json = serde_json::to_string(&ev).unwrap();
        let back: RunTraceEvent = serde_json::from_str(&json).unwrap();
        assert_eq!(back.run_id, "run-1");
        assert_eq!(back.cursor, 5);
        assert_eq!(back.status, RunLiveStatus::InProgress);
        match back.record {
            RunRecord::Turn(t) => assert_eq!(t.index, 4),
            other => panic!("expected Turn, got {other:?}"),
        }
    }

    #[test]
    fn run_subscribe_response_turns_only_snapshot() {
        let resp = RunSubscribeResponse {
            run_id: "run-1".to_string(),
            agent_id: "agent-a".to_string(),
            turns: vec![RunRecord::Turn(RunTurn {
                index: 0,
                proposal_id: None,
                action_id: None,
                action_status: None,
                action_duration_ms: None,
                action_completed_at: None,
                depends_on: None,
                state_dependencies: None,
                prompt: None,
                tool: Some("drive_cli".to_string()),
                parameters: Value::Null,
                output: None,
                cli_outcome: None,
                verifier_verdict: VerifierVerdict::NotRun,
                policy_rejected: None,
            })],
            cursor: 0,
            limit: 100,
            next_cursor: None,
            live_cursor: 1,
            subscribed: true,
            status: RunLiveStatus::InProgress,
        };
        let json = serde_json::to_string(&resp).unwrap();
        let back: RunSubscribeResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.cursor, 0);
        assert_eq!(back.live_cursor, 1);
        assert!(back.subscribed);
        assert_eq!(back.turns.len(), 1);
        assert!(matches!(back.turns[0], RunRecord::Turn(_)));
    }

    // FIX 1: the canonical harness builds the outcome itself and sends
    // `{status, summary, evidence, metrics, tools_called}` with NO `timestamp`
    // and an EXTRA `tools_called` field. RunCompleteRequest.outcome must
    // deserialize this shape, otherwise `runs.complete` fails and the run is
    // never marked ended (recorded Incomplete).
    #[test]
    fn run_complete_request_accepts_harness_outcome_shape() {
        let req_json = serde_json::json!({
            "run_id": "r1",
            "outcome": {
                "status": "success",
                "summary": "Created file",
                "evidence": [],
                "metrics": {
                    "turns": 3,
                    "tool_calls": 3,
                    "actions_succeeded": 3,
                    "actions_failed": 0
                },
                "tools_called": ["drive_cli", "check_outcome", "finish"]
            }
        });

        let req: RunCompleteRequest =
            serde_json::from_value(req_json).expect("harness outcome shape must deserialize");
        assert_eq!(req.run_id, "r1");
        assert_eq!(req.outcome.status, car_ir::OutcomeStatus::Success);
        assert_eq!(req.outcome.summary, "Created file");
        assert_eq!(req.outcome.metrics.turns, 3);
        assert_eq!(req.outcome.metrics.tool_calls, 3);
        assert_eq!(req.outcome.metrics.actions_succeeded, 3);
        assert_eq!(req.outcome.metrics.actions_failed, 0);
        // omitted metrics fields default to zero
        assert_eq!(req.outcome.metrics.duration_ms, 0.0);
        assert_eq!(req.outcome.metrics.retries, 0);
    }

    #[test]
    fn run_cancel_contract_is_strict_and_capability_gated() {
        let negotiated = negotiate_capabilities(
            &[RUNS_CANCEL_CAPABILITY.to_string()],
            &[RUNS_PAGINATION_CAPABILITY.to_string()],
        )
        .unwrap();
        assert_eq!(
            negotiated,
            vec![
                RUNS_CANCEL_CAPABILITY.to_string(),
                RUNS_PAGINATION_CAPABILITY.to_string()
            ]
        );
        let request: RunCancelRequest = serde_json::from_value(serde_json::json!({
            "run_id":"run-1","idempotency_key":"cancel-1","reason":"operator stop"
        }))
        .unwrap();
        assert_eq!(request.reason, "operator stop");
        assert!(
            serde_json::from_value::<RunCancelRequest>(serde_json::json!({
                "run_id":"run-1","idempotency_key":"cancel-1","reason":"stop","extra":true
            }))
            .is_err()
        );
    }

    #[test]
    fn cancelled_termination_and_body_free_records_round_trip() {
        let identity = RunCancellationIdentity {
            receipt_version: 1,
            run_id: "run-1".into(),
            idempotency_key: "cancel-1".into(),
            reason_digest: "a".repeat(64),
            principal: "agent:daily-continuity-newsroom".into(),
            action_id: Some("editor".into()),
            request_id: Some("cb-7".into()),
        };
        let ended = RunRecord::Ended(RunEnded {
            run_id: "run-1".into(),
            client_id: Some("client-1".into()),
            agent_id: "daily-continuity-newsroom".into(),
            termination: RunTermination::Cancelled {
                cancellation: identity,
            },
            completion_digest: Some("b".repeat(64)),
            ended_at: Utc::now(),
        });
        let json = serde_json::to_string(&ended).unwrap();
        assert!(json.contains("\"kind\":\"cancelled\""));
        assert!(!json.contains("operator stop"));
        assert!(matches!(
            serde_json::from_str::<RunRecord>(&json).unwrap(),
            RunRecord::Ended(RunEnded {
                termination: RunTermination::Cancelled { .. },
                ..
            })
        ));
    }
}