trustee-api 0.20.6

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

use std::sync::Arc;

use axum::{
    extract::{
        ws::{Message, WebSocket, WebSocketUpgrade},
        Path, State,
    },
    http::{header, StatusCode},
    response::{IntoResponse, Json, Response},
};
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

use crate::state::SessionError;
use crate::ServerState;

/// Attach a `Set-Cookie` header to a response if the cookie value is present.
fn with_rolling_cookie(mut response: Response, cookie: Option<String>) -> Response {
    if let Some(cookie_str) = cookie {
        if let Ok(value) = cookie_str.parse() {
            response.headers_mut().insert(header::SET_COOKIE, value);
        }
    }
    response
}

// ---------------------------------------------------------------------------
// DTOs
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
pub struct SessionResponse {
    pub workflow_state: String,
    pub output_lines: Vec<String>,
    pub todo_lines: Vec<String>,
    pub mcp_servers: Vec<McpServerJson>,
    pub context_tokens: usize,
    pub input: String,
    pub resume_info_present: bool,
    pub session_name: Option<String>,
    pub project_name: Option<String>,
    pub session_id: Option<String>,
    /// abk 0.21.4: live compaction status — `in_progress` while a
    /// summarization run is in flight (the /compact command never enters the
    /// transcript — it is intercepted before becoming a task message), plus
    /// the durable `last` trace. Additive field: old consoles ignore it;
    /// new consoles render a "compacting…" banner that survives a refresh
    /// (the tombstone-disclosure pattern, pairing-safe both directions).
    pub compaction: abk::resume::CompactionStatus,
}

#[derive(Debug, Serialize)]
pub struct McpServerJson {
    pub name: String,
    pub connected: bool,
    pub tool_count: usize,
    pub error: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct CommandRequest {
    pub command: String,
    pub session_id: Option<String>,
    /// Optional agent identity content. If provided and the session has no
    /// identity yet, it is set before executing the command.
    #[serde(default)]
    pub identity: Option<String>,
    /// Optional model override — name of a provider from `[llm.providers.{name}]`
    /// in the config TOML. When set, that provider's model/base_url/api_key
    /// override `[llm.provider]` for this command.
    #[serde(default)]
    pub model: Option<String>,
    /// Optional multimodal attachments for this command (base64, in
    /// memory — the client encodes; the server never touches the filesystem
    /// for these). Images render as image parts; text/markdown files are
    /// inlined as fenced synthetic text. Validated by
    /// [`validate_attachments`] before execution.
    #[serde(default)]
    pub attachments: Vec<AttachmentInput>,
}

/// One attachment on a [`CommandRequest`] (multimodal input).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AttachmentInput {
    /// MIME type. Accepted: image/jpeg, image/png, image/gif, image/webp
    /// (rendered as image parts) and text/plain, text/markdown,
    /// text/x-markdown (inlined as fenced synthetic text).
    pub mime: String,
    /// Base64-encoded file bytes. A `data:{mime};base64,` prefix is
    /// tolerated and stripped.
    pub data: String,
    /// Original file name, when the client knows it (display + fence info).
    #[serde(default)]
    pub filename: Option<String>,
}

/// Attachment limits (v1): bounded so a single request cannot balloon.
pub const MAX_ATTACHMENTS: usize = 4;
/// Maximum decoded size per image.
pub const MAX_IMAGE_BYTES: usize = 6 * 1024 * 1024; // 6 MiB
/// Maximum decoded size per text/markdown file. Text rides the prompt
/// itself, so it is bounded far tighter than images (token cost).
pub const MAX_TEXT_BYTES: usize = 256 * 1024; // 256 KiB
/// Body-limit applied to the command routes (base64 inflates by 4/3).
pub const ATTACH_BODY_LIMIT: usize = 40 * 1024 * 1024; // 40 MiB

/// Accepted image MIME types (mirrors abk's file-extension whitelist).
pub const ALLOWED_IMAGE_MIMES: [&str; 4] = ["image/jpeg", "image/png", "image/gif", "image/webp"];

/// Accepted text MIME types. `text/x-markdown` is accepted and normalized
/// to `text/markdown`.
pub const ALLOWED_TEXT_MIMES: [&str; 3] = ["text/plain", "text/markdown", "text/x-markdown"];

/// Validated attachment set: image sidecars (umf wire form) plus decoded
/// text files (inlined into the task text by the session layer).
#[derive(Debug, Default)]
pub struct ValidatedAttachments {
    pub images: Vec<umf::chatml::ImageAttachment>,
    pub text_files: Vec<trustee_core::session::TextFileAttachment>,
}

/// Decode and clean the base64 payload of one attachment.
///
/// Tolerates a data-URL prefix and whitespace the client may have inserted
/// when chunking long base64 strings.
fn decode_attachment_base64(
    idx: usize,
    name: &str,
    input: &AttachmentInput,
) -> Result<Vec<u8>, String> {
    use base64::Engine as _;
    let raw = input
        .data
        .trim()
        .strip_prefix("data:")
        .and_then(|rest| rest.split_once(";base64,"))
        .map(|(_, b64)| b64)
        .unwrap_or_else(|| input.data.trim());
    let cleaned: String = raw.chars().filter(|c| !c.is_whitespace()).collect();
    base64::engine::general_purpose::STANDARD
        .decode(cleaned.as_bytes())
        .map_err(|e| format!("Attachment {} ({}): invalid base64: {}", idx + 1, name, e))
}

/// Validate request attachments and split them into image sidecars and
/// decoded text files.
///
/// Fails closed with a descriptive message on: too many attachments
/// (across BOTH families), unsupported MIME, undecodable base64, an image
/// over [`MAX_IMAGE_BYTES`], a text file over [`MAX_TEXT_BYTES`], or text
/// that is not valid UTF-8.
pub fn validate_attachments(inputs: &[AttachmentInput]) -> Result<ValidatedAttachments, String> {
    if inputs.len() > MAX_ATTACHMENTS {
        return Err(format!(
            "Too many attachments: {} (max {})",
            inputs.len(),
            MAX_ATTACHMENTS
        ));
    }

    let mut out = ValidatedAttachments::default();
    for (idx, input) in inputs.iter().enumerate() {
        let name = input.filename.as_deref().unwrap_or("unnamed");
        let mime = input.mime.trim().to_ascii_lowercase();
        let decoded = decode_attachment_base64(idx, name, input)?;

        if ALLOWED_IMAGE_MIMES.contains(&mime.as_str()) {
            if decoded.len() > MAX_IMAGE_BYTES {
                return Err(format!(
                    "Attachment {} ({}): {} MiB decoded exceeds the {} MiB limit",
                    idx + 1,
                    name,
                    decoded.len() / (1024 * 1024),
                    MAX_IMAGE_BYTES / (1024 * 1024)
                ));
            }
            use base64::Engine as _;
            let cleaned_b64 = base64::engine::general_purpose::STANDARD.encode(&decoded);
            let display_name = if name.is_empty() {
                format!(
                    "attachment-{}.{}",
                    idx + 1,
                    mime.trim_start_matches("image/")
                )
            } else {
                name.to_string()
            };
            out.images.push(
                umf::chatml::ImageAttachment::new(mime.clone(), cleaned_b64)
                    .with_filename(display_name),
            );
        } else if ALLOWED_TEXT_MIMES.contains(&mime.as_str()) {
            // text/x-markdown is an alias — normalize for the wire/header.
            let mime = if mime == "text/x-markdown" {
                "text/markdown".to_string()
            } else {
                mime
            };
            if decoded.len() > MAX_TEXT_BYTES {
                return Err(format!(
                    "Attachment {} ({}): {} KiB of text exceeds the {} KiB limit",
                    idx + 1,
                    name,
                    decoded.len() / 1024,
                    MAX_TEXT_BYTES / 1024
                ));
            }
            let content = String::from_utf8(decoded).map_err(|_| {
                format!(
                    "Attachment {} ({}): not valid UTF-8 — text attachments must decode to UTF-8 (is this a binary file?)",
                    idx + 1,
                    name
                )
            })?;
            let filename = if name.is_empty() {
                format!(
                    "attachment-{}.{}",
                    idx + 1,
                    if mime == "text/markdown" { "md" } else { "txt" }
                )
            } else {
                name.to_string()
            };
            out.text_files
                .push(trustee_core::session::TextFileAttachment {
                    mime,
                    filename,
                    content,
                });
        } else {
            return Err(format!(
                "Attachment {} ({}): unsupported type '{}' — expected one of {} (images) or {} (text/markdown files)",
                idx + 1,
                name,
                input.mime,
                ALLOWED_IMAGE_MIMES.join(", "),
                ["text/plain", "text/markdown"].join(", ")
            ));
        }
    }
    Ok(out)
}

#[derive(Debug, Serialize)]
pub struct CommandResponse {
    pub accepted: bool,
}

#[derive(Debug, Serialize)]
pub struct HealthResponse {
    pub status: String,
    pub version: String,
}

// ---------------------------------------------------------------------------
// Session discovery DTOs (checkpoint-based, legacy)
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize)]
pub struct SessionListResponse {
    pub sessions: Vec<trustee_core::sessions::SessionSummary>,
}

#[derive(Debug, Serialize)]
pub struct SessionDetailResponse {
    pub session: trustee_core::sessions::SessionSummary,
    pub checkpoints: Vec<trustee_core::sessions::CheckpointSummary>,
}

#[derive(Debug, Serialize)]
pub struct ResumeResponse {
    pub accepted: bool,
    pub session_id: String,
    pub checkpoint_id: String,
    pub iteration: u32,
    /// 7df3cae2: present when the resumed chain carries a destroy tombstone —
    /// the explicit resume is honored, but the destruction is DISCLOSED
    /// (tombstoned-but-non-empty loudly), never swallowed.
    pub tombstoned_at: Option<String>,
}

#[derive(Debug, Clone, Deserialize)]
pub struct ResumeRequestBody {
    pub checkpoint_id: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct SessionHistoryResponse {
    pub session_id: String,
    pub checkpoint_id: String,
    pub task_description: String,
    pub iteration: u32,
    pub total_messages: usize,
    pub messages: Vec<trustee_core::sessions::HistoryMessage>,
    /// 7df3cae2: destroy-tombstone stamp when the chain was explicitly
    /// destroyed while its transcript stays preserved on disk — the console
    /// renders the disclosure instead of a silent, unexplained legacy view.
    pub tombstoned_at: Option<String>,
}

// ---------------------------------------------------------------------------
// MSU new-session DTOs
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
pub struct CreateSessionRequest {
    #[serde(default)]
    pub session_name: Option<String>,
    #[serde(default)]
    pub resume_from: Option<String>,
    /// Optional agent identity content prepended to the system prompt.
    #[serde(default)]
    pub identity: Option<String>,
    /// Optional model override — name of a provider from `[llm.providers.{name}]`.
    #[serde(default)]
    pub model: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct CreateSessionResponse {
    pub session_id: String,
    pub accepted: bool,
}

// ---------------------------------------------------------------------------
// Naming DTOs
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
pub struct SetNameRequest {
    pub name: String,
}

#[derive(Debug, Deserialize)]
pub struct NewSessionRequest {
    pub session_name: Option<String>,
    /// Optional agent identity content prepended to the system prompt.
    #[serde(default)]
    pub identity: Option<String>,
    /// Optional model override — name of a provider from `[llm.providers.{name}]`.
    #[serde(default)]
    pub model: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct SetNameResponse {
    pub accepted: bool,
    pub name: String,
}

#[derive(Debug, Serialize)]
pub struct NewSessionResponse {
    pub accepted: bool,
}

// ---------------------------------------------------------------------------
// Models DTOs
// ---------------------------------------------------------------------------

/// One selectable model entry.
#[derive(Debug, Serialize)]
pub struct ModelInfo {
    /// The literal model string sent to the LLM API (e.g. "GLM-5.2").
    /// This is what the client sends back in the `model` field.
    pub model: String,
}

/// One provider (endpoint) with its selectable models.
#[derive(Debug, Serialize)]
pub struct ProviderInfo {
    /// Display label (e.g. "glm-zai").
    pub name: Option<String>,
    /// Base URL (not a secret). Useful for UI tooltips.
    pub base_url: Option<String>,
    /// Default model for this endpoint.
    pub default_model: Option<String>,
    /// All selectable models (single-element if `models` was absent).
    pub models: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct ModelsResponse {
    /// The active provider (from `[llm.provider]`). Always present.
    pub provider: ProviderInfo,
    /// Alternative providers (from `[llm.providers.*]`).
    pub providers: Vec<ProviderInfo>,
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Build a SessionResponse from a locked session.
/// 7df3cae2 (tombstone-shadow class): a destroy-tombstoned chain must answer
/// LOUDLY and specifically — never the generic lying "Session not found".
/// The chain EXISTS (destroyed by explicit user terminate) while its
/// checkpoints sit intact on disk; the auto-restore refusal is by design,
/// but the refusal must name itself. Falls back to the generic 404 only when
/// no tombstone exists (genuinely unknown id).
fn loud_tombstoned_chain_error(
    state: &ServerState,
    user_key: &str,
    session_id: &str,
    status: StatusCode,
    verb: &str,
) -> (StatusCode, String) {
    match state.chain_tombstone_stamp(user_key, session_id) {
        Some(stamp) => (
            status,
            format!(
                "chain {session_id} was DESTROYED {stamp} — {verb} refused (destroyed chains never auto-resurrect); transcript preserved on disk: GET /sessions/{session_id}/history reads it, POST /sessions/{session_id}/resume restores it explicitly"
            ),
        ),
        None => (StatusCode::NOT_FOUND, "Session not found".to_string()),
    }
}

fn session_to_response(session: &trustee_core::session::Session) -> SessionResponse {
    let workflow_state = match session.workflow_state {
        trustee_core::types::WorkflowState::Idle => "Idle",
        trustee_core::types::WorkflowState::Running => "Running",
        trustee_core::types::WorkflowState::Cancelling => "Cancelling",
    };

    let mcp_servers = session
        .mcp_servers
        .iter()
        .map(|s| McpServerJson {
            name: s.name.clone(),
            connected: s.status == trustee_core::types::McpServerStatus::Connected,
            tool_count: s.tool_count,
            error: s.error.clone(),
        })
        .collect();

    SessionResponse {
        workflow_state: workflow_state.to_string(),
        output_lines: session.output_lines.clone(),
        todo_lines: session.todo_lines.clone(),
        mcp_servers,
        context_tokens: session.current_context_tokens,
        input: session.input.clone(),
        resume_info_present: session.resume_info.is_some(),
        session_name: session.session_name.clone(),
        project_name: session.project_name.clone(),
        session_id: session.session_id.clone(),
        // std Mutex, never held across an await — the session lock is already
        // held by the caller, so this is a short nested critical section.
        compaction: session
            .compaction_status
            .lock()
            .map(|s| s.clone())
            .unwrap_or_default(),
    }
}

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

/// GET /api/v1/health
pub async fn health() -> Json<HealthResponse> {
    Json(HealthResponse {
        status: "ok".to_string(),
        // The BIN's version when the bin injected it (set_bin_version) —
        // what `trustee --version` prints. Consumers (torpi THQ registry,
        // agent console menu) display this as THE trustee version.
        version: crate::bin_version().to_string(),
    })
}

/// GET /api/v1/models — list available LLM providers and their models.
///
/// Resolves the per-user config (shared + overlay + ${VAR} substitution),
/// then extracts `[llm.provider]` (active) and `[llm.providers.*]`
/// (alternatives). For each provider, returns its display name, base_url
/// (not a secret), and full `models` list. API keys are NEVER returned.
pub async fn list_models(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::LIST_MODELS)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let empty = || ModelsResponse {
        provider: ProviderInfo {
            name: None,
            base_url: None,
            default_model: None,
            models: vec![],
        },
        providers: vec![],
    };

    let Some(config_toml) = state.resolve_user_config(&user_key) else {
        return Ok(with_rolling_cookie(Json(empty()).into_response(), cookie));
    };

    let Ok(table) = config_toml.parse::<toml::Value>() else {
        return Ok(with_rolling_cookie(Json(empty()).into_response(), cookie));
    };

    let get_str = |v: &toml::Value, k: &str| -> Option<String> {
        v.get(k).and_then(|m| m.as_str()).map(|s| s.to_string())
    };
    let get_models = |v: &toml::Value| -> Vec<String> {
        v.get("models")
            .and_then(|m| m.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|m| m.as_str().map(|s| s.to_string()))
                    .collect()
            })
            .unwrap_or_default()
    };
    let to_info = |v: &toml::Value| -> ProviderInfo {
        let default_model = get_str(v, "model");
        let mut models = get_models(v);
        // Fallback: single-element list from `model` when `models` absent.
        if models.is_empty() {
            if let Some(ref m) = default_model {
                models = vec![m.clone()];
            }
        }
        ProviderInfo {
            name: get_str(v, "name"),
            base_url: get_str(v, "base_url"),
            default_model,
            models,
        }
    };

    let provider = table
        .get("llm")
        .and_then(|l| l.get("provider"))
        .map(|p| to_info(p))
        .unwrap_or(ProviderInfo {
            name: None,
            base_url: None,
            default_model: None,
            models: vec![],
        });

    let providers = table
        .get("llm")
        .and_then(|l| l.get("providers"))
        .and_then(|p| p.as_table())
        .map(|ps| ps.iter().map(|(_, v)| to_info(v)).collect::<Vec<_>>())
        .unwrap_or_default();

    let resp = Json(ModelsResponse {
        provider,
        providers,
    });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

async fn handle_ws(
    socket: WebSocket,
    session_arc: std::sync::Arc<tokio::sync::Mutex<trustee_core::session::Session>>,
    ws_tx: broadcast::Sender<String>,
    route_session_id: String,
) {
    use futures::{SinkExt, StreamExt};
    let (mut sender, mut receiver) = socket.split();
    let mut ws_rx = ws_tx.subscribe();

    // Send current session state as the first message
    {
        let session = session_arc.lock().await;
        let mut snapshot = session_to_response(&session);
        // The snapshot's session_id = the HANDLE the client connected to (the
        // route's {id}) — NOT the session's internal chain-identity field.
        // For a resumed session that field holds the SOURCE chain id (the
        // continue-the-source semantics); the web frontend's snapshot
        // adoption would otherwise flip its command target from the handle
        // back to the source — the next command then runs on the source and
        // its events broadcast on the source's WS while the client listens on
        // the handle's: the first interaction after a resume renders nothing
        // until a manual refresh. The client attached to {id}; the snapshot
        // echoes {id}.
        snapshot.session_id = Some(route_session_id);
        if let Ok(json) = serde_json::to_string(&snapshot) {
            let _ = sender.send(Message::Text(json.into())).await;
        }
    }

    loop {
        tokio::select! {
            msg = ws_rx.recv() => {
                match msg {
                    Ok(text) => {
                        if sender.send(Message::Text(text.into())).await.is_err() {
                            break;
                        }
                    }
                    Err(broadcast::error::RecvError::Lagged(n)) => {
                        let warn = serde_json::json!({"type":"Warning","message":format!("Lagged {} messages", n)});
                        let _ = sender.send(Message::Text(warn.to_string().into())).await;
                    }
                    Err(broadcast::error::RecvError::Closed) => break,
                }
            }
            msg = receiver.next() => {
                match msg {
                    Some(Ok(Message::Close(_))) | None => break,
                    _ => {}
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Session discovery handlers (checkpoint-based — existing, migrated)
// ---------------------------------------------------------------------------

/// GET /api/v1/sessions — list all checkpoint sessions available for resume.
pub async fn list_sessions(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::LIST_SESSIONS)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let (config_toml, home_dir) = {
        let (config, home) = state.get_user_config_and_home(&user_key);
        match config {
            Some(c) => (c, home),
            None => {
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Configuration not loaded".to_string(),
                ))
            }
        }
    };

    let sessions = trustee_core::sessions::list_all_sessions(&config_toml, home_dir.as_deref())
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    let resp = Json(SessionListResponse { sessions });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// GET /api/v1/sessions/live — list only in-memory (active) MSU sessions.
pub async fn list_live_sessions(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::LIST_SESSIONS)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let items = state.list_sessions(&user_key).await;

    let resp = Json(serde_json::json!({ "sessions": items }));
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// GET /api/v1/sessions/{id} — get checkpoint session detail.
pub async fn get_session_detail(
    State(state): State<ServerState>,
    Path(session_id): Path<String>,
    headers: axum::http::HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::VIEW_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let (config_toml, home_dir) = {
        let (config, home) = state.get_user_config_and_home(&user_key);
        match config {
            Some(c) => (c, home),
            None => {
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Configuration not loaded".to_string(),
                ))
            }
        }
    };

    let detail =
        trustee_core::sessions::get_session_detail(&config_toml, &session_id, home_dir.as_deref())
            .await
            .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    match detail {
        Some((session, checkpoints)) => {
            let resp = Json(SessionDetailResponse {
                session,
                checkpoints,
            });
            Ok(with_rolling_cookie(resp.into_response(), cookie))
        }
        None => Err((StatusCode::NOT_FOUND, "Session not found".to_string())),
    }
}

/// POST /api/v1/sessions/{id}/resume — resume from checkpoint.
///
/// Creates a NEW in-memory MSU session and loads the checkpoint data
/// from disk into it. Returns the NEW session ID (not the checkpoint
/// session ID) so the frontend can connect WS to the right session.
///
/// The resumed session CONTINUES the source chain (resume = view/continue
/// onto one logical conversation — NOT a fork; forking is the explicit
/// POST /api/v1/sessions/{id}/fork feature). The live-id → chain-id
/// mapping is recorded ON DISK (write_resume_pointer — the session
/// constants' `resumed_from`) so restore-by-held-id works after an engine
/// restart (Ravand 2026-10-27, owner feedback: fork-on-resume REVERTED).
pub async fn resume_session(
    State(state): State<ServerState>,
    Path(checkpoint_session_id): Path<String>,
    headers: axum::http::HeaderMap,
    _body: Option<Json<ResumeRequestBody>>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::RESUME_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    // 1. Get config + home_dir without creating a session (read-only)
    let (config_toml, home_dir) = {
        let (config, home) = state.get_user_config_and_home(&user_key);
        match config {
            Some(c) => (c, home),
            None => {
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Configuration not loaded".to_string(),
                ))
            }
        }
    };

    // 2. Load checkpoint data from disk
    let resume_info = trustee_core::sessions::create_resume_info(
        &config_toml,
        &checkpoint_session_id,
        home_dir.as_deref(),
    )
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    let resume_info = match resume_info {
        Some(info) => info,
        None => {
            return Err((
                StatusCode::NOT_FOUND,
                "Session or checkpoint not found".to_string(),
            ))
        }
    };

    let checkpoint_id = resume_info.checkpoint_id.clone();
    let iteration = resume_info.iteration;

    // 3. Create a NEW MSU session for this resume.
    // Name it from the checkpoint session's stored description (the LLM-generated
    // friendly title) so resumed sessions are recognizable in live-session lists.
    // Fall back to "Resumed: {sid}" when no description was ever persisted.
    let session_name = match trustee_core::sessions::get_session_detail(
        &config_toml,
        &checkpoint_session_id,
        home_dir.as_deref(),
    )
    .await
    {
        Ok(Some((summary, _))) => summary.description.filter(|d| !d.trim().is_empty()),
        _ => None,
    }
    .map(|d| format!("Resumed: {}", d))
    .unwrap_or_else(|| format!("Resumed: {}", checkpoint_session_id));

    // activate=false → REMOVED with the pointer (2026-10-27): resuming a
    // checkpoint never hijacks anything — there is no active-session pointer
    // anymore. Both consumers are session-scoped and re-point themselves from
    // this response's session_id (the THQ console and the Android app
    // post-4801f26).
    let new_sid = state
        .create_session(&user_key, Some(session_name), None)
        .await
        .map_err(|e| match e {
            crate::state::SessionError::MaxSessionsReached(n) => (
                StatusCode::TOO_MANY_REQUESTS,
                format!("Max {} sessions reached", n),
            ),
            crate::state::SessionError::NotFound(_) => {
                (StatusCode::NOT_FOUND, "Session not found".to_string())
            }
            crate::state::SessionError::NotIdle(_) => {
                (StatusCode::CONFLICT, "Session is busy".to_string())
            }
        })?;

    // 4. Record the resume handle's disk mapping (Ravand 2026-10-27, owner
    // feedback): the resumed session CONTINUES the source chain — its
    // checkpoints land under the SOURCE chain dir while its live id is a
    // fresh key. The mapping lives ON DISK (the session constants'
    // `resumed_from`) so restore-by-held-id works after an engine restart.
    // Fork-on-resume was REVERTED (resume = view/continue; fork = the
    // explicit /fork feature). Fail loud: without the pointer the resumed
    // session is un-restorable after a restart — the exact gap this closes.
    trustee_core::sessions::write_resume_pointer(
        &config_toml,
        &checkpoint_session_id,
        &new_sid,
        home_dir.as_deref(),
    )
    .await
    .map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to record resume handle: {}", e),
        )
    })?;

    // 5. Load checkpoint data into the new session
    {
        let (session_arc, _ws_tx) = state.get_session(&user_key, &new_sid).await.ok_or((
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to get new session".to_string(),
        ))?;

        let mut session = session_arc.lock().await;
        // resume_info points at the SOURCE chain — the workflow continues
        // the source conversation; the checkpoints accumulate under the
        // source chain dir (one logical conversation = one chain dir).
        session.resume_info = Some(resume_info);
        // session.session_id = the SOURCE chain id (the continue-the-source
        // semantics): the chain identity is the source's; the live registry
        // key (new_sid) is the handle, mapped on disk via the resume pointer.
        session.session_id = Some(checkpoint_session_id.clone());

        // Load conversation history into output_lines so the WS snapshot
        // includes them. Without this, the resumed session shows blank
        // until the user sends a new command.
        if let Some(history) = trustee_core::sessions::load_session_history(
            &checkpoint_session_id,
            home_dir.as_deref(),
        )
        .await
        .ok()
        .flatten()
        {
            session.output_lines.clear();
            for msg in &history.messages {
                if msg.role == "user" {
                    session.output_lines.push(format!("> {}", msg.content));
                } else if !msg.content.is_empty() {
                    session.output_lines.push(msg.content.clone());
                }
            }
        }
    }

    // 6. Broadcast resume event on the new session's WS
    let (_, ws_tx) = state.get_session(&user_key, &new_sid).await.ok_or((
        StatusCode::INTERNAL_SERVER_ERROR,
        "Failed to get session WS".to_string(),
    ))?;
    let msg = serde_json::json!({
        "type": "SessionResumed",
        "session_id": checkpoint_session_id,
        "checkpoint_id": checkpoint_id,
    });
    let _ = ws_tx.send(msg.to_string());

    let resp = Json(ResumeResponse {
        accepted: true,
        session_id: new_sid.clone(),
        checkpoint_id,
        iteration,
        // 7df3cae2: explicit resume of a destroyed chain is honored — the
        // user asked — but the destruction is disclosed on the wire.
        tombstoned_at: state.chain_tombstone_stamp(&user_key, &checkpoint_session_id),
    });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// POST /api/v1/sessions/{id}/fork — FORK a session chain (explicit feature,
/// owner order 2026-10-27: forking is a first-class action with its own
/// endpoint + UI icon — NEVER a side effect of resume).
///
/// Copies the source chain's checkpoints into a NEW chain dir under the new
/// session id (fork_session_chain) and creates a NEW live session continuing
/// from the fork's latest checkpoint. The fork is INDEPENDENT of the source:
/// its checkpoints accumulate under its own chain dir; the source stays
/// intact at its pre-fork state. Returns the NEW session ID (the handle —
/// which is also the fork's chain id, so restore-by-held-id works after an
/// engine restart with no pointer machinery).
pub async fn fork_session(
    State(state): State<ServerState>,
    Path(source_session_id): Path<String>,
    headers: axum::http::HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::CREATE_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    // 1. Config + home without creating a session (read-only)
    let (config_toml, home_dir) = {
        let (config, home) = state.get_user_config_and_home(&user_key);
        match config {
            Some(c) => (c, home),
            None => {
                return Err((
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "Configuration not loaded".to_string(),
                ))
            }
        }
    };

    // 2. The source must exist with checkpoints (the fork copies them).
    let source_info = trustee_core::sessions::create_resume_info(
        &config_toml,
        &source_session_id,
        home_dir.as_deref(),
    )
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;
    let source_info = source_info.ok_or((
        StatusCode::NOT_FOUND,
        "Session or checkpoint not found".to_string(),
    ))?;
    let checkpoint_id = source_info.checkpoint_id.clone();
    let iteration = source_info.iteration;

    // 3. Name the fork from the source's stored description.
    let session_name = match trustee_core::sessions::get_session_detail(
        &config_toml,
        &source_session_id,
        home_dir.as_deref(),
    )
    .await
    {
        Ok(Some((summary, _))) => summary.description.filter(|d| !d.trim().is_empty()),
        _ => None,
    }
    .map(|d| format!("Forked: {}", d))
    .unwrap_or_else(|| format!("Forked: {}", source_session_id));

    // 4. Create the NEW live session (the pin sets session.session_id = the
    // registry key — which becomes the fork's chain id).
    let new_sid = state
        .create_session(&user_key, Some(session_name), None)
        .await
        .map_err(|e| match e {
            crate::state::SessionError::MaxSessionsReached(n) => (
                StatusCode::TOO_MANY_REQUESTS,
                format!("Max {} sessions reached", n),
            ),
            crate::state::SessionError::NotFound(_) => {
                (StatusCode::NOT_FOUND, "Session not found".to_string())
            }
            crate::state::SessionError::NotIdle(_) => {
                (StatusCode::CONFLICT, "Session is busy".to_string())
            }
        })?;

    // 5. Fork the chain on disk: the source's checkpoints copied under the
    // new chain id (metadata.session_id rewritten). Fail loud — a fork
    // without its chain dir would be un-restorable after a restart.
    let fork_info = trustee_core::sessions::fork_session_chain(
        &config_toml,
        &source_session_id,
        &new_sid,
        home_dir.as_deref(),
    )
    .await
    .map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            format!("Failed to fork session chain: {}", e),
        )
    })?
    .ok_or((
        StatusCode::INTERNAL_SERVER_ERROR,
        "Failed to fork session chain: source checkpoints vanished".to_string(),
    ))?;

    // 6. The fork continues from ITS OWN chain's latest checkpoint.
    {
        let (session_arc, _ws_tx) = state.get_session(&user_key, &new_sid).await.ok_or((
            StatusCode::INTERNAL_SERVER_ERROR,
            "Failed to get new session".to_string(),
        ))?;
        let mut session = session_arc.lock().await;
        session.resume_info = Some(fork_info);
    }

    // 7. Broadcast the fork event on the new session's WS.
    let (_, ws_tx) = state.get_session(&user_key, &new_sid).await.ok_or((
        StatusCode::INTERNAL_SERVER_ERROR,
        "Failed to get session WS".to_string(),
    ))?;
    let msg = serde_json::json!({
        "type": "SessionForked",
        "session_id": new_sid,
        "forked_from": source_session_id,
        "checkpoint_id": checkpoint_id,
    });
    let _ = ws_tx.send(msg.to_string());

    let resp = Json(ResumeResponse {
        accepted: true,
        session_id: new_sid,
        checkpoint_id,
        iteration,
        tombstoned_at: None,
    });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// GET /api/v1/sessions/{id}/history — load conversation history from checkpoint.
pub async fn get_session_history(
    State(state): State<ServerState>,
    Path(session_id): Path<String>,
    headers: axum::http::HeaderMap,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::VIEW_HISTORY)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let home_dir = state.get_user_home_dir(&user_key);

    let history = trustee_core::sessions::load_session_history(&session_id, home_dir.as_deref())
        .await
        .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?;

    // 7df3cae2: a served transcript for a destroyed chain rides WITH the
    // destruction stamp — tombstoned-but-non-empty must be loud, and the
    // pre-0.9.5 Amad-nox corpus is exactly this shape.
    let tombstoned_at = state.chain_tombstone_stamp(&user_key, &session_id);

    match history {
        Some(h) => {
            let resp = Json(SessionHistoryResponse {
                session_id: h.session_id,
                checkpoint_id: h.checkpoint_id,
                task_description: h.task_description,
                iteration: h.iteration,
                total_messages: h.total_messages,
                messages: h.messages,
                tombstoned_at,
            });
            Ok(with_rolling_cookie(resp.into_response(), cookie))
        }
        None => Err((StatusCode::NOT_FOUND, "Session not found".to_string())),
    }
}

// ---------------------------------------------------------------------------
// MSU: New session-scoped route handlers (/api/v1/sessions/*)
// ---------------------------------------------------------------------------

/// POST /api/v1/sessions — create a new live session.
pub async fn create_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Json(req): Json<CreateSessionRequest>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::CREATE_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let session_id = state
        .create_session(&user_key, req.session_name.clone(), req.identity.clone())
        .await
        .map_err(|e| match e {
            SessionError::MaxSessionsReached(n) => (
                StatusCode::TOO_MANY_REQUESTS,
                format!("Max {} sessions per user", n),
            ),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        })?;

    // Set model override on the new session if provided.
    if let Some(ref model) = req.model {
        if let Some((session_arc, _)) = state.get_session(&user_key, &session_id).await {
            let mut session = session_arc.lock().await;
            session.model = Some(model.clone());
        }
    }

    // If resume_from is provided, set resume_info on the new session
    if let Some(resume_from) = req.resume_from {
        if let Some((session_arc, _)) = state.get_session(&user_key, &session_id).await {
            let mut session = session_arc.lock().await;
            if let Some(ref config_toml) = session.config_toml.clone() {
                let home_dir = session.home_dir.as_deref();
                if let Ok(Some(info)) =
                    trustee_core::sessions::create_resume_info(config_toml, &resume_from, home_dir)
                        .await
                {
                    session.resume_info = Some(info);
                }
            }
        }
    }

    let resp = Json(CreateSessionResponse {
        session_id,
        accepted: true,
    });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// GET /api/v1/sessions/{id}/live — get live session state by ID.
///
/// NOTE: This uses /live suffix to avoid conflict with the existing
/// GET /api/v1/sessions/{id} checkpoint detail route.
pub async fn get_live_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::VIEW_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let (_live_key, session_arc, _ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .ok_or_else(|| {
            // 7df3cae2: absence must say WHICH absence. A destroy-tombstoned
            // chain is not "not found" — it exists, destroyed, transcript
            // preserved. (Status stays 404: there is no live session.)
            loud_tombstoned_chain_error(
                &state,
                &user_key,
                &session_id,
                StatusCode::NOT_FOUND,
                "no live session",
            )
        })?;

    let session = session_arc.lock().await;
    let resp = Json(session_to_response(&session));
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// POST /api/v1/sessions/{id}/command — submit command to a specific session.
pub async fn post_command_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
    Json(req): Json<CommandRequest>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::COMMAND_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let (_live_key, session_arc, ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .ok_or_else(|| {
            // 7df3cae2: commanding a destroyed chain is a CONFLICT (the chain
            // exists, destroyed), never a lying "not found".
            loud_tombstoned_chain_error(
                &state,
                &user_key,
                &session_id,
                StatusCode::CONFLICT,
                "command",
            )
        })?;

    // Get token_store from user's session collection
    let token_store = {
        let user_sessions = state.sessions.get(&user_key).unwrap();
        user_sessions.token_store.clone()
    };

    execute_command_inner(
        &state,
        &headers,
        &session_arc,
        &ws_tx,
        &token_store,
        &user_key,
        req,
    )
    .await?;

    let resp = Json(CommandResponse { accepted: true });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// POST /api/v1/sessions/{id}/cancel — cancel workflow on a specific session.
pub async fn post_cancel_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::CANCEL_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let (_live_key, session_arc, ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .ok_or_else(|| {
            // 7df3cae2: cancelling a destroyed chain is a CONFLICT, never a
            // lying "not found".
            loud_tombstoned_chain_error(
                &state,
                &user_key,
                &session_id,
                StatusCode::CONFLICT,
                "cancel",
            )
        })?;

    let cancelled = {
        let session = session_arc.lock().await;
        let c = session.workflow_state == trustee_core::types::WorkflowState::Running;
        if c {
            session.cancel_token.cancel();
        }
        c
    };

    if cancelled {
        let state_msg = serde_json::json!({"type": "StateChanged", "state": "Cancelling"});
        let _ = ws_tx.send(state_msg.to_string());
    }

    let resp = Json(CommandResponse { accepted: true });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// POST /api/v1/sessions/{id}/handoff — trigger handoff on a specific session.
pub async fn post_handoff_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::HANDOFF_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    // Resolve by live MSU registry key OR checkpoint/session identity
    // (session.session_id). The web frontend holds the checkpoint id from
    // ResumeInfo; Torpi/THQ holds the live key. Both must work.
    let (_live_key, session_arc, _ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .ok_or_else(|| {
            // 7df3cae2: handing off from a destroyed chain is a CONFLICT,
            // never a lying "not found".
            loud_tombstoned_chain_error(
                &state,
                &user_key,
                &session_id,
                StatusCode::CONFLICT,
                "handoff",
            )
        })?;

    let mut session = session_arc.lock().await;
    session.request_handoff(String::new());

    let resp = Json(CommandResponse { accepted: true });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// POST /api/v1/sessions/{id}/name — set name on a specific session.
pub async fn set_session_name_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
    Json(req): Json<SetNameRequest>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::UPDATE_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    let (_live_key, session_arc, _ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;

    {
        let mut session = session_arc.lock().await;
        session.session_name = Some(req.name.clone());
    }

    let resp = Json(SetNameResponse {
        accepted: true,
        name: req.name,
    });
    Ok(with_rolling_cookie(resp.into_response(), cookie))
}

/// DELETE /api/v1/sessions/{id} — destroy a live session.
pub async fn destroy_session(
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
) -> Result<Response, (StatusCode, String)> {
    let (cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::DELETE_SESSION)
            .await
            .map_err(|s| (s, "Unauthorized".to_string()))?;

    // Resolve to the live registry key first (accepts checkpoint/session id too)
    let (live_key, _session_arc, _ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .ok_or((StatusCode::NOT_FOUND, "Session not found".to_string()))?;

    state
        .destroy_session(&user_key, &live_key)
        .await
        .map_err(|e| match e {
            SessionError::NotFound(_) => (StatusCode::NOT_FOUND, e.to_string()),
            SessionError::NotIdle(_) => (StatusCode::CONFLICT, e.to_string()),
            _ => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
        })?;

    Ok(with_rolling_cookie(
        StatusCode::NO_CONTENT.into_response(),
        cookie,
    ))
}

/// GET /api/v1/sessions/{id}/stream — WebSocket for a specific session.
pub async fn ws_session_handler(
    ws: WebSocketUpgrade,
    State(state): State<ServerState>,
    headers: axum::http::HeaderMap,
    Path(session_id): Path<String>,
) -> Result<Response, StatusCode> {
    let (_cookie, user_key) =
        crate::auth::check_auth(&state.auth, &headers, crate::auth::actions::VIEW_SESSION).await?;
    let (session_arc, ws_tx) = state
        .get_or_restore_session_by_any_id(&user_key, &session_id)
        .await
        .map(|(_, s, ws)| (s, ws))
        .ok_or(StatusCode::NOT_FOUND)?;
    Ok(ws.on_upgrade(move |socket| handle_ws(socket, session_arc, ws_tx, session_id)))
}

// ---------------------------------------------------------------------------
// Static file serving
// ---------------------------------------------------------------------------

/// GET / — serve index.html
///
/// The `__TRUSTEE_VERSION__` placeholder in the burger-menu footer is
/// replaced at serve time with the bin's version (see [`crate::bin_version`]).
pub async fn serve_index() -> Response {
    match trustee_web::Asset::get("index.html") {
        Some(content) => {
            let html = String::from_utf8_lossy(&content.data)
                .replace("__TRUSTEE_VERSION__", crate::bin_version());
            (
                StatusCode::OK,
                [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
                html.into_bytes(),
            )
                .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            [(header::CONTENT_TYPE, "text/plain")],
            "Not found".to_string().into_bytes(),
        )
            .into_response(),
    }
}

/// GET /{file} — serve static files from trustee-web
pub async fn serve_static(Path(file): Path<String>) -> Response {
    match trustee_web::Asset::get(&file) {
        Some(content) => {
            let mime = mime_guess::from_path(&file).first_or_octet_stream();
            (
                StatusCode::OK,
                [(header::CONTENT_TYPE, mime.as_ref())],
                content.data.to_vec(),
            )
                .into_response()
        }
        None => (
            StatusCode::NOT_FOUND,
            [(header::CONTENT_TYPE, "text/plain")],
            "Not found".to_string().into_bytes(),
        )
            .into_response(),
    }
}

// ---------------------------------------------------------------------------
// Command execution helper (shared between legacy and session-scoped routes)
// ---------------------------------------------------------------------------

/// Execute a command on a session. Shared between `post_command` (legacy)
/// and `post_command_session` (session-scoped).
///
/// Handles token injection, workflow state check, session_id/resume_info
/// setup, concurrency permit, and execution trigger.
#[allow(clippy::too_many_arguments)]
async fn execute_command_inner(
    state: &ServerState,
    headers: &axum::http::HeaderMap,
    session_arc: &std::sync::Arc<tokio::sync::Mutex<trustee_core::session::Session>>,
    ws_tx: &broadcast::Sender<String>,
    token_store: &Arc<pep::MemoryTokenStore>,
    user_key: &str,
    req: CommandRequest,
) -> Result<(), (StatusCode, String)> {
    // Multimodal: validate attachments FIRST — a malformed or oversized
    // payload must fail with 400 before any session state is touched.
    let attachments =
        validate_attachments(&req.attachments).map_err(|e| (StatusCode::BAD_REQUEST, e))?;

    let agent_name = {
        let session = session_arc.lock().await;
        session.agent_name.clone()
    };
    inject_session_token(&state.auth, headers, &agent_name, token_store).await;

    {
        let mut session = session_arc.lock().await;

        if session.workflow_state != trustee_core::types::WorkflowState::Idle {
            return Err((
                StatusCode::CONFLICT,
                "Workflow is running or cancelling".to_string(),
            ));
        }

        // Handle session_id / resume_info (same as original post_command)
        if let Some(ref client_session_id) = req.session_id {
            // NOTE: session.session_id is PINNED at creation (c2f9508 — the
            // registry key) or set to the resumed chain id (resume_session) —
            // it is never overwritten by a client id (pre-0.9.17 semantics
            // preserved: clobbering the chain id with a client id would
            // corrupt checkpoint routing). Torpi/THQ consoles send the live
            // registry key here; trustee-web sends the checkpoint-chain id
            // from ResumeInfo — both already match what the session holds.
            if session.session_id.is_none() {
                session.session_id = Some(client_session_id.clone());
            }

            // Bug 3: after a handoff rotation the session has rotated its
            // chain identity but not yet produced its first checkpoint —
            // resume_info is None and session.session_id already holds the
            // NEW chain id. A queued or fast-follow command still carrying
            // the OLD chain id (the client's last ResumeInfo) must NOT
            // resurrect the old disk chain: that would orphan the briefing
            // run and split the context. During that window, only a client id
            // matching the CURRENT chain may build resume_info; anything else
            // runs fresh under the current chain.
            let id_matches_current_chain = session
                .session_id
                .as_deref()
                .is_some_and(|sid| sid == client_session_id.as_str());
            let rotation_pending_first_checkpoint =
                session.handoff_count > 0 && session.resume_info.is_none();
            let stale_during_rotation_window =
                rotation_pending_first_checkpoint && !id_matches_current_chain;

            if session.resume_info.is_none() && !stale_during_rotation_window {
                if let Some(ref config_toml) = session.config_toml.clone() {
                    let home_dir = session.home_dir.as_deref();
                    if let Ok(Some(info)) = trustee_core::sessions::create_resume_info(
                        config_toml,
                        client_session_id,
                        home_dir,
                    )
                    .await
                    {
                        session.resume_info = Some(info);
                    }
                }
            }
        }

        // Set identity from request if session doesn't have one yet.
        // Allows identity to be passed on the first command of a legacy session.
        if session.identity.is_none() {
            session.identity = req.identity;
        }

        // Set model override for this command (consumed by execute_command).
        session.model = req.model;

        let permit = state
            .workflow_semaphore
            .clone()
            .acquire_owned()
            .await
            .map_err(|_| {
                (
                    StatusCode::SERVICE_UNAVAILABLE,
                    "Server overloaded".to_string(),
                )
            })?;

        // 16C: resolve the per-user MCP loader lazily at dispatch start so
        // overlay edits apply without session recreation; the fingerprint
        // check rebuilds on change and swaps the session's Arc.
        let mcp_loader = state
            .get_or_build_mcp_loader(user_key, token_store)
            .await
            .map_err(|e| {
                (
                    StatusCode::BAD_GATEWAY,
                    format!("MCP loader unavailable: {}", e),
                )
            })?;
        session.mcp_loader = mcp_loader;

        session.token_store = Some(token_store.clone());
        session.workflow_permit = Some(permit);
        let command = req.command.clone();
        session.input = req.command;
        session.input_images = attachments.images;
        session.input_text_files = attachments.text_files;
        session.execute_command();

        // Broadcast the user's command echo to live WS clients (Hamrah
        // 2026-10-27 finding): execute_command pushes '> {command}' DIRECTLY
        // into output_lines (trustee-core session.rs) — a direct mutation,
        // not a TuiMessage — so the drain never carries it and connected WS
        // clients never receive the user's own bubble while the WS is live
        // (the poll is suppressed; the echo only arrives via the snapshot or
        // the poll). RAW ws_tx.send, NOT a TuiMessage through the drain:
        // handle_workflow_message would push it into output_lines AGAIN (the
        // line doubled). Sent while the session lock is still held so the
        // echo lands on the WS BEFORE the drain's StateChanged/workflow
        // events — the bubble arrives first, matching the transcript order.
        let echo = serde_json::json!({
            "type": "OutputLine",
            "line": format!("> {}", command),
        });
        let _ = ws_tx.send(echo.to_string());
    }

    let state_msg = serde_json::json!({"type": "StateChanged", "state": "Running"});
    let _ = ws_tx.send(state_msg.to_string());

    Ok(())
}

// ---------------------------------------------------------------------------
// MCP session token injection (C1 — web-session credentials)
// ---------------------------------------------------------------------------

const WEB_SESSION_CRED_NAME: &str = "__web_session";

async fn inject_session_token(
    auth: &Option<Arc<crate::auth::AuthState>>,
    headers: &axum::http::HeaderMap,
    _agent_name: &str,
    token_store: &pep::MemoryTokenStore,
) {
    use pep::{StoredToken, TokenStore};

    let Some(auth_state) = auth.as_ref() else {
        return;
    };

    let access_token = match resolve_access_token_for_mcp(auth_state, headers).await {
        Ok(token) => token,
        Err(e) => {
            tracing::debug!("Skipping MCP session token injection: {}", e);
            return;
        }
    };

    let expires_at = jwt_expiry(&access_token).unwrap_or_else(|| {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        compute_rfc3339(now + 900)
    });

    let stored = StoredToken::new(&access_token, None, "Bearer", &expires_at, None);

    if let Err(e) = token_store.save(WEB_SESSION_CRED_NAME, &stored) {
        tracing::warn!("Failed to write session token to MemoryTokenStore: {}", e);
    } else {
        tracing::debug!(
            "Injected session token for web-session MCP credentials (expires {})",
            expires_at
        );
    }
}

async fn resolve_access_token_for_mcp(
    auth: &crate::auth::AuthState,
    headers: &axum::http::HeaderMap,
) -> Result<String, String> {
    if let Some(token) = headers
        .get(header::AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .map(|s| s.to_string())
    {
        if token.starts_with("dev:") {
            return Err("dev tokens not supported for MCP".to_string());
        }
        return Ok(token);
    }

    let session_id = headers
        .get(header::COOKIE)
        .and_then(|v| v.to_str().ok())
        .and_then(|cookies| {
            cookies.split(';').map(|c| c.trim()).find_map(|c| {
                c.strip_prefix(&format!("{}=", auth.config.cookie_name))
                    .map(|s| s.to_string())
            })
        })
        .ok_or("no session cookie")?;

    if session_id.starts_with("dev:") {
        return Err("dev tokens not supported for MCP".to_string());
    }

    auth.session_manager
        .get_token(&session_id)
        .await
        .map_err(|e| format!("session lookup: {e}"))
}

fn jwt_expiry(token: &str) -> Option<String> {
    let parts: Vec<&str> = token.split('.').collect();
    if parts.len() < 2 {
        return None;
    }

    use base64::Engine;
    let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(parts[1])
        .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(parts[1]))
        .ok()?;

    let json: serde_json::Value = serde_json::from_slice(&payload).ok()?;
    let exp = json.get("exp")?.as_u64()?;

    Some(compute_rfc3339(exp))
}

fn compute_rfc3339(epoch_secs: u64) -> String {
    let days = epoch_secs / 86400;
    let rem = epoch_secs % 86400;
    let h = rem / 3600;
    let m = (rem % 3600) / 60;
    let s = rem % 60;
    let z = days as i64 + 719468;
    let era = if z >= 0 { z } else { z - 146096 } / 146097;
    let doe = (z - era * 146097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let mon = if mp < 10 { mp + 3 } else { mp - 9 };
    let yr = if mon <= 2 { y + 1 } else { y };
    format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", yr, mon, d, h, m, s)
}

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

    /// The burger-menu footer must carry the real version, never the
    /// placeholder (a literal "v__TRUSTEE_VERSION__" in the UI = bug).
    #[tokio::test]
    async fn index_serves_real_version_no_placeholder() {
        let resp = serve_index().await;
        assert_eq!(resp.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .expect("body");
        let html = String::from_utf8(bytes.to_vec()).expect("utf8");
        assert!(
            !html.contains("__TRUSTEE_VERSION__"),
            "placeholder must be replaced at serve time"
        );
        assert!(
            html.contains(&format!("trustee v{}", crate::bin_version())),
            "burger-menu footer must show the version label"
        );
    }
}

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

    const TINY_PNG_B64: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";

    fn input(mime: &str, data: &str) -> AttachmentInput {
        AttachmentInput {
            mime: mime.to_string(),
            data: data.to_string(),
            filename: Some("test.img".to_string()),
        }
    }

    #[test]
    fn test_validate_attachments_happy_path() {
        let out = validate_attachments(&[input("image/png", TINY_PNG_B64)]).unwrap();
        assert_eq!(out.images.len(), 1);
        assert_eq!(out.images[0].mime, "image/png");
        assert_eq!(out.images[0].data, TINY_PNG_B64);
        assert_eq!(out.images[0].filename.as_deref(), Some("test.img"));
    }

    #[test]
    fn test_validate_attachments_mime_normalized_and_whitelisted() {
        // Uppercase MIME normalizes; all four whitelisted types pass.
        assert!(validate_attachments(&[input("IMAGE/JPEG", TINY_PNG_B64)]).is_ok());
        assert!(validate_attachments(&[input("image/gif", TINY_PNG_B64)]).is_ok());
        assert!(validate_attachments(&[input("image/webp", TINY_PNG_B64)]).is_ok());
        assert!(validate_attachments(&[input("application/pdf", TINY_PNG_B64)]).is_err());
        assert!(validate_attachments(&[input("image/svg+xml", TINY_PNG_B64)]).is_err());
    }

    #[test]
    fn test_validate_attachments_data_url_prefix_stripped() {
        let data_url = format!("data:image/png;base64,{}", TINY_PNG_B64);
        let out = validate_attachments(&[input("image/png", &data_url)]).unwrap();
        assert_eq!(out.images[0].data, TINY_PNG_B64);
    }

    #[test]
    fn test_validate_attachments_invalid_base64_rejected() {
        let err = validate_attachments(&[input("image/png", "not@@base64!!!")]).unwrap_err();
        assert!(err.contains("invalid base64"), "got: {}", err);
    }

    #[test]
    fn test_validate_attachments_too_many_rejected() {
        let inputs: Vec<_> = (0..=MAX_ATTACHMENTS)
            .map(|_| input("image/png", TINY_PNG_B64))
            .collect();
        let err = validate_attachments(&inputs).unwrap_err();
        assert!(err.contains("Too many attachments"), "got: {}", err);
    }

    #[test]
    fn test_validate_attachments_oversize_rejected() {
        // >6 MiB decoded: ~8 MiB + 16 chars of valid base64 ('A' padding
        // decodes fine) lands just over the MAX_IMAGE_BYTES boundary.
        let big = "QUJD".repeat(2 * 1024 * 1024 + 4); // ~6.0000xx MiB decoded
        let err = validate_attachments(&[input("image/png", &big)]).unwrap_err();
        assert!(err.contains("exceeds"), "got: {}", err);
    }

    fn text_input(mime: &str, content: &str) -> AttachmentInput {
        use base64::Engine as _;
        AttachmentInput {
            mime: mime.to_string(),
            data: base64::engine::general_purpose::STANDARD.encode(content.as_bytes()),
            filename: Some("notes.md".to_string()),
        }
    }

    #[test]
    fn test_validate_attachments_text_happy_path() {
        let out = validate_attachments(&[
            text_input("text/plain", "hello world"),
            text_input("text/markdown", "# Title\n\nbody"),
        ])
        .unwrap();
        assert!(out.images.is_empty());
        assert_eq!(out.text_files.len(), 2);
        assert_eq!(out.text_files[0].mime, "text/plain");
        assert_eq!(out.text_files[0].content, "hello world");
        assert_eq!(out.text_files[0].filename, "notes.md");
        assert_eq!(out.text_files[1].mime, "text/markdown");
        assert_eq!(out.text_files[1].content, "# Title\n\nbody");
    }

    #[test]
    fn test_validate_attachments_x_markdown_normalized() {
        let out = validate_attachments(&[text_input("text/x-markdown", "# x")]).unwrap();
        assert_eq!(out.text_files[0].mime, "text/markdown");
    }

    #[test]
    fn test_validate_attachments_text_data_url_prefix_stripped() {
        use base64::Engine as _;
        let b64 = base64::engine::general_purpose::STANDARD.encode(b"readme body");
        let data_url = format!("data:text/plain;base64,{}", b64);
        let out = validate_attachments(&[input("text/plain", &data_url)]).unwrap();
        assert_eq!(out.text_files[0].content, "readme body");
    }

    #[test]
    fn test_validate_attachments_text_invalid_utf8_rejected() {
        let err = validate_attachments(&[input("text/plain", "/v8A")]).unwrap_err(); // 0xFF 0xDF 0x00
        assert!(err.contains("UTF-8"), "got: {}", err);
    }

    #[test]
    fn test_validate_attachments_text_oversize_rejected() {
        let big = "x".repeat(MAX_TEXT_BYTES + 1024);
        let err = validate_attachments(&[text_input("text/plain", &big)]).unwrap_err();
        assert!(err.contains("exceeds"), "got: {}", err);
        // Exactly at the cap passes.
        let at_cap = "x".repeat(MAX_TEXT_BYTES);
        assert!(validate_attachments(&[text_input("text/plain", &at_cap)]).is_ok());
    }

    #[test]
    fn test_validate_attachments_mixed_families_preserved() {
        let out = validate_attachments(&[
            input("image/png", TINY_PNG_B64),
            text_input("text/markdown", "# plan"),
        ])
        .unwrap();
        assert_eq!(out.images.len(), 1);
        assert_eq!(out.text_files.len(), 1);
        assert_eq!(out.text_files[0].content, "# plan");
    }

    #[test]
    fn test_validate_attachments_too_many_across_families() {
        let mut inputs = vec![
            input("image/png", TINY_PNG_B64),
            input("image/png", TINY_PNG_B64),
            input("image/png", TINY_PNG_B64),
            text_input("text/plain", "one"),
        ];
        assert!(validate_attachments(&inputs).is_ok()); // exactly 4 = cap
        inputs.push(text_input("text/markdown", "two")); // 5 > cap
        let err = validate_attachments(&inputs).unwrap_err();
        assert!(err.contains("Too many attachments"), "got: {}", err);
    }

    #[test]
    fn test_validate_attachments_unsupported_names_both_families() {
        let err = validate_attachments(&[input("application/pdf", TINY_PNG_B64)]).unwrap_err();
        assert!(err.contains("text/plain"), "got: {}", err);
        assert!(err.contains("image/jpeg"), "got: {}", err);
    }

    #[test]
    fn test_command_request_attachments_default_empty() {
        // Old clients (no attachments field) must keep deserializing.
        let req: CommandRequest = serde_json::from_str(r#"{"command": "hello"}"#).unwrap();
        assert!(req.attachments.is_empty());
        let req: CommandRequest = serde_json::from_str(
            r#"{"command": "hi", "attachments": [{"mime": "image/png", "data": "AAAA"}]}"#,
        )
        .unwrap();
        assert_eq!(req.attachments.len(), 1);
        assert!(req.attachments[0].filename.is_none());
    }
}

#[cfg(test)]
mod tombstone_disclosure_tests {
    use super::*;
    use crate::state::ServerState;
    use trustee_core::session::Session;

    /// Deterministic throwaway user (restore_tests pattern, state.rs).
    struct TempUser {
        key: String,
    }

    impl TempUser {
        fn new(tag: &str) -> Self {
            let key = format!("tomb-disclose-{tag}-{}@test.invalid", std::process::id());
            let home = dirs::home_dir()
                .expect("HOME available in test env")
                .join(".trustee")
                .join("users")
                .join(trustee_core::user_hash(&key));
            std::fs::create_dir_all(home).expect("create user home");
            Self { key }
        }
    }

    fn fresh_state() -> ServerState {
        let (session, _rx) = Session::new();
        let (ws_tx, _ws_rx) = tokio::sync::broadcast::channel::<String>(16);
        let mut state = ServerState::new(session, ws_tx, None);
        state.config_toml = Some("[agent]\nname = \"trustee\"\n".to_string());
        state
    }

    /// Destroy a session attached to a fixed chain id → the marker exists.
    async fn destroyed_chain(state: &ServerState, user: &TempUser, chain: &str) {
        let sid = state
            .create_session(&user.key, None, None)
            .await
            .expect("create session");
        let (session, _ws) = state.get_session(&user.key, &sid).await.unwrap();
        {
            let mut s = session.lock().await;
            s.session_id = Some(chain.to_string());
        }
        state
            .destroy_session(&user.key, &sid)
            .await
            .expect("destroy");
    }

    /// 7df3cae2: a destroy-tombstoned chain must answer LOUDLY and
    /// specifically — status the caller asked for, body naming the
    /// destruction, the preserved transcript, and both recovery lanes.
    /// Never the generic lying "Session not found".
    #[tokio::test]
    async fn tombstoned_chain_error_names_the_destruction() {
        let state = fresh_state();
        let user = TempUser::new("loud");
        let chain = "session_2026_10_04_07_24_feedface";
        destroyed_chain(&state, &user, chain).await;

        let (status, body) =
            loud_tombstoned_chain_error(&state, &user.key, chain, StatusCode::CONFLICT, "command");
        assert_eq!(status, StatusCode::CONFLICT);
        assert!(
            body.contains("DESTROYED"),
            "body must name the destruction: {body}"
        );
        assert!(body.contains(chain), "body must name the chain: {body}");
        assert!(
            body.contains("/history"),
            "body must point at the preserved transcript: {body}"
        );
        assert!(
            body.contains("/resume"),
            "body must point at the explicit restore lane: {body}"
        );

        // No tombstone → genuinely unknown id → the generic honest 404.
        let (status2, body2) = loud_tombstoned_chain_error(
            &state,
            &user.key,
            "session_2099_01_01_00_00_unknown0",
            StatusCode::CONFLICT,
            "command",
        );
        assert_eq!(status2, StatusCode::NOT_FOUND);
        assert_eq!(body2, "Session not found");
    }

    /// 7df3cae2: the tombstone stamp reader — Some(stamp) for a destroyed
    /// chain, None for anything else; the stamp is the marker's timestamp.
    #[tokio::test]
    async fn chain_tombstone_stamp_roundtrips() {
        let state = fresh_state();
        let user = TempUser::new("stamp");
        let chain = "session_2026_10_04_07_24_c0ffee00";
        destroyed_chain(&state, &user, chain).await;

        let stamp = state
            .chain_tombstone_stamp(&user.key, chain)
            .expect("destroyed chain must carry a stamp");
        assert!(
            stamp.starts_with("20"),
            "stamp must be a timestamp, got: {stamp}"
        );
        assert!(
            state
                .chain_tombstone_stamp(&user.key, "session_2099_01_01_00_00_nomarker")
                .is_none(),
            "unknown chain must carry no stamp"
        );
    }
}