car-server-core 0.55.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! The `feedback.*` JSON-RPC surface — CAR's in-app feedback intake (PR A,
//! wave 2, U4 of the plan in `docs/plans/2026-08-31-car-feedback-system.md`;
//! outcomes contract `docs/outcomes/car-feedback-system-outcomes.md`).
//!
//! Four methods, all gated behind `requires_protocol_v2` exactly like
//! `diagnostics.secret_store_activity` (PAR-1):
//!
//! - `feedback.compose_preview` — assemble the redacted diagnostic bundle and
//!   return it WITHOUT persisting anything. This is the consent preview: what
//!   it returns is byte-for-byte what `feedback.submit` spools (PREV-2, plan
//!   requirement 8). The response carries an opaque `preview_id` handle; the
//!   composed bundle is retained in a small in-daemon cache
//!   ([`PREVIEW_CACHE_CAP`] entries / [`PREVIEW_TTL`]) so a follow-up
//!   `feedback.submit {preview_id}` enqueues the EXACT previewed bundle even
//!   if logs grew in between — the approved-bytes handoff the consent moment
//!   requires. A missing/expired/mismatched handle is REFUSED with the
//!   structured `PREVIEW_EXPIRED` error (see below) — never silently
//!   re-composed.
//! - `feedback.submit` — the stored previewed bundle when a valid
//!   `preview_id` is supplied, [`compose_bundle`] fresh when NO `preview_id`
//!   is supplied, then [`car_feedback_core::spool::Spool::enqueue`]. **This
//!   is the only code path in this module — and in this crate — that writes
//!   a spool entry** (PRIV-2): `compose_preview` never opens the spool for
//!   writing, and `status`/`list` only read (the spool's own `open()`
//!   maintenance sweep removes crash leftovers/expired entries; it never
//!   creates one).
//! - `feedback.status` — local spool summaries, each row carrying
//!   `source: "local"`. The single-entry form (`{submission_id}`) also
//!   carries `description`: the stored bundle's redacted description, read
//!   back from the persisted artifact via `Spool::load_bundle` (finding #19's
//!   daemon half — the host detail view renders it without a second surface).
//! - `feedback.list` — the local spool rows MERGED with the signed-in user's
//!   server-side report rows (the F2b `fetch_my_feedback` transport seam,
//!   now `GET /api/v1/orgs/{orgId}/car-feedback/mine`), keyed on the SERVER row id only
//!   (see [`merge_server_rows`] — `/mine` DOES expose `clientSubmissionId`
//!   now; keying unacknowledged local rows on it is a recorded follow-up).
//!   Rows carry `source: "local" | "server"` and an optional `note`; a local
//!   row whose server row advanced shows the server state. Signed out (no
//!   `parslee_session`), the list is local-only — no network call is made.
//!
//! ## Closed world by construction (plan requirement 16 / BND-2)
//!
//! The wire surface carries **no path parameter anywhere**. The named-log set
//! is built daemon-side by [`named_log_set`]: the supervised agents' log files
//! (ids read from the registry manifest `agents.json` — only the `id` field is
//! used; the manifest's env maps, which carry secrets, never enter the bundle)
//! plus the daemon stderr-tee file. A client cannot name a file to include.
//!
//! ## Identity lane (plan requirement 14 / PREV-5)
//!
//! `feedback.submit` binds the lane (anonymous vs authenticated{org_id}) at
//! enqueue time — the consent moment — into the durable spool state. The spool
//! offers no API to rewrite it, so a signed-out submission can never later
//! drain with a bearer.
//!
//! ## Where the screenshot rides (wave-2 decision, recorded in the unit
//! hand-off)
//!
//! [`car_feedback_core::bundle::RedactedBundle`] has no first-class screenshot
//! field, and the spool persists exactly a `RedactedBundle` — so the
//! host-captured window screenshot (already consent-gated, already capped by
//! the ChatAttachments pipeline) rides `runtime_context.screenshot` as
//! `{jpeg_b64, byte_len}`, injected AFTER redaction: it is a pixel capture,
//! not text (the text scrub engine would destroy base64 image data via the
//! high-entropy rule), and the manifest gains an accounted `screenshot` item
//! so the consent preview stays honest. The daemon does not trust the host
//! pipeline: the payload must decode as base64, carry JPEG SOI/EOI magic,
//! and fit [`SCREENSHOT_MAX_BYTES`] — any failure SOFT-FAILS (BND-5): the
//! screenshot is omitted with a manifest note and the report still lands.
//! With `include_screenshot: false` the bundle contains no screenshot item
//! anywhere — not even a manifest note (PREV-3).
//!
//! ## The approved-bytes handoff (preview handle)
//!
//! Preview and submit are two RPCs; logs can grow between them, so "one code
//! path composes both" is not enough — the user approves bundle A and must
//! not spool bundle B. `compose_preview` therefore stores the composed bundle
//! under a random opaque `preview_id`, alongside the [`ComposeKey`] of the
//! inputs it was composed from; `submit {preview_id}` enqueues the STORED
//! bundle byte-for-byte when the handle is still valid (same CAR home, same
//! compose inputs after normalization — trimmed description, toggle flags,
//! screenshot byte hash — inside [`PREVIEW_TTL`]).
//!
//! A `preview_id` that is missing, expired, or whose stored inputs mismatch
//! the submit's inputs is REFUSED with a structured error whose message
//! carries the literal `PREVIEW_EXPIRED` token (the pinned wire seam; hosts
//! key their re-preview flow off it). It must NEVER silently compose fresh:
//! the user approved specific bytes in the consent sheet, and substituting
//! freshly-composed ones would spool content nobody saw (re-review finding
//! #1). Only a submit WITHOUT a `preview_id` composes fresh — that is the
//! CLI/no-preview path, where the submit params themselves are the consent.

use std::collections::VecDeque;
use std::path::{Path, PathBuf};
use std::sync::{Mutex as StdMutex, OnceLock};
use std::time::{Duration, Instant};

use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine as _;
use serde::Deserialize;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use uuid::Uuid;

use car_feedback_core::bundle::{
    collect, extract_dedup_from_named_logs, valid_manifest_id, BundleItem, CollectInputs,
    NamedLogInput, RedactedBundle,
};
use car_feedback_core::spool::{
    EnqueueOutcome, IdentityLane, Spool, SpoolEntryId, SpoolEntrySummary, SpoolState,
    ThrottleVerdict,
};
use car_parslee::feedback_transport::ServerReportRow;

use crate::handler::JsonRpcMessage;
use crate::session::ServerState;

/// Spool directory under the CAR state root — the U3 spool contract's
/// conventional root (`<CAR_HOME>/feedback-outbox`).
pub(crate) const FEEDBACK_OUTBOX_DIR: &str = "feedback-outbox";

/// The daemon stderr tee's file name under `<CAR_HOME>/logs` (plan capture
/// manifest item 6; the tee itself ships in a sibling unit of this PR). Named
/// here so the log set includes it the moment the tee exists — absence is a
/// clean "missing" manifest note, never an error.
pub(crate) const DAEMON_STDERR_TEE_FILE: &str = "car-server.stderr.log";

/// Decoded screenshot ceiling — mirrors the ChatAttachments per-image cap
/// (`ChatAttachments.swift`: 1568px max edge, JPEG, ≤5MB/image). Server-side
/// defense: the host pipeline enforces this before encoding, but the daemon
/// must not trust that — and the WebSocket layer is NOT the bound either:
/// `handler.rs` accepts with `accept_async` and installs no `WebSocketConfig`,
/// so tokio-tungstenite's defaults apply (16 MiB per frame, but 64 MiB per
/// multi-frame message), and a client can deliver a ~60 MiB `screenshot_b64`
/// in one request. This cap, its pre-decode twin [`SCREENSHOT_B64_MAX_LEN`],
/// and [`DESCRIPTION_MAX_CHARS`] are the enforcement.
pub(crate) const SCREENSHOT_MAX_BYTES: usize = 5 * 1024 * 1024;

/// The longest base64 text a payload within [`SCREENSHOT_MAX_BYTES`] can
/// encode to (4 chars per 3 bytes, rounded up to one padded quartet). Checked
/// against `screenshot_b64.len()` BEFORE decoding, so an oversize payload is
/// refused on its string length alone and the decoded bytes are never
/// materialized; an encoding of ≤ the cap is never refused by this gate.
pub(crate) const SCREENSHOT_B64_MAX_LEN: usize = SCREENSHOT_MAX_BYTES * 4 / 3 + 4;

/// Description ceiling, enforced at param parse — before any compose — so an
/// over-long description is a clear refusal, never a multi-MB redaction pass
/// or a spooled entry the server will 400. The bound is the server's own
/// (`docs/plans/2026-08-31-car-feedback-system.md` L226: the server enforces
/// 10–5000 chars after trim); the transport's constant is the single source
/// of truth, re-validated again at drain time. The 10-char minimum stays a
/// host-side novice prompt — the daemon refuses only what the server would
/// certainly reject.
pub(crate) const DESCRIPTION_MAX_CHARS: usize =
    car_parslee::feedback_transport::DESCRIPTION_MAX_CHARS;

/// Title cap for the spool entry summary (the outbox list's one-line label).
const TITLE_MAX_CHARS: usize = 80;

/// The preview-handle cache holds at most this many composed bundles. Small
/// on purpose: one host shows one consent sheet at a time; a handful covers
/// re-previews from toggles while bounding daemon memory.
pub(crate) const PREVIEW_CACHE_CAP: usize = 5;

/// A stored preview expires this long after `compose_preview` returned it —
/// past that, `submit {preview_id}` composes fresh (the sheet has sat long
/// enough that "what the user approved" is itself stale).
pub(crate) const PREVIEW_TTL: Duration = Duration::from_secs(10 * 60);

// ---------------------------------------------------------------------------
// Wire params (snake_case, matching every existing daemon method — the Swift
// BrowserDrawer models decode `can_go_back`-style keys, so a camelCase island
// here would break host-side decoding conventions).
// ---------------------------------------------------------------------------

/// Params shared by `feedback.compose_preview` and `feedback.submit`.
/// Unknown fields are ignored (tolerant mappers, PAR-7348 lesson) — and there
/// is deliberately no path-shaped field to be tolerant ABOUT: a client-sent
/// `path`/`log_tails` extra is inert.
/// The preview-handle cache honors a `preview_id` only when the submit's
/// [`ComposeKey`] (normalized description, toggle flags, screenshot byte
/// hash, host version fields) EQUALS the previewed one — any real change
/// refuses the handle with `PREVIEW_EXPIRED`.
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ComposeParams {
    description: String,
    #[serde(default)]
    include_screenshot: bool,
    #[serde(default)]
    include_diagnostics: bool,
    #[serde(default)]
    screenshot_b64: Option<String>,
    /// Host app version (CFBundleShortVersionString), folded into the
    /// version stamp (capture manifest item 4) via the collector's
    /// `host_version_fields` — redacted like all caller JSON.
    #[serde(default)]
    host_version: Option<String>,
    /// Host OS version string, same folding as `host_version`.
    #[serde(default)]
    macos_version: Option<String>,
}

impl ComposeParams {
    /// Client-facing caps applied right after parse, BEFORE compose: the
    /// description must fit [`DESCRIPTION_MAX_CHARS`] after trim (the same
    /// normalization the server and [`ComposeKey`] apply). Structured like
    /// the parse errors (`invalid params: …`) so hosts treat it as one.
    fn validate(&self) -> Result<(), String> {
        let chars = self.description.trim().chars().count();
        if chars > DESCRIPTION_MAX_CHARS {
            return Err(format!(
                "invalid params: description is {chars} characters after trimming; the \
                 maximum is {DESCRIPTION_MAX_CHARS} — shorten it before submitting"
            ));
        }
        Ok(())
    }
}

/// The identity lane as it appears on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
enum LaneParam {
    Authenticated,
    Anonymous,
}

#[derive(Debug, Clone, Deserialize)]
struct SubmitParams {
    #[serde(flatten)]
    compose: ComposeParams,
    lane: LaneParam,
    #[serde(default)]
    org_id: Option<String>,
    /// Opaque handle from the last `feedback.compose_preview`. Present and
    /// valid ⇒ the daemon enqueues the STORED previewed bundle byte-for-byte.
    /// Present but expired/unknown/mismatched ⇒ the structured
    /// `PREVIEW_EXPIRED` error — never a silent fresh compose. Absent ⇒
    /// compose fresh (the no-preview consent path).
    #[serde(default)]
    preview_id: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct StatusParams {
    #[serde(default)]
    submission_id: Option<String>,
    /// Maximum rows returned by the all-entries form. Ignored when a
    /// submission_id selects one row.
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, Clone, Deserialize, Default)]
struct ListParams {
    /// Maximum rows returned. Values above [`FEEDBACK_LIST_MAX_LIMIT`] are
    /// clamped rather than rejected so older tolerant clients stay usable.
    #[serde(default)]
    limit: Option<usize>,
}

/// Default and hard ceiling for an outbox response. The spool itself retains
/// its full durable history; this only bounds one JSON-RPC response.
const FEEDBACK_LIST_DEFAULT_LIMIT: usize = 100;
const FEEDBACK_LIST_MAX_LIMIT: usize = 200;

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

/// `feedback.compose_preview` — assemble and return the exact post-redaction
/// bundle submit would spool. Persists nothing durable (PRIV-2's preview
/// half); the composed bundle is retained in the in-memory preview cache so
/// `feedback.submit {preview_id}` can enqueue the approved bytes verbatim.
pub(crate) async fn handle_compose_preview(
    req: &JsonRpcMessage,
    state: &ServerState,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let params: ComposeParams = parse_params(&req.params)?;
    params.validate()?;
    let home = car_home_dir(state)?;
    // The runtime snapshot walks every active session's event log; compose
    // only reads it when diagnostics are consented, so gather it only then.
    let daemon_ctx = if params.include_diagnostics {
        Some(daemon_runtime_context(state).await)
    } else {
        None
    };
    let session_id = session.client_id.clone();
    let diagnostics = state.feedback_diagnostics.clone();
    let (bundle, preview_id) = run_blocking(move || -> Result<_, String> {
        let bundle = compose_bundle(&params, &home, &diagnostics, daemon_ctx)?;
        let preview_id = store_preview(&session_id, &home, &params, &bundle);
        Ok((bundle, preview_id))
    })
    .await??;
    let bundle_value =
        serde_json::to_value(&bundle).map_err(|e| format!("serialize bundle: {e}"))?;
    let manifest = bundle_value.get("manifest").cloned().unwrap_or(Value::Null);
    Ok(json!({
        "bundle": bundle_value,
        "manifest": manifest,
        "preview_id": preview_id,
    }))
}

/// `feedback.submit` — the SAME [`compose_bundle`] output as the preview,
/// durably enqueued. The only spool-writing path in this crate (PRIV-2).
pub(crate) async fn handle_submit(
    req: &JsonRpcMessage,
    state: &ServerState,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let params: SubmitParams = parse_params(&req.params)?;
    params.compose.validate()?;
    let active_org = state
        .parslee_session
        .get()
        .and_then(|session| session.identity.active_organization.as_deref())
        .filter(|org| !org.trim().is_empty());
    let lane = resolve_lane(params.lane, params.org_id.as_deref(), active_org)?;

    let home = car_home_dir(state)?;
    // Same laziness as the preview: the snapshot costs O(sessions × log
    // size) on the hot consent path, and only a FRESH compose with
    // diagnostics consented reads it — the handle path enqueues the stored
    // preview byte-for-byte and never looks at it.
    let daemon_ctx = if params.preview_id.is_none() && params.compose.include_diagnostics {
        Some(daemon_runtime_context(state).await)
    } else {
        None
    };
    let session_id = session.client_id.clone();
    let diagnostics = state.feedback_diagnostics.clone();
    run_blocking(move || -> Result<Value, String> {
        // The approved-bytes handoff: a valid preview handle enqueues the
        // STORED previewed bundle byte-for-byte. A handle that fails to
        // redeem (unknown, expired, or composed from different inputs) is
        // REFUSED — silently composing fresh would spool bytes the user
        // never saw in the consent sheet (re-review finding #1). Only a
        // submit WITHOUT a handle composes fresh.
        //
        // A redeemed entry is HELD whole (not yet forgotten) until the
        // enqueue below actually lands: the throttle verdict comes out of the
        // atomic `enqueue_if_allowed` pair, so a Throttled outcome — or a
        // spool failure — hands the entry back via `SubmitBundle::release`
        // and the user retries with the same handle instead of re-consenting
        // to a fresh preview for a report that never landed (finding F10).
        let source = match params.preview_id.as_deref() {
            Some(id) => match take_preview(id, &session_id, &home, &params.compose) {
                Some(entry) => SubmitBundle::Previewed(entry),
                None => return Err(preview_expired_error()),
            },
            None => SubmitBundle::Fresh(compose_bundle(
                &params.compose,
                &home,
                &diagnostics,
                daemon_ctx,
            )?),
        };
        let title = title_from_description(&source.bundle().description);

        let spool = match open_spool(&home) {
            Ok(spool) => spool,
            Err(e) => {
                source.release();
                return Err(e);
            }
        };
        // Client-side per-install throttle (plan requirement 12), checked and
        // enqueued ATOMICALLY under the spool's cross-process lock (the U3
        // `enqueue_if_allowed` pair) so a concurrent CLI enqueue cannot
        // jointly exceed the cap; no stable install identifier is ever needed
        // server-side.
        let id = match spool.enqueue_if_allowed(source.bundle(), lane, &title) {
            Ok(EnqueueOutcome::Enqueued(id)) => id,
            Ok(EnqueueOutcome::Throttled(verdict)) => {
                // Nothing was written: the approved bytes stay redeemable.
                source.release();
                return Err(throttled_error(verdict));
            }
            Err(e) => {
                source.release();
                return Err(format!("feedback spool enqueue failed: {e}"));
            }
        };
        // The entry is durable from here on. Wake the drain (U5) so it starts
        // uploading without any poll — a no-op when no drain is running
        // (CLI/tests) — and report success whatever the read-back below does.
        crate::feedback_drain::wake_feedback_drain();

        // `enqueue` mints the client_submission_id internally (the IDEM-1
        // idempotency key); read it back through the contract's list surface.
        submit_result(&id, spool.list())
    })
    .await?
}

/// The `feedback.submit` result for a DURABLY enqueued entry. `read_back` is
/// the spool's list surface — the canonical source of the minted
/// `client_submission_id`. Its failure must NOT become an RPC error (grace
/// r2): the enqueue already landed, the host would render the error as a
/// failed submit, and the user's retry would mint a SECOND entry — a
/// duplicate report that also double-spends the hourly throttle and that the
/// drain later uploads twice. So a failed read-back (or a listing that
/// somehow misses the entry) degrades to the locally known facts: the id is
/// authoritative, the state is Queued by construction, and the idempotency
/// key is recovered from the entry id ([`client_submission_id_from_entry_id`])
/// — `null` only if even that fails, which the host decodes as optional.
fn submit_result(
    id: &SpoolEntryId,
    read_back: std::io::Result<Vec<SpoolEntrySummary>>,
) -> Result<Value, String> {
    let summary = match read_back {
        Ok(rows) => rows.into_iter().find(|s| &s.id == id),
        Err(e) => {
            tracing::warn!(
                target: "car::feedback",
                entry = %id, error = %e,
                "feedback spool read-back failed after a durable enqueue; \
                 reporting the enqueued entry from local facts"
            );
            None
        }
    };
    let (client_submission_id, state) = match summary {
        Some(s) => (Some(s.client_submission_id), s.state),
        None => (client_submission_id_from_entry_id(id), SpoolState::Queued),
    };
    Ok(json!({
        "submission_id": id.as_str(),
        "client_submission_id": client_submission_id,
        "state": state_value(&state)?,
        "source": "local",
    }))
}

/// Recover the idempotency key from an entry id — the read-back FALLBACK
/// only. The spool mints ids as `<zero-padded creation millis>-<uuid>` where
/// the UUID IS the entry's `client_submission_id`; the suffix is validated as
/// a UUID so a format change yields `None` rather than a wrong key, and
/// `entry_id_carries_the_client_submission_id` pins the equality against a
/// real enqueue so such a change fails this crate's tests.
fn client_submission_id_from_entry_id(id: &SpoolEntryId) -> Option<String> {
    let (_, suffix) = id.as_str().split_once('-')?;
    Uuid::parse_str(suffix).ok()?;
    Some(suffix.to_string())
}

/// `feedback.status {submission_id?}` — one entry's local state, or all when
/// no id is given (same rows as `feedback.list`). The single-entry form also
/// carries `description` — the stored bundle's redacted description, read
/// back from the persisted artifact via `Spool::load_bundle` (the pinned wire
/// seam; finding #19's daemon half). The all-entries form stays summary-only:
/// loading every bundle to list the outbox would defeat the summary contract.
pub(crate) async fn handle_status(
    req: &JsonRpcMessage,
    state: &ServerState,
) -> Result<Value, String> {
    let params: StatusParams = parse_params(&req.params)?;
    let home = car_home_dir(state)?;
    run_blocking(move || -> Result<Value, String> {
        let spool = open_spool(&home)?;
        let entries = if let Some(wanted) = &params.submission_id {
            let rows = spool
                .list()
                .map_err(|e| format!("feedback spool list failed: {e}"))?;
            let row = rows
                .into_iter()
                .find(|r| r.id.as_str() == wanted)
                .ok_or_else(|| format!("unknown submission_id: {wanted}"))?;
            let description = match spool.load_bundle(&row.id) {
                Ok(bundle) => Some(bundle.description),
                Err(error) => {
                    tracing::warn!(
                        target: "car::feedback",
                        entry = %row.id,
                        error = %error,
                        "feedback bundle is unreadable; returning its durable status without a description"
                    );
                    None
                }
            };
            let mut value = summary_value(&row)?;
            if let Some(map) = value.as_object_mut() {
                map.insert(
                    "description".to_string(),
                    description.map(Value::String).unwrap_or(Value::Null),
                );
            }
            vec![value]
        } else {
            summaries(&spool)?
        };
        let (entries, has_more) = if params.submission_id.is_some() {
            (entries, false)
        } else {
            limit_rows(entries, params.limit)
        };
        Ok(json!({
            "entries": entries,
            "has_more": has_more,
            "staleness": staleness_value(&spool)?,
        }))
    })
    .await?
}

/// `feedback.list {}` — every local spool entry, oldest first, merged with
/// the signed-in user's server-side report rows (source `"server"`), plus the
/// SPOOL-3 staleness notice when any pending entry has waited too long.
/// Signed out, the list is local-only and no network is touched.
pub(crate) async fn handle_list(
    req: &JsonRpcMessage,
    state: &ServerState,
) -> Result<Value, String> {
    let params: ListParams = parse_params(&req.params)?;
    let home = car_home_dir(state)?;
    let server_rows = fetch_server_rows(state).await;
    run_blocking(move || -> Result<Value, String> {
        let spool = open_spool(&home)?;
        let mut entries = summaries(&spool)?;
        if let Some(rows) = server_rows {
            entries = merge_server_rows(entries, rows);
        }
        let (entries, has_more) = limit_rows(entries, params.limit);
        Ok(json!({
            "entries": entries,
            "has_more": has_more,
            "staleness": staleness_value(&spool)?,
        }))
    })
    .await?
}

// ---------------------------------------------------------------------------
// The one compose path (PREV-2)
// ---------------------------------------------------------------------------

/// Assemble the redacted bundle for THIS machine: the daemon-built named-log
/// set, the doctor report and runtime context when diagnostics are consented,
/// and the host-supplied screenshot when consented — all through
/// [`car_feedback_core::bundle::collect`], which redacts before returning.
///
/// Preview and submit both call exactly this function with exactly the
/// caller's params; there is no second assembly path (PREV-2 / requirement 8).
/// `daemon_ctx` is the [`daemon_runtime_context`] snapshot gathered by the
/// async handler (capture manifest item 7) — it rides `runtime_context`
/// through the collector, so it is redacted like everything else and visible
/// in the preview manifest. It is only read when `include_diagnostics` is
/// set, so the handlers pass `None` otherwise (and unit tests without a
/// ServerState always do); the minimal version-only fallback below covers a
/// diagnostics-on compose handed `None`.
#[derive(Debug, Clone, Copy)]
enum FeedbackDiagnosticsProbe {
    Production,
    Isolated,
}

/// Model-discovery inputs used when feedback composition actually runs.
/// Production resolves CAR's shared model cache lazily at compose time;
/// integration tests inject private roots and an inert registry instead.
#[derive(Debug, Clone)]
pub(crate) enum FeedbackDiagnostics {
    Production,
    Isolated {
        models_dir: PathBuf,
        huggingface_hub_root: PathBuf,
    },
}

impl FeedbackDiagnostics {
    pub(crate) fn production() -> Self {
        Self::Production
    }

    pub(crate) fn isolated(models_dir: PathBuf, huggingface_hub_root: PathBuf) -> Self {
        Self::Isolated {
            models_dir,
            huggingface_hub_root,
        }
    }
}

pub(crate) fn compose_bundle(
    params: &ComposeParams,
    car_home: &Path,
    diagnostics: &FeedbackDiagnostics,
    daemon_ctx: Option<Value>,
) -> Result<RedactedBundle, String> {
    match diagnostics {
        FeedbackDiagnostics::Production => {
            let models_dir = car_inference::default_models_dir();
            compose_bundle_at(
                params,
                car_home,
                &models_dir,
                None,
                FeedbackDiagnosticsProbe::Production,
                daemon_ctx,
            )
        }
        FeedbackDiagnostics::Isolated {
            models_dir,
            huggingface_hub_root,
        } => compose_bundle_at(
            params,
            car_home,
            models_dir,
            Some(huggingface_hub_root),
            FeedbackDiagnosticsProbe::Isolated,
            daemon_ctx,
        ),
    }
}

fn compose_bundle_at(
    params: &ComposeParams,
    car_home: &Path,
    models_dir: &Path,
    isolated_huggingface_hub: Option<&Path>,
    probe: FeedbackDiagnosticsProbe,
    daemon_ctx: Option<Value>,
) -> Result<RedactedBundle, String> {
    let mut inputs = CollectInputs {
        description: params.description.clone(),
        state_root: Some(car_home.to_path_buf()),
        ..CollectInputs::default()
    };

    // Host-passed version fields fold into the version stamp (capture
    // manifest item 4) regardless of the diagnostics toggle — the stamp is a
    // standing item, and these are version strings, not diagnostics.
    if params.host_version.is_some() || params.macos_version.is_some() {
        inputs.host_version_fields = Some(json!({
            "host_version": params.host_version,
            "macos_version": params.macos_version,
        }));
    }

    let mut post_notes: Vec<BundleItem> = Vec::new();
    if params.include_diagnostics {
        let (log_tails, manifest_notes) = named_log_set(car_home);
        // Dedup material (capture manifest item 8): extracted from the SAME
        // closed named-log set the bundle collects — no other path is ever
        // read. The logs directory is the one `named_log_set` joined every
        // path under (`<state root>/logs`); the extractor canonicalizes it
        // and refuses any named path outside it (the #5 containment gate).
        // None (no error line anywhere) leaves the bundle without a dedup
        // signature; item 8 is optional by design.
        inputs.dedup = extract_dedup_from_named_logs(&log_tails, &car_home.join("logs"));
        inputs.log_tails = log_tails;
        for note in manifest_notes {
            post_notes.push(omitted_item("log:supervised-agents", note));
        }
        // `car doctor`'s offline diagnosis, serialized (capture manifest item
        // 3). State follows CAR_HOME while weights stay in the same
        // machine-global cache the inference engine uses.
        let opts = car_inference::doctor::DoctorOptions::default();
        let report = match probe {
            FeedbackDiagnosticsProbe::Isolated => car_inference::doctor::diagnose_at_isolated(
                car_home,
                models_dir,
                isolated_huggingface_hub
                    .expect("isolated feedback diagnostics always carry a Hugging Face root"),
                &opts,
            ),
            FeedbackDiagnosticsProbe::Production => {
                car_inference::doctor::diagnose_at(car_home, models_dir, &opts)
            }
        };
        match serde_json::to_value(&report) {
            Ok(v) => inputs.doctor_report = Some(v),
            Err(e) => post_notes.push(omitted_item(
                "doctor_report",
                format!("unserializable: {e}"),
            )),
        }
        // Daemon-held runtime context (capture manifest item 7): daemon
        // identity (version/pid/role), connection state, active session +
        // agent ids, pending-approvals count. Small named fields only —
        // never journals/trajectories (RED-7).
        inputs.runtime_context = Some(daemon_ctx.unwrap_or_else(|| {
            json!({
                "daemon_version": env!("CARGO_PKG_VERSION"),
                "protocol_version": car_proto::PROTOCOL_VERSION,
            })
        }));
    } else {
        post_notes.push(omitted_item("diagnostics", "excluded by user toggle"));
    }

    let mut bundle = collect(inputs).map_err(|e| e.to_string())?;

    // Screenshot (capture manifest item 2) — consent toggle is authoritative:
    // when off, the supplied bytes are DROPPED and no screenshot item exists
    // anywhere in the bundle, not even a manifest note (PREV-3). When on, the
    // payload is validated (base64, JPEG SOI/EOI magic, size cap) and any
    // failure SOFT-FAILS per BND-5: the screenshot is omitted with a manifest
    // note and the report continues — a bad screenshot must never abort the
    // submission.
    if params.include_screenshot {
        match validate_screenshot(params.screenshot_b64.as_deref()) {
            Ok((b64, byte_len)) => {
                let entry = json!({ "jpeg_b64": b64, "byte_len": byte_len });
                match &mut bundle.runtime_context {
                    Some(Value::Object(map)) => {
                        map.insert("screenshot".to_string(), entry);
                    }
                    // Diagnostics off (or a non-object context, which this
                    // module never builds): the screenshot becomes the whole
                    // context object.
                    other => *other = Some(json!({ "screenshot": entry })),
                }
                bundle.manifest.items.push(BundleItem {
                    name: "screenshot".to_string(),
                    bytes: b64.len() as u64,
                    included: true,
                    truncated: false,
                    moved_to_overflow: false,
                    note: None,
                });
                bundle.manifest.total_inline_bytes += b64.len() as u64;
            }
            Err(note) => post_notes.push(omitted_item("screenshot", note)),
        }
    }

    bundle.manifest.items.extend(post_notes);
    Ok(bundle)
}

/// Validate a consented screenshot payload (BND-5's soft-fail arm): base64
/// that decodes, JPEG SOI (`FF D8 FF`) + EOI (`FF D9`) magic, and the
/// [`SCREENSHOT_MAX_BYTES`] cap. `Ok` returns the b64 (borrowed) plus the
/// decoded byte length; `Err` is the human-readable manifest omitted-note.
fn validate_screenshot(b64: Option<&str>) -> Result<(&str, usize), String> {
    let Some(b64) = b64 else {
        return Err("requested but no screenshot_b64 supplied".to_string());
    };
    // Length gate BEFORE decode (finding F9): base64 text longer than
    // [`SCREENSHOT_B64_MAX_LEN`] cannot decode to ≤ the cap, so it is refused
    // on its length alone — a 100 MB string never becomes 75 MB of bytes.
    // Same soft-fail as the post-decode cap check (BND-5): omitted + note.
    if b64.len() > SCREENSHOT_B64_MAX_LEN {
        return Err(format!(
            "exceeds the {SCREENSHOT_MAX_BYTES}-byte cap ({} bytes of base64 text, over the \
             {SCREENSHOT_B64_MAX_LEN}-byte encoded ceiling; not decoded) — screenshot omitted",
            b64.len()
        ));
    }
    let decoded = BASE64
        .decode(b64.as_bytes())
        .map_err(|e| format!("invalid base64 ({e}) — screenshot omitted"))?;
    if decoded.len() > SCREENSHOT_MAX_BYTES {
        return Err(format!(
            "exceeds the {SCREENSHOT_MAX_BYTES}-byte cap ({} bytes) — screenshot omitted",
            decoded.len()
        ));
    }
    let has_soi = decoded.len() >= 4 && decoded.starts_with(&[0xFF, 0xD8, 0xFF]);
    let has_eoi = decoded.len() >= 4 && decoded.ends_with(&[0xFF, 0xD9]);
    if !has_soi || !has_eoi {
        return Err("not a JPEG (missing SOI/EOI magic) — screenshot omitted".to_string());
    }
    Ok((b64, decoded.len()))
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Bind the identity lane at the consent moment (plan requirement 14).
/// `org_id` alongside an anonymous lane is ignored on purpose: the anonymous
/// lane must carry no org identity into the spooled state.
fn resolve_lane(
    lane: LaneParam,
    claimed_org_id: Option<&str>,
    active_org_id: Option<&str>,
) -> Result<IdentityLane, String> {
    match lane {
        LaneParam::Anonymous => Ok(IdentityLane::Anonymous),
        LaneParam::Authenticated => {
            let active = active_org_id.ok_or_else(|| {
                "lane \"authenticated\" requires a signed-in Parslee session with an active \
                 organization — submit signed-out reports with lane \"anonymous\""
                    .to_string()
            })?;
            // A legacy/current host may still echo the org it observed. It is
            // only a consistency assertion: authority comes from the daemon's
            // authenticated Parslee session, never from caller JSON.
            if let Some(claimed) = claimed_org_id {
                if claimed != active {
                    return Err(
                        "invalid params: claimed 'org_id' does not match the signed-in session's \
                         active organization"
                            .to_string(),
                    );
                }
            }
            car_parslee::feedback_transport::validate_org_id(active).map_err(|reason| {
                format!(
                    "signed-in session has an invalid active organization id ({reason}) — \
                     choose a valid Parslee organization before submitting"
                )
            })?;
            Ok(IdentityLane::Authenticated {
                org_id: active.to_string(),
            })
        }
    }
}

fn parse_params<T: for<'de> Deserialize<'de>>(params: &Value) -> Result<T, String> {
    // A JSON-RPC call with no params arrives as Value::Null; treat it as {}.
    let value = if params.is_null() {
        json!({})
    } else {
        params.clone()
    };
    serde_json::from_value(value).map_err(|e| format!("invalid params: {e}"))
}

/// The CAR state root this daemon runs against, derived from the state's
/// journal dir exactly the way the chat-goals store derives it
/// (`journal_dir`'s parent is the car dir), falling back to the process-env
/// resolution for embedders with a bare relative journal dir.
pub(crate) fn car_home_dir(state: &ServerState) -> Result<PathBuf, String> {
    state
        .journal_dir
        .parent()
        .map(PathBuf::from)
        .filter(|p| !p.as_os_str().is_empty())
        .or_else(car_home::root)
        .ok_or_else(|| "no CAR state root resolved (no journal dir parent, no home)".to_string())
}

fn open_spool(car_home: &Path) -> Result<Spool, String> {
    Spool::open(&car_home.join(FEEDBACK_OUTBOX_DIR))
        .map_err(|e| format!("feedback spool unavailable: {e}"))
}

/// The FIXED named-log set (capture manifest items 5–6): one
/// `<id>.{stdout,stderr}` pair per supervised agent named in the registry
/// manifest, plus the daemon stderr tee. Only the manifest's `id` field is
/// read — env maps and everything else in `agents.json` never enter the
/// bundle (RED-1's collector half). Every deserialized id passes
/// [`valid_manifest_id`] BEFORE being joined into a path: a corrupt or
/// hand-edited manifest id (`../…`, absolute, separators) must not be able
/// to point the log read outside `logs/` (finding #5's manifest half); an
/// invalid id skips that agent with a manifest note. Returns the manifest
/// notes (unreadable manifest / skipped invalid ids) — the report still
/// submits either way.
fn named_log_set(car_home: &Path) -> (Vec<NamedLogInput>, Vec<String>) {
    let logs = car_home.join("logs");
    let mut out = Vec::new();
    let mut notes = Vec::new();
    match car_registry::supervisor::Supervisor::list_from_manifest(&car_home.join("agents.json")) {
        Ok(agents) => {
            for agent in agents {
                let id = agent.spec.id;
                if !valid_manifest_id(&id) {
                    // Deliberately does NOT echo the raw id: it is untrusted
                    // manifest content, and the note is enough to diagnose.
                    notes.push(
                        "agents.json entry with an invalid id skipped — its logs are omitted"
                            .to_string(),
                    );
                    continue;
                }
                out.push(NamedLogInput {
                    name: format!("{id}.stdout"),
                    path: logs.join(format!("{id}.stdout.log")),
                    max_bytes: None,
                });
                out.push(NamedLogInput {
                    name: format!("{id}.stderr"),
                    path: logs.join(format!("{id}.stderr.log")),
                    max_bytes: None,
                });
            }
        }
        Err(e) => notes.push(format!("agents.json unreadable: {e}")),
    };
    // The daemon stderr tee (item 6). Included unconditionally: when the tee
    // has not written yet, the collector notes it "missing" — an honest
    // manifest row beats a silent omission.
    out.push(NamedLogInput {
        name: "car-server.stderr".to_string(),
        path: logs.join(DAEMON_STDERR_TEE_FILE),
        max_bytes: None,
    });
    (out, notes)
}

// ---------------------------------------------------------------------------
// Preview-handle cache (the approved-bytes handoff, finding #1)
// ---------------------------------------------------------------------------

/// The literal token the expired-handle error message carries on the wire —
/// the pinned seam hosts key their re-preview flow off. Structured exactly
/// like the module's other refusals (an error `message` string over the
/// standard JSON-RPC error shape, the way the throttle refusal is).
pub(crate) const PREVIEW_EXPIRED_TOKEN: &str = "PREVIEW_EXPIRED";

/// The structured refusal for a `preview_id` that is unknown, expired, or was
/// composed from different inputs. Deliberately one message for all three
/// causes: the recovery is identical (re-preview, re-approve), and
/// distinguishing "expired" from "unknown" would leak whether a given handle
/// ever existed.
fn preview_expired_error() -> String {
    format!(
        "{PREVIEW_EXPIRED_TOKEN}: the preview handle is missing, expired, or was composed \
         from different inputs — call feedback.compose_preview again and re-approve the \
         refreshed bundle"
    )
}

/// The compose inputs a preview handle is bound to — what redemption compares
/// (finding #1: an expired OR input-mismatched handle must refuse, so the
/// cache must persist the inputs alongside the bundle to detect the
/// mismatch). Normalized so the host's wire round-trip (it trims/clamps the
/// description before sending) cannot spuriously refuse a genuinely-unchanged
/// approval, while any REAL change — a description edit, a toggle flip,
/// different screenshot bytes — mismatches:
///
/// - `description` is compared trimmed (the same normalization on both the
///   preview and the submit side);
/// - the screenshot participates as a sha256 over its DECODED bytes (the
///   "screenshot byte hash" — the cache must not hold a second multi-MB
///   copy of the payload; an undecodable payload hashes its raw b64 so it
///   still compares stably);
/// - the toggles and host version fields compare verbatim.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ComposeKey {
    description: String,
    include_screenshot: bool,
    include_diagnostics: bool,
    screenshot_sha256: Option<String>,
    host_version: Option<String>,
    macos_version: Option<String>,
}

impl ComposeKey {
    fn of(params: &ComposeParams) -> Self {
        let screenshot_sha256 = params.screenshot_b64.as_deref().map(|b64| {
            let mut hasher = Sha256::new();
            // Same pre-decode length gate as `validate_screenshot` (finding
            // F9): an oversize payload can never ride the bundle, so it is
            // hashed as raw text like an undecodable one — the multi-MB
            // decode is skipped here too, and the key still compares stably.
            let decoded = if b64.len() > SCREENSHOT_B64_MAX_LEN {
                None
            } else {
                BASE64.decode(b64.as_bytes()).ok()
            };
            match decoded {
                Some(bytes) => hasher.update(&bytes),
                None => hasher.update(b64.as_bytes()),
            }
            format!("{:x}", hasher.finalize())
        });
        ComposeKey {
            description: params.description.trim().to_string(),
            include_screenshot: params.include_screenshot,
            include_diagnostics: params.include_diagnostics,
            screenshot_sha256,
            host_version: params.host_version.clone(),
            macos_version: params.macos_version.clone(),
        }
    }
}

/// One retained preview: the composed bundle plus the [`ComposeKey`] of what
/// it was composed FROM, so a submit can only redeem the handle for the same
/// home + inputs.
struct PreviewEntry {
    id: String,
    /// The exact WebSocket session that displayed this preview. A leaked
    /// handle is not consent for another authenticated connection.
    session_id: String,
    car_home: PathBuf,
    key: ComposeKey,
    bundle: RedactedBundle,
    stored_at: Instant,
}

/// Daemon-wide preview cache. A process-level static, like the drain's
/// `DRAIN_HANDLE`: one daemon process holds one preview cache, whatever
/// embedder built the `ServerState`. Entries are keyed by random UUIDs, so
/// two states in one test process cannot collide, and redemption re-checks
/// the CAR home besides the id.
static PREVIEW_CACHE: OnceLock<StdMutex<VecDeque<PreviewEntry>>> = OnceLock::new();

fn preview_cache() -> &'static StdMutex<VecDeque<PreviewEntry>> {
    PREVIEW_CACHE.get_or_init(|| StdMutex::new(VecDeque::new()))
}

/// Retain one composed preview and mint its opaque handle. Expired entries
/// are dropped first; the cache then evicts oldest-first past
/// [`PREVIEW_CACHE_CAP`] entries **per CAR home** (production runs one home
/// per daemon, so this IS the cap; scoping it per home keeps concurrent
/// test states from evicting each other's live previews).
fn store_preview(
    session_id: &str,
    car_home: &Path,
    params: &ComposeParams,
    bundle: &RedactedBundle,
) -> String {
    let id = Uuid::new_v4().to_string();
    let mut cache = preview_cache().lock().expect("preview cache poisoned");
    insert_preview(
        &mut cache,
        PreviewEntry {
            id: id.clone(),
            session_id: session_id.to_string(),
            car_home: car_home.to_path_buf(),
            key: ComposeKey::of(params),
            bundle: bundle.clone(),
            stored_at: Instant::now(),
        },
    );
    id
}

/// The one insertion discipline, shared by a fresh store and a restore:
/// expired entries dropped first, then oldest-first eviction past
/// [`PREVIEW_CACHE_CAP`] per CAR home.
fn insert_preview(cache: &mut VecDeque<PreviewEntry>, entry: PreviewEntry) {
    let car_home = entry.car_home.clone();
    cache.retain(|e| e.stored_at.elapsed() < PREVIEW_TTL);
    cache.push_back(entry);
    // Oldest-first eviction by CONSENT TIME, not deque position: a restored
    // entry ([`restore_preview`]) re-enters carrying its original `stored_at`
    // — possibly older than handles minted while its submit was in flight —
    // so position-based eviction would drop a newer unrelated handle instead
    // of the one the documented policy names (codex cross-review, F10).
    while cache.iter().filter(|e| e.car_home == car_home).count() > PREVIEW_CACHE_CAP {
        let oldest = cache
            .iter()
            .enumerate()
            .filter(|(_, e)| e.car_home == car_home)
            .min_by_key(|(_, e)| e.stored_at)
            .map(|(index, _)| index);
        match oldest {
            Some(index) => {
                cache.remove(index);
            }
            None => break,
        }
    }
}

/// Redeem a preview handle: `Some(entry)` only when the id exists, is inside
/// [`PREVIEW_TTL`], and was composed for the SAME CAR home from the SAME
/// [`ComposeKey`] (a description edit, toggle flip, or screenshot change
/// mismatches; the caller turns `None` into the `PREVIEW_EXPIRED` refusal).
/// Redemption consumes the entry — a handle spools at most once — and hands
/// the WHOLE entry back so a submit that then fails to enqueue can
/// [`restore_preview`] it unchanged.
fn take_preview(
    id: &str,
    session_id: &str,
    car_home: &Path,
    params: &ComposeParams,
) -> Option<PreviewEntry> {
    let key = ComposeKey::of(params);
    let mut cache = preview_cache().lock().expect("preview cache poisoned");
    cache.retain(|e| e.stored_at.elapsed() < PREVIEW_TTL);
    let position = cache.iter().position(|e| {
        e.id == id && e.session_id == session_id && e.car_home == car_home && e.key == key
    })?;
    cache.remove(position)
}

/// Hand a redeemed-but-unspooled entry back (finding F10). `feedback.submit`
/// consumes the entry BEFORE the atomic throttle-check + enqueue, so a
/// Throttled verdict (or a spool failure) would otherwise burn the user's
/// approved bytes and force a re-preview + re-consent for a report that
/// never landed. The entry returns with its ORIGINAL `stored_at` — the TTL
/// keeps counting from the consent moment — under the same cap discipline as
/// a fresh store. Only a non-enqueue outcome may restore: restoring after a
/// successful enqueue would let one handle spool twice.
fn restore_preview(entry: PreviewEntry) {
    let mut cache = preview_cache().lock().expect("preview cache poisoned");
    insert_preview(&mut cache, entry);
}

/// What one `feedback.submit` spools: the bytes a redeemed preview handle
/// holds — kept whole so a non-enqueue outcome can hand the handle back — or
/// a fresh compose (the handle-less consent path).
enum SubmitBundle {
    Previewed(PreviewEntry),
    Fresh(RedactedBundle),
}

impl SubmitBundle {
    fn bundle(&self) -> &RedactedBundle {
        match self {
            SubmitBundle::Previewed(entry) => &entry.bundle,
            SubmitBundle::Fresh(bundle) => bundle,
        }
    }

    /// Nothing landed in the spool: a redeemed handle goes back to the cache
    /// ([`restore_preview`], finding F10); a fresh compose is simply dropped.
    fn release(self) {
        if let SubmitBundle::Previewed(entry) = self {
            restore_preview(entry);
        }
    }
}

/// The throttle refusal (plan requirement 12) for a non-enqueued submit.
fn throttled_error(verdict: ThrottleVerdict) -> String {
    match verdict {
        ThrottleVerdict::Throttled {
            used_in_window,
            limit,
            retry_after_secs,
        } => format!(
            "feedback submission throttled: {used_in_window}/{limit} reports in the \
             last hour — retry in {retry_after_secs}s"
        ),
        ThrottleVerdict::Allowed { .. } => {
            "feedback spool returned an inconsistent throttle verdict".to_string()
        }
    }
}

/// Test-only clock control: age a stored preview backward so the TTL expiry
/// arm is testable without a ten-minute sleep. `Instant` cannot be forged, so
/// the entry's `stored_at` is rewound instead.
#[cfg(test)]
fn age_preview_for_test(id: &str, by: Duration) {
    let mut cache = preview_cache().lock().expect("preview cache poisoned");
    for entry in cache.iter_mut() {
        if entry.id == id {
            if let Some(rewound) = entry.stored_at.checked_sub(by) {
                entry.stored_at = rewound;
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Runtime context (capture manifest item 7, finding #17)
// ---------------------------------------------------------------------------

/// Snapshot the daemon-held runtime context the capture manifest's item 7
/// names: daemon identity (version / pid / manifest role), connection state,
/// active session + agent ids, the pending-approvals count, and the
/// per-session `metrics.summary` rollup — all read from `ServerState` where
/// the daemon already holds them. The snapshot rides
/// `CollectInputs::runtime_context`, so it goes through the normal redact
/// path and shows in the consent preview like every other item.
///
/// The metrics rollup (finding #17) is the in-process equivalent of the
/// `metrics.summary` RPC: `car_eventlog::summarize_log` over each active
/// session's runtime event log — the same fold `handle_metrics_summary`
/// serves per session, snapshotted here across all of them. The sessions map
/// is cloned out before any log lock is taken, so this never holds the
/// sessions mutex across an await.
async fn daemon_runtime_context(state: &ServerState) -> Value {
    let role = if state.observer_manifest_path().is_some() {
        "observer"
    } else {
        "primary"
    };
    let sessions: Vec<(String, std::sync::Arc<crate::session::ClientSession>)> = state
        .sessions
        .lock()
        .await
        .iter()
        .map(|(id, session)| (id.clone(), session.clone()))
        .collect();
    let mut session_ids: Vec<String> = sessions.iter().map(|(id, _)| id.clone()).collect();
    session_ids.sort();
    let mut metrics_summary: Vec<Value> = Vec::new();
    for (id, session) in &sessions {
        let summary = {
            let log = session.runtime.log.lock().await;
            car_eventlog::summarize_log(&log)
        };
        if let Ok(value) = serde_json::to_value(&summary) {
            metrics_summary.push(json!({ "session_id": id, "summary": value }));
        }
    }
    metrics_summary.sort_by(|a, b| {
        a["session_id"]
            .as_str()
            .unwrap_or_default()
            .cmp(b["session_id"].as_str().unwrap_or_default())
    });
    let agents: Vec<Value> = state
        .host
        .agents()
        .await
        .into_iter()
        .map(|a| {
            json!({
                "id": a.id,
                "session_id": a.session_id,
                "status": a.status,
            })
        })
        .collect();
    let pending_approvals = state
        .host
        .approvals()
        .await
        .iter()
        .filter(|a| a.status == car_proto::HostApprovalStatus::Pending)
        .count();
    json!({
        "daemon_version": env!("CARGO_PKG_VERSION"),
        "protocol_version": car_proto::PROTOCOL_VERSION,
        "daemon": {
            "version": env!("CARGO_PKG_VERSION"),
            "pid": std::process::id(),
            "role": role,
        },
        "connection": {
            "active_ws_sessions": session_ids.len(),
            "parslee_session": state.parslee_session.get().is_some(),
        },
        "active_sessions": session_ids,
        "active_agents": agents,
        "pending_approvals": pending_approvals,
        "metrics_summary": metrics_summary,
    })
}

// ---------------------------------------------------------------------------
// Server-row merge for feedback.list (finding #13, daemon half)
// ---------------------------------------------------------------------------

/// Fetch the signed-in user's server report rows via the F2b transport
/// (`car_parslee::feedback_transport::fetch_my_feedback`), gated on session
/// presence: `None` (local-only list, ZERO network calls) unless a Parslee
/// session with an active organization is installed. Any fetch failure —
/// including a 401 — degrades to the local-only list rather than failing
/// `feedback.list`: the outbox view must work offline.
async fn fetch_server_rows(state: &ServerState) -> Option<Vec<ServerReportRow>> {
    let session = state.parslee_session.get()?;
    // The /mine route is org-in-route (IDOR-checked server-side against the
    // authenticated principal), so the fetch needs the session's active org.
    let org = session
        .identity
        .active_organization
        .as_deref()
        .filter(|org| !org.is_empty())?
        .to_string();
    let transport = match car_parslee::feedback_transport::FeedbackTransport::live() {
        Ok(t) => t,
        Err(e) => {
            tracing::debug!(
                target: "car::feedback",
                error = %e,
                "feedback.list server merge unavailable (no transport); local-only"
            );
            return None;
        }
    };
    match transport.fetch_my_feedback(&org).await {
        Ok(rows) => Some(rows),
        Err(e) => {
            tracing::debug!(
                target: "car::feedback",
                error = ?e,
                "feedback.list mine fetch failed; local-only"
            );
            None
        }
    }
}

/// Merge local spool rows with server rows, keyed on the SERVER row id ONLY:
/// a local row whose persisted `Acknowledged.server_id` matches a server
/// row's id shows the server's state (`source: "server"`, `server_status`, a
/// human-readable `note`); server rows with no local counterpart are appended
/// as `source: "server"` rows.
///
/// Honesty note (re-review finding #13, updated for the frozen contract):
/// the `/mine` route (`CarFeedbackMineItem` — see [`ServerReportRow`]) now
/// DOES expose `clientSubmissionId`, so a true dedupe of unacknowledged
/// local rows against their server counterparts is possible — that keying is
/// a recorded follow-up, and this merge still keys on acknowledged server
/// ids only. The invariant that survives either way: matching the local
/// `client_submission_id` against the SERVER id is a fabricated key — the
/// server id is a prefixed document id, never the client's idempotency key.
/// Bound a list response to its newest rows while retaining oldest-first order
/// within the returned window. A zero limit is valid and reports `has_more`
/// whenever any rows exist.
fn limit_rows(mut rows: Vec<Value>, requested: Option<usize>) -> (Vec<Value>, bool) {
    let limit = requested
        .unwrap_or(FEEDBACK_LIST_DEFAULT_LIMIT)
        .min(FEEDBACK_LIST_MAX_LIMIT);
    let has_more = rows.len() > limit;
    if has_more {
        rows = rows.split_off(rows.len() - limit);
    }
    (rows, has_more)
}

fn merge_server_rows(mut local: Vec<Value>, server: Vec<ServerReportRow>) -> Vec<Value> {
    let mut matched: Vec<String> = Vec::new();
    for row in &mut local {
        let acked_server_id = row["state"]["server_id"].as_str().map(str::to_string);
        let hit = server
            .iter()
            .find(|s| acked_server_id.as_deref() == Some(s.id.as_str()));
        if let (Some(s), Some(map)) = (hit, row.as_object_mut()) {
            map.insert("source".to_string(), json!("server"));
            map.insert("server_status".to_string(), json!(s.status));
            map.insert("server_updated_at".to_string(), json!(s.updated_at));
            map.insert(
                "note".to_string(),
                json!(format!("server status: {}", s.status)),
            );
            matched.push(s.id.clone());
        }
    }
    for s in &server {
        if matched.iter().any(|m| m == &s.id) {
            continue;
        }
        // A server report with no local counterpart (filed from another
        // install, or locally pruned past the TTL). Its one-line label comes
        // from the description the server holds (`/mine` exposes no AI
        // summary — the minimal-by-design row set).
        let title = s
            .description
            .as_deref()
            .map(title_from_description)
            .unwrap_or_else(|| "(server report)".to_string());
        local.push(json!({
            "id": s.id,
            "title": title,
            "source": "server",
            "server_status": s.status,
            "note": format!("server status: {}", s.status),
            "updated_at": s.updated_at,
        }));
    }
    local
}

fn omitted_item(name: &str, note: impl Into<String>) -> BundleItem {
    BundleItem {
        name: name.to_string(),
        bytes: 0,
        included: false,
        truncated: false,
        moved_to_overflow: false,
        note: Some(note.into()),
    }
}

/// One-line outbox label: the description's first line, capped at
/// [`TITLE_MAX_CHARS`] characters.
fn title_from_description(description: &str) -> String {
    let first_line = description.lines().next().unwrap_or("").trim();
    first_line.chars().take(TITLE_MAX_CHARS).collect()
}

fn state_value(state: &SpoolState) -> Result<Value, String> {
    serde_json::to_value(state).map_err(|e| format!("serialize spool state: {e}"))
}

/// Spool summaries as wire rows, each stamped `source: "local"` so wave 3's
/// server merge can add `source: "server"` rows without a wire change.
fn summaries(spool: &Spool) -> Result<Vec<Value>, String> {
    let rows = spool
        .list()
        .map_err(|e| format!("feedback spool list failed: {e}"))?;
    rows.iter().map(summary_value).collect()
}

/// One spool summary as a wire row, stamped `source: "local"`.
fn summary_value(row: &SpoolEntrySummary) -> Result<Value, String> {
    let mut value = serde_json::to_value(row).map_err(|e| format!("serialize summary: {e}"))?;
    if let Some(map) = value.as_object_mut() {
        map.insert("source".to_string(), Value::String("local".to_string()));
    }
    Ok(value)
}

fn staleness_value(spool: &Spool) -> Result<Value, String> {
    let notice = spool
        .staleness()
        .map_err(|e| format!("feedback spool staleness failed: {e}"))?;
    Ok(match notice {
        Some(n) => json!({
            "pending_count": n.pending_count,
            "oldest_age_days": n.oldest_age_days,
        }),
        None => Value::Null,
    })
}

/// The blocking-work seam: compose reads bounded log windows and the spool
/// does fsync-backed writes, so neither belongs on the async reactor.
async fn run_blocking<T, F>(work: F) -> Result<T, String>
where
    T: Send + 'static,
    F: FnOnce() -> T + Send + 'static,
{
    tokio::task::spawn_blocking(work)
        .await
        .map_err(|e| format!("feedback task failed: {e}"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn compose_params(description: &str) -> ComposeParams {
        ComposeParams {
            description: description.to_string(),
            include_screenshot: false,
            include_diagnostics: false,
            screenshot_b64: None,
            host_version: None,
            macos_version: None,
        }
    }

    fn compose_bundle(
        params: &ComposeParams,
        car_home: &Path,
        daemon_ctx: Option<Value>,
    ) -> Result<RedactedBundle, String> {
        let diagnostics = FeedbackDiagnostics::isolated(
            car_home.join("feedback-test-models"),
            car_home.join("feedback-test-huggingface-hub"),
        );
        super::compose_bundle(params, car_home, &diagnostics, daemon_ctx)
    }

    /// Minimal bytes that pass the JPEG SOI/EOI magic check.
    fn fake_jpeg() -> Vec<u8> {
        let mut v = vec![0xFF, 0xD8, 0xFF, 0xE0];
        v.extend_from_slice(b"jfif-pixel-payload");
        v.extend_from_slice(&[0xFF, 0xD9]);
        v
    }

    #[test]
    fn title_is_first_line_capped_at_80_chars() {
        assert_eq!(title_from_description("hello\nworld"), "hello");
        let long = "x".repeat(200);
        assert_eq!(title_from_description(&long).chars().count(), 80);
        assert_eq!(title_from_description("  spaced  \nrest"), "spaced");
    }

    #[test]
    fn named_log_set_names_agent_pairs_and_the_stderr_tee_never_globs() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("agents.json"),
            r#"{"agents":[{"id":"agent-a","name":"A","command":"/bin/true"}]}"#,
        )
        .unwrap();
        // A stray file in logs/ must NOT be picked up: the set is built from
        // the manifest ids + the tee name, never from a directory listing.
        fs::create_dir_all(tmp.path().join("logs")).unwrap();
        fs::write(tmp.path().join("logs/stray.log"), "not yours").unwrap();

        let (set, notes) = named_log_set(tmp.path());
        assert!(notes.is_empty());
        let names: Vec<&str> = set.iter().map(|l| l.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["agent-a.stdout", "agent-a.stderr", "car-server.stderr"]
        );
        assert!(set.iter().all(|l| !l.path.ends_with("stray.log")));
    }

    #[test]
    fn named_log_set_missing_manifest_is_just_the_tee() {
        let tmp = TempDir::new().unwrap();
        let (set, notes) = named_log_set(tmp.path());
        assert!(notes.is_empty(), "an absent manifest is an empty agent set");
        assert_eq!(set.len(), 1);
        assert_eq!(set[0].name, "car-server.stderr");
    }

    #[test]
    fn named_log_set_corrupt_manifest_notes_and_still_includes_the_tee() {
        let tmp = TempDir::new().unwrap();
        fs::write(tmp.path().join("agents.json"), "{not json").unwrap();
        let (set, notes) = named_log_set(tmp.path());
        assert_eq!(notes.len(), 1);
        assert_eq!(set.len(), 1);
    }

    /// Finding #5 (manifest half), the distinguishing corrupt-id test: a
    /// traversal-shaped id deserialized from `agents.json` must NEVER be
    /// joined into a log path. Pre-fix code produced
    /// `logs/../../outside.stdout.log`-style paths; post-fix the agent is
    /// skipped with a manifest note and only valid ids + the tee remain.
    #[test]
    fn named_log_set_rejects_traversal_and_separator_ids_from_the_manifest() {
        let tmp = TempDir::new().unwrap();
        fs::write(
            tmp.path().join("agents.json"),
            r#"{"agents":[
                {"id":"../../outside","name":"Evil","command":"/bin/true"},
                {"id":"/etc/passwd","name":"Evil2","command":"/bin/true"},
                {"id":"good-agent","name":"Good","command":"/bin/true"}
            ]}"#,
        )
        .unwrap();

        let (set, notes) = named_log_set(tmp.path());
        let names: Vec<&str> = set.iter().map(|l| l.name.as_str()).collect();
        assert_eq!(
            names,
            vec![
                "good-agent.stdout",
                "good-agent.stderr",
                "car-server.stderr"
            ],
            "only the valid id and the tee may survive"
        );
        let logs_root = tmp.path().join("logs");
        assert!(
            set.iter().all(|l| l.path.starts_with(&logs_root)),
            "every named-log path must stay under logs/: {set:?}"
        );
        assert_eq!(notes.len(), 2, "each skipped id leaves a manifest note");
        assert!(notes.iter().all(|n| n.contains("invalid id")));
    }

    #[test]
    fn valid_manifest_id_matches_supervisor_rules() {
        for good in ["agent-a", "a_b.c", "A9"] {
            assert!(valid_manifest_id(good), "{good} should be valid");
        }
        for bad in ["", ".", "..", "../x", "a/b", "a\\b", "a b", "/abs"] {
            assert!(!valid_manifest_id(bad), "{bad} should be invalid");
        }
    }

    #[test]
    fn feedback_bundle_counts_models_from_the_global_cache_when_car_home_is_relocated() {
        let state_home = TempDir::new().unwrap();
        let global_cache = TempDir::new().unwrap();
        let huggingface_hub = TempDir::new().unwrap();
        let model = global_cache.path().join("Qwen3-Embedding-0.6B");
        fs::create_dir(&model).unwrap();
        fs::write(model.join("model.gguf"), b"weights").unwrap();
        let mut params = compose_params("model count must follow the runtime cache");
        params.include_diagnostics = true;

        let bundle = compose_bundle_at(
            &params,
            state_home.path(),
            global_cache.path(),
            Some(huggingface_hub.path()),
            FeedbackDiagnosticsProbe::Isolated,
            None,
        )
        .unwrap();
        assert!(
            !state_home.path().join("models").exists(),
            "the relocated state root must not contain the model weights"
        );
        assert_eq!(
            bundle.doctor_report.as_ref().unwrap()["installed_models"],
            json!(1),
            "only the model in the test-owned global cache may be counted"
        );
        assert_eq!(
            car_inference::doctor::diagnose_at_isolated(
                state_home.path(),
                &state_home.path().join("models"),
                huggingface_hub.path(),
                &car_inference::doctor::DoctorOptions::default(),
            )
            .installed_models,
            0,
            "the old state-root-derived weights path must remain empty"
        );
    }

    #[test]
    fn compose_with_screenshot_toggle_off_drops_supplied_bytes_entirely() {
        let tmp = TempDir::new().unwrap();
        let payload = BASE64.encode(fake_jpeg());
        let mut params = compose_params("something broke");
        params.screenshot_b64 = Some(payload.clone());
        params.include_screenshot = false;

        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();
        let serialized = serde_json::to_string(&bundle).unwrap();
        assert!(
            !serialized.contains("screenshot"),
            "toggle off must leave no screenshot item anywhere (PREV-3): {serialized}"
        );
        assert!(!serialized.contains(&payload));
    }

    #[test]
    fn compose_with_screenshot_toggle_on_accounts_it_in_the_manifest() {
        let tmp = TempDir::new().unwrap();
        let jpeg = fake_jpeg();
        let payload = BASE64.encode(&jpeg);
        let mut params = compose_params("something broke");
        params.screenshot_b64 = Some(payload.clone());
        params.include_screenshot = true;

        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();
        let context = bundle.runtime_context.as_ref().expect("screenshot context");
        assert_eq!(context["screenshot"]["jpeg_b64"], json!(payload));
        assert_eq!(context["screenshot"]["byte_len"], json!(jpeg.len()));
        let item = bundle
            .manifest
            .items
            .iter()
            .find(|i| i.name == "screenshot")
            .expect("manifest accounts the screenshot");
        assert!(item.included);
        assert_eq!(item.bytes, payload.len() as u64);
    }

    /// Finding #6, the distinguishing soft-fail tests: a text blob posing as
    /// a screenshot, an oversized payload, and undecodable base64 must each
    /// land the report WITHOUT the screenshot plus a manifest omitted-note —
    /// never abort the submission (BND-5). Pre-fix code returned `Err` for
    /// oversize/bad-base64 and silently accepted the non-JPEG blob.
    #[test]
    fn compose_soft_fails_non_jpeg_oversize_and_bad_base64_screenshots() {
        let tmp = TempDir::new().unwrap();

        let cases: Vec<(String, &str)> = vec![
            (
                BASE64.encode(b"just some text pretending to be a screenshot"),
                "not a JPEG",
            ),
            (BASE64.encode(vec![0u8; SCREENSHOT_MAX_BYTES + 1]), "cap"),
            ("!!!not-base64!!!".to_string(), "invalid base64"),
        ];
        for (payload, expected_note) in cases {
            let mut params = compose_params("desc");
            params.include_screenshot = true;
            params.screenshot_b64 = Some(payload.clone());

            let bundle = compose_bundle(&params, tmp.path(), None)
                .expect("a bad screenshot must not abort the report (BND-5)");
            assert!(
                bundle.runtime_context.is_none()
                    || bundle
                        .runtime_context
                        .as_ref()
                        .unwrap()
                        .get("screenshot")
                        .is_none(),
                "the bad screenshot must not ride the bundle"
            );
            let item = bundle
                .manifest
                .items
                .iter()
                .find(|i| i.name == "screenshot")
                .expect("the omission must be visible in the manifest");
            assert!(!item.included);
            let note = item.note.as_deref().unwrap_or_default();
            assert!(
                note.contains(expected_note),
                "note {note:?} should mention {expected_note:?}"
            );
            let serialized = serde_json::to_string(&bundle).unwrap();
            assert!(
                !serialized.contains(&payload),
                "payload bytes must be dropped"
            );
        }
    }

    /// Finding F9(b), the distinguishing test: base64 text just over the
    /// encoded ceiling is refused on LENGTH, before any decode. The payload is
    /// deliberately NOT valid base64 — pre-fix code decoded first and reported
    /// "invalid base64"; the post-fix note names the cap, which proves the
    /// decoder never ran on it. At exactly the ceiling the gate stays open
    /// and the decoder (not the gate) is what refuses the garbage.
    #[test]
    fn oversize_screenshot_b64_is_refused_by_length_before_any_decode() {
        let over = "!".repeat(SCREENSHOT_B64_MAX_LEN + 1);
        let note = validate_screenshot(Some(&over)).unwrap_err();
        assert!(
            note.contains("cap"),
            "length gate must name the cap: {note}"
        );
        assert!(
            !note.contains("invalid base64"),
            "an over-ceiling payload must never reach the decoder: {note}"
        );

        let at_ceiling = "!".repeat(SCREENSHOT_B64_MAX_LEN);
        let note = validate_screenshot(Some(&at_ceiling)).unwrap_err();
        assert!(
            note.contains("invalid base64"),
            "at the ceiling the decoder still runs (strict > gate): {note}"
        );

        // The ceiling never refuses a real payload at the cap: a JPEG of
        // exactly SCREENSHOT_MAX_BYTES encodes under it.
        let mut max_jpeg = vec![0xFF, 0xD8, 0xFF, 0xE0];
        max_jpeg.resize(SCREENSHOT_MAX_BYTES, 0u8);
        let n = max_jpeg.len();
        max_jpeg[n - 2] = 0xFF;
        max_jpeg[n - 1] = 0xD9;
        let b64 = BASE64.encode(&max_jpeg);
        assert!(b64.len() <= SCREENSHOT_B64_MAX_LEN);
        assert_eq!(
            validate_screenshot(Some(&b64)).unwrap().1,
            SCREENSHOT_MAX_BYTES
        );

        // The ComposeKey applies the same gate: an over-ceiling VALID base64
        // payload hashes its raw text (pre-fix it decoded all of it).
        let oversize_valid = BASE64.encode(vec![0u8; SCREENSHOT_MAX_BYTES + 1024]);
        assert!(oversize_valid.len() > SCREENSHOT_B64_MAX_LEN);
        let mut params = compose_params("desc");
        params.screenshot_b64 = Some(oversize_valid.clone());
        let mut raw_hash = Sha256::new();
        raw_hash.update(oversize_valid.as_bytes());
        assert_eq!(
            ComposeKey::of(&params).screenshot_sha256,
            Some(format!("{:x}", raw_hash.finalize())),
            "the key must hash the raw text of an oversize payload, never decode it"
        );
        // And compose still soft-fails it with the cap note (BND-5).
        params.include_screenshot = true;
        let tmp = TempDir::new().unwrap();
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();
        let item = bundle
            .manifest
            .items
            .iter()
            .find(|i| i.name == "screenshot")
            .expect("omission visible in the manifest");
        assert!(!item.included);
        assert!(item.note.as_deref().unwrap_or_default().contains("cap"));
    }

    /// Finding F9(a): the description cap is enforced at param parse, before
    /// any compose — over the server's 5000-char bound (plan L226) is a
    /// structured `invalid params` refusal; exactly at the bound, and at the
    /// bound plus surrounding whitespace (trimmed like the server does), pass.
    #[test]
    fn parse_refuses_a_description_over_the_server_maximum() {
        let over: ComposeParams = parse_params(&json!({
            "description": "a".repeat(DESCRIPTION_MAX_CHARS + 1),
        }))
        .unwrap();
        let err = over.validate().unwrap_err();
        assert!(err.starts_with("invalid params"), "{err}");
        assert!(err.contains(&DESCRIPTION_MAX_CHARS.to_string()), "{err}");

        let at_max: ComposeParams = parse_params(&json!({
            "description": "a".repeat(DESCRIPTION_MAX_CHARS),
        }))
        .unwrap();
        at_max.validate().unwrap();

        let padded: ComposeParams = parse_params(&json!({
            "description": format!("  {} \n", "a".repeat(DESCRIPTION_MAX_CHARS)),
        }))
        .unwrap();
        padded
            .validate()
            .expect("whitespace around an at-max description is trimmed, not counted");

        // The submit shape (flattened compose params) carries the same cap.
        let submit: SubmitParams = parse_params(&json!({
            "description": "a".repeat(DESCRIPTION_MAX_CHARS + 1),
            "lane": "anonymous",
        }))
        .unwrap();
        assert!(submit.compose.validate().is_err());
    }

    #[test]
    fn validate_screenshot_accepts_jpeg_magic_and_reports_decoded_len() {
        let jpeg = fake_jpeg();
        let b64 = BASE64.encode(&jpeg);
        let (ret, len) = validate_screenshot(Some(&b64)).unwrap();
        assert_eq!(ret, b64);
        assert_eq!(len, jpeg.len());
        assert!(validate_screenshot(None)
            .unwrap_err()
            .contains("no screenshot_b64"));
    }

    #[test]
    fn compose_diagnostics_off_notes_the_exclusion_and_collects_no_logs() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("logs")).unwrap();
        fs::write(tmp.path().join("logs").join(DAEMON_STDERR_TEE_FILE), "boom").unwrap();

        let bundle = compose_bundle(&compose_params("desc"), tmp.path(), None).unwrap();
        assert!(bundle.log_tails.is_empty());
        assert!(bundle.doctor_report.is_none());
        assert!(bundle.runtime_context.is_none());
        assert!(bundle
            .manifest
            .items
            .iter()
            .any(|i| i.name == "diagnostics" && !i.included));
    }

    /// Capture-manifest item 8, wired: a fixture log with a panic yields a
    /// bundle whose manifest carries a 16-hex dedup signature — and the SAME
    /// crash re-logged with different timestamp/index noise yields the SAME
    /// signature (requirement 6: recurrence must dedup; an implementation
    /// hashing raw lines fails the second half).
    #[test]
    fn compose_with_diagnostics_extracts_16hex_dedup_signature_stable_across_timestamps() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("logs")).unwrap();
        let tee = tmp.path().join("logs").join(DAEMON_STDERR_TEE_FILE);
        fs::write(
            &tee,
            "2026-08-31T12:00:01Z starting up\n\
             2026-08-31T12:00:02Z thread 'main' panicked at src/executor.rs:412: \
             index out of bounds: the len is 3 but the index is 9\n",
        )
        .unwrap();

        let mut params = compose_params("it crashed");
        params.include_diagnostics = true;
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();

        let sig = bundle
            .dedup_signature
            .as_deref()
            .expect("a panic in the tee must yield a dedup signature")
            .to_string();
        assert_eq!(sig.len(), 16, "signature must be the 16-hex recipe prefix");
        assert!(sig.chars().all(|c| c.is_ascii_hexdigit()));
        let item = bundle
            .manifest
            .items
            .iter()
            .find(|i| i.name == "dedup_signature")
            .expect("the manifest must account item 8");
        assert!(item.included);

        // The same crash, next week: new timestamps, new indices — one
        // signature.
        fs::write(
            &tee,
            "2026-09-07T23:11:45Z starting up\n\
             2026-09-07T23:11:46Z thread 'main' panicked at src/executor.rs:498: \
             index out of bounds: the len is 12 but the index is 44\n",
        )
        .unwrap();
        let recurrence = compose_bundle(&params, tmp.path(), None).unwrap();
        assert_eq!(
            recurrence.dedup_signature.as_deref(),
            Some(sig.as_str()),
            "timestamp/index noise must not change the signature"
        );
    }

    #[test]
    fn compose_with_clean_logs_has_no_dedup_signature() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("logs")).unwrap();
        fs::write(
            tmp.path().join("logs").join(DAEMON_STDERR_TEE_FILE),
            "starting up\nall good\nready\n",
        )
        .unwrap();

        let mut params = compose_params("just a suggestion");
        params.include_diagnostics = true;
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();

        assert!(bundle.dedup_signature.is_none(), "item 8 is optional");
        assert!(
            !bundle
                .manifest
                .items
                .iter()
                .any(|i| i.name == "dedup_signature"),
            "no signature ⇒ no manifest item"
        );
    }

    /// Durable-state trace (harness checklist #1): the dedup signature is not
    /// just a wire value — it survives into the spool's persisted bundle,
    /// read back through the spool contract from disk.
    #[test]
    fn submitted_spool_entry_durably_carries_the_dedup_signature() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir_all(tmp.path().join("logs")).unwrap();
        fs::write(
            tmp.path().join("logs").join(DAEMON_STDERR_TEE_FILE),
            "thread 'main' panicked at src/lib.rs:7: boom\n",
        )
        .unwrap();

        let mut params = compose_params("crash report");
        params.include_diagnostics = true;
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();
        let expected = bundle
            .dedup_signature
            .clone()
            .expect("panic yields a signature");

        let spool = Spool::open(&tmp.path().join(FEEDBACK_OUTBOX_DIR)).unwrap();
        let id = spool
            .enqueue(&bundle, IdentityLane::Anonymous, "crash report")
            .unwrap();
        // Reopen and load from the persisted artifact — not the in-memory
        // bundle.
        let reopened = Spool::open(&tmp.path().join(FEEDBACK_OUTBOX_DIR)).unwrap();
        let persisted = reopened.load_bundle(&id).unwrap();
        assert_eq!(
            persisted.dedup_signature.as_deref(),
            Some(expected.as_str())
        );
    }

    // ---- grace r2: a failed read-back never turns a durable enqueue into an
    // error (the host would retry and mint a duplicate report) -------------

    /// Distinguishing test: the old inline read-back was
    /// `spool.list().map_err(..)?` / `.ok_or_else(..)?` — an `Err` read-back
    /// (or a listing missing the entry) returned an RPC error for an entry
    /// that was already durable on disk. The result must be success from the
    /// locally known facts, identical to the healthy read-back's, with the
    /// entry on disk exactly once.
    #[test]
    fn submit_result_survives_a_failed_read_back_without_an_error() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path().join(FEEDBACK_OUTBOX_DIR);
        let spool = Spool::open(&root).unwrap();
        let bundle = compose_bundle(&compose_params("the deck froze"), tmp.path(), None).unwrap();
        let id = spool
            .enqueue(&bundle, IdentityLane::Anonymous, "the deck froze")
            .unwrap();

        let healthy = submit_result(&id, spool.list()).unwrap();
        assert_eq!(healthy["submission_id"], id.as_str());
        assert_eq!(healthy["state"]["state"], "queued");
        assert_eq!(healthy["source"], "local");
        assert!(healthy["client_submission_id"].is_string());

        let io_failure = submit_result(&id, Err(std::io::Error::other("too many open files")))
            .expect("a read-back failure after a durable enqueue is not an RPC error");
        assert_eq!(io_failure, healthy, "same wire result from local facts");

        let missing = submit_result(&id, Ok(Vec::new()))
            .expect("an entry the listing misses is still the enqueued entry");
        assert_eq!(missing, healthy);

        // Exactly one entry on disk — nothing about the fallback wrote again.
        assert_eq!(spool.list().unwrap().len(), 1);
    }

    /// Pins the fallback's derivation against the spool's REAL id format: the
    /// idempotency key recovered from the entry id equals the one the spool
    /// lists. A spool id-format change fails here instead of silently
    /// reporting a wrong key on the degraded path.
    #[test]
    fn entry_id_carries_the_client_submission_id() {
        let tmp = TempDir::new().unwrap();
        let spool = Spool::open(&tmp.path().join(FEEDBACK_OUTBOX_DIR)).unwrap();
        let bundle = compose_bundle(&compose_params("desc"), tmp.path(), None).unwrap();
        let id = spool
            .enqueue(&bundle, IdentityLane::Anonymous, "t")
            .unwrap();
        let listed = spool
            .list()
            .unwrap()
            .into_iter()
            .find(|s| s.id == id)
            .unwrap()
            .client_submission_id;
        assert_eq!(
            client_submission_id_from_entry_id(&id).as_deref(),
            Some(listed.as_str())
        );
        // Anything that is not `<prefix>-<uuid>` yields None, never a guess.
        let bogus: SpoolEntryId = serde_json::from_value(json!("not-a-uuid-suffix")).unwrap();
        assert_eq!(client_submission_id_from_entry_id(&bogus), None);
    }

    #[test]
    fn lane_authenticated_without_org_id_is_a_structured_error() {
        assert!(resolve_lane(LaneParam::Authenticated, None, None)
            .unwrap_err()
            .contains("signed-in Parslee session"));
        assert!(
            resolve_lane(LaneParam::Authenticated, Some("org_other"), Some("org_x"))
                .unwrap_err()
                .contains("does not match")
        );
        assert_eq!(
            resolve_lane(LaneParam::Authenticated, None, Some("org_x")).unwrap(),
            IdentityLane::Authenticated {
                org_id: "org_x".to_string()
            }
        );
        assert_eq!(
            resolve_lane(LaneParam::Authenticated, Some("org_x"), Some("org_x")).unwrap(),
            IdentityLane::Authenticated {
                org_id: "org_x".to_string()
            }
        );
        // org_id alongside anonymous is dropped, never bound.
        assert_eq!(
            resolve_lane(LaneParam::Anonymous, Some("org_x"), Some("org_real")).unwrap(),
            IdentityLane::Anonymous
        );
    }

    // ---- preview-handle cache (finding #1) --------------------------------

    #[test]
    fn preview_cache_round_trips_only_for_matching_home_and_inputs() {
        let tmp = TempDir::new().unwrap();
        let other = TempDir::new().unwrap();
        let params = compose_params("preview me");
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();

        let id = store_preview("session-a", tmp.path(), &params, &bundle);

        // Wrong session: a leaked opaque handle is not transferable.
        assert!(take_preview(&id, "session-b", tmp.path(), &params).is_none());
        // Wrong home: no redemption (and the entry survives).
        assert!(take_preview(&id, "session-a", other.path(), &params).is_none());
        // Changed inputs (a toggle flip): no redemption.
        let mut flipped = params.clone();
        flipped.include_diagnostics = true;
        assert!(take_preview(&id, "session-a", tmp.path(), &flipped).is_none());
        // A description edit: no redemption.
        let mut edited = params.clone();
        edited.description = "preview me, edited".to_string();
        assert!(take_preview(&id, "session-a", tmp.path(), &edited).is_none());
        // Different screenshot bytes under the same toggles: no redemption
        // (the ComposeKey carries the screenshot byte hash).
        let mut swapped_shot = params.clone();
        swapped_shot.screenshot_b64 = Some(BASE64.encode(fake_jpeg()));
        assert!(take_preview(&id, "session-a", tmp.path(), &swapped_shot).is_none());
        // Exact match: the STORED bundle comes back…
        let redeemed =
            take_preview(&id, "session-a", tmp.path(), &params).expect("valid handle redeems");
        assert_eq!(redeemed.bundle, bundle);
        // …and redemption consumed the handle.
        assert!(take_preview(&id, "session-a", tmp.path(), &params).is_none());
        // An unknown id never redeems.
        assert!(take_preview("no-such-handle", "session-a", tmp.path(), &params).is_none());
    }

    #[test]
    fn concurrent_redemption_allows_exactly_one_submitter() {
        let tmp = TempDir::new().unwrap();
        let home = tmp.path().to_path_buf();
        let params = compose_params("one consent, one redemption");
        let bundle = compose_bundle(&params, &home, None).unwrap();
        let id = store_preview("session-a", &home, &params, &bundle);
        let barrier = std::sync::Arc::new(std::sync::Barrier::new(3));

        let handles: Vec<_> = (0..2)
            .map(|_| {
                let barrier = barrier.clone();
                let id = id.clone();
                let home = home.clone();
                let params = params.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    take_preview(&id, "session-a", &home, &params).is_some()
                })
            })
            .collect();
        barrier.wait();
        let redeemed = handles
            .into_iter()
            .map(|handle| handle.join().expect("redemption thread"))
            .filter(|won| *won)
            .count();
        assert_eq!(redeemed, 1, "a handle may be consumed only once");
    }

    /// Finding F10, the primitive: a redeemed entry that did NOT enqueue goes
    /// back into the cache and redeems again with the SAME bundle and the
    /// SAME handle — pre-fix `take_preview` was the point of no return, so a
    /// throttled submit forced a re-preview + re-consent.
    #[test]
    fn restored_preview_redeems_again_with_its_original_bundle_then_is_consumed() {
        let tmp = TempDir::new().unwrap();
        let params = compose_params("throttled once, approved once");
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();
        let id = store_preview("session-a", tmp.path(), &params, &bundle);

        let redeemed =
            take_preview(&id, "session-a", tmp.path(), &params).expect("first redemption");
        assert!(
            take_preview(&id, "session-a", tmp.path(), &params).is_none(),
            "redemption consumes the handle"
        );
        // The submit did not land (throttled): hand the entry back.
        SubmitBundle::Previewed(redeemed).release();
        let again = take_preview(&id, "session-a", tmp.path(), &params)
            .expect("a released handle must redeem again without a re-preview");
        assert_eq!(
            again.bundle, bundle,
            "the restored entry holds the approved bytes"
        );
        // A fresh compose releases to nothing — no phantom cache entry.
        SubmitBundle::Fresh(bundle.clone()).release();
        assert!(
            take_preview(&id, "session-a", tmp.path(), &params).is_none(),
            "the second redemption consumed it for good"
        );
    }

    /// Eviction is by consent time even for a RESTORED handle: fill the cap,
    /// redeem the oldest, mint a new preview into the freed slot, then restore
    /// the redeemed one (its `stored_at` is the oldest in the cache). The
    /// restored entry — not the newest unrelated handle — is what the cap
    /// evicts (codex cross-review, F10 regression).
    #[test]
    fn restoring_a_handle_at_capacity_evicts_by_consent_time_not_position() {
        let tmp = TempDir::new().unwrap();
        let mut ids = Vec::new();
        for i in 0..PREVIEW_CACHE_CAP {
            let params = compose_params(&format!("capacity fill {i}"));
            let bundle = compose_bundle(&params, tmp.path(), None).unwrap();
            ids.push((
                store_preview("session-a", tmp.path(), &params, &bundle),
                params,
            ));
            std::thread::sleep(std::time::Duration::from_millis(2));
        }
        let (oldest_id, oldest_params) = ids[0].clone();
        let redeemed = take_preview(&oldest_id, "session-a", tmp.path(), &oldest_params)
            .expect("oldest redeems");

        // A fresh preview takes the freed slot while the submit is in flight.
        let newest_params = compose_params("minted during the in-flight submit");
        let newest_bundle = compose_bundle(&newest_params, tmp.path(), None).unwrap();
        let newest_id = store_preview("session-a", tmp.path(), &newest_params, &newest_bundle);

        // Throttled: the oldest handle comes back — and is the one over cap.
        SubmitBundle::Previewed(redeemed).release();
        assert!(
            take_preview(&newest_id, "session-a", tmp.path(), &newest_params).is_some(),
            "the newest unrelated handle must survive a restore at capacity"
        );
        assert!(
            take_preview(&oldest_id, "session-a", tmp.path(), &oldest_params).is_none(),
            "the restored entry is the oldest by consent time, so the cap evicts IT"
        );
        for (id, params) in &ids[1..] {
            assert!(
                take_preview(id, "session-a", tmp.path(), params).is_some(),
                "the other capacity fills are untouched"
            );
        }
    }

    /// The ComposeKey normalization: the host trims the description before
    /// submitting, so a trailing-whitespace-only difference must still
    /// redeem — while the TTL expiry arm refuses even a perfect match.
    #[test]
    fn preview_redeems_after_trim_normalization_but_not_after_expiry() {
        let tmp = TempDir::new().unwrap();
        let mut previewed = compose_params("described in the sheet");
        previewed.description = "  described in the sheet \n".to_string();
        let bundle = compose_bundle(&previewed, tmp.path(), None).unwrap();

        // Trim-equal description redeems (same normalization on both sides).
        let id = store_preview("session-a", tmp.path(), &previewed, &bundle);
        let trimmed = compose_params("described in the sheet");
        assert!(
            take_preview(&id, "session-a", tmp.path(), &trimmed).is_some(),
            "a trim-only difference is the host's wire normalization, not a user edit"
        );

        // An expired entry refuses even the exact params.
        let id = store_preview("session-a", tmp.path(), &previewed, &bundle);
        age_preview_for_test(&id, PREVIEW_TTL + Duration::from_secs(1));
        assert!(
            take_preview(&id, "session-a", tmp.path(), &previewed).is_none(),
            "an expired handle must not redeem"
        );
    }

    /// The wire message for a failed redemption carries the pinned literal
    /// token hosts key their re-preview flow off.
    #[test]
    fn preview_expired_error_carries_the_pinned_token() {
        assert!(preview_expired_error().contains("PREVIEW_EXPIRED"));
        assert!(preview_expired_error().contains("compose_preview"));
    }

    #[test]
    fn preview_cache_evicts_oldest_beyond_cap() {
        let tmp = TempDir::new().unwrap();
        let params = compose_params("cap check");
        let bundle = compose_bundle(&params, tmp.path(), None).unwrap();

        let first = store_preview("session-a", tmp.path(), &params, &bundle);
        let mut rest = Vec::new();
        for _ in 0..PREVIEW_CACHE_CAP {
            rest.push(store_preview("session-a", tmp.path(), &params, &bundle));
        }
        assert!(
            take_preview(&first, "session-a", tmp.path(), &params).is_none(),
            "the oldest entry past the cap must be evicted"
        );
        assert!(take_preview(rest.last().unwrap(), "session-a", tmp.path(), &params).is_some());
    }

    // ---- server-row merge for feedback.list (finding #13) ------------------

    fn local_row(id: &str, csid: &str, state: Value) -> Value {
        json!({
            "id": id,
            "client_submission_id": csid,
            "state": state,
            "title": "local report",
            "source": "local",
        })
    }

    fn server_row(id: &str, status: &str) -> ServerReportRow {
        ServerReportRow {
            id: id.to_string(),
            client_submission_id: None,
            status: status.to_string(),
            description: Some("filed from another install".to_string()),
            omitted: Vec::new(),
            created_at: None,
            updated_at: Some("2026-09-01T00:00:00Z".to_string()),
        }
    }

    #[test]
    fn merge_marks_acknowledged_row_with_advanced_server_state() {
        let local = vec![local_row(
            "e1",
            "csid-1",
            json!({"state": "acknowledged", "server_id": "srv-9"}),
        )];
        let merged = merge_server_rows(local, vec![server_row("srv-9", "resolved")]);
        assert_eq!(merged.len(), 1, "matched rows must not duplicate");
        assert_eq!(merged[0]["source"], "server");
        assert_eq!(merged[0]["server_status"], "resolved");
        assert!(merged[0]["note"].as_str().unwrap().contains("resolved"));
    }

    #[test]
    fn merge_appends_server_only_rows_and_leaves_local_rows_local() {
        let local = vec![local_row("e1", "csid-1", json!({"state": "queued"}))];
        let merged = merge_server_rows(local, vec![server_row("srv-42", "open")]);
        assert_eq!(merged.len(), 2);
        assert_eq!(
            merged[0]["source"], "local",
            "unmatched local row stays local"
        );
        assert!(merged[0].get("note").is_none() || merged[0]["note"].is_null());
        assert_eq!(merged[1]["source"], "server");
        assert_eq!(merged[1]["id"], "srv-42");
        assert_eq!(merged[1]["server_status"], "open");
        assert_eq!(merged[1]["title"], "filed from another install");
    }

    /// Finding #13, the honest model (still binding under the frozen
    /// contract): the merge keys on acknowledged server ids only, so a
    /// server row must never collapse into a local row via an id
    /// COINCIDENCE. An earlier revision's test fabricated a server id equal
    /// to the local `client_submission_id` to hide exactly this — even that
    /// adversarial coincidence must not match, because the server id is a
    /// prefixed document id, never the client's idempotency key. (A real
    /// csid↔csid dedupe — `/mine` now exposes `clientSubmissionId` — is a
    /// recorded follow-up and would key csid against csid, never against id.)
    #[test]
    fn server_rows_without_client_ids_append_and_never_collapse_local_rows() {
        let local = vec![local_row("e1", "csid-7", json!({"state": "queued"}))];
        // The server row's id happens to equal the local client id — the one
        // shape the dishonest keying would have (wrongly) merged.
        let merged = merge_server_rows(local, vec![server_row("csid-7", "received")]);
        assert_eq!(
            merged.len(),
            2,
            "an id coincidence is not a shared key: the rows must not collapse"
        );
        assert_eq!(merged[0]["source"], "local", "the local row stays local");
        assert_eq!(merged[0]["id"], "e1");
        assert_eq!(merged[1]["source"], "server");
        assert_eq!(merged[1]["id"], "csid-7");
        assert_eq!(merged[1]["server_status"], "received");
    }
}