zynk 1.1.0

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

#[derive(Debug, Args)]
pub struct DbServeArgs {
    #[arg(long, default_value = "127.0.0.1")]
    pub host: String,
    #[arg(long, default_value_t = 8787)]
    pub port: u16,
    #[arg(long, help = "serve one request, then exit")]
    pub once: bool,
    #[arg(
        long,
        help = "import outputs/ artifacts before each render (opt-in; OFF by default — does not change the ADR 025 DB-read-only default)"
    )]
    pub auto_import: bool,
    #[arg(
        long,
        default_value = "outputs",
        help = "runtime outputs root: used for --auto-import imports and, when --allow-writes is set, as the artifact root the browser composer send writes under (ADR 031 D3)"
    )]
    pub root: PathBuf,
    #[arg(
        long,
        help = "enable browser-originated writes (ADR 031); OFF by default — the dashboard is read-only unless set."
    )]
    pub allow_writes: bool,
    #[arg(
        long,
        default_value = "herdr",
        help = "herdr executable the composer send shells out to (ADR 031)."
    )]
    pub herdr_bin: String,
}

/// ADR 031: per-serve write configuration. Present only when `--allow-writes` is
/// set; carries the CSRF token, the bound authority (`127.0.0.1:<port>`), and the
/// herdr binary the composer send shells out to.
struct WriteConfig {
    token: String,
    authority: String,
    herdr_bin: String,
}

/// Per-serve, thread-shared connection config. Carries the served authority (for
/// the exact-Host read guard, ADR 032 P1) so read routes can validate Host even
/// when writes are disabled.
struct ServeContext {
    db_path: PathBuf,
    root: PathBuf,
    auto_import: bool,
    authority: String,
    writes: Option<WriteConfig>,
    /// ADR 032 D3: count of currently-live SSE streams, shared across connection
    /// threads. `serve_sse` increments on entry and an RAII guard decrements on
    /// every exit path, so the cap bounds concurrent SSE resource use.
    active_sse: Arc<std::sync::atomic::AtomicUsize>,
}

struct DashboardSession {
    session_id: String,
    title: String,
    phase: String,
    mode: String,
    workflow_status: String,
    lead_agent_id: String,
    artifact_ref: String,
    updated_at: String,
    next_action: String,
    blockers: String,
    asks_for_zevs: String,
    risk_or_residual_uncertainty: String,
    expected_wait: String,
}

pub fn serve(path: &Path, args: DbServeArgs) -> CliResult<()> {
    if args.host != "127.0.0.1" {
        return Err(CliError::usage(
            "db dashboard server binds only to 127.0.0.1 in v0.2",
        ));
    }
    crate::db::open_database(path)?;
    let listener = TcpListener::bind((args.host.as_str(), args.port)).map_err(|error| {
        CliError::failure(format!(
            "failed to bind dashboard server on {}:{}: {error}",
            args.host, args.port
        ))
    })?;
    let address = listener.local_addr().map_err(|error| {
        CliError::failure(format!(
            "failed to read dashboard listener address: {error}"
        ))
    })?;
    println!("listening on http://{address}/");
    std::io::stdout()
        .flush()
        .map_err(|error| CliError::failure(format!("failed to flush dashboard URL: {error}")))?;

    // ADR 031: writes are OFF unless --allow-writes. The CSRF token is minted once
    // per serve and embedded in the rendered composer; the authority pins the exact
    // Host/Origin the write authorization requires.
    let authority = address.to_string();
    let writes = args.allow_writes.then(|| WriteConfig {
        token: crate::dashboard_write::mint_csrf_token(),
        authority: authority.clone(),
        herdr_bin: args.herdr_bin.clone(),
    });
    let context = Arc::new(ServeContext {
        db_path: path.to_path_buf(),
        root: args.root.clone(),
        auto_import: args.auto_import,
        authority,
        writes,
        active_sse: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
    });

    if args.once {
        let (stream, _) = listener.accept().map_err(|error| {
            CliError::failure(format!("failed to accept dashboard request: {error}"))
        })?;
        return handle_connection(stream, &context);
    }

    for stream in listener.incoming() {
        let stream = stream.map_err(|error| {
            CliError::failure(format!("failed to accept dashboard request: {error}"))
        })?;
        let context = Arc::clone(&context);
        std::thread::spawn(move || {
            if let Err(error) = handle_connection(stream, &context) {
                eprintln!("dashboard connection error: {}", error.message);
            }
        });
    }
    Ok(())
}

fn handle_connection(mut stream: TcpStream, ctx: &ServeContext) -> CliResult<()> {
    stream
        .set_read_timeout(Some(Duration::from_secs(5)))
        .map_err(|error| CliError::failure(format!("failed to set read timeout: {error}")))?;
    let (head, raw_body) = read_http_request(&mut stream)?;
    let request = crate::dashboard_write::parse_request(&head, raw_body);

    // ADR 032 P1: anti-DNS-rebind. Every request (reads, SSE, and the write POST)
    // must carry the exact served authority as Host; no-CORS alone does not stop a
    // same-origin read by a DNS-rebound page. (The write path also re-checks Host
    // in authorize_write; this guards the read surface too.)
    //
    // R1 P5: the header map keeps last-value-wins, so a request with TWO Host lines
    // is ambiguous; require EXACTLY one Host header that equals the served authority
    // (zero or 2+ Host lines fail closed).
    if request.host_count != 1 || request.header("host") != Some(ctx.authority.as_str()) {
        return write_response(
            &mut stream,
            "403 Forbidden",
            "text/plain; charset=utf-8",
            "",
            "host mismatch\n",
        );
    }

    // ADR 032 D3: GET /events is the SSE live stream. Its response is written
    // incrementally (no fixed Content-Length), so it cannot flow through the
    // `(status, content_type, body, location)` tuple below — handle it inline and
    // return. It runs AFTER the Task 2 Host guard above.
    if request.method == "GET" && request.route == "/events" {
        return serve_sse(
            &mut stream,
            ctx,
            query_param(&request.query, "session").as_deref(),
        );
    }

    // ADR 031 D6: POST /send is a write surface; ADR 035 D1: POST /reveal is the
    // plaintext un-redaction surface. Validation + authorization happen here, BEFORE
    // any child spawns; GET/HEAD never dispatch a write. The 5th tuple element is
    // `extra_headers` — empty `""` for every route except the reveal-plaintext 200,
    // which emits `Cache-Control: no-store` + `Pragma: no-cache` +
    // `X-Content-Type-Options: nosniff` (ADR 035 D1); it is threaded into
    // `write_response` below as additional `\r\n`-terminated header lines.
    let (status, content_type, body, location, extra_headers) = if request.method == "POST"
        && request.route == "/send"
    {
        match ctx.writes.as_ref() {
            Some(config) => match crate::dashboard_write::authorize_write(
                &request,
                &config.authority,
                &config.token,
            ) {
                Ok(()) => {
                    match crate::dashboard_write::handle_send(
                        &request,
                        ctx.db_path.as_path(),
                        ctx.root.as_path(),
                        &config.herdr_bin,
                    ) {
                        crate::dashboard_write::WriteOutcome::Redirect(loc) => (
                            "303 See Other",
                            "text/plain; charset=utf-8",
                            String::new(),
                            Some(loc),
                            "",
                        ),
                        // /send never produces RevealPlaintext, but the variant must
                        // be handled — treat it as an internal error rather than ever
                        // surfacing un-redacted content from a non-reveal route.
                        crate::dashboard_write::WriteOutcome::RevealPlaintext(_) => (
                            "500 Internal Server Error",
                            "text/plain; charset=utf-8",
                            "unexpected reveal from send\n".to_string(),
                            None,
                            "",
                        ),
                        crate::dashboard_write::WriteOutcome::Error { status, message } => (
                            status,
                            "text/html; charset=utf-8",
                            format!(
                                "<!doctype html><meta charset=\"utf-8\"><pre>{}</pre>",
                                escape_html(&message)
                            ),
                            None,
                            "",
                        ),
                    }
                }
                Err(error) => (
                    "403 Forbidden",
                    "text/plain; charset=utf-8",
                    format!("{}\n", error.message),
                    None,
                    "",
                ),
            },
            None => (
                "405 Method Not Allowed",
                "text/plain; charset=utf-8",
                "writes disabled\n".to_string(),
                None,
                "",
            ),
        }
    } else if request.method == "POST" && request.route.starts_with("/decide/") {
        // ADR 033 M2b T4 / ADR 031 D6: POST /decide/<type> is a browser write —
        // the SAME authorization + child-spawn discipline as /send. The
        // exact-Host guard already ran for ALL requests at the top of
        // handle_connection (so it covers /decide/* too); here we gate on
        // --allow-writes (else 405), authorize_write (exact Host/Origin +
        // per-serve CSRF, else 403), then handle_decide (C7 validation +
        // current_exe shell-out to the audited `zynk decide`). The route NEVER
        // writes the DB directly. The WriteOutcome→response mapping is identical
        // to /send (303-PRG on success; the child output HTML-escaped on error).
        let decision_type = request
            .route
            .strip_prefix("/decide/")
            .unwrap_or("")
            .to_string();
        match ctx.writes.as_ref() {
            Some(config) => match crate::dashboard_write::authorize_write(
                &request,
                &config.authority,
                &config.token,
            ) {
                Ok(()) => {
                    match crate::dashboard_write::handle_decide(
                        &request,
                        &decision_type,
                        ctx.db_path.as_path(),
                        ctx.root.as_path(),
                        &config.herdr_bin,
                    ) {
                        crate::dashboard_write::WriteOutcome::Redirect(loc) => (
                            "303 See Other",
                            "text/plain; charset=utf-8",
                            String::new(),
                            Some(loc),
                            "",
                        ),
                        // /decide never produces RevealPlaintext, but the variant
                        // must be handled — treat it as an internal error rather than
                        // ever surfacing un-redacted content from a non-reveal route.
                        crate::dashboard_write::WriteOutcome::RevealPlaintext(_) => (
                            "500 Internal Server Error",
                            "text/plain; charset=utf-8",
                            "unexpected reveal from decide\n".to_string(),
                            None,
                            "",
                        ),
                        crate::dashboard_write::WriteOutcome::Error { status, message } => (
                            status,
                            "text/html; charset=utf-8",
                            format!(
                                "<!doctype html><meta charset=\"utf-8\"><pre>{}</pre>",
                                escape_html(&message)
                            ),
                            None,
                            "",
                        ),
                    }
                }
                Err(error) => (
                    "403 Forbidden",
                    "text/plain; charset=utf-8",
                    format!("{}\n", error.message),
                    None,
                    "",
                ),
            },
            None => (
                "405 Method Not Allowed",
                "text/plain; charset=utf-8",
                "writes disabled\n".to_string(),
                None,
                "",
            ),
        }
    } else if request.method == "POST" && request.route == "/reveal" {
        // ADR 035 D1-D4: POST /reveal is the plaintext un-redaction surface — the
        // SAME authorization + child-spawn discipline as /send + /decide (the
        // exact-Host guard already ran for ALL requests at the top of
        // handle_connection; here we gate on --allow-writes (else 405),
        // authorize_write (exact Host/Origin + per-serve CSRF, else 403), then
        // handle_reveal (D3 session-scoped validate + current_exe shell-out to the
        // audited `zynk reveal`). THE KEY DIVERGENCE (D1): on success the plaintext
        // is rendered INLINE under `no-store` — NEVER 303-PRG'd (the read view
        // redacts). On a nonzero child it surfaces ONLY the escaped stderr (D4),
        // NEVER the child's stdout as plaintext.
        match ctx.writes.as_ref() {
            Some(config) => match crate::dashboard_write::authorize_write(
                &request,
                &config.authority,
                &config.token,
            ) {
                Ok(()) => {
                    match crate::dashboard_write::handle_reveal(
                            &request,
                            ctx.db_path.as_path(),
                            ctx.root.as_path(),
                        ) {
                            crate::dashboard_write::WriteOutcome::RevealPlaintext(text) => (
                                "200 OK",
                                "text/html; charset=utf-8",
                                format!(
                                    "<!doctype html><meta charset=\"utf-8\"><pre>{}</pre>",
                                    escape_html(&text)
                                ),
                                None,
                                // ADR 035 D1: the plaintext is transient — never cached
                                // by the browser or any intermediary, never sniffed.
                                "Cache-Control: no-store\r\nPragma: no-cache\r\nX-Content-Type-Options: nosniff\r\n",
                            ),
                            // ADR 035 D1: reveal never 303-PRGs (the read view redacts).
                            // The variant must be handled; treat it as an internal error.
                            crate::dashboard_write::WriteOutcome::Redirect(_) => (
                                "500 Internal Server Error",
                                "text/plain; charset=utf-8",
                                "reveal must not redirect\n".to_string(),
                                None,
                                "",
                            ),
                            crate::dashboard_write::WriteOutcome::Error { status, message } => (
                                status,
                                "text/html; charset=utf-8",
                                format!(
                                    "<!doctype html><meta charset=\"utf-8\"><pre>{}</pre>",
                                    escape_html(&message)
                                ),
                                None,
                                "",
                            ),
                        }
                }
                Err(error) => (
                    "403 Forbidden",
                    "text/plain; charset=utf-8",
                    format!("{}\n", error.message),
                    None,
                    "",
                ),
            },
            None => (
                "405 Method Not Allowed",
                "text/plain; charset=utf-8",
                "writes disabled\n".to_string(),
                None,
                "",
            ),
        }
    } else if !matches!(request.method.as_str(), "GET" | "HEAD") {
        (
            "405 Method Not Allowed",
            "text/plain; charset=utf-8",
            "method not allowed\n".to_string(),
            None,
            "",
        )
    } else if matches!(request.route.as_str(), "/" | "/index.html") {
        // v0.2.2: when --auto-import is set, import file artifacts immediately
        // before rendering so the dashboard always reflects the latest writes
        // (no time-based staleness). Tied to the render path, so 404/405/asset
        // requests do not trigger imports. Import is idempotent (reused path).
        if ctx.auto_import {
            crate::db::import_outputs_root(ctx.db_path.as_path(), ctx.root.as_path())?;
        }
        let connection = crate::db::open_read_database(ctx.db_path.as_path())?;
        (
            "200 OK",
            "text/html; charset=utf-8",
            render_dashboard(
                &connection,
                query_param(&request.query, "session").as_deref(),
                ctx.writes.as_ref().map(|config| config.token.as_str()),
            )?,
            None,
            "",
        )
    } else if matches!(request.route.as_str(), "/audit") {
        if ctx.auto_import {
            crate::db::import_outputs_root(ctx.db_path.as_path(), ctx.root.as_path())?;
        }
        let connection = crate::db::open_read_database(ctx.db_path.as_path())?;
        (
            "200 OK",
            "text/html; charset=utf-8",
            render_audit(
                &connection,
                query_param(&request.query, "session").as_deref(),
            )?,
            None,
            "",
        )
    } else {
        (
            "404 Not Found",
            "text/plain; charset=utf-8",
            "not found\n".to_string(),
            None,
            "",
        )
    };
    match location {
        Some(target) => redirect_response(&mut stream, &target),
        None => write_response(&mut stream, status, content_type, extra_headers, &body),
    }
}

/// ADR 032 D3: bound concurrent live SSE streams (loopback, single operator) so a
/// misbehaving client opening many streams cannot multiply the per-stream thread +
/// per-tick `herdr pane list` subprocess unboundedly.
const SSE_CONNECTION_CAP: usize = 8;

/// ADR 032 D4: the live feed is a "windowed (last-N), oldest-first" feed. Both the
/// SSE per-tick render and the static `#feed` render apply this bound so they agree
/// (a long design session does not stream/render thousands of rows every tick).
const FEED_WINDOW: usize = 200;

/// Keep the last `n` items of an oldest-first slice (the suffix); if the slice is
/// `<= n`, keep all. When the window slides (the feed grows past `n`), the front
/// changes, so `diff_feed` sees a non-prefix and returns `Reset` — the intended
/// reset-on-uncertainty (ADR 032 D4); we do not special-case it here.
fn windowed<T: Clone>(events: &[T], n: usize) -> Vec<T> {
    if events.len() > n {
        events[events.len() - n..].to_vec()
    } else {
        events.to_vec()
    }
}

fn serve_sse(stream: &mut TcpStream, ctx: &ServeContext, session: Option<&str>) -> CliResult<()> {
    // ADR 032 D3: count this stream as active; the RAII guard decrements on EVERY
    // exit path (the 503 below, a normal disconnect `return Ok(())`, or an error
    // `?`), so the counter never leaks. Placed before the SSE headers so the cap
    // is enforced before any work.
    struct SseGuard(std::sync::Arc<std::sync::atomic::AtomicUsize>);
    impl Drop for SseGuard {
        fn drop(&mut self) {
            self.0.fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
        }
    }
    let active = ctx
        .active_sse
        .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
        + 1;
    let _guard = SseGuard(ctx.active_sse.clone());
    if active > SSE_CONNECTION_CAP {
        return write_response(
            stream,
            "503 Service Unavailable",
            "text/plain; charset=utf-8",
            "",
            "too many live connections\n",
        );
    }

    // SSE headers — note: NO CORS headers (ADR 032 D7).
    let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nCache-Control: no-cache\r\nConnection: close\r\n\r\n";
    stream
        .write_all(headers.as_bytes())
        .map_err(|e| CliError::failure(format!("failed to write SSE headers: {e}")))?;

    use std::time::Duration;
    // ADR 033 M2b (T5): the per-serve CSRF token (when `--allow-writes`) so a live
    // feed-appended/reset gate or conflict card carries its functional decide control
    // (the delegated `.decide-form` submit handler on the static page binds it). When
    // writes are off this is `None` and the streamed cards stay read-only.
    let writes_token = ctx.writes.as_ref().map(|config| config.token.as_str());
    let mut last_keys: Vec<String> = Vec::new();
    // M4a U2 (Codex C3): track the previous usage diff key across ticks so the `usage`
    // event streams ONLY when the aggregate changes (mirrors the feed's prev-key
    // tracking). The key includes the aggregate values, so a usage change streams to
    // the top-bar/budget even when no new feed row landed.
    let mut last_usage_key: Option<String> = None;
    let mut first = true;
    loop {
        // Short-lived read connection per tick; dropped before the sleep (no DB
        // handle held across the stream — ADR 032 D3).
        let (keys, reset_html, append_html_from, participants, session_state_html, usage) = {
            let connection = crate::db::open_read_database(&ctx.db_path)?;
            // Resolve the selected session from the SAME session list the static page
            // renders, so the live `session-state` fragments match the page's chrome.
            let sessions = load_sessions(&connection)?;
            let selected = session
                .and_then(|id| sessions.iter().find(|s| s.session_id == id))
                .or_else(|| sessions.first());
            let selected_id = selected.map(|s| s.session_id.clone());
            // ADR 032 D4: window to the last-N oldest-first events. When the window
            // slides (feed grows past N), the front changes and diff_feed resets.
            let feed = match &selected_id {
                Some(id) => windowed(
                    &crate::read_model::feed_oldest_first(&connection, id)?,
                    FEED_WINDOW,
                ),
                None => Vec::new(),
            };
            // ADR 033 M2b (T2): the gate/conflict decision overlay for this tick,
            // computed ONCE in the SAME per-tick connection scope as the feed (no DB
            // handle held across the stream — ADR 032 D3). Threaded into the feed
            // render so a live decided gate/conflict card carries its overlay; the
            // map is whole-session so a windowed/append slice still resolves by id.
            let decision_overlay = match &selected_id {
                Some(id) => crate::read_model::decision_overlay_for_session(&connection, id)?,
                None => BTreeMap::new(),
            };
            // Roster participants computed in the SAME per-tick connection scope (no
            // DB handle held across the stream — ADR 032 D3); `load_roster` runs
            // AFTER the scope on the by-value tuples. R1 P3: source from the DB
            // roster state (lead_agent + agents/session_agents), NOT just the audit
            // participants, so a status-only session still has a non-empty roster.
            // (`known_targets`/`known_targets_pairs` stay the composer allow-list.)
            let participants = match &selected_id {
                Some(id) => roster_db_participants(&connection, id)?,
                None => Vec::new(),
            };
            // ADR 032 D4 (R1 P1): the current-state chrome (sidebar nav + timeline
            // header + detail panel), rendered with the SAME inner renderers the
            // static page uses. Joined by ASCII record separator (U+001E) — not a
            // CR/LF, so `sse_event`'s line handling preserves the delimiter; each
            // fragment is server-rendered + `escape_html`-escaped (trusted HTML).
            // R1 hardening: strip any literal U+001E from each fragment first so a
            // free-text field containing U+001E can't mis-split the payload client-side.
            // v1.0 M4a R1 (Codex C4): a 4th fragment — the audit-chain summary — so the
            // right-rail chain section refreshes live on a chain change (the Status
            // section is p[2], the chain summary p[3]). Each fragment mounts into its OWN
            // child (`#detail-status` / `#detail-chain`) so the SSE refresh never wipes
            // the sibling sections (artifacts/budget/controls/transport). Adding p[3] is
            // backward-compatible — p[0..2] indices are unchanged.
            // v1.0 M4a M2: a 5th fragment — the left mode rail (p[4]) — so the current-mode
            // highlight follows a live mode change. Appending p[4] is backward-compatible:
            // the p[0..3] indices/handlers are unchanged; the client handler only ADDS a
            // `#mode-rail` mount that ignores an absent p[4].
            let session_state_html = format!(
                "{}\u{1e}{}\u{1e}{}\u{1e}{}\u{1e}{}",
                render_session_nav_inner(&sessions, selected_id.as_deref()).replace('\u{1e}', ""),
                render_timeline_header_inner(selected).replace('\u{1e}', ""),
                render_detail_inner(selected).replace('\u{1e}', ""),
                render_chain_summary_inner(&connection, selected_id.as_deref())?
                    .replace('\u{1e}', ""),
                render_mode_rail_inner(selected).replace('\u{1e}', ""),
            );
            // M4a U2 (Codex C3): the per-session usage aggregate, computed in the SAME
            // per-tick connection scope as the feed/roster (no DB handle held across the
            // stream — ADR 032 D3). Render to a String here and emit AFTER the scope
            // (like the roster), keyed by `usage_diff_key` for content-sensitive
            // only-on-change streaming. A `None` aggregate (no usage events) renders the
            // empty-state strip (0 tokens + `—`), never a fabricated card or $0.00.
            let usage = match &selected_id {
                Some(id) => {
                    let agg = crate::read_model::usage_aggregate(&connection, id)?;
                    let usage_key = crate::dashboard_live::usage_diff_key(&agg);
                    let usage_html = crate::dashboard_live::render_usage_html(&agg);
                    Some((usage_key, usage_html))
                }
                None => None,
            };
            // M2b R1 P2: key each feed item by its COMBINED diff key — the row's own
            // mutable render fields PLUS the rendered decision state (a gate/conflict
            // overlay digest from `decision_overlay`, or a standalone decision item's
            // notification_status). A decision is an OVERLAY (not a feed row), so
            // without folding it in, a post-connect gate/conflict decision would leave
            // the work-event row's `feed_key` unchanged and only emit a heartbeat —
            // the open dashboard would miss the verdict until reload. Folding it in
            // flips the key for that item -> `diff_feed` resets -> the overlay rides in
            // on a `feed-reset`. Used for BOTH branches below so the vectors agree.
            let keys: Vec<String> = feed
                .iter()
                .map(|event| crate::dashboard_live::feed_diff_key(event, &decision_overlay))
                .collect();
            let delta = if first {
                crate::dashboard_live::FeedDelta::Reset
            } else {
                crate::dashboard_live::diff_feed(&last_keys, &keys)
            };
            match delta {
                crate::dashboard_live::FeedDelta::Reset => (
                    keys,
                    Some(render_feed_html(&feed, &decision_overlay, writes_token)),
                    None,
                    participants,
                    session_state_html,
                    usage,
                ),
                crate::dashboard_live::FeedDelta::Append(from) if from < feed.len() => (
                    keys,
                    None,
                    Some(render_feed_html(
                        &feed[from..],
                        &decision_overlay,
                        writes_token,
                    )),
                    participants,
                    session_state_html,
                    usage,
                ),
                crate::dashboard_live::FeedDelta::Append(_) => {
                    (keys, None, None, participants, session_state_html, usage)
                } // no feed change
            }
        };
        let mut buf = Vec::new();
        if let Some(html) = reset_html {
            crate::dashboard_live::sse_event(&mut buf, "feed-reset", &html);
        } else if let Some(html) = append_html_from {
            crate::dashboard_live::sse_event(&mut buf, "feed-append", &html);
        } else {
            crate::dashboard_live::sse_event(&mut buf, "heartbeat", "");
        }
        // ADR 032 D4 (R1 P1): emit the current-state chrome each tick so a live
        // status change updates the sidebar badges / header / detail rail without a
        // reload (the feed alone would leave those panels stale).
        crate::dashboard_live::sse_event(&mut buf, "session-state", &session_state_html);
        // Roster (ADR 032 D5): live-herdr when HERDR_ENV=1, else db-fallback. The
        // DB connection is already dropped; `load_roster` works on the by-value
        // participants and never fails the stream (errors degrade to db-fallback).
        let herdr_bin = ctx
            .writes
            .as_ref()
            .map(|w| w.herdr_bin.as_str())
            .unwrap_or("herdr");
        let roster = crate::dashboard_live::load_roster(herdr_bin, participants);
        crate::dashboard_live::sse_event(
            &mut buf,
            "roster",
            &crate::dashboard_live::render_roster_html(&roster),
        );
        // M4a U2 (Codex C3): emit the `usage` event ONLY when the aggregate changed
        // (content-sensitive via `usage_diff_key`) — additive to the feed/roster/
        // session-state events. The DB connection is already dropped; we emit the
        // String rendered in the scope (no DB handle across the sleep).
        if let Some((usage_key, usage_html)) = usage {
            if Some(&usage_key) != last_usage_key.as_ref() {
                crate::dashboard_live::sse_event(&mut buf, "usage", &usage_html);
                last_usage_key = Some(usage_key);
            }
        }
        if stream.write_all(&buf).is_err() {
            return Ok(()); // client disconnected — end the stream thread cleanly
        }
        last_keys = keys;
        first = false;
        std::thread::sleep(Duration::from_millis(750));
    }
}

/// ADR 031 D6: Post/Redirect/Get — after a successful write, send a 303 so a
/// refresh re-renders (GET) instead of re-submitting the POST.
fn redirect_response(stream: &mut TcpStream, location: &str) -> CliResult<()> {
    let response = format!(
        "HTTP/1.1 303 See Other\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
    );
    stream
        .write_all(response.as_bytes())
        .map_err(|error| CliError::failure(format!("failed to write redirect: {error}")))
}

fn query_param(query: &str, name: &str) -> Option<String> {
    query.split('&').find_map(|part| {
        let (key, value) = part.split_once('=')?;
        (key == name).then(|| percent_decode(value))
    })
}

fn read_http_request(stream: &mut TcpStream) -> CliResult<(String, Vec<u8>)> {
    let mut buf = Vec::new();
    let mut chunk = [0_u8; 1024];
    // Read until the end-of-headers marker (or a sane cap).
    let header_end = loop {
        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
            break pos + 4;
        }
        if buf.len() > 16_384 {
            break buf.len();
        }
        let count = stream.read(&mut chunk).map_err(|error| {
            CliError::failure(format!("failed to read dashboard request: {error}"))
        })?;
        if count == 0 {
            break buf.len();
        }
        buf.extend_from_slice(&chunk[..count]);
    };
    let head = String::from_utf8_lossy(&buf[..header_end.min(buf.len())]).to_string();
    let mut body = buf.get(header_end..).unwrap_or(&[]).to_vec();
    // Read the remaining Content-Length body bytes (POST), capped at 1 MiB.
    let content_length = head
        .split("\r\n")
        .filter_map(|line| line.split_once(':'))
        .find(|(key, _)| key.trim().eq_ignore_ascii_case("content-length"))
        .and_then(|(_, value)| value.trim().parse::<usize>().ok())
        .unwrap_or(0)
        .min(1_048_576);
    while body.len() < content_length {
        let count = stream.read(&mut chunk).map_err(|error| {
            CliError::failure(format!("failed to read dashboard body: {error}"))
        })?;
        if count == 0 {
            break;
        }
        body.extend_from_slice(&chunk[..count]);
    }
    body.truncate(content_length);
    Ok((head, body))
}

fn write_response(
    stream: &mut TcpStream,
    status: &str,
    content_type: &str,
    extra_headers: &str,
    body: &str,
) -> CliResult<()> {
    // `extra_headers` (ADR 035 D1) is a block of additional `\r\n`-terminated header
    // lines (e.g. `Cache-Control: no-store\r\nPragma: no-cache\r\n...`), or `""` for
    // routes that add none. It is emitted BEFORE the blank line that ends the headers.
    let response = format!(
        "HTTP/1.1 {status}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nConnection: close\r\n{extra_headers}\r\n{body}",
        body.len()
    );
    stream
        .write_all(response.as_bytes())
        .map_err(|error| CliError::failure(format!("failed to write dashboard response: {error}")))
}

/// ADR 031 D1: the known `agent:address` targets for a session — the distinct
/// participants (source + target) in its `audit_records`. The composer offers
/// only these, and the write path enforces the same allow-list before spawning
/// (so a browser write can never free-type an arbitrary herdr target).
pub(crate) fn known_targets(connection: &Connection, session_id: &str) -> CliResult<Vec<String>> {
    let mut statement = connection
        .prepare(
            "SELECT DISTINCT agent_id || ':' || address AS target FROM (
                 SELECT target_agent_id AS agent_id, target_address AS address
                   FROM audit_records WHERE session_id = ?1
                 UNION
                 SELECT source_agent_id AS agent_id, source_address AS address
                   FROM audit_records WHERE session_id = ?1
             )
             WHERE agent_id IS NOT NULL AND address IS NOT NULL
             ORDER BY target",
        )
        .map_err(|error| CliError::failure(format!("failed to prepare known_targets: {error}")))?;
    let rows = statement
        .query_map([session_id], |row| row.get::<_, String>(0))
        .map_err(|error| CliError::failure(format!("failed to query known_targets: {error}")))?;
    let mut targets = Vec::new();
    for row in rows {
        targets.push(
            row.map_err(|error| CliError::failure(format!("failed to read target: {error}")))?,
        );
    }
    Ok(targets)
}

/// ADR 031 + M3b (Codex C6): the SENDABLE herdr targets for a session — the strict
/// allow-list used by composer/redirect/notify WRITE-validation. DISTINCT from the
/// display roster (`known_targets`/`known_targets_pairs`, ADR 032), which may include
/// non-sendable participants (e.g. `operator:cli` from decide/reveal) for display only.
/// A sendable target is a REAL herdr send participant: from a `transport != 'none'` row,
/// an `agent:address` pair, excluding the non-transport sentinels (`none` agent/address)
/// and non-pane addresses (`cli`, `dashboard`).
pub(crate) fn sendable_targets(
    connection: &Connection,
    session_id: &str,
) -> CliResult<Vec<String>> {
    let mut statement = connection
        .prepare(
            "SELECT DISTINCT agent_id || ':' || address AS target FROM (
                 SELECT target_agent_id AS agent_id, target_address AS address
                   FROM audit_records WHERE session_id = ?1 AND transport != 'none'
                 UNION
                 SELECT source_agent_id AS agent_id, source_address AS address
                   FROM audit_records WHERE session_id = ?1 AND transport != 'none'
             )
             WHERE agent_id IS NOT NULL AND address IS NOT NULL
               AND agent_id != 'none' AND address NOT IN ('none', 'cli', 'dashboard')
             ORDER BY target",
        )
        .map_err(|error| {
            CliError::failure(format!("failed to prepare sendable_targets: {error}"))
        })?;
    let rows = statement
        .query_map([session_id], |row| row.get::<_, String>(0))
        .map_err(|error| CliError::failure(format!("failed to query sendable_targets: {error}")))?;
    let mut targets = Vec::new();
    for row in rows {
        targets.push(row.map_err(|error| {
            CliError::failure(format!("failed to read sendable target: {error}"))
        })?);
    }
    Ok(targets)
}

/// The `(agent, address)` form of `known_targets` for a session — used to seed the
/// live roster (ADR 032 D5) with the session participants without holding a DB
/// handle across the SSE stream.
pub(crate) fn known_targets_pairs(
    connection: &Connection,
    session_id: &str,
) -> CliResult<Vec<(String, String)>> {
    Ok(known_targets(connection, session_id)?
        .into_iter()
        .filter_map(|t| {
            t.split_once(':')
                .map(|(a, b)| (a.to_string(), b.to_string()))
        })
        .collect())
}

/// ADR 032 D5 (R1 P3): the db-fallback roster participants — `(agent, address,
/// db_status)` gathered from the DB roster state, NOT only the audit participants.
/// A STATUS-ONLY session (a projected `lead_agent_id` + an `agents` row, no audit
/// rows) would otherwise yield an empty roster. We UNION:
///   (a) the session's `lead_agent_id` (address from `agents.current_address`,
///       db_status from `agents.current_agent_status`), skipped only when the lead
///       agent is NULL/`unknown`;
///   (b) the audit participants (`known_targets` agent:address; db_status joined
///       from `agents.current_agent_status`);
///   (c) `session_agents JOIN agents` (forward-compat: `session_agents` currently
///       has NO producer, so this contributes nothing today; queried for the day
///       it does, with db_status from `session_agents.agent_status`).
/// Deduped by `agent`, preferring an entry that carries a non-empty address.
pub(crate) fn roster_db_participants(
    connection: &Connection,
    session_id: &str,
) -> CliResult<Vec<crate::dashboard_live::RosterParticipant>> {
    let mut rows: Vec<(String, String, String)> = Vec::new();

    // (a) lead agent of the session.
    let mut lead_stmt = connection
        .prepare(
            "SELECT s.lead_agent_id,
                    COALESCE(a.current_address, ''),
                    COALESCE(a.current_agent_status, 'unknown')
             FROM sessions AS s
             LEFT JOIN agents AS a ON a.agent_id = s.lead_agent_id
             WHERE s.session_id = ?1
               AND s.lead_agent_id IS NOT NULL
               AND s.lead_agent_id <> 'unknown'",
        )
        .map_err(|e| CliError::failure(format!("failed to prepare roster lead query: {e}")))?;
    let lead_rows = lead_stmt
        .query_map([session_id], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
            ))
        })
        .map_err(|e| CliError::failure(format!("failed to query roster lead: {e}")))?;
    for row in lead_rows {
        rows.push(row.map_err(|e| CliError::failure(format!("failed to read roster lead: {e}")))?);
    }

    // (b) audit participants (same source as the composer allow-list), with
    // db_status overlaid from the agents row when present.
    for (agent, address) in known_targets_pairs(connection, session_id)? {
        let db_status: String = connection
            .query_row(
                "SELECT COALESCE(current_agent_status, 'unknown') FROM agents WHERE agent_id = ?1",
                [agent.as_str()],
                |row| row.get(0),
            )
            .unwrap_or_else(|_| "unknown".to_string());
        rows.push((agent, address, db_status));
    }

    // (c) session_agents rows (forward-compat; no producer today).
    let mut sa_stmt = connection
        .prepare(
            "SELECT sa.agent_id,
                    COALESCE(a.current_address, ''),
                    sa.agent_status
             FROM session_agents AS sa
             LEFT JOIN agents AS a ON a.agent_id = sa.agent_id
             WHERE sa.session_id = ?1",
        )
        .map_err(|e| {
            CliError::failure(format!(
                "failed to prepare roster session_agents query: {e}"
            ))
        })?;
    let sa_rows = sa_stmt
        .query_map([session_id], |row| {
            Ok((
                row.get::<_, String>(0)?,
                row.get::<_, String>(1)?,
                row.get::<_, String>(2)?,
            ))
        })
        .map_err(|e| CliError::failure(format!("failed to query roster session_agents: {e}")))?;
    for row in sa_rows {
        rows.push(row.map_err(|e| {
            CliError::failure(format!("failed to read roster session_agents: {e}"))
        })?);
    }

    // Dedup by agent, preferring an entry with a non-empty address (so the audit
    // participant's transport address survives over a lead-only blank).
    let mut deduped: Vec<(String, String, String)> = Vec::new();
    for (agent, address, db_status) in rows {
        if let Some(existing) = deduped.iter_mut().find(|(a, _, _)| *a == agent) {
            if existing.1.is_empty() && !address.is_empty() {
                existing.1 = address;
                existing.2 = db_status;
            }
        } else {
            deduped.push((agent, address, db_status));
        }
    }
    deduped.sort_by(|left, right| left.0.cmp(&right.0));

    // ADR 036 D6: the CURRENT participant overlays for this session, read ONCE in this
    // SAME per-tick connection scope (no DB handle held across the SSE stream — ADR 032
    // D3). The fold fails loud on a malformed row, propagating up as a stream error like
    // every other per-tick read (feed/decision/usage). We mutate the map as we consume
    // subjects so the leftover subjects (D8 below) are exactly the overlay-only ones.
    let mut overlays = crate::read_model::participant_overlays_for_session(connection, session_id)?;

    // Promote the deduped positional rows to the named `RosterParticipant` (ADR 036 T7),
    // enriching each whose `agent` matches an overlay subject with that subject's CURRENT
    // actor-kind / role label / trait badges (D6). `remove` consumes the matched subject
    // so the D8 union below only sees overlay-only subjects (no double-render).
    let mut participants: Vec<crate::dashboard_live::RosterParticipant> = deduped
        .into_iter()
        .map(|(agent, address, db_status)| {
            let overlay = overlays.remove(&agent);
            let (actor_kind, role_label, traits) = match overlay {
                Some(view) => (view.actor_kind, view.role_label, view.traits),
                None => (None, None, Vec::new()),
            };
            crate::dashboard_live::RosterParticipant {
                agent,
                address,
                db_status,
                actor_kind,
                role_label,
                traits,
            }
        })
        .collect();

    // ADR 036 D8: the operator-as-subject DISPLAY-ONLY union. A subject declared ONLY via
    // an overlay (e.g. `operator`, assigned `actor-kind human`) is NOT an audit/roster
    // participant, so it has no row above. Add it to the DISPLAY roster so it renders with
    // its actor-kind/role/trait marker, but with NO transport address (`n/a`) and
    // `Unknown` provenance. Critically, this NEVER touches `known_targets`/
    // `sendable_targets` (the composer allow-lists are derived separately from
    // audit_records), so an overlay-only subject can NEVER become a sendable target.
    let mut leftover: Vec<crate::dashboard_live::RosterParticipant> = overlays
        .into_values()
        .map(|view| crate::dashboard_live::RosterParticipant {
            agent: view.subject_actor_id,
            address: "n/a".to_string(),
            db_status: "unknown".to_string(),
            actor_kind: view.actor_kind,
            role_label: view.role_label,
            traits: view.traits,
        })
        .collect();
    leftover.sort_by(|left, right| left.agent.cmp(&right.agent));
    participants.extend(leftover);

    Ok(participants)
}

/// ADR 031 D1: whether a session row exists in the served DB. Browser writes
/// target an existing selected session; the server must not trust the posted id
/// (a trusted id would let the audited-send projection create a new session).
pub(crate) fn session_exists(connection: &Connection, session_id: &str) -> CliResult<bool> {
    let count: i64 = connection
        .query_row(
            "SELECT COUNT(*) FROM sessions WHERE session_id = ?1",
            [session_id],
            |row| row.get(0),
        )
        .map_err(|error| CliError::failure(format!("failed to check session: {error}")))?;
    Ok(count > 0)
}

fn render_dashboard(
    connection: &Connection,
    selected_session_id: Option<&str>,
    csrf_token: Option<&str>,
) -> CliResult<String> {
    let sessions = load_sessions(connection)?;
    let selected = selected_session_id
        .and_then(|session_id| {
            sessions
                .iter()
                .find(|session| session.session_id == session_id)
        })
        .or_else(|| sessions.first());
    let selected_id = selected.map(|session| session.session_id.as_str());
    // v0.8 T6: render the initial timeline OLDEST-first to match the SSE
    // `feed-reset` payload (`feed_oldest_first`); otherwise the chat feed visibly
    // flips order ~750ms after load when the first SSE tick lands. ADR 032 D4:
    // window to the last-N so the initial page and the stream agree.
    let feed = match selected_id {
        Some(id) => windowed(&feed_oldest_first(connection, id)?, FEED_WINDOW),
        None => Vec::new(),
    };
    // ADR 033 M2b (T2): the gate/conflict decision overlay, computed ONCE per render
    // (keyed by `target_work_event_id`), threaded into each feed-event render so a
    // decided gate/conflict card carries its verdict/resolution overlay.
    let decision_overlay = match selected_id {
        Some(id) => decision_overlay_for_session(connection, id)?,
        None => BTreeMap::new(),
    };
    let mut html = String::new();
    html.push_str("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">");
    html.push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
    html.push_str("<title>zynk dashboard</title><style>");
    html.push_str(STYLES);
    html.push_str("</style></head><body>");
    // v1.0 M4a M1: the TopBar above the 3-pane `.app-shell` — session label + the usage
    // aggregate (a `[data-usage]` mount, SAME fragment as the right-rail budget) + the
    // relocated `#view-toggle` (the T1 toggle JS still binds it by id) + the current mode.
    // The usage mount is a STABLE wrapper (`<div class="usage-mount" data-usage>`); the
    // `usage` SSE handler sets `innerHTML` on every `[data-usage]` so the TopBar AND the
    // budget live-update from one event (no duplicate `id="usage"`).
    html.push_str("<header class=\"topbar\">");
    if let Some(session) = selected {
        html.push_str(&format!(
            "<span class=\"topbar-session\">{}</span><span class=\"topbar-mode\">{}</span>",
            escape_html(&session.session_id),
            escape_html(&session.mode),
        ));
    }
    html.push_str("<div class=\"usage-mount\" data-usage>");
    if let Some(id) = selected_id {
        html.push_str(&crate::dashboard_live::render_usage_html(
            &crate::read_model::usage_aggregate(connection, id)?,
        ));
    }
    html.push_str("</div>");
    // The relocated chat<->audit view toggle. The `id="view-toggle"`, `data-view-toggle`,
    // and aria attrs stay STABLE so the T1 toggle script (below, in `<main>`) still binds.
    html.push_str(
        "<button id=\"view-toggle\" data-view-toggle type=\"button\" aria-controls=\"audit-view\" aria-expanded=\"false\">Audit</button>",
    );
    html.push_str("</header>");
    html.push_str("<div class=\"app-shell\">");
    html.push_str(
        "<aside class=\"sidebar\"><div class=\"brand\">zynk</div><nav id=\"session-nav\">",
    );
    html.push_str(&render_session_nav_inner(&sessions, selected_id));
    html.push_str("</nav>");
    // v1.0 M4a M2: the left mode rail — the canonical workflow modes with the session's
    // CURRENT mode highlighted (the decide -> review -> validate progression). READ-ONLY:
    // it mounts `render_mode_rail_inner` (state-only, no write surface) and refreshes live
    // via the `session-state` SSE event (the p[4] fragment) so the highlight follows a
    // live mode change. The `#mode-rail` id is the SSE mount target; p[0..3] are unchanged.
    html.push_str("<nav class=\"mode-rail\" id=\"mode-rail\">");
    html.push_str(&render_mode_rail_inner(selected));
    html.push_str("</nav>");
    html.push_str("<section id=\"roster\" class=\"roster-panel\"><h2>Participants</h2><div class=\"roster-mount\"></div></section>");
    html.push_str("</aside>");

    html.push_str(
        "<main class=\"timeline\"><header id=\"timeline-header\" class=\"timeline-header\">",
    );
    html.push_str(&render_timeline_header_inner(selected));
    html.push_str("</header>");
    // M4a U2 (Codex C3) + R1 (Codex C4) + M1: the usage aggregate mounts in TWO places —
    // the TopBar (above `.app-shell`) AND the right-rail Context budget section (below) —
    // each a stable `<div class="usage-mount" data-usage>` wrapping the SAME
    // `render_usage_html` fragment (which no longer hardcodes `id="usage"`, so there is
    // no duplicate id). The SSE `usage` event sets `innerHTML` on every `[data-usage]`
    // via `querySelectorAll`, so one event live-updates both; a feed-reset never touches
    // them (they are outside `#feed`).
    // ADR 031 D1: the operator composer — rendered only when writes are enabled
    // (a per-serve token is present) and a session is selected. The token rides in
    // a hidden field for the JS to lift into the required X-Zynk-CSRF header; the
    // server authorizes on the header, never the body field.
    if let (Some(token), Some(session)) = (csrf_token, selected) {
        // ADR 031 D1: the target is chosen from a server-side allow-list, never
        // free-typed. v1 M3b review note 2 (Codex A2): SOURCE these WRITE dropdowns
        // (composer to-select + the decide notify/redirect selects) from
        // `sendable_targets` — the SAME strict gate the server re-enforces before
        // spawn — so the offered options match the gate and never present a
        // non-sendable sentinel (operator:cli / none:none) that the server then 400s.
        // The DISPLAY roster (ADR 032 participant list) stays on `known_targets`.
        let targets = sendable_targets(connection, &session.session_id)?;
        // v1 M4a B1 (Codex C7) / Track A: the "All sendable targets" option is a
        // UI-only FAN-OUT, NOT a pseudo-target. `__all__` is a CLIENT-side sentinel:
        // when chosen, the submit script expands it into ONE real `POST /send` per
        // real sendable target (each its own DISTINCT mid + audit + proof). The
        // server NEVER sees `__all__`/`__both__`/`both`/`all` as a target —
        // `sendable_targets` (the same gate `handle_send` re-enforces) would reject
        // it, since it is not a sendable target. NO new write route, NO new server
        // endpoint: the fan-out reuses the existing `POST /send` exactly. The
        // sentinel is offered ONLY when there is more than one real target.
        let mut options = String::new();
        if targets.len() > 1 {
            options.push_str(&format!(
                "<option value=\"__all__\">All sendable targets ({})</option>",
                targets.len()
            ));
        }
        for target in &targets {
            options.push_str(&format!(
                "<option value=\"{}\">{}</option>",
                escape_html(target),
                escape_html(target),
            ));
        }
        // Emit the REAL sendable targets as a JSON array on the form, for the
        // fan-out JS to iterate. This list NEVER contains `__all__` (only the real
        // `agent:address` rows), so the fan-out can only POST real targets. The
        // whole attribute value is `escape_html`-escaped (so `"` -> `&quot;`),
        // which the browser un-escapes back to valid JSON for `getAttribute`.
        let sendable_json = {
            let mut json = String::from("[");
            for (index, target) in targets.iter().enumerate() {
                if index > 0 {
                    json.push(',');
                }
                json.push('"');
                // Targets are `agent:address` rows (no quotes/backslashes in
                // practice), but escape the two JSON-significant chars defensively
                // so a hostile address can never break out of the JSON string.
                json.push_str(&target.replace('\\', "\\\\").replace('"', "\\\""));
                json.push('"');
            }
            json.push(']');
            json
        };
        html.push_str(&format!(
            "<form class=\"composer\" method=\"post\" action=\"/send\" data-sendable-targets=\"{}\">\
             <input type=\"hidden\" name=\"csrf\" value=\"{}\">\
             <input type=\"hidden\" name=\"session\" value=\"{}\">\
             <select name=\"to\" required>{}</select>\
             <input name=\"type\" value=\"status-update\">\
             <input name=\"body\" placeholder=\"message\u{2026}\" required>\
             <button>Send</button></form>\
             <div class=\"composer-status\" hidden></div>",
            escape_html(&sendable_json),
            escape_html(token),
            escape_html(&session.session_id),
            options,
        ));
        if targets.is_empty() {
            html.push_str("<p class=\"composer-note\">No known targets for this session yet.</p>");
        }
        // v1 M4a B1 (Codex C7) / Track A: the composer submit handler. For a single
        // target it is the UNCHANGED ADR 031 path (one `POST /send`, PRG-follow /
        // escaped error). For the UI-only `__all__` sentinel it FANS OUT CLIENT-side:
        // ONE separate `fetch('/send', …)` per real sendable target (read from
        // `data-sendable-targets`), each via the SAME CSRF header + `/send` route,
        // each with a DISTINCT client `mid` (`all-<n>-<rand>`); it collects each
        // result {target, ok, status} and renders a per-target success/failure
        // summary. The server mints its OWN audited mid per call and NEVER receives
        // `__all__` — N real audited sends, N proofs, no fabricated target, no new
        // write surface.
        html.push_str(
            "<script>document.querySelector('.composer').addEventListener('submit',function(e){\
e.preventDefault();var f=e.target;var token=f.csrf.value;var session=f.session.value;\
var to=f.to.value;var type=f.type.value;var body=f.body.value;\
function doSend(target,mid){return fetch('/send',{method:'POST',\
headers:{'X-Zynk-CSRF':token,'Content-Type':'application/x-www-form-urlencoded'},\
body:new URLSearchParams({session:session,to:target,type:type,body:body,mid:mid})});}\
if(to!=='__all__'){doSend(to,'op-'+Date.now().toString(36)).then(function(r){\
if(r.redirected){location=r.url}else{r.text().then(function(t){document.body.innerHTML=t})}});return;}\
var targets=JSON.parse(f.getAttribute('data-sendable-targets')||'[]');\
var strip=f.parentNode.querySelector('.composer-status');if(strip){strip.hidden=false;strip.textContent='Sending to '+targets.length+' targets\u{2026}';}\
var stamp=Date.now().toString(36);\
Promise.all(targets.map(function(target,i){return doSend(target,'all-'+i+'-'+stamp)\
.then(function(r){return{target:target,ok:r.redirected||r.ok,status:r.status};})\
.catch(function(){return{target:target,ok:false,status:0};});}))\
.then(function(results){if(!strip)return;strip.innerHTML='';\
results.forEach(function(res){var row=document.createElement('div');\
row.className='composer-result '+(res.ok?'ok':'fail');\
row.textContent=res.target+': '+(res.ok?'sent':'failed ('+res.status+')');strip.appendChild(row);});});});</script>",
        );
        // ADR 033 M2b (T5): the STANDALONE mode/interrupt/redirect decision controls,
        // in <main> (OUTSIDE #feed, like the composer) so a feed-reset never wipes
        // them. Reuses the composer's known-target allow-list for the notify/redirect
        // selects (no free-typed pane/address). Gated on the same per-serve token.
        render_decision_controls(&mut html, token, &session.session_id, &targets);
        // ADR 033 M2b (T5): one DELEGATED submit handler for EVERY `.decide-form` —
        // the standalone controls above AND the per-card gate/conflict controls that
        // are inserted LIVE via SSE `feed-append`/`feed-reset` (a direct
        // addEventListener would miss those). It lifts the hidden `csrf` field into
        // the required `X-Zynk-CSRF` header (mirrors the composer JS) and PRG-follows
        // the 303 / re-renders the escaped error body — the same trust model.
        html.push_str(
            "<script>document.addEventListener('submit',function(e){var f=e.target;if(!f.classList||!f.classList.contains('decide-form'))return;e.preventDefault();fetch(f.getAttribute('action'),{method:'POST',headers:{'X-Zynk-CSRF':f.csrf.value,'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(new FormData(f,e.submitter))}).then(function(r){if(r.redirected){location=r.url}else{r.text().then(function(t){document.body.innerHTML=t})}});});</script>",
        );
        // ADR 035 D5: one DELEGATED submit handler for EVERY `.reveal-form` — the
        // per-message proof-strip control AND the per-card gate/conflict/standalone
        // decision controls that may ride in LIVE via SSE `feed-append`/`feed-reset`
        // (a direct addEventListener would miss those). It lifts the hidden `csrf`
        // field into the required `X-Zynk-CSRF` header (mirrors the composer JS) and
        // — UNLIKE /send (D1: reveal NEVER 303-PRGs to the redacted read view) —
        // ALWAYS replaces the body with the escaped `r.text()` plaintext/error result.
        html.push_str(
            "<script>document.addEventListener('submit',function(e){var f=e.target;if(!f.classList||!f.classList.contains('reveal-form'))return;e.preventDefault();fetch(f.getAttribute('action'),{method:'POST',headers:{'X-Zynk-CSRF':f.csrf.value,'Content-Type':'application/x-www-form-urlencoded'},body:new URLSearchParams(new FormData(f))}).then(function(r){return r.text()}).then(function(t){document.body.innerHTML=t});});</script>",
        );
    }
    // v1.0 M4a T1 (Codex C2) + M1: the CLIENT-side chat<->audit view toggle button is
    // now relocated into the TopBar (above `.app-shell`); the `#view-toggle` id +
    // `data-view-toggle` + aria attrs stay STABLE so the handler (script below) still
    // binds it by id. The handler flips `#audit-view` `hidden` + `#feed`'s `chat-hidden`
    // class — pure show/hide, the EventSource is untouched.
    // v0.8 T6 (concern #1 fix): `id="feed"` wraps ONLY the feed articles, not the
    // whole `<main>`. The SSE `feed-reset`/`feed-append` payloads carry only the
    // article fragments, so `feed.innerHTML = …` must not destroy the timeline
    // `<header>` or the ADR 031 composer — they stay in `<main>`, OUTSIDE `#feed`.
    html.push_str("<div id=\"feed\">");
    if feed.is_empty() {
        html.push_str("<section class=\"empty-state\">No feed entries yet.</section>");
    } else {
        for event in &feed {
            render_feed_event(&mut html, event, &decision_overlay, csrf_token);
        }
    }
    html.push_str("</div>");
    // v1.0 M4a T1 (Codex C2): the INLINE audit panel — a SEPARATE sibling of `#feed`
    // INSIDE `<main>`, reusing `render_audit_inner` (the same audit-trail fragment as
    // the `/audit` route, REDACTED — the toggle never un-redacts; M3b reveal is the
    // only un-redaction). HIDDEN by default; the toggle button above shows it while
    // hiding `#feed` (which stays in the DOM so `feed-*` SSE events keep updating it,
    // no lost state). `feed-reset` stays scoped to `#feed` ONLY (never this panel,
    // the composer, the top-bar, or the right rail).
    html.push_str("<section id=\"audit-view\" class=\"audit-view\" hidden>");
    html.push_str("<h2>Audit Trail</h2>");
    html.push_str(&render_audit_inner(connection, selected_id)?);
    html.push_str("</section>");
    // The toggle handler: pure client-side show/hide, NO navigation, EventSource
    // untouched. Flips `#audit-view` `hidden` + `#feed`'s `chat-hidden` class and
    // the button label chat<->audit.
    html.push_str(
        "<script>(function(){var b=document.getElementById('view-toggle');\
         var f=document.getElementById('feed');var a=document.getElementById('audit-view');\
         if(!b||!f||!a)return;b.addEventListener('click',function(){\
         var showAudit=a.hidden;a.hidden=!showAudit;f.classList.toggle('chat-hidden',showAudit);\
         b.textContent=showAudit?'Chat':'Audit';b.setAttribute('aria-expanded',showAudit?'true':'false');});})();</script>",
    );
    html.push_str("</main>");

    // v1.0 M4a R1 (Codex C4 / D6/D7): the right rail is a sectioned ContextPanel — NOT
    // tabs — where every section maps to a real M1/M2/M3 producer (empty-states, not
    // mock cards). Status (M1 fields, `render_detail_inner` UNCHANGED) + an audit-chain
    // summary (intact/count/latest, reusing `verify_chain`) + Artifacts (the M1
    // `Artifact` work-events) + Context budget (the U2 usage aggregate — a
    // `[data-usage]` mount, the SAME fragment the M1 TopBar also mounts) +
    // operator controls (the live decide/reveal/composer surface stays in `<main>`; this
    // is a rail-level header, NO new write surface) + a transport/connection sub-panel
    // (connection + provenance ONLY, no fake latency). The Status + chain sections mount
    // into `#detail-status` / `#detail-chain` so the `session-state` SSE event refreshes
    // them in place WITHOUT wiping the other sections; the budget refreshes via the
    // `usage` SSE event alongside the TopBar (both are `[data-usage]` mounts).
    html.push_str("<aside id=\"detail\" class=\"context-panel\">");
    html.push_str("<section class=\"panel-section status-section\"><div id=\"detail-status\">");
    html.push_str(&render_detail_inner(selected));
    html.push_str("</div></section>");
    html.push_str("<section class=\"panel-section chain-section\"><div id=\"detail-chain\">");
    html.push_str(&render_chain_summary_inner(connection, selected_id)?);
    html.push_str("</div></section>");
    html.push_str("<section class=\"panel-section artifacts-section\">");
    html.push_str(&render_artifacts_inner(connection, selected_id)?);
    html.push_str("</section>");
    html.push_str("<section class=\"panel-section budget-section\"><h2>Context budget</h2>");
    // v1.0 M4a M1: the budget usage display is a STABLE `[data-usage]` mount — the SAME
    // shape + fragment as the TopBar mount — so the one `usage` SSE event live-updates
    // BOTH via `querySelectorAll('[data-usage]')` (no duplicate `id="usage"`).
    html.push_str("<div class=\"usage-mount\" data-usage>");
    if let Some(id) = selected_id {
        html.push_str(&crate::dashboard_live::render_usage_html(
            &crate::read_model::usage_aggregate(connection, id)?,
        ));
    }
    html.push_str("</div>");
    html.push_str("</section>");
    html.push_str(
        "<section class=\"panel-section controls-section\"><h2>Operator controls</h2><p class=\"controls-note\">Decide, reveal, and compose from the live feed and composer.</p></section>",
    );
    html.push_str("<section class=\"panel-section transport-panel\">");
    html.push_str(&render_transport_inner());
    html.push_str("</section>");
    html.push_str("</aside></div>");
    // ADR 032 D7 / ADR 031 D4: a SEPARATE vanilla-JS SSE client (no build pipeline)
    // that live-updates the feed + roster. The feed/roster payloads are server-
    // rendered AND HTML-escaped (`render_feed_event` / `render_roster_html` via
    // `escape_html`), so `innerHTML`/`insertAdjacentHTML` here render TRUSTED server
    // output — the same trust model as the ADR 031 composer error branch above. No
    // client-side sanitization: the server escape is the load-bearing XSS control.
    //
    // Session ids are agent-created free-form strings, so they must NEVER be
    // interpolated into the <script> body: `{:?}` makes a valid JS string literal
    // but does NOT escape `</script>`, so a hostile id (e.g.
    // `</script><script>…</script>`) would break out and execute. Instead we emit
    // the id ONCE into an `escape_html`-escaped HTML data attribute (safe in
    // attribute context — `<` `>` `"` `'` `&` are escaped, no breakout) and the
    // STATIC script reads it via `dataset.sid`. The <script> body has zero dynamic
    // interpolation.
    if let Some(session) = selected {
        html.push_str(&format!(
            "<div id=\"sse-cfg\" data-sid=\"{}\" hidden></div>",
            escape_html(&session.session_id),
        ));
        html.push_str(
            "<script>(function(){var sid=document.getElementById('sse-cfg').dataset.sid;\
             var es=new EventSource('/events?session='+encodeURIComponent(sid));\
             var feed=document.getElementById('feed');var roster=document.querySelector('.roster-mount');\
             es.addEventListener('feed-reset',function(e){if(feed)feed.innerHTML=e.data;});\
             es.addEventListener('feed-append',function(e){if(feed)feed.insertAdjacentHTML('beforeend',e.data);});\
             es.addEventListener('roster',function(e){if(roster)roster.innerHTML=e.data;});\
             es.addEventListener('usage',function(e){document.querySelectorAll('[data-usage]').forEach(function(el){el.innerHTML=e.data;});});\
             es.addEventListener('session-state',function(e){var p=e.data.split(String.fromCharCode(30));\
             var nav=document.getElementById('session-nav');if(nav&&p[0]!==undefined)nav.innerHTML=p[0];\
             var hdr=document.getElementById('timeline-header');if(hdr&&p[1]!==undefined)hdr.innerHTML=p[1];\
             var det=document.getElementById('detail-status');if(det&&p[2]!==undefined)det.innerHTML=p[2];\
             var chn=document.getElementById('detail-chain');if(chn&&p[3]!==undefined)chn.innerHTML=p[3];\
             var mr=document.getElementById('mode-rail');if(mr&&p[4]!==undefined)mr.innerHTML=p[4];});\
             })();</script>",
        );
    }
    html.push_str("</body></html>");
    Ok(html)
}

/// ADR 032 D4 (R1 P1): the inner HTML of the sidebar `<nav id="session-nav">`. The
/// static page and the live `session-state` SSE event share this one renderer so
/// the sidebar badges update on a live status change without a reload. `selected_id`
/// is accepted for parity with the other inner renderers (the current markup does
/// not highlight the selected link).
fn render_session_nav_inner(sessions: &[DashboardSession], _selected_id: Option<&str>) -> String {
    let mut html = String::new();
    if sessions.is_empty() {
        html.push_str("<p class=\"empty\">No sessions in this database.</p>");
    } else {
        for session in sessions {
            html.push_str(&format!(
                "<a class=\"session-link\" href=\"/?session={}\"><span>{}</span><span class=\"badge status-{}\">{}</span></a>",
                escape_url_component(&session.session_id),
                escape_html(&session.session_id),
                escape_class(&session.workflow_status),
                escape_html(&session.workflow_status),
            ));
        }
    }
    html
}

/// v1.0 M4a M2: the inner HTML of the left `<nav class="mode-rail">` — the workflow
/// mode rail. Lists EVERY canonical workflow mode (`crate::decision::CANONICAL_MODES`,
/// the shared const — not an invented list) with the session's CURRENT mode
/// (`session.mode`, the M2 C3=b current state) marked `active`. READ-ONLY: this renders
/// state only and adds NO mode-write surface — the ADR 033-D4 decide/mode-switch route
/// is unchanged. Shared by the static page and the `session-state` SSE event (the p[4]
/// fragment) so the highlight follows a live mode change without a reload. The modes
/// are static `&str` consts (no untrusted input), so no escaping is needed.
fn render_mode_rail_inner(selected: Option<&DashboardSession>) -> String {
    let current = selected.map(|s| s.mode.as_str());
    let mut html = String::new();
    for mode in crate::decision::CANONICAL_MODES {
        let class = if current == Some(mode) {
            "mode active"
        } else {
            "mode"
        };
        html.push_str(&format!("<span class=\"{class}\">{mode}</span>"));
    }
    html
}

/// ADR 032 D4 (R1 P1): the inner HTML of `<header id="timeline-header">`. Shared by
/// the static page and the `session-state` SSE event so the header (session / phase
/// / mode) updates live.
fn render_timeline_header_inner(selected: Option<&DashboardSession>) -> String {
    let mut html = String::from("<div><h1>Timeline</h1>");
    if let Some(session) = selected {
        html.push_str(&format!(
            "<p>{} / {} / {}</p>",
            escape_html(&session.session_id),
            escape_html(&session.phase),
            escape_html(&session.mode)
        ));
    }
    html.push_str("</div>");
    html
}

/// ADR 032 D4 (R1 P1): the inner HTML of the right `<aside id="detail">` status
/// rail. Shared by the static page and the `session-state` SSE event so the detail
/// panel updates live on a status change.
fn render_detail_inner(selected: Option<&DashboardSession>) -> String {
    let mut html = String::from("<h2>Status</h2>");
    if let Some(session) = selected {
        html.push_str(&format!(
            "<dl><dt>Session</dt><dd>{}</dd><dt>State</dt><dd>{}</dd><dt>Next</dt><dd>{}</dd><dt>Ask</dt><dd>{}</dd><dt>Blockers</dt><dd>{}</dd><dt>Risk</dt><dd>{}</dd><dt>Expected wait</dt><dd>{}</dd><dt>Artifact</dt><dd>{}</dd><dt>Lead</dt><dd>{}</dd><dt>Updated</dt><dd>{}</dd></dl>",
            escape_html(&session.title),
            escape_html(&session.workflow_status),
            escape_html(&session.next_action),
            escape_html(&session.asks_for_zevs),
            escape_html(&session.blockers),
            escape_html(&session.risk_or_residual_uncertainty),
            escape_html(&session.expected_wait),
            escape_html(&session.artifact_ref),
            escape_html(&session.lead_agent_id),
            escape_html(&session.updated_at),
        ));
    }
    html
}

/// v1.0 M4a R1 (Codex C4 / ADR 033 D6): the COMPACT audit-chain summary for the
/// right-rail ContextPanel — an intact/anomaly badge, the record count, and the
/// latest audit_id/proof. REUSES `verify_chain` (the same chain VERIFY as
/// `render_audit_inner`); the FULL trail stays in the T1 `#audit-view` toggle, not
/// here. Shared by the static page and the `session-state` SSE event so the summary
/// refreshes on a live chain change.
fn render_chain_summary_inner(
    connection: &Connection,
    session_id: Option<&str>,
) -> CliResult<String> {
    let mut html = String::from("<h2>Audit chain</h2>");
    let Some(id) = session_id else {
        html.push_str("<p class=\"chain-summary empty\">No session.</p>");
        return Ok(html);
    };
    let verification = verify_chain(connection, id)?;
    let badge = if verification.ok { "intact" } else { "anomaly" };
    // The latest audit_id is the last row in chain order (timestamp, audit_id) — the
    // SAME ordering `render_audit_inner` uses for the full trail.
    let latest: Option<String> = connection
        .query_row(
            "SELECT audit_id FROM audit_records WHERE session_id = ?1
             ORDER BY timestamp DESC, audit_id DESC LIMIT 1",
            [id],
            |row| row.get(0),
        )
        .ok();
    let detail = if verification.ok {
        match latest {
            Some(audit_id) => format!(
                "chain {} \u{00b7} {} verified \u{00b7} latest {}",
                badge, verification.verified_count, audit_id
            ),
            None => format!(
                "chain {} \u{00b7} {} verified",
                badge, verification.verified_count
            ),
        }
    } else {
        format!(
            "chain {} at {}",
            badge,
            verification.broken_at.clone().unwrap_or_default()
        )
    };
    html.push_str(&format!(
        "<p class=\"chain-summary {}\">{}</p>",
        badge,
        escape_html(&detail)
    ));
    Ok(html)
}

/// v1.0 M4a R1 (Codex C4 / D7): the Artifacts section for the right-rail
/// ContextPanel — the session's `kind='artifact'` work-events, each listing its
/// `Artifact { files }` paths. Reads `work_events.payload` and round-trips the typed
/// value via `from_storage` (the SAME pattern as `usage_aggregate`). When the session
/// has NO artifact events it renders an empty-state ("No artifacts"), NEVER a
/// fabricated row.
fn render_artifacts_inner(connection: &Connection, session_id: Option<&str>) -> CliResult<String> {
    let mut html = String::from("<h2>Artifacts</h2>");
    let Some(id) = session_id else {
        html.push_str("<p class=\"empty-state\">No artifacts.</p>");
        return Ok(html);
    };
    let mut statement = connection
        .prepare(
            "SELECT work_event_id, payload FROM work_events
             WHERE session_id = ?1 AND kind = 'artifact' ORDER BY timestamp, work_event_id",
        )
        .map_err(|e| CliError::failure(format!("failed to prepare artifacts query: {e}")))?;
    let rows = statement
        .query_map([id], |row| {
            Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?))
        })
        .map_err(|e| CliError::failure(format!("failed to query artifacts: {e}")))?;
    let mut paths: Vec<crate::work_event::ArtifactFile> = Vec::new();
    for row in rows {
        let (work_event_id, payload) =
            row.map_err(|e| CliError::failure(format!("failed to read artifact: {e}")))?;
        // R1 Major (Codex): the schema CHECK constrains only the `kind` STRING, not its
        // agreement with the typed payload — a raw-SQL row could be kind='artifact' yet
        // carry a non-Artifact payload. Fail loud (matching `work_events`) rather than
        // silently skip the row, which would render "No artifacts" and hide the corrupt
        // row (ADR 027 fail-loud). A session with NO artifact rows is still the
        // legitimate empty-state below.
        match crate::work_event::WorkEventPayload::from_storage(&payload)? {
            crate::work_event::WorkEventPayload::Artifact { files } => paths.extend(files),
            other => {
                return Err(CliError::failure(format!(
                    "render_artifacts: work_event {work_event_id} kind='artifact' has non-Artifact payload (payload kind {:?})",
                    other.kind()
                )));
            }
        }
    }
    if paths.is_empty() {
        html.push_str("<p class=\"empty-state\">No artifacts.</p>");
    } else {
        html.push_str("<ul class=\"artifact-list\">");
        for file in &paths {
            html.push_str(&format!(
                "<li><span class=\"path\">{}</span> <i class=\"d-add\">+{}</i><i class=\"d-rem\">\u{2212}{}</i></li>",
                escape_html(&file.path),
                file.add,
                file.rem,
            ));
        }
        html.push_str("</ul>");
    }
    Ok(html)
}

/// v1.0 M4a R1 (Codex C4): the transport/connection sub-panel for the right-rail
/// ContextPanel — connection state + roster provenance ONLY. NO latency metrics
/// (no fabricated `ms`): zynk has no transport-timing producer, so a latency card
/// would be a mock (D7). The connection is always loopback (ADR 025 read-only bind);
/// the provenance mirrors `load_roster`'s source selection (HERDR_ENV=1 ->
/// live-herdr, else db-fallback) WITHOUT shelling out (this is the static-render
/// hint; the live `roster` SSE event carries the per-entry authoritative provenance).
fn render_transport_inner() -> String {
    let provenance = if std::env::var("HERDR_ENV").as_deref() == Ok("1") {
        "live-herdr"
    } else {
        "db-fallback"
    };
    format!(
        "<h2>Transport</h2><dl class=\"transport\"><dt>Connection</dt><dd>loopback (127.0.0.1, read-only)</dd><dt>Roster source</dt><dd>{provenance}</dd></dl>"
    )
}

/// Render a feed (already in display order) to concatenated, HTML-escaped article
/// fragments — the SSE payload AND the static-page body share this.
fn render_feed_html(
    events: &[FeedEvent],
    overlay: &BTreeMap<i64, DecisionView>,
    writes: Option<&str>,
) -> String {
    let mut html = String::new();
    for event in events {
        render_feed_event(&mut html, event, overlay, writes);
    }
    html
}

/// ADR 030 D2/D6: render one read-model feed entry — a message shows its body
/// (or a redacted marker for hash-only), with the proof strip carrying the latest
/// delivery state, the transport addresses, and the stable permalink.
///
/// ADR 033 M2b (T2): `overlay` is the gate/conflict decision overlay map for the
/// session (computed ONCE per render, keyed by `target_work_event_id`). A `work_events`
/// gate/conflict card looks itself up by id and, if a decision exists, renders the
/// decision verdict/resolution overlay on the card; a standalone mode/interrupt/redirect
/// decision (`source_table=operator_decisions`, `event.decision.is_some()`) renders a
/// typed decision card. EVERY decision-derived string is `escape_html`-escaped (ADR
/// 031/032 XSS discipline; the v0.8 script-breakout regression — server-side escape is
/// the load-bearing control).
///
/// ADR 033 M2b (T5): `writes` is the per-serve CSRF token when `--allow-writes` is set
/// (else `None`). When present, a gate/conflict card additionally renders a FUNCTIONAL
/// decide control (a `.decide-form` POSTing `/decide/gate` or `/decide/conflict`) — the
/// only browser write surface besides the ADR 031 composer. When `None` the dashboard
/// stays read-only (no decide form renders). Every form value is `escape_html`-escaped.
fn render_feed_event(
    html: &mut String,
    event: &FeedEvent,
    overlay: &BTreeMap<i64, DecisionView>,
    writes: Option<&str>,
) {
    // ADR 033 M2b (T2): a standalone operator-decision feed item (mode/interrupt/
    // redirect — gate/conflict decisions overlay their work card, they are never feed
    // items) carries the TYPED `DecisionView`. Render a per-`decision_type` card; all
    // decision-derived text is `escape_html`-escaped.
    if event.source_table == "operator_decisions" {
        if let Some(decision) = &event.decision {
            render_decision_card(html, event, decision, writes);
            return;
        }
    }
    // ADR 033 M1 (T6): a `work_events` feed entry carries the TYPED payload — render
    // a distinct per-kind card instead of the message/status branch. All
    // payload-derived text is `escape_html`-escaped (ADR 031/032 XSS discipline:
    // server-side escape is the load-bearing control; never interpolate untrusted
    // text unescaped). `event.kind` is the stored work-event kind, so `kind-{}`
    // gives `kind-think`/`kind-tool`/… for styling and the M1 acceptance.
    if let Some(work) = &event.work {
        use crate::work_event::WorkEventPayload::*;
        html.push_str(&format!(
            "<article class=\"feed-item kind-{}\"><div class=\"timestamp\">{}</div>",
            escape_class(&event.kind),
            escape_html(&event.timestamp)
        ));
        html.push_str(&format!(
            "<h2>{} <span class=\"kind\">{}</span></h2>",
            escape_html(event.actor_agent_id.as_deref().unwrap_or("system")),
            escape_html(&event.kind)
        ));
        match work {
            Think { text } | System { text } => {
                html.push_str(&format!("<p class=\"body\">{}</p>", escape_html(text)))
            }
            Tool {
                name,
                arg,
                output,
                ok,
            } => html.push_str(&format!(
                "<div class=\"tool\"><code>{}({})</code><pre>{}</pre><span class=\"ok-{}\">{}</span></div>",
                escape_html(name),
                escape_html(arg),
                escape_html(output),
                ok,
                if *ok { "ok" } else { "fail" }
            )),
            Diff {
                file,
                added,
                removed,
                ..
            } => html.push_str(&format!(
                "<div class=\"diff\"><span class=\"path\">{}</span><i class=\"d-add\">+{}</i><i class=\"d-rem\">\u{2212}{}</i></div>",
                escape_html(file),
                added,
                removed
            )),
            Plan { title, checklist } => {
                html.push_str(&format!("<div class=\"plan\"><b>{}</b><ul>", escape_html(title)));
                for it in checklist {
                    html.push_str(&format!("<li>{}</li>", escape_html(it)));
                }
                html.push_str("</ul></div>");
            }
            Artifact { files } => {
                html.push_str("<div class=\"artifact\"><ul>");
                for f in files {
                    html.push_str(&format!(
                        "<li>{} <i class=\"d-add\">+{}</i><i class=\"d-rem\">\u{2212}{}</i></li>",
                        escape_html(&f.path),
                        f.add,
                        f.rem
                    ));
                }
                html.push_str("</ul></div>");
            }
            Usage { agent, tokens, .. } => html.push_str(&format!(
                "<div class=\"usage\">{} \u{00b7} <b>{}</b> tokens</div>",
                escape_html(agent),
                thousands(*tokens)
            )),
            Gate {
                title,
                summary,
                actions,
                ..
            } => {
                html.push_str(&format!(
                    "<div class=\"gate\"><b>{}</b><p>{}</p><div class=\"actions\">",
                    escape_html(title),
                    escape_html(summary)
                ));
                for a in actions {
                    html.push_str(&format!("<span class=\"act\">{}</span>", escape_html(a)));
                }
                html.push_str("</div>");
                render_decision_overlay(html, event, overlay, writes);
                render_gate_control(html, event, writes);
                html.push_str("</div>");
            }
            Conflict {
                topic, positions, ..
            } => {
                html.push_str(&format!("<div class=\"conflict\"><b>{}</b>", escape_html(topic)));
                for p in positions {
                    html.push_str(&format!(
                        "<div class=\"pos\"><span class=\"who\">{}</span> {}</div>",
                        escape_html(&p.from),
                        escape_html(&p.stance)
                    ));
                }
                render_decision_overlay(html, event, overlay, writes);
                render_conflict_control(html, event, writes);
                html.push_str("</div>");
            }
        }
        html.push_str("</article>");
        return;
    }
    html.push_str(&format!(
        "<article class=\"feed-item kind-{}\"><div class=\"timestamp\">{}</div>",
        escape_class(&event.kind),
        escape_html(&event.timestamp),
    ));
    let who = event.actor_agent_id.as_deref().unwrap_or("system");
    let label = event.subtype.as_deref().unwrap_or(event.kind.as_str());
    html.push_str(&format!(
        "<h2>{} <span class=\"kind\">{}</span>",
        escape_html(who),
        escape_html(label),
    ));
    if let Some(mid) = &event.mid {
        html.push_str(&format!(" <span class=\"mid\">{}</span>", escape_html(mid)));
    }
    html.push_str("</h2>");
    match &event.body {
        Some(body) => html.push_str(&format!("<p class=\"body\">{}</p>", escape_html(body))),
        None if event.kind == "message" => {
            html.push_str("<p class=\"redacted\">\u{2298} redacted \u{00b7} hash-only</p>")
        }
        None => {
            if let Some(summary) = &event.summary {
                html.push_str(&format!("<p>{}</p>", escape_html(summary)));
            }
        }
    }
    if event.proof_audit_id.is_some() {
        html.push_str("<div class=\"proof-strip\">");
        html.push_str(&format!(
            "<span class=\"proof proof-{}\">{} / {}</span>",
            escape_class(event.delivery_status.as_deref().unwrap_or("unknown")),
            escape_html(event.delivery_status.as_deref().unwrap_or("unknown")),
            escape_html(event.verified_by.as_deref().unwrap_or("unknown")),
        ));
        if let (Some(source), Some(target)) = (&event.source_address, &event.target_address) {
            html.push_str(&format!(
                "<span class=\"addr\">{} \u{2192} {} \u{00b7} {}</span>",
                escape_html(source),
                escape_html(target),
                escape_html(event.transport.as_deref().unwrap_or("?")),
            ));
        }
        if let Some(link) = permalink(event) {
            html.push_str(&format!(
                "<span class=\"permalink\">{}</span>",
                escape_html(&link)
            ));
        }
        // ADR 035 D5: the reveal affordance for this message's sender-audit proof —
        // rendered ONLY under `--allow-writes` AND only when `revealable` (the proof
        // has a custody_vault row AND a non-`full` redaction policy). `proof_audit_id`
        // is the candidate audit_id (guaranteed `Some` in this branch).
        if let Some(audit_id) = &event.proof_audit_id {
            render_reveal_control(html, &event.session_id, audit_id, event.revealable, writes);
        }
        html.push_str("</div>");
    }
    html.push_str("</article>");
}

/// ADR 033 M2b (T2): render the gate/conflict decision OVERLAY on a `work_events`
/// card. The overlay map is keyed by the bound `target_work_event_id`; this card's
/// work-event id is `event.source_id` (the i64 stringified). When a decision exists,
/// emit a stable `decision-verdict`/`decision-resolution` marker carrying the typed
/// verdict/resolution, the operator actor, the decision timestamp, and an optional
/// note. EVERY decision-derived string is `escape_html`-escaped (the typed
/// `DecisionView` columns, NOT parsed audit text; the v0.8 script-breakout XSS).
///
/// ADR 035 D5: `writes` is the per-serve CSRF token under `--allow-writes` (else
/// `None`). When present AND the gate/conflict decision is `revealable` (a
/// custody_vault row + non-`full` policy), the overlay additionally renders the
/// reveal affordance for the DECISION's `audit_id` (a gate/conflict decision is never
/// its own feed item, so the control rides on the overlaid work-event card). When
/// `None` (or not revealable) nothing reveal-related renders — read-only stays read-only.
fn render_decision_overlay(
    html: &mut String,
    event: &FeedEvent,
    overlay: &BTreeMap<i64, DecisionView>,
    writes: Option<&str>,
) {
    let Ok(work_event_id) = event.source_id.parse::<i64>() else {
        return; // a non-numeric work-event source_id can carry no overlay (defensive)
    };
    let Some(decision) = overlay.get(&work_event_id) else {
        return; // this gate/conflict has not been decided yet
    };
    // gate-decision -> verdict; conflict-resolve -> resolution. Both render the same
    // overlay shape with a type-specific marker class + the resolved value.
    let (marker, value) = match decision.verdict.as_deref() {
        Some(verdict) => ("decision-verdict", verdict),
        None => (
            "decision-resolution",
            decision.resolution.as_deref().unwrap_or(""),
        ),
    };
    let actor = decision.actor_agent_id.as_deref().unwrap_or("operator");
    html.push_str(&format!(
        "<div class=\"decision-overlay {}\"><span class=\"verdict\">{}</span>\
         <span class=\"by\">{} \u{00b7} {}</span>",
        escape_class(marker),
        escape_html(value),
        escape_html(actor),
        escape_html(&decision.timestamp),
    ));
    render_notify_badge(html, decision);
    if let Some(note) = &decision.note {
        html.push_str(&format!("<p class=\"note\">{}</p>", escape_html(note)));
    }
    // ADR 035 D5: the reveal affordance for this gate/conflict DECISION's audit_id
    // (the decision is an overlay on the work card, never its own feed item).
    render_reveal_control(
        html,
        &event.session_id,
        &decision.audit_id,
        decision.revealable,
        writes,
    );
    html.push_str("</div>");
}

/// ADR 033 M2b (T2) / C4=b notify honesty: render the decision's notification status
/// (`sent`/`failed`) as a small escaped badge so the operator sees whether the
/// decision reached the agent. Suppressed for `not-requested` (the common no-notify
/// case) to keep an unnotified decision card clean. Escaped (typed column, not text).
fn render_notify_badge(html: &mut String, decision: &DecisionView) {
    if decision.notification_status == "not-requested" {
        return;
    }
    html.push_str(&format!(
        "<span class=\"notify notify-{}\">notify: {}</span>",
        escape_class(&decision.notification_status),
        escape_html(&decision.notification_status),
    ));
}

/// ADR 033 M2b (T2): render a STANDALONE typed operator-decision card — a
/// mode-switch / interrupt / redirect (gate/conflict decisions overlay their work
/// card, they are never feed items). A per-`decision_type` body shows the typed
/// fields (mode_to / reason / target_agent), all `escape_html`-escaped (the typed
/// `DecisionView` columns, NOT parsed audit text; the v0.8 script-breakout XSS).
///
/// ADR 035 D5: `writes` is the per-serve CSRF token under `--allow-writes` (else
/// `None`). When present AND the decision is `revealable` (a custody_vault row +
/// non-`full` policy), the card additionally renders the reveal affordance for the
/// decision's own `audit_id`. When `None` (or not revealable) the card stays read-only.
fn render_decision_card(
    html: &mut String,
    event: &FeedEvent,
    decision: &DecisionView,
    writes: Option<&str>,
) {
    // A stable per-type marker class (`decision-mode`/`decision-interrupt`/
    // `decision-redirect`) for styling + the M2b acceptance, derived from the typed
    // `decision_type` (`mode-switch`/`interrupt`/`redirect`).
    let marker = match decision.decision_type.as_str() {
        "mode-switch" => "decision-mode",
        "interrupt" => "decision-interrupt",
        "redirect" => "decision-redirect",
        _ => "decision-other",
    };
    html.push_str(&format!(
        "<article class=\"feed-item decision {}\"><div class=\"timestamp\">{}</div>",
        escape_class(marker),
        escape_html(&event.timestamp),
    ));
    html.push_str(&format!(
        "<h2>{} <span class=\"kind\">{}</span></h2>",
        escape_html(decision.actor_agent_id.as_deref().unwrap_or("operator")),
        escape_html(&decision.decision_type),
    ));
    html.push_str("<div class=\"decision-body\">");
    match decision.decision_type.as_str() {
        "mode-switch" => {
            html.push_str(&format!(
                "<span class=\"mode-to\">\u{2192} {}</span>",
                escape_html(decision.mode_to.as_deref().unwrap_or("")),
            ));
        }
        "interrupt" => {
            if let Some(reason) = &decision.reason {
                html.push_str(&format!("<p class=\"reason\">{}</p>", escape_html(reason)));
            }
        }
        "redirect" => {
            html.push_str(&format!(
                "<span class=\"target-agent\">\u{2192} {}</span>",
                escape_html(decision.target_agent.as_deref().unwrap_or("")),
            ));
            if let Some(reason) = &decision.reason {
                html.push_str(&format!("<p class=\"reason\">{}</p>", escape_html(reason)));
            }
        }
        _ => {}
    }
    render_notify_badge(html, decision);
    if let Some(note) = &decision.note {
        html.push_str(&format!("<p class=\"note\">{}</p>", escape_html(note)));
    }
    // ADR 035 D5: the reveal affordance for this standalone decision's own audit_id.
    render_reveal_control(
        html,
        &event.session_id,
        &decision.audit_id,
        decision.revealable,
        writes,
    );
    html.push_str("</div></article>");
}

/// ADR 035 D5: render the reveal AFFORDANCE for a revealable read-model record — a
/// `.reveal-form` POSTing the C1 `/reveal` route with the record's `audit_id` + the
/// served `session`. Rendered ONLY when `writes` is `Some` (the per-serve CSRF token
/// under `--allow-writes`) AND `revealable` is true (the record has a `custody_vault`
/// row AND a redaction policy that is NOT `full` — a `full`-redaction record is
/// already shown plainly, so it gets no control). When EITHER is absent, nothing
/// renders — the read surface stays read-only. The token rides in a hidden field that
/// the delegated `.reveal-form` submit handler lifts into the required `X-Zynk-CSRF`
/// header (mirrors the ADR 031 composer JS); on success the escaped plaintext result
/// replaces the view (`r.text()` -> `document.body.innerHTML`). EVERY value is
/// `escape_html`-escaped (ADR 031/032 XSS discipline; the v0.8 script-breakout lesson).
fn render_reveal_control(
    html: &mut String,
    session_id: &str,
    audit_id: &str,
    revealable: bool,
    writes: Option<&str>,
) {
    let Some(token) = writes else {
        return; // read-only: no reveal control without --allow-writes
    };
    if !revealable {
        return; // not revealable (no vault row, or full-redaction already shown plainly)
    }
    html.push_str(&format!(
        "<form class=\"reveal-form\" method=\"post\" action=\"/reveal\">\
         <input type=\"hidden\" name=\"csrf\" value=\"{}\">\
         <input type=\"hidden\" name=\"session\" value=\"{}\">\
         <input type=\"hidden\" name=\"audit_id\" value=\"{}\">\
         <button type=\"submit\">Reveal</button>\
         </form>",
        escape_html(token),
        escape_html(session_id),
        escape_html(audit_id),
    ));
}

/// ADR 033 M2b (T5): render the FUNCTIONAL gate decision control on a gate work-event
/// card — a `.decide-form` POSTing the T4 `/decide/gate` route with approve /
/// request-changes verdicts. Rendered ONLY when `writes` is `Some` (the per-serve
/// CSRF token under `--allow-writes`); when `None` the card stays read-only. The
/// token rides in a hidden field that the shared `.decide-form` submit handler lifts
/// into the required `X-Zynk-CSRF` header (mirrors the ADR 031 `/send` composer JS).
/// `ref` is the bound work-event id (`event.source_id`); the verdict is supplied by
/// the clicked submit button (`name="verdict"`), so a single form offers both. EVERY
/// value is `escape_html`-escaped (ADR 031/032 XSS; the v0.8 script-breakout lesson).
fn render_gate_control(html: &mut String, event: &FeedEvent, writes: Option<&str>) {
    let Some(token) = writes else {
        return; // read-only: no decide form without --allow-writes
    };
    html.push_str(&format!(
        "<form class=\"decide-form decide-gate\" method=\"post\" action=\"/decide/gate\">\
         <input type=\"hidden\" name=\"csrf\" value=\"{}\">\
         <input type=\"hidden\" name=\"session\" value=\"{}\">\
         <input type=\"hidden\" name=\"ref\" value=\"{}\">\
         <input name=\"note\" placeholder=\"note (optional)\u{2026}\">\
         <button type=\"submit\" name=\"verdict\" value=\"approve\">Approve</button>\
         <button type=\"submit\" name=\"verdict\" value=\"request-changes\">Request changes</button>\
         </form>",
        escape_html(token),
        escape_html(&event.session_id),
        escape_html(&event.source_id),
    ));
}

/// ADR 033 M2b (T5): render the FUNCTIONAL conflict resolution control on a conflict
/// work-event card — a `.decide-form` POSTing the T4 `/decide/conflict` route with a
/// `resolution` text input + optional note. Same write-gating + CSRF-lift as
/// `render_gate_control` (rendered ONLY under `--allow-writes`; the token rides in a
/// hidden field the shared submit handler lifts into `X-Zynk-CSRF`). `ref` is the
/// bound work-event id (`event.source_id`). EVERY value is `escape_html`-escaped.
fn render_conflict_control(html: &mut String, event: &FeedEvent, writes: Option<&str>) {
    let Some(token) = writes else {
        return; // read-only: no decide form without --allow-writes
    };
    html.push_str(&format!(
        "<form class=\"decide-form decide-conflict\" method=\"post\" action=\"/decide/conflict\">\
         <input type=\"hidden\" name=\"csrf\" value=\"{}\">\
         <input type=\"hidden\" name=\"session\" value=\"{}\">\
         <input type=\"hidden\" name=\"ref\" value=\"{}\">\
         <input name=\"resolution\" placeholder=\"resolution\u{2026}\" required>\
         <input name=\"note\" placeholder=\"note (optional)\u{2026}\">\
         <button type=\"submit\">Resolve</button>\
         </form>",
        escape_html(token),
        escape_html(&event.session_id),
        escape_html(&event.source_id),
    ));
}

/// ADR 033 M2b (T5): render the STANDALONE mode / interrupt / redirect decision
/// controls — emitted in `<main>` (OUTSIDE `#feed`, like the ADR 031 composer) so a
/// live `feed-reset` never wipes them. Rendered ONLY under `--allow-writes` (the
/// per-serve CSRF token present). The mode control is a `<select>` of the ADR 020
/// `CANONICAL_MODES` POSTing `/decide/mode`; interrupt POSTs `/decide/interrupt` with
/// an optional reason; redirect POSTs `/decide/redirect` with a `--to` target agent +
/// optional reason. Any notify target is a known-target `<select>` (the `/send`
/// allow-list — NEVER free-typed); when a session has no known targets the notify
/// control is omitted. Each form is a `.decide-form` whose hidden CSRF field the
/// shared submit handler lifts into `X-Zynk-CSRF`. EVERY value is `escape_html`-escaped.
fn render_decision_controls(
    html: &mut String,
    token: &str,
    session_id: &str,
    known_targets: &[String],
) {
    // The known-target notify <select> (reused across all three forms). An EMPTY
    // first option means "no notify" so a control with notify-capable targets can
    // still be submitted without one; when the session has no known targets the
    // whole select is omitted (no free-typed pane/address is ever offered).
    let notify_select = if known_targets.is_empty() {
        String::new()
    } else {
        let mut options = String::from("<option value=\"\">no notify</option>");
        for target in known_targets {
            options.push_str(&format!(
                "<option value=\"{}\">{}</option>",
                escape_html(target),
                escape_html(target),
            ));
        }
        format!("<select name=\"notify\">{options}</select>")
    };
    html.push_str("<section class=\"decide-controls\">");
    // mode-switch: a <select> of the canonical modes.
    let mut mode_options = String::new();
    for mode in crate::decision::CANONICAL_MODES {
        mode_options.push_str(&format!(
            "<option value=\"{}\">{}</option>",
            escape_html(mode),
            escape_html(mode),
        ));
    }
    html.push_str(&format!(
        "<form class=\"decide-form decide-mode\" method=\"post\" action=\"/decide/mode\">\
         <input type=\"hidden\" name=\"csrf\" value=\"{token}\">\
         <input type=\"hidden\" name=\"session\" value=\"{session}\">\
         <label>mode <select name=\"to\" required>{modes}</select></label>\
         <button type=\"submit\">Switch mode</button>\
         </form>",
        token = escape_html(token),
        session = escape_html(session_id),
        modes = mode_options,
    ));
    // interrupt: an optional reason + optional notify.
    html.push_str(&format!(
        "<form class=\"decide-form decide-interrupt\" method=\"post\" action=\"/decide/interrupt\">\
         <input type=\"hidden\" name=\"csrf\" value=\"{token}\">\
         <input type=\"hidden\" name=\"session\" value=\"{session}\">\
         <input name=\"reason\" placeholder=\"interrupt reason (optional)\u{2026}\">{notify}\
         <button type=\"submit\">Interrupt</button>\
         </form>",
        token = escape_html(token),
        session = escape_html(session_id),
        notify = notify_select,
    ));
    // redirect: the target agent comes from the known-target <select> (an agent:address
    // pair); the `--to` half is the same value. Omitted when no known targets exist.
    if !known_targets.is_empty() {
        let mut redirect_options = String::new();
        for target in known_targets {
            redirect_options.push_str(&format!(
                "<option value=\"{}\">{}</option>",
                escape_html(target),
                escape_html(target),
            ));
        }
        html.push_str(&format!(
            "<form class=\"decide-form decide-redirect\" method=\"post\" action=\"/decide/redirect\">\
             <input type=\"hidden\" name=\"csrf\" value=\"{token}\">\
             <input type=\"hidden\" name=\"session\" value=\"{session}\">\
             <label>redirect to <select name=\"to\" required>{targets}</select></label>\
             <input name=\"reason\" placeholder=\"reason (optional)\u{2026}\">\
             <button type=\"submit\">Redirect</button>\
             </form>",
            token = escape_html(token),
            session = escape_html(session_id),
            targets = redirect_options,
        ));
    }
    html.push_str("</section>");
}

/// ADR 030 D5/D7 + v1.0 M4a T1 (Codex C2): the audit-trail BODY fragment — a
/// chain-shape verification summary plus the full `audit_records` chain for the
/// session, WITHOUT the `<html>`/`<head>`/`<style>` shell or the `<main>`/header
/// wrapper. Both the `/audit` route (via `render_audit`, which wraps this in its
/// shell — byte-identical output) and the dashboard's INLINE `#audit-view` panel
/// reuse this one renderer so the audit trail shows in-place via the client-side
/// toggle without a route navigation (the SSE EventSource is never torn down).
fn render_audit_inner(
    connection: &Connection,
    selected_session_id: Option<&str>,
) -> CliResult<String> {
    let sessions = load_sessions(connection)?;
    let selected = selected_session_id
        .and_then(|id| sessions.iter().find(|session| session.session_id == id))
        .or_else(|| sessions.first());
    let mut html = String::new();
    if let Some(session) = selected {
        let verification = verify_chain(connection, &session.session_id)?;
        let label = if verification.ok {
            format!(
                "chain intact \u{00b7} {} verified",
                verification.verified_count
            )
        } else {
            format!(
                "chain anomaly at {}",
                verification.broken_at.unwrap_or_default()
            )
        };
        html.push_str(&format!("<p class=\"verify\">{}</p>", escape_html(&label)));
        let mut statement = connection
            .prepare(
                "SELECT audit_id, COALESCE(previous_audit_id, 'genesis'), record_type,
                        delivery_status, verified_by, payload_hash, timestamp
                 FROM audit_records WHERE session_id = ?1 ORDER BY timestamp, audit_id",
            )
            .map_err(|error| CliError::failure(format!("failed to query audit view: {error}")))?;
        let rows = statement
            .query_map([session.session_id.as_str()], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, String>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, String>(3)?,
                    row.get::<_, String>(4)?,
                    row.get::<_, String>(5)?,
                    row.get::<_, String>(6)?,
                ))
            })
            .map_err(|error| CliError::failure(format!("failed to read audit view: {error}")))?
            .collect::<Result<Vec<_>, _>>()
            .map_err(|error| CliError::failure(format!("failed to read audit view: {error}")))?;
        for (audit_id, previous, record_type, delivery, verified, hash, timestamp) in rows {
            html.push_str(&format!(
                "<article class=\"feed-item\"><div class=\"timestamp\">{}</div><h2>{} <span class=\"kind\">{}</span></h2><p>\u{2190} {} \u{00b7} {} / {} \u{00b7} {}</p></article>",
                escape_html(&timestamp),
                escape_html(&audit_id),
                escape_html(&record_type),
                escape_html(&previous),
                escape_html(&delivery),
                escape_html(&verified),
                escape_html(&hash),
            ));
        }
    } else {
        html.push_str("<section class=\"empty-state\">No session.</section>");
    }
    Ok(html)
}

/// ADR 030 D5/D7: the read-only audit-trail view — a chain-shape verification
/// summary plus the full `audit_records` chain for the session (the feed shows
/// only the latest proof per message; the whole chain lives here). The `/audit`
/// route wraps `render_audit_inner` in the standalone page shell; output is
/// unchanged from the pre-T1 single-function form.
fn render_audit(connection: &Connection, selected_session_id: Option<&str>) -> CliResult<String> {
    let mut html = String::new();
    html.push_str("<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">");
    html.push_str("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
    html.push_str("<title>zynk audit</title><style>");
    html.push_str(STYLES);
    html.push_str("</style></head><body><div class=\"app-shell\"><main class=\"timeline\">");
    html.push_str("<header class=\"timeline-header\"><div><h1>Audit Trail</h1></div></header>");
    html.push_str(&render_audit_inner(connection, selected_session_id)?);
    html.push_str("</main></div></body></html>");
    Ok(html)
}

fn load_sessions(connection: &Connection) -> CliResult<Vec<DashboardSession>> {
    let mut statement = connection
        .prepare(
            // ADR 027 / v0.3.1: derive displayed current-state from the latest
            // status_event (already joined as se), falling back to the sessions
            // row only when no status_event exists. Import is append-only and does
            // not advance the sessions row, so an import-only session would
            // otherwise render a stale phase/mode/workflow_status/updated_at.
            "SELECT
                s.session_id,
                s.title,
                COALESCE(se.phase, s.phase),
                COALESCE(se.mode, s.mode),
                COALESCE(se.workflow_status, s.workflow_status),
                COALESCE(s.lead_agent_id, 'unknown'),
                COALESCE(s.artifact_ref, 'unknown'),
                COALESCE(se.timestamp, s.updated_at),
                COALESCE(se.next_action, 'unknown'),
                COALESCE(se.blockers, 'unknown'),
                COALESCE(se.asks_for_zevs, 'unknown'),
                COALESCE(se.risk_or_residual_uncertainty, 'unknown'),
                COALESCE(se.expected_wait, 'unknown')
             FROM sessions AS s
             LEFT JOIN status_events AS se
               ON se.status_event_id = (
                 SELECT status_event_id
                 FROM status_events
                 WHERE session_id = s.session_id
                 ORDER BY timestamp DESC, status_event_id DESC
                 LIMIT 1
               )
             ORDER BY COALESCE(se.timestamp, s.updated_at) DESC, s.session_id",
        )
        .map_err(|error| {
            CliError::failure(format!("failed to query dashboard sessions: {error}"))
        })?;
    let mut sessions = statement
        .query_map([], |row| {
            Ok(DashboardSession {
                session_id: row.get(0)?,
                title: row.get(1)?,
                phase: row.get(2)?,
                mode: row.get(3)?,
                workflow_status: row.get(4)?,
                lead_agent_id: row.get(5)?,
                artifact_ref: row.get(6)?,
                updated_at: row.get(7)?,
                next_action: row.get(8)?,
                blockers: row.get(9)?,
                asks_for_zevs: row.get(10)?,
                risk_or_residual_uncertainty: row.get(11)?,
                expected_wait: row.get(12)?,
            })
        })
        .map_err(|error| CliError::failure(format!("failed to read dashboard sessions: {error}")))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| {
            CliError::failure(format!("failed to read dashboard sessions: {error}"))
        })?;
    // ADR 033 M2b T3 (C3=b): make the current-state `mode` latest-writer across BOTH
    // the agent `status_events.mode` (resolved above as `s.mode` over the latest
    // status_event) AND the latest `mode-switch` operator decision's `mode_to`. The
    // query already exposes `updated_at` = COALESCE(se.timestamp, s.updated_at) — the
    // timestamp the status-derived `mode` was effectively written at. If the latest
    // mode-switch decision is STRICTLY newer than that, the operator decision wins for
    // `mode` ONLY; otherwise the status mode stands (ties keep the status mode —
    // deterministic, matching the SQL `ORDER BY timestamp DESC`). RFC3339-UTC strings
    // compare lexicographically the same way SQLite orders them. We override `mode`
    // in Rust rather than bolt a second-source pick into the single-statement query
    // so NO other current-state field (phase/workflow_status/next_action/…) is
    // touched — the operator never authored those, only the mode. Provenance stays in
    // the typed `operator_decisions` table (see `latest_mode_decision`); no synthetic
    // status_event is invented.
    for session in &mut sessions {
        if let Some((decision_ts, mode_to)) =
            crate::db::latest_mode_decision(connection, &session.session_id)?
        {
            if decision_ts.as_str() > session.updated_at.as_str() {
                session.mode = mode_to;
            }
        }
    }
    Ok(sessions)
}

pub(crate) fn escape_html(value: &str) -> String {
    value
        .replace('&', "&amp;")
        .replace('<', "&lt;")
        .replace('>', "&gt;")
        .replace('"', "&quot;")
        .replace('\'', "&#39;")
}

/// Group a token count's digits with `,` (e.g. `4700` -> `4,700`) for the usage
/// card. Plain ASCII-digit grouping; no locale handling needed.
fn thousands(n: u64) -> String {
    let digits = n.to_string();
    let bytes = digits.as_bytes();
    let mut grouped = String::with_capacity(digits.len() + digits.len() / 3);
    let len = bytes.len();
    for (index, byte) in bytes.iter().enumerate() {
        if index > 0 && (len - index).is_multiple_of(3) {
            grouped.push(',');
        }
        grouped.push(*byte as char);
    }
    grouped
}

fn escape_class(value: &str) -> String {
    escape_html(value)
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_') {
                ch
            } else {
                '-'
            }
        })
        .collect()
}

pub(crate) fn escape_url_component(value: &str) -> String {
    let mut escaped = String::new();
    for byte in value.bytes() {
        if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
            escaped.push(byte as char);
        } else {
            escaped.push_str(&format!("%{byte:02X}"));
        }
    }
    escaped
}

pub(crate) fn percent_decode(value: &str) -> String {
    let mut decoded = Vec::new();
    let bytes = value.as_bytes();
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] == b'%' && index + 2 < bytes.len() {
            if let Ok(hex) = std::str::from_utf8(&bytes[index + 1..index + 3]) {
                if let Ok(byte) = u8::from_str_radix(hex, 16) {
                    decoded.push(byte);
                    index += 3;
                    continue;
                }
            }
        }
        decoded.push(bytes[index]);
        index += 1;
    }
    String::from_utf8_lossy(&decoded).to_string()
}

const STYLES: &str = r#"
:root { color-scheme: light; --ink: #1c2024; --muted: #667085; --line: #d6dbe1; --panel: #f7f8fa; --accent: #0f766e; --warn: #9a3412; --ok: #166534; }
* { box-sizing: border-box; }
body { margin: 0; font: 14px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; color: var(--ink); background: #ffffff; letter-spacing: 0; }
.topbar { display: flex; align-items: center; gap: 14px; padding: 10px clamp(14px, 2vw, 24px); border-bottom: 1px solid var(--line); background: var(--panel); }
.topbar-session { font-weight: 600; }
.topbar-mode { font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); border: 1px solid var(--line); border-radius: 6px; padding: 2px 8px; background: #fff; }
.topbar .usage-mount { margin-left: auto; }
.topbar #view-toggle { margin: 0; }
.app-shell { min-height: 100vh; display: grid; grid-template-columns: minmax(220px, 18vw) minmax(0, 1fr) minmax(260px, 22vw); }
.sidebar, .context-panel { background: var(--panel); border-color: var(--line); padding: 18px; overflow: auto; }
.sidebar { border-right: 1px solid var(--line); }
.context-panel { border-left: 1px solid var(--line); }
.context-panel .panel-section { margin: 0 0 18px; padding: 0 0 14px; border-bottom: 1px solid var(--line); }
.context-panel .panel-section:last-child { border-bottom: 0; margin-bottom: 0; padding-bottom: 0; }
.context-panel h2 { font-size: 12px; text-transform: uppercase; letter-spacing: 0.04em; color: var(--muted); margin: 0 0 8px; }
.chain-summary.intact { color: var(--ok); }
.chain-summary.anomaly { color: var(--warn); }
.artifact-list { list-style: none; margin: 0; padding: 0; }
.artifact-list li { display: flex; gap: 6px; align-items: baseline; font-size: 12px; padding: 2px 0; }
.controls-note { color: var(--muted); font-size: 12px; margin: 0; }
.brand { font-weight: 700; font-size: 18px; margin-bottom: 18px; }
.session-link { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 8px; align-items: center; color: inherit; text-decoration: none; padding: 9px 0; border-bottom: 1px solid var(--line); }
.badge, .proof { display: inline-flex; align-items: center; min-height: 24px; padding: 3px 8px; border: 1px solid var(--line); border-radius: 6px; background: #fff; font-size: 12px; white-space: nowrap; }
.status-working, .proof-observed { border-color: #86efac; color: var(--ok); }
.status-blocked, .status-waiting-for-operator, .proof-failed { border-color: #fdba74; color: var(--warn); }
.proof-sent { border-color: #5eead4; color: var(--accent); }
.status-idle, .status-done, .proof-drafted, .proof-unknown { border-color: #d0d5dd; color: var(--muted); }
.timeline { padding: 20px clamp(18px, 3vw, 42px); overflow: auto; }
.timeline-header { display: flex; justify-content: space-between; align-items: end; border-bottom: 1px solid var(--line); margin-bottom: 18px; padding-bottom: 12px; }
h1 { font-size: 24px; margin: 0; }
h2 { font-size: 15px; margin: 4px 0; }
p { color: var(--muted); margin: 4px 0; }
.timeline-item { max-width: 860px; border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; margin: 0 0 12px; background: #fff; }
.timestamp { color: var(--muted); font-size: 12px; }
.proof-strip { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
dl { display: grid; grid-template-columns: 96px minmax(0, 1fr); gap: 9px 12px; margin: 0; }
dt { color: var(--muted); }
dd { margin: 0; overflow-wrap: anywhere; }
.empty, .empty-state { color: var(--muted); }
.chat-hidden { display: none; }
#view-toggle { display: inline-flex; align-items: center; min-height: 28px; padding: 4px 12px; margin: 0 0 12px; border: 1px solid var(--line); border-radius: 6px; background: #fff; color: var(--ink); font: inherit; cursor: pointer; }
.mode-rail { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); }
.mode-rail .mode { display: inline-flex; align-items: center; min-height: 24px; padding: 3px 8px; border: 1px solid var(--line); border-radius: 6px; background: #fff; font-size: 12px; color: var(--muted); }
.mode-rail .mode.active { color: var(--ink); border-color: var(--accent, var(--ink)); font-weight: 600; }
.roster-panel { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); }
.roster { list-style: none; margin: 0; padding: 0; }
.roster li { display: flex; align-items: center; gap: 8px; padding: 5px 0; }
.feed-item { max-width: 860px; border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; margin: 0 0 12px; background: #fff; }
.feed-item .body { color: var(--ink); white-space: pre-wrap; overflow-wrap: anywhere; margin: 6px 0; }
.feed-item .redacted { color: var(--muted); font-style: italic; }
.kind { color: var(--muted); font-weight: 400; font-size: 12px; }
.mid { color: var(--muted); font-size: 12px; }
.addr, .permalink { color: var(--muted); font-size: 12px; }
.verify { color: var(--ok); font-weight: 600; }
.tool code { font-size: 12px; color: var(--ink); }
.tool pre { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 8px 10px; margin: 6px 0; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
.tool .ok-true { color: var(--ok); font-weight: 600; }
.tool .ok-false { color: var(--warn); font-weight: 600; }
.diff { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 6px 0; }
.diff .path { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; overflow-wrap: anywhere; }
.d-add { color: var(--ok); font-style: normal; font-size: 12px; }
.d-rem { color: var(--warn); font-style: normal; font-size: 12px; }
.plan ul, .artifact ul { margin: 6px 0; padding-left: 18px; color: var(--ink); }
.plan li, .artifact li { margin: 2px 0; }
.usage { margin: 6px 0; color: var(--ink); }
.gate { margin: 6px 0; }
.gate .actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
.gate .act { display: inline-flex; align-items: center; min-height: 24px; padding: 3px 8px; border: 1px solid var(--line); border-radius: 6px; background: #fff; font-size: 12px; }
.conflict { margin: 6px 0; }
.conflict .pos { margin: 4px 0; color: var(--ink); }
.conflict .who { color: var(--muted); font-weight: 600; }
.decision-overlay { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 8px; padding-top: 8px; border-top: 1px dashed var(--line); }
.decision-overlay .verdict { font-weight: 600; padding: 2px 8px; border-radius: 6px; background: var(--panel); border: 1px solid var(--line); font-size: 12px; }
.decision-overlay.decision-verdict .verdict { color: var(--ok); }
.decision-overlay.decision-resolution .verdict { color: var(--accent, var(--ink)); }
.decision-overlay .by { color: var(--muted); font-size: 12px; }
.decision-overlay .note, .decision .note { color: var(--ink); font-size: 12px; margin: 4px 0 0; flex-basis: 100%; }
.feed-item.decision .decision-body { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 6px 0; color: var(--ink); }
.feed-item.decision .mode-to, .feed-item.decision .target-agent { font-weight: 600; }
.feed-item.decision .reason { color: var(--muted); font-size: 12px; flex-basis: 100%; margin: 0; }
.notify { font-size: 11px; padding: 1px 6px; border-radius: 6px; border: 1px solid var(--line); }
.notify-sent { color: var(--ok); }
.notify-failed { color: var(--warn); }
@media (max-width: 900px) { .app-shell { grid-template-columns: 1fr; } .sidebar, .context-panel { border: 0; border-bottom: 1px solid var(--line); } }
"#;

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

    #[test]
    fn windowed_keeps_last_n_else_all() {
        // ADR 032 D4: the SSE/initial feed is a windowed (last-N) oldest-first feed.
        // len > n -> keep the last n (the suffix); len <= n -> keep all.
        let five = [1, 2, 3, 4, 5];
        assert_eq!(windowed(&five, 3), vec![3, 4, 5]);
        let two = [1, 2];
        assert_eq!(windowed(&two, 3), vec![1, 2]);
        // exact boundary -> all
        assert_eq!(windowed(&five, 5), vec![1, 2, 3, 4, 5]);
        // empty -> empty
        assert_eq!(windowed::<i32>(&[], 3), Vec::<i32>::new());
    }

    // v1 M3b A1 (Codex C6): `sendable_targets` is the STRICT write-validation
    // allow-list — only REAL herdr send participants (a `transport != 'none'` row,
    // agent:address, excluding the `none` sentinels and the non-pane addresses
    // `cli`/`dashboard`). It must NOT leak the non-transport sentinels that the
    // display roster (`known_targets`) carries: decide/reveal records have
    // `transport='none'`, `target none/none`, and `source operator/cli`.
    //
    // Seed approach: a real v9 DB (open_database migrates to head, so the M3a-P4
    // `audit_records_no_sent_nontransport_proof_insert` + `no_sent_agent` triggers
    // are live). We insert the rows directly with `delivery_status='observed'`
    // (never `sent`), so neither the v9 non-transport-proof trigger nor the
    // sent+agent trigger can fire on any of the three rows.
    #[test]
    fn sendable_targets_excludes_non_transport_sentinels() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("zynk.db");

        {
            let conn = crate::db::open_database(&db_path).unwrap();
            conn.execute(
                "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
                 VALUES ('p1', 'P1', '/tmp/p1', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
                [],
            )
            .unwrap();
            conn.execute(
                "INSERT INTO sessions (
                    session_id, project_id, title, phase, mode, workflow_status,
                    created_at, updated_at
                 )
                 VALUES (
                    's1', 'p1', 'S1', 'implementation', 'review', 'working',
                    '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z'
                 )",
                [],
            )
            .unwrap();

            // (1) a REAL herdr message: transport=herdr, claude/w-1 -> codex/w-2.
            // delivery_status=observed keeps it past both sent-guard triggers.
            conn.execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id, target_agent_id,
                    source_address, target_address, transport, workspace_id, mid, record_type,
                    command_origin, payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES (
                    'aud-herdr', NULL, 's1', 'claude', 'codex', 'w-1', 'w-2', 'herdr', 'w',
                    'm1', 'note', 'agent', 'sha256:test', 'hash-only', 12,
                    'observed', 'codex', 'agent', '2026-05-29T01:00:00Z'
                 )",
                [],
            )
            .unwrap();

            // (2) a decide record: transport=none, source operator/cli, target none/none.
            conn.execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id, target_agent_id,
                    source_address, target_address, transport, workspace_id, mid, record_type,
                    command_origin, payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES (
                    'aud-decide', NULL, 's1', 'operator', 'none', 'cli', 'none', 'none', 'none',
                    'm2', 'gate-decision', 'operator', 'sha256:test', 'full', 12,
                    'observed', 'operator', 'operator', '2026-05-29T01:01:00Z'
                 )",
                [],
            )
            .unwrap();

            // (3) a reveal record: transport=none, target none/none.
            conn.execute(
                "INSERT INTO audit_records (
                    audit_id, previous_audit_id, session_id, source_agent_id, target_agent_id,
                    source_address, target_address, transport, workspace_id, mid, record_type,
                    command_origin, payload_hash, payload_redaction_policy, content_size,
                    delivery_status, observed_by, verified_by, timestamp
                 )
                 VALUES (
                    'aud-reveal', NULL, 's1', 'operator', 'none', 'cli', 'none', 'none', 'none',
                    'm3', 'reveal', 'operator', 'sha256:test', 'full', 12,
                    'observed', 'operator', 'operator', '2026-05-29T01:02:00Z'
                 )",
                [],
            )
            .unwrap();
        }

        let conn = crate::db::open_read_database(&db_path).unwrap();
        let targets = crate::db_dashboard::sendable_targets(&conn, "s1").unwrap();

        // CONTAINS the real herdr send participants (both source and target).
        assert!(
            targets.contains(&"claude:w-1".to_string()),
            "must include the real herdr source: {targets:?}"
        );
        assert!(
            targets.contains(&"codex:w-2".to_string()),
            "must include the real herdr target: {targets:?}"
        );
        // EXCLUDES the non-transport sentinels + non-pane addresses.
        assert!(
            !targets.contains(&"none:none".to_string()),
            "must not leak the none:none sentinel: {targets:?}"
        );
        assert!(
            !targets.contains(&":".to_string()),
            "must not leak an empty agent:address pair: {targets:?}"
        );
        assert!(
            !targets.contains(&"operator:cli".to_string()),
            "must not leak operator:cli (decide/reveal source): {targets:?}"
        );
        assert!(
            !targets.iter().any(|t| t.ends_with(":cli")),
            "must not leak any *:cli address: {targets:?}"
        );
        assert!(
            !targets.iter().any(|t| t.ends_with(":dashboard")),
            "must not leak any *:dashboard address: {targets:?}"
        );
    }

    // v1 M4a R1 (Codex Major): the `work_events.kind` column is only string-checked,
    // not constrained to AGREE with the stored payload — so a raw-SQL row with
    // kind='artifact' but a NON-Artifact payload is parseable yet mismatched.
    // `render_artifacts_inner` must FAIL LOUD on it (matching `work_events`), NOT
    // silently skip the row (which would render "No artifacts" and hide a corrupt row).
    // The producer enforces agreement, so the mismatch can only be created by a direct
    // INSERT. The legitimate empty-state (NO artifact rows at all) is covered by the
    // `right_rail_artifacts_empty_state` integration test.
    #[test]
    fn artifacts_fails_loud_on_kind_payload_mismatch() {
        let tmp = tempfile::tempdir().unwrap();
        let db_path = tmp.path().join("zynk.db");
        let conn = crate::db::open_database(&db_path).unwrap();
        conn.execute(
            "INSERT INTO projects (project_id, name, root_path, created_at, updated_at)
             VALUES ('p1', 'P1', '/tmp/p1', '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO sessions (
                session_id, project_id, title, phase, mode, workflow_status,
                created_at, updated_at
             )
             VALUES (
                's1', 'p1', 'S1', 'implementation', 'review', 'working',
                '2026-05-29T00:00:00Z', '2026-05-29T00:00:00Z'
             )",
            [],
        )
        .unwrap();
        let non_artifact = crate::work_event::WorkEventPayload::System {
            text: "not an artifact payload".into(),
        };
        let stored = non_artifact.to_storage().unwrap();
        conn.execute(
            "INSERT INTO work_events
                (session_id, actor_agent_id, kind, timestamp, payload, content_hash, created_at)
             VALUES ('s1', 'codex', 'artifact', '2026-05-29T00:05:00Z', ?1, 'sha256:bad',
                     '2026-05-29T00:05:00Z')",
            [&stored],
        )
        .unwrap();
        let error = render_artifacts_inner(&conn, Some("s1"))
            .expect_err("a kind='artifact' row with a non-Artifact payload must fail loud, not render 'No artifacts'");
        assert!(
            error.message.contains("render_artifacts") && error.message.contains("non-Artifact"),
            "error must name the artifacts kind/payload mismatch: {}",
            error.message
        );
    }
}