atm-agent-mcp 0.14.0

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

use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

use agent_team_mail_core::InboxMessage;
use agent_team_mail_core::home::get_home_dir;
use agent_team_mail_core::text::{truncate_chars, truncate_chars_slice};
use agent_team_mail_core::io::{inbox_append, inbox_update};
use serde_json::{Value, json};
use tokio::sync::Mutex;

use crate::lock::release_lock;
use crate::session::{SessionRegistry, SessionStatus, ThreadState};

/// Maximum allowed message length in characters (FR-8.4).
const MAX_MESSAGE_LEN: usize = 4096;

/// Truncation suffix appended when a message is cut to [`MAX_MESSAGE_LEN`].
const TRUNCATION_SUFFIX: &str = " [...truncated]";

/// Default maximum number of messages returned by [`handle_atm_read`] when
/// the caller does not provide a `limit` parameter.
const DEFAULT_READ_LIMIT: usize = 10;

// ---------------------------------------------------------------------------
// Identity resolution
// ---------------------------------------------------------------------------

/// Resolve the effective caller identity for an ATM tool call.
///
/// Precedence:
/// 1. `args["identity"]` — explicit per-call override
/// 2. `config_identity` — proxy-level default from `AgentMcpConfig.identity`
///
/// Returns `None` when neither source provides a value, which must cause
/// the caller to return [`ERR_IDENTITY_REQUIRED`].
pub fn resolve_identity(args: &Value, config_identity: Option<&str>) -> Option<String> {
    if let Some(id) = args.get("identity").and_then(|v| v.as_str()) {
        if !id.is_empty() {
            return Some(id.to_string());
        }
    }
    config_identity.map(|s| s.to_string())
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Truncate `text` to [`MAX_MESSAGE_LEN`] and append [`TRUNCATION_SUFFIX`] when truncated.
fn maybe_truncate(text: &str) -> String {
    if text.chars().count() <= MAX_MESSAGE_LEN {
        text.to_string()
    } else {
        truncate_chars(text, MAX_MESSAGE_LEN, TRUNCATION_SUFFIX)
    }
}

/// Auto-generate a summary from the first 60 characters of a message.
fn auto_summary(message: &str) -> String {
    let trimmed = message.trim();
    if trimmed.is_empty() {
        return "(empty message)".to_string();
    }
    if trimmed.chars().count() <= 60 {
        trimmed.to_string()
    } else {
        format!("{}...", truncate_chars_slice(trimmed, 60))
    }
}

/// Parse the `to` field into `(agent, team)`.
///
/// `"arch-ctm@atm-dev"` → `("arch-ctm", "atm-dev")`
/// `"arch-ctm"` → `("arch-ctm", default_team)`
fn parse_to(to: &str, default_team: &str) -> Result<(String, String), String> {
    if let Some((agent, team)) = to.split_once('@') {
        let agent = agent.trim();
        let team = team.trim();
        if agent.is_empty() {
            return Err("atm_send: invalid 'to' parameter: empty agent name".to_string());
        }
        if team.is_empty() {
            return Err("atm_send: invalid 'to' parameter: empty team name".to_string());
        }
        Ok((agent.to_string(), team.to_string()))
    } else {
        let agent = to.trim();
        if agent.is_empty() {
            return Err("atm_send: invalid 'to' parameter: empty agent name".to_string());
        }
        Ok((agent.to_string(), default_team.to_string()))
    }
}

/// Build the path to an agent's inbox file.
///
/// `<home>/.claude/teams/<team>/inboxes/<agent>.json`
fn inbox_path(home: &std::path::Path, team: &str, agent: &str) -> PathBuf {
    home.join(".claude")
        .join("teams")
        .join(team)
        .join("inboxes")
        .join(format!("{agent}.json"))
}

/// Build a UTC ISO 8601 timestamp for the current moment.
///
/// Uses a simple hand-formatted RFC 3339 string without pulling in `chrono` as
/// an additional dependency in this crate (the proxy already depends on uuid).
fn now_iso8601() -> String {
    // We use SystemTime → Duration since UNIX_EPOCH to avoid a chrono dependency.
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    // Convert seconds to calendar components (UTC, no leap-second handling)
    let s = secs % 60;
    let m = (secs / 60) % 60;
    let h = (secs / 3600) % 24;
    let days = secs / 86400; // days since 1970-01-01
    let (y, mo, d) = days_to_ymd(days);
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
}

/// Convert days since Unix epoch to (year, month, day).
fn days_to_ymd(days: u64) -> (u64, u64, u64) {
    // Algorithm from https://howardhinnant.github.io/date_algorithms.html
    let z = days + 719468;
    let era = z / 146097;
    let doe = z % 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + 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 mo = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if mo <= 2 { y + 1 } else { y };
    (y, mo, d)
}

/// Build a new [`InboxMessage`] from parts.
fn build_message(from: &str, text: String, summary: Option<String>) -> InboxMessage {
    let message_id = Some(uuid::Uuid::new_v4().to_string());
    let auto_sum = auto_summary(&text);
    InboxMessage {
        from: from.to_string(),
        text,
        timestamp: now_iso8601(),
        read: false,
        summary: Some(summary.unwrap_or(auto_sum)),
        message_id,
        unknown_fields: HashMap::new(),
    }
}

/// Construct a successful MCP result response.
fn make_mcp_success(id: &Value, text: String) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": {
            "content": [{"type": "text", "text": text}]
        }
    })
}

/// Construct an MCP result response that signals an application-level error.
///
/// This uses `isError: true` inside the `result` (not a JSON-RPC `error` object)
/// so that callers can detect tool-level failures without treating them as
/// transport-level protocol errors.
pub fn make_mcp_error_result(id: &Value, message: &str) -> Value {
    json!({
        "jsonrpc": "2.0",
        "id": id,
        "result": {
            "content": [{"type": "text", "text": message}],
            "isError": true
        }
    })
}

// ---------------------------------------------------------------------------
// Public tool handlers
// ---------------------------------------------------------------------------

/// Handle an `atm_send` tool call.
///
/// Delivers a message to the target agent's inbox file.  The `to` parameter
/// supports `"agent"` or `"agent@team"` notation.  Messages exceeding
/// [`MAX_MESSAGE_LEN`] are truncated.
///
/// # Parameters (from `args`)
///
/// | Field     | Required | Description                            |
/// |-----------|----------|----------------------------------------|
/// | `to`      | yes      | Target agent, optionally `agent@team`  |
/// | `message` | yes      | Message body                           |
/// | `summary` | no       | Short summary (auto-generated if absent)|
///
/// # Returns
///
/// MCP result with `"Message sent to <agent>@<team>"` on success.
pub fn handle_atm_send(id: &Value, args: &Value, identity: &str, team: &str) -> Value {
    let to = match args.get("to").and_then(|v| v.as_str()) {
        Some(s) if !s.is_empty() => s,
        _ => return make_mcp_error_result(id, "atm_send: 'to' parameter is required"),
    };

    let raw_message = match args.get("message").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => return make_mcp_error_result(id, "atm_send: 'message' parameter is required"),
    };

    let (agent, effective_team) = match parse_to(to, team) {
        Ok(parsed) => parsed,
        Err(e) => return make_mcp_error_result(id, &e),
    };
    let message_text = maybe_truncate(raw_message);
    let summary = args
        .get("summary")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let msg = build_message(identity, message_text, summary);

    let home = match get_home_dir() {
        Ok(h) => h,
        Err(e) => {
            return make_mcp_error_result(id, &format!("atm_send: cannot resolve home dir: {e}"));
        }
    };

    let path = inbox_path(&home, &effective_team, &agent);

    // Ensure parent directory exists
    if let Some(parent) = path.parent() {
        if let Err(e) = std::fs::create_dir_all(parent) {
            return make_mcp_error_result(
                id,
                &format!("atm_send: cannot create inbox directory: {e}"),
            );
        }
    }

    match inbox_append(&path, &msg, &effective_team, &agent) {
        Ok(_) => make_mcp_success(id, format!("Message sent to {agent}@{effective_team}")),
        Err(e) => make_mcp_error_result(id, &format!("atm_send: failed to write inbox: {e}")),
    }
}

/// Handle an `atm_read` tool call.
///
/// Reads messages from the caller's own inbox, with optional filtering.
///
/// # Parameters (from `args`)
///
/// | Field       | Required | Description                                     |
/// |-------------|----------|-------------------------------------------------|
/// | `all`       | no       | If `true`, include already-read messages         |
/// | `mark_read` | no       | If `false`, do not mark returned messages as read|
/// | `limit`     | no       | Max messages to return (default: 10)             |
/// | `since`     | no       | ISO 8601 timestamp; only messages after this     |
/// | `from`      | no       | Filter by sender identity                        |
///
/// # Returns
///
/// MCP result whose text is a JSON array of `{from, text, timestamp, message_id}` objects.
pub fn handle_atm_read(id: &Value, args: &Value, identity: &str, team: &str) -> Value {
    let home = match get_home_dir() {
        Ok(h) => h,
        Err(e) => {
            return make_mcp_error_result(id, &format!("atm_read: cannot resolve home dir: {e}"));
        }
    };

    let path = inbox_path(&home, team, identity);

    // If inbox doesn't exist, return empty array (not an error).
    if !path.exists() {
        return make_mcp_success(id, "[]".to_string());
    }

    // Read current messages
    let content = match std::fs::read(&path) {
        Ok(c) => c,
        Err(e) => return make_mcp_error_result(id, &format!("atm_read: cannot read inbox: {e}")),
    };
    let messages: Vec<InboxMessage> = match serde_json::from_slice(&content) {
        Ok(m) => m,
        Err(e) => {
            return make_mcp_error_result(id, &format!("atm_read: failed to parse inbox: {e}"));
        }
    };

    // Parse optional params
    let include_all = args.get("all").and_then(|v| v.as_bool()).unwrap_or(false);
    let mark_read = args
        .get("mark_read")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let limit = args
        .get("limit")
        .and_then(|v| v.as_u64())
        .map(|n| n as usize)
        .unwrap_or(DEFAULT_READ_LIMIT);
    let since = args
        .get("since")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    let from_filter = args
        .get("from")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    // Apply filters
    let filtered: Vec<&InboxMessage> = messages
        .iter()
        .filter(|m| {
            // Unread filter
            if !include_all && m.read {
                return false;
            }
            // Since filter
            if let Some(ref since_ts) = since {
                if m.timestamp.as_str() < since_ts.as_str() {
                    return false;
                }
            }
            // From filter
            if let Some(ref sender) = from_filter {
                if &m.from != sender {
                    return false;
                }
            }
            true
        })
        .take(limit)
        .collect();

    // Collect message IDs to mark as read
    let ids_to_mark: Vec<String> = if mark_read {
        filtered
            .iter()
            .filter_map(|m| m.message_id.clone())
            .collect()
    } else {
        Vec::new()
    };

    // Build output before potentially mutating messages
    let output: Vec<Value> = filtered
        .iter()
        .map(|m| {
            json!({
                "from": m.from,
                "text": m.text,
                "timestamp": m.timestamp,
                "message_id": m.message_id,
            })
        })
        .collect();

    // Mark messages as read if requested
    if mark_read && !ids_to_mark.is_empty() {
        let ids_set: std::collections::HashSet<String> = ids_to_mark.into_iter().collect();
        // Also mark messages without a message_id that match the filtered set.
        // Collect timestamps+from for id-less messages.
        let id_less_keys: Vec<(String, String)> = filtered
            .iter()
            .filter(|m| m.message_id.is_none())
            .map(|m| (m.from.clone(), m.timestamp.clone()))
            .collect();

        if let Err(e) = inbox_update(&path, team, identity, |latest_messages| {
            for msg in latest_messages.iter_mut() {
                let should_mark = if let Some(ref mid) = msg.message_id {
                    ids_set.contains(mid)
                } else {
                    id_less_keys
                        .iter()
                        .any(|(f, t)| f == &msg.from && t == &msg.timestamp)
                };
                if should_mark {
                    msg.read = true;
                }
            }
        }) {
            tracing::warn!("atm_read: failed to persist mark-read via atomic update: {e}");
        }
    }

    let text = serde_json::to_string_pretty(&output).unwrap_or_else(|_| "[]".to_string());
    make_mcp_success(id, text)
}

/// Handle an `atm_broadcast` tool call.
///
/// Sends a message to every member of the team except the caller.
///
/// # Parameters (from `args`)
///
/// | Field     | Required | Description                                     |
/// |-----------|----------|-------------------------------------------------|
/// | `message` | yes      | Message body                                    |
/// | `summary` | no       | Short summary (auto-generated if absent)         |
/// | `team`    | no       | Override team (defaults to proxy config team)    |
///
/// # Returns
///
/// MCP result with `"Broadcast sent to N members of <team>"` on success.
pub fn handle_atm_broadcast(id: &Value, args: &Value, identity: &str, team: &str) -> Value {
    let raw_message = match args.get("message").and_then(|v| v.as_str()) {
        Some(s) => s,
        None => return make_mcp_error_result(id, "atm_broadcast: 'message' parameter is required"),
    };

    let effective_team = args
        .get("team")
        .and_then(|v| v.as_str())
        .unwrap_or(team)
        .to_string();

    let message_text = maybe_truncate(raw_message);
    let summary = args
        .get("summary")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let home = match get_home_dir() {
        Ok(h) => h,
        Err(e) => {
            return make_mcp_error_result(
                id,
                &format!("atm_broadcast: cannot resolve home dir: {e}"),
            );
        }
    };

    // Read team config to find members
    let config_path = home
        .join(".claude")
        .join("teams")
        .join(&effective_team)
        .join("config.json");

    let config_content = match std::fs::read(&config_path) {
        Ok(c) => c,
        Err(e) => {
            return make_mcp_error_result(
                id,
                &format!(
                    "atm_broadcast: cannot read team config at '{}': {e}. \
                     Ensure the team '{effective_team}' exists.",
                    config_path.display()
                ),
            );
        }
    };

    let team_config: agent_team_mail_core::TeamConfig =
        match serde_json::from_slice(&config_content) {
            Ok(c) => c,
            Err(e) => {
                return make_mcp_error_result(
                    id,
                    &format!("atm_broadcast: failed to parse team config: {e}"),
                );
            }
        };

    // Send to all members except caller
    let recipients: Vec<String> = team_config
        .members
        .iter()
        .map(|m| m.name.clone())
        .filter(|name| name != identity)
        .collect();

    let mut sent_count = 0usize;
    for recipient in &recipients {
        let msg = build_message(identity, message_text.clone(), summary.clone());
        let path = inbox_path(&home, &effective_team, recipient);

        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }

        match inbox_append(&path, &msg, &effective_team, recipient) {
            Ok(_) => sent_count += 1,
            Err(e) => {
                tracing::warn!("atm_broadcast: failed to deliver to '{recipient}': {e}");
            }
        }
    }

    make_mcp_success(
        id,
        format!("Broadcast sent to {sent_count} members of {effective_team}"),
    )
}

/// Handle an `atm_pending_count` tool call.
///
/// Returns the number of unread messages in the caller's inbox without
/// marking any messages as read.
///
/// # Returns
///
/// MCP result whose text is `{"unread": N}`.
pub fn handle_atm_pending_count(id: &Value, _args: &Value, identity: &str, team: &str) -> Value {
    let home = match get_home_dir() {
        Ok(h) => h,
        Err(e) => {
            return make_mcp_error_result(
                id,
                &format!("atm_pending_count: cannot resolve home dir: {e}"),
            );
        }
    };

    let path = inbox_path(&home, team, identity);

    if !path.exists() {
        return make_mcp_success(id, r#"{"unread":0}"#.to_string());
    }

    let content = match std::fs::read(&path) {
        Ok(c) => c,
        Err(e) => {
            return make_mcp_error_result(
                id,
                &format!("atm_pending_count: cannot read inbox: {e}"),
            );
        }
    };

    let messages: Vec<InboxMessage> = match serde_json::from_slice(&content) {
        Ok(m) => m,
        Err(e) => {
            return make_mcp_error_result(
                id,
                &format!("atm_pending_count: failed to parse inbox: {e}"),
            );
        }
    };

    let unread = messages.iter().filter(|m| !m.read).count();
    make_mcp_success(id, format!(r#"{{"unread":{unread}}}"#))
}

// ---------------------------------------------------------------------------
// Session management tool handlers (FR-10.1, FR-10.2)
// ---------------------------------------------------------------------------

/// Handle an `agent_sessions` tool call (FR-10.1).
///
/// Returns a JSON array of all sessions currently tracked by the registry,
/// regardless of status. Each element includes `agent_id`, `backend`,
/// `backend_id` (Codex threadId), `team`, `identity`, `agent_name`,
/// `agent_source`, `tag`, `status`, `last_active`, and `resumable`.
///
/// A session is `resumable` when it is [`SessionStatus::Stale`] **and** has a
/// non-`None` `thread_id`, meaning the prior Codex thread may still be alive.
///
/// The `agent_name` field is derived from the file stem of `agent_source` when
/// present, falling back to `identity`.
///
/// # Returns
///
/// MCP result whose text is a pretty-printed JSON array of session objects.
pub async fn handle_agent_sessions(id: &Value, registry: Arc<Mutex<SessionRegistry>>) -> Value {
    let guard = registry.lock().await;
    let sessions: Vec<Value> = guard
        .list_all()
        .iter()
        .map(|e| {
            let status_str = match e.status {
                SessionStatus::Active => "active",
                SessionStatus::Stale => "stale",
                SessionStatus::Closed => "closed",
            };
            let thread_state_str = match e.thread_state {
                ThreadState::Busy => "busy",
                ThreadState::Idle => "idle",
                ThreadState::Closed => "closed",
            };
            let resumable = e.status == SessionStatus::Stale && e.thread_id.is_some();
            let agent_name = e
                .agent_source
                .as_deref()
                .and_then(|p| std::path::Path::new(p).file_stem())
                .and_then(|s| s.to_str())
                .unwrap_or(&e.identity)
                .to_string();
            json!({
                "agent_id": e.agent_id,
                "backend": "codex",
                "backend_id": e.thread_id,
                "team": e.team,
                "identity": e.identity,
                "agent_name": agent_name,
                "agent_source": e.agent_source,
                "tag": e.tag,
                "status": status_str,
                "thread_state": thread_state_str,
                "last_active": e.last_active,
                "resumable": resumable,
            })
        })
        .collect();

    let text = serde_json::to_string_pretty(&sessions).unwrap_or_else(|_| "[]".to_string());
    make_mcp_success(id, text)
}

/// Count the number of unread messages in an agent's inbox.
///
/// Returns `0` when the inbox file does not exist or cannot be parsed.
/// This is used by [`handle_agent_status`] (and its callers) to compute the
/// aggregate pending mail count across all active sessions.
pub fn count_unread_for_identity(identity: &str, team: &str, home: &std::path::Path) -> u64 {
    let path = inbox_path(home, team, identity);
    if !path.exists() {
        return 0;
    }
    let content = match std::fs::read(&path) {
        Ok(c) => c,
        Err(_) => return 0,
    };
    let messages: Vec<agent_team_mail_core::InboxMessage> = match serde_json::from_slice(&content) {
        Ok(m) => m,
        Err(_) => return 0,
    };
    messages.iter().filter(|m| !m.read).count() as u64
}

/// Handle an `agent_status` tool call (FR-10.2).
///
/// Returns a JSON object summarising the proxy's runtime status: whether a
/// Codex child process is alive, the ATM team name, startup timestamp, uptime
/// in seconds, active thread count, aggregate unread mail count across all
/// active sessions, and the current identity→threadId map for active sessions.
///
/// # Parameters
///
/// * `pending_mail_count` — pre-computed total unread message count across all
///   active sessions; callers should compute this before acquiring the registry
///   lock to keep this function pure relative to the registry state.
///
/// # Returns
///
/// MCP result whose text is a pretty-printed JSON status object.
pub async fn handle_agent_status(
    id: &Value,
    registry: Arc<Mutex<SessionRegistry>>,
    child_alive: bool,
    team: &str,
    started_at: &str,
    uptime_secs: u64,
    pending_mail_count: u64,
) -> Value {
    let guard = registry.lock().await;
    let active_count = guard.active_count();
    let busy_count = guard
        .list_all()
        .iter()
        .filter(|e| e.status == SessionStatus::Active && e.thread_state == ThreadState::Busy)
        .count();
    let idle_count = guard
        .list_all()
        .iter()
        .filter(|e| e.status == SessionStatus::Active && e.thread_state == ThreadState::Idle)
        .count();
    let identity_map: serde_json::Map<String, Value> = guard
        .list_all()
        .iter()
        .filter(|e| e.status == SessionStatus::Active)
        .map(|e| {
            (
                e.identity.clone(),
                Value::String(e.thread_id.clone().unwrap_or_default()),
            )
        })
        .collect();

    let status = json!({
        "child_alive": child_alive,
        "team": team,
        "started_at": started_at,
        "uptime_secs": uptime_secs,
        "active_thread_count": active_count,
        "busy_thread_count": busy_count,
        "idle_thread_count": idle_count,
        "pending_mail_count": pending_mail_count,
        "identity_map": identity_map,
    });

    let text = serde_json::to_string_pretty(&status).unwrap_or_default();
    make_mcp_success(id, text)
}

/// Handle an `agent_close` tool call (FR-17).
///
/// Closes the specified agent session, releasing its identity lock.  The tool
/// accepts either `agent_id` (direct lookup) or `identity` (looked up via the
/// active identity map).
///
/// Close is **idempotent** (FR-17.9): closing an already-closed session returns
/// a success response with `"status": "already_closed"`.
///
/// If the thread is `Busy` at close time the session is still closed immediately
/// and `"status": "interrupted"` is returned.  Actual in-flight turn cancellation
/// is deferred to Sprint A.7.
///
/// # Parameters (from `args`)
///
/// | Field       | Required | Description                                     |
/// |-------------|----------|-------------------------------------------------|
/// | `agent_id`  | one of   | Direct session identifier                        |
/// | `identity`  | one of   | ATM identity (looks up via identity map)         |
///
/// # Returns
///
/// MCP result with a JSON object:
/// ```json
/// {"closed": true, "agent_id": "...", "status": "closed"|"interrupted"|"already_closed"}
/// ```
pub async fn handle_agent_close(
    id: &Value,
    args: &Value,
    registry: Arc<Mutex<SessionRegistry>>,
    elicitation_registry: Arc<Mutex<crate::elicitation::ElicitationRegistry>>,
) -> Value {
    use crate::proxy::ERR_SESSION_NOT_FOUND;

    // Resolve agent_id from args
    let explicit_agent_id = args
        .get("agent_id")
        .and_then(|v| v.as_str())
        .map(String::from);
    let explicit_identity = args
        .get("identity")
        .and_then(|v| v.as_str())
        .map(String::from);

    if explicit_agent_id.is_none() && explicit_identity.is_none() {
        return make_mcp_error_result(
            id,
            "agent_close: one of 'agent_id' or 'identity' is required",
        );
    }

    let mut guard = registry.lock().await;

    // Resolve the final agent_id
    let resolved_agent_id: String = if let Some(ref aid) = explicit_agent_id {
        aid.clone()
    } else if let Some(ref ident) = explicit_identity {
        match guard.find_by_identity(ident) {
            Some(aid) => aid.to_string(),
            None => {
                // Not in active identity map — check if any session has this identity
                let found = guard
                    .list_all()
                    .iter()
                    .find(|e| e.identity == *ident)
                    .map(|e| e.agent_id.clone());
                match found {
                    Some(aid) => aid,
                    None => {
                        drop(guard);
                        return crate::proxy::make_error_response(
                            id.clone(),
                            ERR_SESSION_NOT_FOUND,
                            &format!("agent_close: no session found for identity '{ident}'"),
                            json!({"error_source": "proxy", "identity": ident}),
                        );
                    }
                }
            }
        }
    } else {
        unreachable!()
    };

    // Look up the session
    let entry = match guard.get(&resolved_agent_id) {
        Some(e) => e.clone(),
        None => {
            drop(guard);
            return crate::proxy::make_error_response(
                id.clone(),
                ERR_SESSION_NOT_FOUND,
                &format!("agent_close: session not found for agent_id '{resolved_agent_id}'"),
                json!({"error_source": "proxy", "agent_id": resolved_agent_id}),
            );
        }
    };

    // Idempotent: already closed → success no-op (FR-17.9)
    if entry.status == SessionStatus::Closed || entry.thread_state == ThreadState::Closed {
        drop(guard);
        if let Err(e) = release_lock(&entry.team, &entry.identity).await {
            tracing::debug!(
                team = %entry.team,
                identity = %entry.identity,
                "agent_close: lock release skipped/failed for already-closed session: {e:#}"
            );
        }
        let result = json!({
            "closed": true,
            "agent_id": resolved_agent_id,
            "status": "already_closed"
        });
        return make_mcp_success(
            id,
            serde_json::to_string_pretty(&result).unwrap_or_default(),
        );
    }

    // Determine close status based on current thread state
    let close_status = if entry.thread_state == ThreadState::Busy {
        "interrupted"
    } else {
        "closed"
    };

    // Close the session (sets status + thread_state to Closed, releases identity)
    guard.close(&resolved_agent_id);
    drop(guard);

    if let Err(e) = release_lock(&entry.team, &entry.identity).await {
        tracing::warn!(
            team = %entry.team,
            identity = %entry.identity,
            "agent_close: failed to release identity lock: {e:#}"
        );
    }

    // Cancel any pending elicitations for this agent (FR-18.5)
    elicitation_registry.lock().await.cancel_for_agent(
        &resolved_agent_id,
        serde_json::json!({"error": {"code": -32003, "message": "session closed"}}),
    );

    let result = json!({
        "closed": true,
        "agent_id": resolved_agent_id,
        "status": close_status
    });
    make_mcp_success(
        id,
        serde_json::to_string_pretty(&result).unwrap_or_default(),
    )
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lock::{acquire_lock, check_lock};
    use serde_json::json;
    use serial_test::serial;
    use std::fs;
    use tempfile::TempDir;

    // -----------------------------------------------------------------------
    // Helper utilities
    // -----------------------------------------------------------------------

    /// Set ATM_HOME to `dir` and return a cleanup guard.
    fn set_atm_home(dir: &TempDir) -> String {
        let p = dir.path().to_string_lossy().to_string();
        // SAFETY: single-threaded within a test function; serial attribute prevents races.
        unsafe { std::env::set_var("ATM_HOME", &p) };
        p
    }

    fn unset_atm_home() {
        unsafe { std::env::remove_var("ATM_HOME") };
    }

    /// Write a minimal team config with the given member names.
    fn write_team_config(home: &std::path::Path, team: &str, member_names: &[&str]) {
        let team_dir = home.join(".claude").join("teams").join(team);
        fs::create_dir_all(&team_dir).unwrap();

        let members: Vec<serde_json::Value> = member_names
            .iter()
            .map(|name| {
                json!({
                    "agentId": format!("{name}@{team}"),
                    "name": name,
                    "agentType": "general-purpose",
                    "model": "claude-sonnet-4-6",
                    "joinedAt": 1000000u64,
                    "cwd": "/tmp"
                })
            })
            .collect();

        let config = json!({
            "name": team,
            "createdAt": 1000000u64,
            "leadAgentId": format!("{}@{}", member_names[0], team),
            "leadSessionId": "test-session-id",
            "members": members
        });

        fs::write(
            team_dir.join("config.json"),
            serde_json::to_string_pretty(&config).unwrap(),
        )
        .unwrap();
    }

    /// Seed an inbox file with the provided messages.
    fn seed_inbox(home: &std::path::Path, team: &str, agent: &str, messages: &[InboxMessage]) {
        let dir = home
            .join(".claude")
            .join("teams")
            .join(team)
            .join("inboxes");
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join(format!("{agent}.json"));
        fs::write(&path, serde_json::to_string_pretty(messages).unwrap()).unwrap();
    }

    /// Build a minimal test InboxMessage.
    fn make_msg(from: &str, text: &str, read: bool, msg_id: Option<&str>) -> InboxMessage {
        InboxMessage {
            from: from.to_string(),
            text: text.to_string(),
            timestamp: "2026-02-18T10:00:00Z".to_string(),
            read,
            summary: None,
            message_id: msg_id.map(|s| s.to_string()),
            unknown_fields: HashMap::new(),
        }
    }

    /// Read and parse an inbox file for assertions.
    fn read_inbox(home: &std::path::Path, team: &str, agent: &str) -> Vec<InboxMessage> {
        let path = home
            .join(".claude")
            .join("teams")
            .join(team)
            .join("inboxes")
            .join(format!("{agent}.json"));
        let content = fs::read_to_string(&path).unwrap();
        serde_json::from_str(&content).unwrap()
    }

    // -----------------------------------------------------------------------
    // resolve_identity tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_resolve_identity_explicit_param() {
        let args = json!({"identity": "explicit-id"});
        let result = resolve_identity(&args, Some("config-id"));
        assert_eq!(result, Some("explicit-id".to_string()));
    }

    #[test]
    fn test_resolve_identity_config_fallback() {
        let args = json!({});
        let result = resolve_identity(&args, Some("config-id"));
        assert_eq!(result, Some("config-id".to_string()));
    }

    #[test]
    fn test_resolve_identity_returns_none_when_both_absent() {
        let args = json!({});
        let result = resolve_identity(&args, None);
        assert_eq!(result, None);
    }

    #[test]
    fn test_resolve_identity_empty_string_falls_back_to_config() {
        let args = json!({"identity": ""});
        let result = resolve_identity(&args, Some("config-id"));
        assert_eq!(result, Some("config-id".to_string()));
    }

    // -----------------------------------------------------------------------
    // parse_to tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_atm_send_to_parsing_simple() {
        let (agent, team) = parse_to("arch-ctm", "default-team").expect("valid to");
        assert_eq!(agent, "arch-ctm");
        assert_eq!(team, "default-team");
    }

    #[test]
    fn test_atm_send_to_parsing_at_notation() {
        let (agent, team) = parse_to("arch-ctm@atm-dev", "default-team").expect("valid to");
        assert_eq!(agent, "arch-ctm");
        assert_eq!(team, "atm-dev");
    }

    #[test]
    fn test_atm_send_to_parsing_rejects_empty_agent() {
        let err = parse_to("@atm-dev", "default-team").expect_err("must reject empty agent");
        assert!(err.contains("empty agent name"));
    }

    // -----------------------------------------------------------------------
    // Truncation tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_message_truncation_at_limit() {
        let long_msg = "a".repeat(MAX_MESSAGE_LEN + 100);
        let result = maybe_truncate(&long_msg);
        assert!(result.len() <= MAX_MESSAGE_LEN + TRUNCATION_SUFFIX.len());
        assert!(result.ends_with(TRUNCATION_SUFFIX));
        let result_prefix: String = result.chars().take(MAX_MESSAGE_LEN).collect();
        let expected_prefix: String = long_msg.chars().take(MAX_MESSAGE_LEN).collect();
        assert_eq!(result_prefix, expected_prefix);
    }

    #[test]
    fn test_message_no_truncation_under_limit() {
        let short_msg = "hello world";
        let result = maybe_truncate(short_msg);
        assert_eq!(result, short_msg);
    }

    #[test]
    fn test_message_exact_limit_not_truncated() {
        let exact_msg = "a".repeat(MAX_MESSAGE_LEN);
        let result = maybe_truncate(&exact_msg);
        assert_eq!(result, exact_msg);
        assert!(!result.contains("truncated"));
    }

    #[test]
    fn test_message_truncation_is_utf8_safe() {
        let unicode = "é".repeat(MAX_MESSAGE_LEN + 1);
        let result = maybe_truncate(&unicode);
        assert!(result.ends_with(TRUNCATION_SUFFIX));
    }

    // -----------------------------------------------------------------------
    // Auto-summary tests
    // -----------------------------------------------------------------------

    #[test]
    fn test_auto_summary_generation() {
        let msg = "This is a message longer than sixty characters for testing summary generation";
        let summary = auto_summary(msg);
        assert!(summary.ends_with("..."));
        // 60 chars + "..." — char count, not byte count
        assert_eq!(summary.chars().count(), 63);
    }

    #[test]
    fn test_auto_summary_short_message() {
        let msg = "Short msg";
        let summary = auto_summary(msg);
        assert_eq!(summary, "Short msg");
        assert!(!summary.ends_with("..."));
    }

    #[test]
    fn test_auto_summary_is_utf8_safe() {
        let msg = "é".repeat(100);
        let summary = auto_summary(&msg);
        assert!(summary.ends_with("..."));
    }

    // -----------------------------------------------------------------------
    // atm_send tests
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn test_atm_send_success() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let id = json!(1);
        let args = json!({"to": "arch-ctm", "message": "Hello from test"});
        let resp = handle_atm_send(&id, &args, "team-lead", "atm-dev");

        unset_atm_home();

        assert!(
            resp.get("error").is_none(),
            "should not be an error response"
        );
        assert_eq!(resp["result"]["isError"], Value::Null);

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(text.contains("arch-ctm"), "should mention recipient");

        // Verify inbox file was created
        let msgs = read_inbox(dir.path(), "atm-dev", "arch-ctm");
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].from, "team-lead");
        assert_eq!(msgs[0].text, "Hello from test");
        assert!(!msgs[0].read);
        assert!(msgs[0].message_id.is_some());
    }

    #[test]
    #[serial]
    fn test_atm_send_at_notation_routes_to_correct_team() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let id = json!(2);
        let args = json!({"to": "dev-agent@sprint-team", "message": "Cross-team message"});
        let resp = handle_atm_send(&id, &args, "team-lead", "atm-dev");

        unset_atm_home();

        assert!(resp.get("error").is_none());
        let msgs = read_inbox(dir.path(), "sprint-team", "dev-agent");
        assert_eq!(msgs.len(), 1);
        assert_eq!(msgs[0].text, "Cross-team message");
    }

    #[test]
    #[serial]
    fn test_atm_send_truncates_long_message() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let long_msg = "x".repeat(MAX_MESSAGE_LEN + 50);
        let id = json!(3);
        let args = json!({"to": "agent-a", "message": long_msg});
        handle_atm_send(&id, &args, "sender", "team");

        unset_atm_home();

        let msgs = read_inbox(dir.path(), "team", "agent-a");
        assert_eq!(msgs.len(), 1);
        assert!(msgs[0].text.ends_with(TRUNCATION_SUFFIX));
    }

    #[test]
    fn test_atm_send_missing_to_returns_error() {
        let id = json!(4);
        let args = json!({"message": "hello"});
        let resp = handle_atm_send(&id, &args, "sender", "team");
        assert_eq!(resp["result"]["isError"], json!(true));
    }

    #[test]
    fn test_atm_send_missing_message_returns_error() {
        let id = json!(5);
        let args = json!({"to": "agent"});
        let resp = handle_atm_send(&id, &args, "sender", "team");
        assert_eq!(resp["result"]["isError"], json!(true));
    }

    #[test]
    fn test_atm_send_rejects_empty_agent_in_to() {
        let id = json!(6);
        let args = json!({"to": "@atm-dev", "message": "hello"});
        let resp = handle_atm_send(&id, &args, "sender", "team");
        assert_eq!(resp["result"]["isError"], json!(true));
        let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
        assert!(text.contains("empty agent name"));
    }

    // -----------------------------------------------------------------------
    // atm_read tests
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn test_atm_read_empty_inbox() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let id = json!(10);
        let args = json!({});
        let resp = handle_atm_read(&id, &args, "nobody", "team");

        unset_atm_home();

        // Missing inbox file is not an error
        assert!(resp.get("error").is_none());
        assert_ne!(resp["result"]["isError"], json!(true));
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert!(msgs.is_empty());
    }

    #[test]
    #[serial]
    fn test_atm_read_filters_unread_by_default() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("a", "unread1", false, Some("id-1")),
                make_msg("b", "already-read", true, Some("id-2")),
                make_msg("c", "unread2", false, Some("id-3")),
            ],
        );

        let id = json!(11);
        let args = json!({"mark_read": false});
        let resp = handle_atm_read(&id, &args, "agent", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(msgs.len(), 2);
        assert!(msgs.iter().any(|m| m["text"] == "unread1"));
        assert!(msgs.iter().any(|m| m["text"] == "unread2"));
        assert!(!msgs.iter().any(|m| m["text"] == "already-read"));
    }

    #[test]
    #[serial]
    fn test_atm_read_all_flag() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("a", "unread", false, Some("id-1")),
                make_msg("b", "read", true, Some("id-2")),
            ],
        );

        let id = json!(12);
        let args = json!({"all": true, "mark_read": false});
        let resp = handle_atm_read(&id, &args, "agent", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(msgs.len(), 2);
    }

    #[test]
    #[serial]
    fn test_atm_read_marks_read_by_default() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("a", "msg1", false, Some("id-1")),
                make_msg("b", "msg2", false, Some("id-2")),
            ],
        );

        let id = json!(13);
        let args = json!({});
        handle_atm_read(&id, &args, "agent", "team");

        let msgs = read_inbox(dir.path(), "team", "agent");
        unset_atm_home();

        assert!(
            msgs.iter().all(|m| m.read),
            "all messages should be marked read"
        );
    }

    #[test]
    #[serial]
    fn test_atm_read_limit() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let messages: Vec<InboxMessage> = (0..15)
            .map(|i| {
                make_msg(
                    "sender",
                    &format!("msg{i}"),
                    false,
                    Some(&format!("id-{i}")),
                )
            })
            .collect();
        seed_inbox(dir.path(), "team", "agent", &messages);

        let id = json!(14);
        let args = json!({"limit": 5, "mark_read": false});
        let resp = handle_atm_read(&id, &args, "agent", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(msgs.len(), 5);
    }

    #[test]
    #[serial]
    fn test_atm_read_default_limit_is_ten() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let messages: Vec<InboxMessage> = (0..20)
            .map(|i| {
                make_msg(
                    "sender",
                    &format!("msg{i}"),
                    false,
                    Some(&format!("id-{i}")),
                )
            })
            .collect();
        seed_inbox(dir.path(), "team", "agent", &messages);

        let id = json!(14);
        let args = json!({"mark_read": false});
        let resp = handle_atm_read(&id, &args, "agent", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(msgs.len(), 10);
    }

    #[test]
    #[serial]
    fn test_atm_read_from_filter() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("alice", "from alice", false, Some("id-1")),
                make_msg("bob", "from bob", false, Some("id-2")),
                make_msg("alice", "also alice", false, Some("id-3")),
            ],
        );

        let id = json!(15);
        let args = json!({"from": "alice", "mark_read": false});
        let resp = handle_atm_read(&id, &args, "agent", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(msgs.len(), 2);
        assert!(msgs.iter().all(|m| m["from"] == "alice"));
    }

    #[test]
    #[serial]
    fn test_atm_read_since_filter() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        // Seed 3 messages with distinct timestamps
        let old_msg = InboxMessage {
            from: "sender".to_string(),
            text: "old message".to_string(),
            timestamp: "2026-01-01T00:00:00Z".to_string(),
            read: false,
            summary: None,
            message_id: Some("id-old".to_string()),
            unknown_fields: HashMap::new(),
        };
        let middle_msg = InboxMessage {
            from: "sender".to_string(),
            text: "middle message".to_string(),
            timestamp: "2026-02-01T00:00:00Z".to_string(),
            read: false,
            summary: None,
            message_id: Some("id-middle".to_string()),
            unknown_fields: HashMap::new(),
        };
        let future_msg = InboxMessage {
            from: "sender".to_string(),
            text: "future message".to_string(),
            timestamp: "2026-03-01T00:00:00Z".to_string(),
            read: false,
            summary: None,
            message_id: Some("id-future".to_string()),
            unknown_fields: HashMap::new(),
        };
        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[old_msg, middle_msg, future_msg],
        );

        let id = json!(16);
        // since = "2026-02-01T00:00:00Z" — should include middle and future, exclude old
        let args = json!({"since": "2026-02-01T00:00:00Z", "mark_read": false, "limit": 10});
        let resp = handle_atm_read(&id, &args, "agent", "team");

        unset_atm_home();

        assert!(
            resp.get("error").is_none(),
            "should not be protocol error; got: {resp}"
        );
        assert_ne!(
            resp["result"]["isError"],
            json!(true),
            "should not be isError; got: {resp}"
        );

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let msgs: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(
            msgs.len(),
            2,
            "should return only messages at or after the since timestamp"
        );
        assert!(
            msgs.iter().any(|m| m["text"] == "middle message"),
            "middle message should be included"
        );
        assert!(
            msgs.iter().any(|m| m["text"] == "future message"),
            "future message should be included"
        );
        assert!(
            !msgs.iter().any(|m| m["text"] == "old message"),
            "old message should be excluded"
        );
    }

    // -----------------------------------------------------------------------
    // atm_pending_count tests
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn test_atm_pending_count_zero() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let id = json!(20);
        let args = json!({});
        let resp = handle_atm_pending_count(&id, &args, "nobody", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let v: Value = serde_json::from_str(text).unwrap();
        assert_eq!(v["unread"], json!(0));
    }

    #[test]
    #[serial]
    fn test_atm_pending_count_nonzero() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("a", "msg1", false, Some("id-1")),
                make_msg("b", "msg2", true, Some("id-2")),
                make_msg("c", "msg3", false, Some("id-3")),
            ],
        );

        let id = json!(21);
        let args = json!({});
        let resp = handle_atm_pending_count(&id, &args, "agent", "team");

        unset_atm_home();

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let v: Value = serde_json::from_str(text).unwrap();
        assert_eq!(v["unread"], json!(2));
    }

    #[test]
    #[serial]
    fn test_atm_pending_count_does_not_mark_read() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        seed_inbox(
            dir.path(),
            "team",
            "agent",
            &[
                make_msg("a", "msg1", false, Some("id-1")),
                make_msg("b", "msg2", false, Some("id-2")),
            ],
        );

        let id = json!(22);
        let args = json!({});
        handle_atm_pending_count(&id, &args, "agent", "team");

        let msgs = read_inbox(dir.path(), "team", "agent");
        unset_atm_home();

        assert!(
            msgs.iter().all(|m| !m.read),
            "pending_count must not mark messages as read"
        );
    }

    // -----------------------------------------------------------------------
    // atm_broadcast tests
    // -----------------------------------------------------------------------

    #[test]
    #[serial]
    fn test_atm_broadcast_reads_team_config() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        write_team_config(
            dir.path(),
            "atm-dev",
            &["team-lead", "arch-ctm", "dev-agent"],
        );

        let id = json!(30);
        let args = json!({"message": "broadcast test"});
        let resp = handle_atm_broadcast(&id, &args, "team-lead", "atm-dev");

        unset_atm_home();

        assert!(resp.get("error").is_none());
        assert_ne!(resp["result"]["isError"], json!(true));

        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        assert!(
            text.contains("2 members"),
            "should send to 2 members (excluding self)"
        );
    }

    #[test]
    #[serial]
    fn test_atm_broadcast_skips_caller() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        write_team_config(dir.path(), "team", &["sender", "recip-a", "recip-b"]);

        let id = json!(31);
        let args = json!({"message": "skips-me"});
        handle_atm_broadcast(&id, &args, "sender", "team");

        unset_atm_home();

        // sender's own inbox should NOT have the message
        let sender_inbox_path = dir
            .path()
            .join(".claude")
            .join("teams")
            .join("team")
            .join("inboxes")
            .join("sender.json");
        assert!(
            !sender_inbox_path.exists(),
            "sender should not receive their own broadcast"
        );

        // recip-a and recip-b should have the message
        let ra = read_inbox(dir.path(), "team", "recip-a");
        let rb = read_inbox(dir.path(), "team", "recip-b");
        assert_eq!(ra.len(), 1);
        assert_eq!(rb.len(), 1);
    }

    #[test]
    #[serial]
    fn test_atm_broadcast_missing_config_returns_error() {
        let dir = TempDir::new().unwrap();
        set_atm_home(&dir);

        let id = json!(32);
        let args = json!({"message": "hello"});
        let resp = handle_atm_broadcast(&id, &args, "team-lead", "nonexistent-team");

        unset_atm_home();

        assert_eq!(resp["result"]["isError"], json!(true));
    }

    // -----------------------------------------------------------------------
    // handle_agent_sessions tests
    // -----------------------------------------------------------------------

    fn make_test_registry(max: usize) -> Arc<Mutex<SessionRegistry>> {
        Arc::new(Mutex::new(SessionRegistry::new(max)))
    }

    #[tokio::test]
    async fn test_agent_sessions_empty_registry() {
        let reg = make_test_registry(10);
        let id = json!(100);
        let resp = handle_agent_sessions(&id, reg).await;
        assert!(resp.get("error").is_none());
        assert_ne!(resp["result"]["isError"], json!(true));
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let sessions: Vec<Value> = serde_json::from_str(text).unwrap();
        assert!(sessions.is_empty());
    }

    #[tokio::test]
    async fn test_agent_sessions_active_session_listed() {
        let reg = make_test_registry(10);
        {
            let mut guard = reg.lock().await;
            guard
                .register(
                    "arch-ctm".to_string(),
                    "atm-dev".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
        }
        let id = json!(101);
        let resp = handle_agent_sessions(&id, reg).await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let sessions: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0]["identity"], "arch-ctm");
        assert_eq!(sessions[0]["status"], "active");
        assert_eq!(sessions[0]["resumable"], json!(false));
    }

    #[tokio::test]
    async fn test_agent_sessions_stale_with_thread_id_is_resumable() {
        let reg = make_test_registry(10);
        let agent_id = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "dev-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.set_thread_id(&e.agent_id, "thread-xyz".to_string());
            guard.mark_all_stale();
            e.agent_id.clone()
        };
        let id = json!(102);
        let resp = handle_agent_sessions(&id, Arc::clone(&reg)).await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let sessions: Vec<Value> = serde_json::from_str(text).unwrap();
        let session = sessions.iter().find(|s| s["agent_id"] == agent_id).unwrap();
        assert_eq!(session["status"], "stale");
        assert_eq!(session["resumable"], json!(true));
    }

    #[tokio::test]
    async fn test_agent_sessions_stale_without_thread_id_not_resumable() {
        let reg = make_test_registry(10);
        {
            let mut guard = reg.lock().await;
            guard
                .register(
                    "no-thread".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.mark_all_stale();
        }
        let id = json!(103);
        let resp = handle_agent_sessions(&id, reg).await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let sessions: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(sessions.len(), 1);
        assert_eq!(sessions[0]["resumable"], json!(false));
    }

    #[tokio::test]
    async fn test_agent_sessions_mixed_statuses() {
        let reg = make_test_registry(10);
        {
            let mut guard = reg.lock().await;
            let a = guard
                .register(
                    "active-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            let c = guard
                .register(
                    "closed-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.close(&c.agent_id);
            guard
                .register(
                    "stale-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            let _ = a;
        }
        // Mark non-active sessions stale (mark_all_stale makes ALL stale)
        // Instead close + keep one active, and use insert_stale for the third
        let reg2 = make_test_registry(10);
        {
            let mut guard = reg2.lock().await;
            guard
                .register(
                    "active-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            let closed = guard
                .register(
                    "closed-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.close(&closed.agent_id);
        }
        let id = json!(104);
        let resp = handle_agent_sessions(&id, reg2).await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let sessions: Vec<Value> = serde_json::from_str(text).unwrap();
        assert_eq!(sessions.len(), 2);
        let statuses: Vec<&str> = sessions
            .iter()
            .map(|s| s["status"].as_str().unwrap())
            .collect();
        assert!(statuses.contains(&"active"));
        assert!(statuses.contains(&"closed"));
    }

    // -----------------------------------------------------------------------
    // handle_agent_status tests
    // -----------------------------------------------------------------------

    #[tokio::test]
    async fn test_agent_status_no_sessions() {
        let reg = make_test_registry(10);
        let id = json!(200);
        let resp =
            handle_agent_status(&id, reg, false, "atm-dev", "2026-02-18T00:00:00Z", 42, 0).await;
        assert!(resp.get("error").is_none());
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let status: Value = serde_json::from_str(text).unwrap();
        assert_eq!(status["child_alive"], json!(false));
        assert_eq!(status["team"], "atm-dev");
        assert_eq!(status["started_at"], "2026-02-18T00:00:00Z");
        assert_eq!(status["uptime_secs"], json!(42));
        assert_eq!(status["active_thread_count"], json!(0));
        assert_eq!(status["pending_mail_count"], json!(0));
        assert!(status["identity_map"].as_object().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_agent_status_with_active_session() {
        let reg = make_test_registry(10);
        let agent_id = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "arch-ctm".to_string(),
                    "atm-dev".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.set_thread_id(&e.agent_id, "thread-abc".to_string());
            e.agent_id.clone()
        };
        let id = json!(201);
        let resp = handle_agent_status(
            &id,
            Arc::clone(&reg),
            true,
            "atm-dev",
            "2026-02-18T12:00:00Z",
            3600,
            0,
        )
        .await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let status: Value = serde_json::from_str(text).unwrap();
        assert_eq!(status["child_alive"], json!(true));
        assert_eq!(status["active_thread_count"], json!(1));
        let map = status["identity_map"].as_object().unwrap();
        assert_eq!(
            map.get("arch-ctm").and_then(|v| v.as_str()),
            Some("thread-abc")
        );
        let _ = agent_id;
    }

    #[tokio::test]
    async fn test_agent_status_stale_sessions_not_in_identity_map() {
        let reg = make_test_registry(10);
        {
            let mut guard = reg.lock().await;
            guard
                .register(
                    "stale-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.mark_all_stale();
        }
        let id = json!(202);
        let resp = handle_agent_status(&id, reg, false, "team", "2026-02-18T00:00:00Z", 0, 0).await;
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let status: Value = serde_json::from_str(text).unwrap();
        assert_eq!(status["active_thread_count"], json!(0));
        assert!(status["identity_map"].as_object().unwrap().is_empty());
    }

    // -----------------------------------------------------------------------
    // handle_agent_close tests (FR-17, FR-18.5)
    // -----------------------------------------------------------------------

    fn make_test_elicitation_registry() -> Arc<Mutex<crate::elicitation::ElicitationRegistry>> {
        Arc::new(Mutex::new(crate::elicitation::ElicitationRegistry::new(30)))
    }

    #[tokio::test]
    async fn test_agent_close_by_agent_id_returns_closed() {
        let reg = make_test_registry(10);
        let agent_id = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "close-me".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            // Transition to Idle so close_status is "closed", not "interrupted"
            guard.set_thread_state(&e.agent_id, ThreadState::Idle);
            e.agent_id.clone()
        };
        let elicit_reg = make_test_elicitation_registry();
        let id = json!(300);
        let args = json!({"agent_id": agent_id});
        let resp = handle_agent_close(&id, &args, reg, elicit_reg).await;
        assert!(resp.get("error").is_none());
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let result: Value = serde_json::from_str(text).unwrap();
        assert_eq!(result["closed"], json!(true));
        assert_eq!(result["status"], "closed");
        assert_eq!(result["agent_id"], agent_id);
    }

    #[tokio::test]
    async fn test_agent_close_idempotent_already_closed() {
        let reg = make_test_registry(10);
        let elicit_reg = make_test_elicitation_registry();
        let agent_id = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "already-closed".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.close(&e.agent_id);
            e.agent_id.clone()
        };
        let id = json!(301);
        let args = json!({"agent_id": agent_id});
        // First close (already closed)
        let resp = handle_agent_close(&id, &args, Arc::clone(&reg), Arc::clone(&elicit_reg)).await;
        assert!(resp.get("error").is_none());
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let result: Value = serde_json::from_str(text).unwrap();
        assert_eq!(result["closed"], json!(true));
        assert_eq!(result["status"], "already_closed");
    }

    #[tokio::test]
    async fn test_agent_close_busy_session_returns_interrupted() {
        let reg = make_test_registry(10);
        let elicit_reg = make_test_elicitation_registry();
        let agent_id = {
            let mut guard = reg.lock().await;
            // New sessions default to ThreadState::Busy (FR-17.2)
            let e = guard
                .register(
                    "busy-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            e.agent_id.clone()
        };
        let id = json!(302);
        let args = json!({"agent_id": agent_id});
        let resp = handle_agent_close(&id, &args, reg, elicit_reg).await;
        assert!(resp.get("error").is_none());
        let text = resp["result"]["content"][0]["text"].as_str().unwrap();
        let result: Value = serde_json::from_str(text).unwrap();
        assert_eq!(result["closed"], json!(true));
        assert_eq!(result["status"], "interrupted");
    }

    #[tokio::test]
    async fn test_agent_close_unknown_agent_id_returns_err_session_not_found() {
        let reg = make_test_registry(10);
        let elicit_reg = make_test_elicitation_registry();
        let id = json!(303);
        let args = json!({"agent_id": "does-not-exist"});
        let resp = handle_agent_close(&id, &args, reg, elicit_reg).await;
        // Must be a JSON-RPC error (not an MCP isError result)
        let err = &resp["error"];
        assert_eq!(
            err["code"],
            json!(crate::proxy::ERR_SESSION_NOT_FOUND),
            "expected ERR_SESSION_NOT_FOUND code"
        );
    }

    #[tokio::test]
    async fn test_agent_close_cancels_pending_elicitations() {
        use tokio::sync::oneshot;

        let reg = make_test_registry(10);
        let agent_id = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "elicit-agent".to_string(),
                    "team".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.set_thread_state(&e.agent_id, ThreadState::Idle);
            e.agent_id.clone()
        };

        let elicit_reg = make_test_elicitation_registry();
        // Register a pending elicitation for this agent
        let (_tx, mut rx) = oneshot::channel::<serde_json::Value>();
        {
            let mut guard = elicit_reg.lock().await;
            guard.register(
                agent_id.clone(),
                serde_json::json!(1),
                serde_json::json!(999),
                _tx,
            );
        }

        let id = json!(304);
        let args = json!({"agent_id": agent_id});
        let _resp = handle_agent_close(&id, &args, reg, Arc::clone(&elicit_reg)).await;

        // The receiver should have received the rejection payload sent by cancel_for_agent
        let rejection = rx.try_recv();
        assert!(
            rejection.is_ok(),
            "rejection should have been sent to the elicitation receiver"
        );
        let rejection_val = rejection.unwrap();
        assert_eq!(rejection_val["error"]["code"], json!(-32003));
        // The elicitation should no longer be pending — trying to resolve it returns false
        let resolved_again = elicit_reg
            .lock()
            .await
            .resolve(&serde_json::json!(999), serde_json::json!({}));
        assert!(
            !resolved_again,
            "elicitation should have been removed by cancel_for_agent"
        );
    }

    #[tokio::test]
    #[serial]
    async fn test_agent_close_releases_identity_lock() {
        let dir = tempfile::tempdir().unwrap();
        let _atm_home = set_atm_home(&dir);

        let reg = make_test_registry(10);
        let (agent_id, identity, team) = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "lock-release".to_string(),
                    "team-lock".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.set_thread_state(&e.agent_id, ThreadState::Idle);
            (e.agent_id.clone(), e.identity.clone(), e.team.clone())
        };
        acquire_lock(&team, &identity, &agent_id).await.unwrap();
        assert!(
            check_lock(&team, &identity).await.is_some(),
            "lock should exist before close"
        );

        let elicit_reg = make_test_elicitation_registry();
        let id = json!(305);
        let args = json!({"agent_id": agent_id});
        let _resp = handle_agent_close(&id, &args, reg, elicit_reg).await;

        assert!(
            check_lock(&team, &identity).await.is_none(),
            "lock should be removed after agent_close"
        );
        unset_atm_home();
    }

    #[tokio::test]
    #[serial]
    async fn test_agent_close_already_closed_releases_stale_lock() {
        let dir = tempfile::tempdir().unwrap();
        let _atm_home = set_atm_home(&dir);

        let reg = make_test_registry(10);
        let (agent_id, identity, team) = {
            let mut guard = reg.lock().await;
            let e = guard
                .register(
                    "lock-release-closed".to_string(),
                    "team-lock".to_string(),
                    "/tmp".to_string(),
                    None,
                    None,
                    None,
                )
                .unwrap();
            guard.close(&e.agent_id);
            (e.agent_id.clone(), e.identity.clone(), e.team.clone())
        };
        acquire_lock(&team, &identity, &agent_id).await.unwrap();
        assert!(
            check_lock(&team, &identity).await.is_some(),
            "stale lock should exist before idempotent close"
        );

        let elicit_reg = make_test_elicitation_registry();
        let id = json!(306);
        let args = json!({"agent_id": agent_id});
        let _resp = handle_agent_close(&id, &args, reg, elicit_reg).await;

        assert!(
            check_lock(&team, &identity).await.is_none(),
            "idempotent close should also clear stale lock"
        );
        unset_atm_home();
    }

    // -----------------------------------------------------------------------
    // Identity required error (proxy.rs constant is tested via integration)
    // -----------------------------------------------------------------------

    #[test]
    fn test_identity_required_error_code_value() {
        // Verify the constant value used in proxy.rs is correct
        assert_eq!(crate::proxy::ERR_IDENTITY_REQUIRED, -32009_i64);
    }

    // -----------------------------------------------------------------------
    // make_mcp_error_result shape
    // -----------------------------------------------------------------------

    #[test]
    fn test_make_mcp_error_result_shape() {
        let id = json!(42);
        let resp = make_mcp_error_result(&id, "something went wrong");
        assert_eq!(resp["jsonrpc"], "2.0");
        assert_eq!(resp["id"], 42);
        assert_eq!(resp["result"]["isError"], json!(true));
        assert_eq!(resp["result"]["content"][0]["text"], "something went wrong");
        // Must not be a JSON-RPC error response
        assert!(resp.get("error").is_none());
    }
}