team-bot 0.7.3

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

use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result};
use clap::Parser;
use rusqlite::{params, Connection};
use teloxide::net::Download;
use teloxide::prelude::*;
use teloxide::types::{
    BotCommand, ChatId, InlineKeyboardButton, InlineKeyboardMarkup, InputFile, MessageId,
    ReactionType, ReplyParameters,
};
use tokio::sync::Mutex;

#[derive(Parser, Clone)]
#[command(name = "team-bot", version, about = "Telegram interface for teamctl")]
struct Cli {
    /// Path to the SQLite mailbox.
    #[arg(long, env = "TEAMCTL_MAILBOX")]
    mailbox: PathBuf,

    /// Telegram bot token.
    #[arg(long, env = "TEAMCTL_TELEGRAM_TOKEN")]
    token: String,

    /// Comma-separated list of authorized chat ids. May be empty during
    /// bootstrap — the bot will then reply to `/start` with the caller's
    /// chat id so it can be added to `.env`.
    #[arg(long, env = "TEAMCTL_TELEGRAM_CHATS")]
    authorized_chat_ids: Option<String>,

    /// Scope this bot to one manager. When set, it forwards only messages
    /// addressed to that manager and only surfaces approvals requested by
    /// agents in that project. Two bot instances against the same mailbox
    /// can safely coexist when each scopes to a different manager.
    ///
    /// Format: `<project>:<manager>`.
    #[arg(long, env = "TEAMCTL_MANAGER")]
    manager: Option<String>,

    /// Tmux session prefix (matches `compose.global.supervisor.tmux_prefix`).
    /// Used by slash-passthrough (T-086-G) to compute `<prefix><project>-<role>`
    /// for the manager's tmux session. `teamctl bot up` populates this from
    /// compose; the default matches `team-core`'s default prefix so a hand-
    /// launched bot still works on a stock team.
    #[arg(long, env = "TEAMCTL_TMUX_PREFIX", default_value = "t-")]
    tmux_prefix: String,
}

struct State {
    conn: Mutex<Connection>,
    allow: Vec<i64>,
    /// `<project>:<manager>` if this instance is scoped; otherwise all managers.
    manager: Option<String>,
    /// Tmux session prefix used by slash-passthrough to compute the manager's
    /// session name. Stored on `State` so handle_message can reach it without
    /// re-reading the CLI args.
    tmux_prefix: String,
    /// Directory to write inbound media downloads under (T-086-C). Resolved
    /// from the mailbox path's parent (`<root>/.team/state/inbound-media/`)
    /// at startup so the bot stays self-contained — no extra CLI flag, no
    /// config sync.
    media_root: PathBuf,
}

impl State {
    fn manager_project(&self) -> Option<&str> {
        self.manager
            .as_deref()
            .and_then(|m| m.split_once(':').map(|(p, _)| p))
    }
}

impl State {
    fn is_authorized(&self, chat: i64) -> bool {
        self.allow.is_empty() || self.allow.contains(&chat)
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    tracing_subscriber::fmt()
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_env("TEAM_BOT_LOG")
                .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
        )
        .init();

    let cli = Cli::parse();
    let bot = Bot::new(&cli.token);
    let conn = open_mailbox(&cli.mailbox)?;
    let allow: Vec<i64> = cli
        .authorized_chat_ids
        .as_deref()
        .unwrap_or("")
        .split(',')
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .filter_map(|s| s.parse().ok())
        .collect();
    let media_root = cli
        .mailbox
        .parent()
        .map(|p| p.join("inbound-media"))
        .unwrap_or_else(|| PathBuf::from("inbound-media"));
    let state = Arc::new(State {
        conn: Mutex::new(conn),
        allow,
        manager: cli.manager,
        tmux_prefix: cli.tmux_prefix,
        media_root,
    });

    // T-086-H: register the manager's runtime-appropriate slash commands
    // with Telegram so the operator gets autocomplete on `/`. Manager-scoped
    // CC bots register the curated `CC_SLASH_COMMANDS` list; non-CC and
    // unscoped bots register nothing (clean degrade per Decision 6). The
    // registration is best-effort — a Telegram API error is logged but
    // doesn't abort startup, since slash-passthrough (PR-G) still works
    // when the operator types the chord manually.
    let runtime = if let Some(mgr) = state.manager.as_deref() {
        let c = state.conn.lock().await;
        agent_runtime(&c, mgr)
    } else {
        None
    };
    let commands = commands_for_runtime(runtime.as_deref());
    if !commands.is_empty() {
        if let Err(e) = bot.set_my_commands(commands).await {
            tracing::warn!(
                "set_my_commands failed (operator gets no autocomplete; \
                 slash-passthrough still works manually): {e}"
            );
        }
    }

    // Outbound: poll approvals + mailbox, surface to primary chat.
    {
        let bot = bot.clone();
        let state = state.clone();
        tokio::spawn(async move { outbound_loop(bot, state).await });
    }

    // Inbound: teloxide repl-style, one handler for everything.
    let bot_inbound = bot.clone();

    let handler = dptree::entry()
        .branch(Update::filter_message().endpoint({
            let state = state.clone();
            move |bot: Bot, msg: Message| {
                let state = state.clone();
                async move { handle_message(bot, msg, state).await }
            }
        }))
        .branch(Update::filter_callback_query().endpoint({
            let state = state.clone();
            move |bot: Bot, q: CallbackQuery| {
                let state = state.clone();
                async move { handle_callback(bot, q, state).await }
            }
        }));

    Dispatcher::builder(bot_inbound, handler)
        .enable_ctrlc_handler()
        .build()
        .dispatch()
        .await;
    Ok(())
}

fn open_mailbox(path: &std::path::Path) -> Result<Connection> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let conn = Connection::open(path).context("open mailbox")?;
    conn.busy_timeout(Duration::from_secs(5))?;
    conn.pragma_update(None, "journal_mode", "WAL")?;
    team_core::mailbox::ensure(&conn)?;
    Ok(conn)
}

async fn handle_message(bot: Bot, msg: Message, state: Arc<State>) -> ResponseResult<()> {
    let chat_id = msg.chat.id.0;
    let trimmed = msg.text().map(str::trim).unwrap_or("");

    // Bootstrap: a chat that isn't on the allow list gets a one-shot reply
    // to `/start` exposing its own chat id, so the operator can paste it
    // into `.env` without hunting for @userinfobot.
    if !state.allow.contains(&chat_id) && trimmed == "/start" {
        bot.send_message(
            msg.chat.id,
            format!(
                "This chat isn't authorized yet.\n\n\
                 Your chat id: {chat_id}\n\n\
                 Add it to .env next to your team-compose.yaml:\n\
                 TEAMCTL_TELEGRAM_CHATS={chat_id}\n\n\
                 Then restart team-bot."
            ),
        )
        .await?;
        return Ok(());
    }

    if !state.is_authorized(chat_id) {
        return Ok(());
    }
    // T-086-C inbound media: photos and documents arrive with `msg.text()`
    // empty (the caption sits on `msg.caption()` instead). Detect before the
    // text-routing chain — without this, media messages would silently fall
    // through every arm and the operator would see no acknowledgement.
    if msg.photo().is_some() || msg.document().is_some() {
        return handle_inbound_media(&bot, &msg, &state).await;
    }
    // T-086-B: capture the inbound Telegram message id on every mailbox
    // row we write so agents (via `inbox_peek`) can read it back as
    // `telegram_msg_id` and pass it through `reply_to_message_id` to
    // thread their reply.
    let inbound_msg_id: i64 = msg.id.0 as i64;
    if let Some(rest) = trimmed.strip_prefix("/dm ") {
        if let Some((target, body)) = rest.split_once(' ') {
            if let Some((project, _)) = target.split_once(':') {
                let c = state.conn.lock().await;
                let _ = c.execute(
                    "INSERT INTO messages
                        (project_id, sender, recipient, text, sent_at, telegram_msg_id)
                     VALUES (?1, 'user:telegram', ?2, ?3, strftime('%s','now'), ?4)",
                    params![project, target, body, inbound_msg_id],
                );
                drop(c);
                bot.send_message(msg.chat.id, format!("{target}")).await?;
            }
        }
    } else if !trimmed.is_empty() && !trimmed.starts_with('/') && state.manager.is_some() {
        // Plain text on a manager-scoped bot: route the message to the
        // bot's manager. The whole point of `teamctl bot setup`'s 1:1
        // mapping is that DMing the bot reaches the matching manager
        // without `/dm role text` ceremony.
        let target = state.manager.as_deref().unwrap();
        if let Some((project, _)) = target.split_once(':') {
            let c = state.conn.lock().await;
            let _ = c.execute(
                "INSERT INTO messages
                    (project_id, sender, recipient, text, sent_at, telegram_msg_id)
                 VALUES (?1, 'user:telegram', ?2, ?3, strftime('%s','now'), ?4)",
                params![project, target, trimmed, inbound_msg_id],
            );
            drop(c);
            bot.send_message(msg.chat.id, format!("{target}")).await?;
        }
    } else if trimmed == "/pending" {
        let c = state.conn.lock().await;
        let rows: Vec<(i64, String, String, String)> = {
            let mut stmt = c
                .prepare(
                    "SELECT id, agent_id, action, summary FROM approvals WHERE status='pending' ORDER BY id",
                )
                .unwrap();
            stmt.query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)))
                .unwrap()
                .flatten()
                .collect()
        };
        drop(c);
        if rows.is_empty() {
            bot.send_message(msg.chat.id, "No pending approvals.")
                .await?;
        } else {
            let mut out = String::from("Pending approvals:\n");
            for (id, agent, action, summary) in rows {
                out.push_str(&format!(
                    "#{id} {agent} · {action}: {}\n",
                    render_plain(&summary)
                ));
            }
            bot.send_message(msg.chat.id, out).await?;
        }
    } else if trimmed == "/start" || trimmed == "/help" {
        let body = match state.manager.as_deref() {
            Some(mgr) => format!(
                "teamctl bot — connected to {mgr}\n\
                 Just type a message and it goes straight to {mgr}.\n\
                 /pending — show pending approvals\n\
                 /dm <project>:<agent> <text> — send to a different agent (rare)\n\
                 /<cmd> — slash-passthrough to {mgr}'s tmux session (Claude Code only)"
            ),
            None => "teamctl — Telegram interface\n\
                     /dm <project>:<agent> <message> — send a DM\n\
                     /pending — show pending approvals"
                .into(),
        };
        bot.send_message(msg.chat.id, body).await?;
    } else if trimmed.starts_with('/') && state.manager.is_some() {
        // T-086-G slash-passthrough: any unrecognised slash command on a
        // manager-scoped bot gets typed straight into the manager's tmux
        // session via `tmux send-keys`. Feature-gated on `runtime: claude-code`
        // per Decision 6 (manager-only routing). Trust posture is "operator
        // owns the bot" per Decision 7 — no allowlist on slash content; the
        // bot is per-operator and chat-id-gated, the trust boundary is the
        // same as the operator's existing `tmux attach` access.
        let manager = state.manager.as_deref().unwrap();
        let runtime_opt = {
            let c = state.conn.lock().await;
            agent_runtime(&c, manager)
        };
        let Some(runtime) = runtime_opt else {
            bot.send_message(
                msg.chat.id,
                format!("unknown manager `{manager}` — slash-passthrough aborted"),
            )
            .await?;
            return Ok(());
        };
        match slash_outcome(manager, &runtime, &state.tmux_prefix) {
            SlashOutcome::Passthrough { session } => match tmux_send_keys(&session, trimmed) {
                Ok(()) => {
                    bot.send_message(msg.chat.id, format!("{manager}"))
                        .await?;
                }
                Err(err) => {
                    bot.send_message(msg.chat.id, format!("tmux error: {err}"))
                        .await?;
                }
            },
            SlashOutcome::Reject { reason } => {
                bot.send_message(msg.chat.id, reason).await?;
            }
        }
    }
    Ok(())
}

async fn handle_callback(bot: Bot, q: CallbackQuery, state: Arc<State>) -> ResponseResult<()> {
    let chat_id = q.message.as_ref().map(|m| m.chat().id.0).unwrap_or(0);
    if !state.is_authorized(chat_id) {
        return Ok(());
    }
    let Some(data) = q.data.clone() else {
        return Ok(());
    };
    let Some((verb, id_str)) = data.split_once(':') else {
        return Ok(());
    };
    let Ok(id) = id_str.parse::<i64>() else {
        return Ok(());
    };
    let approved = verb == "approve";

    // Atomic decision: only update if still pending. Returned row count tells
    // us whether this tap was the live decision or a stale duplicate.
    //
    // Order matters: status pin first, delivered_at flip second and
    // *only* when the status pin succeeded. The reverse order — flip
    // delivered_at unconditionally, then try the status pin — would
    // break the invariant `undeliverable ↔ delivered_at IS NULL` on
    // stale taps against rows that gc already moved to undeliverable.
    let decided_now = {
        let c = state.conn.lock().await;
        let n = c
            .execute(
                "UPDATE approvals SET status=?1, decided_at=strftime('%s','now'), decided_by='user:telegram'
                 WHERE id=?2 AND status='pending'",
                params![if approved { "approved" } else { "denied" }, id],
            )
            .map(|n| n > 0)
            .unwrap_or(false);
        if n {
            let _ = c.execute(
                "UPDATE approvals SET delivered_at=strftime('%s','now')
                 WHERE id=?1 AND delivered_at IS NULL",
                params![id],
            );
        }
        n
    };

    if !decided_now {
        // Stale tap: row already terminal. Friendly toast, leave the message.
        bot.answer_callback_query(q.id)
            .text(format!("#{id} already resolved"))
            .await?;
        return Ok(());
    }

    // Live decision: edit the original message in-place to (a) append the
    // outcome line and (b) drop the inline buttons so the card can't be
    // re-clicked.
    if let Some(msg) = q.message.as_ref() {
        let chat = msg.chat().id;
        let mid = msg.id();
        let original = msg.regular_message().and_then(|m| m.text()).unwrap_or("");
        let outcome = if approved {
            "✅ Approved by Alireza"
        } else {
            "❌ Rejected by Alireza"
        };
        let new_text = if original.is_empty() {
            outcome.to_string()
        } else {
            format!("{original}\n\n{outcome}")
        };
        let _ = bot.edit_message_text(chat, mid, new_text).await;
        let _ = bot
            .edit_message_reply_markup(chat, mid)
            .reply_markup(InlineKeyboardMarkup::new(Vec::<Vec<_>>::new()))
            .await;
    }

    bot.answer_callback_query(q.id)
        .text(format!("{} #{id}", if approved { "" } else { "" }))
        .await?;
    Ok(())
}

async fn outbound_loop(bot: Bot, state: Arc<State>) {
    let Some(&primary) = state.allow.first() else {
        tracing::warn!("no authorized_chat_ids — outbound disabled");
        return;
    };
    let chat = ChatId(primary);
    let mut last_approval_id: i64 = current_max(&state, "approvals").await;
    let mut last_msg_id: i64 = current_max(&state, "messages").await;

    loop {
        tokio::time::sleep(Duration::from_millis(500)).await;

        // Project-scope filter only — manager-level routing happens in Rust
        // below so that scoped bots only surface approvals filed by agents
        // that roll up to *their* manager (T-027 single-channel).
        let approvals: Vec<(i64, String, String, String)> = {
            let c = state.conn.lock().await;
            let rows: Vec<(i64, String, String, String)> = match state.manager_project() {
                Some(project) => {
                    let mut stmt = c
                        .prepare(
                            "SELECT id, agent_id, action, summary FROM approvals
                             WHERE status='pending' AND id > ?1 AND project_id = ?2
                             ORDER BY id",
                        )
                        .unwrap();
                    stmt.query_map(params![last_approval_id, project], |r| {
                        Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
                    })
                    .unwrap()
                    .flatten()
                    .collect()
                }
                None => {
                    let mut stmt = c
                        .prepare(
                            "SELECT id, agent_id, action, summary FROM approvals
                             WHERE status='pending' AND id > ?1 ORDER BY id",
                        )
                        .unwrap();
                    stmt.query_map(params![last_approval_id], |r| {
                        Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?))
                    })
                    .unwrap()
                    .flatten()
                    .collect()
                }
            };
            rows
        };
        for (id, agent, action, summary) in approvals {
            last_approval_id = last_approval_id.max(id);
            // T-027: when scoped to a manager, only surface approvals filed by
            // agents that report up to *this* bot's manager. With a manager
            // bot per tier (eng_lead, pm) Alireza sees one prompt per agent.
            // Unscoped bots take the back-compat path (route everything).
            let route_ok = {
                let c = state.conn.lock().await;
                should_route(state.manager.as_deref(), &agent, &c)
            };
            if !route_ok {
                continue;
            }
            let kb = InlineKeyboardMarkup::new(vec![vec![
                InlineKeyboardButton::callback("Approve", format!("approve:{id}")),
                InlineKeyboardButton::callback("Deny", format!("deny:{id}")),
            ]]);
            let text = format!(
                "🔐 #{id}  {agent}\naction: {action}\n{}",
                render_plain(&summary)
            );
            let send_ok = bot.send_message(chat, text).reply_markup(kb).await.is_ok();
            if send_ok {
                let c = state.conn.lock().await;
                let _ = c.execute(
                    "UPDATE approvals SET delivered_at=strftime('%s','now')
                     WHERE id=?1 AND delivered_at IS NULL",
                    params![id],
                );
            }
        }

        // Forward replies addressed to the human. The agent-side `reply_to_user`
        // tool inserts rows with `recipient = 'user:telegram'`. Project-scope
        // is the SQL pre-filter; manager-level routing happens in Rust below
        // via `should_route` so multiple bots in the same project (one per
        // manager) don't fan out the same reply.
        //
        // T-086-A: rows now carry `kind` + `structured_payload` for image and
        // file content. NULL `kind` means text (legacy callers + the
        // text-only `reply_to_user` path), preserving back-compat against
        // older databases without a forced migration.
        let forwardable: Vec<MailboxRow> = {
            let c = state.conn.lock().await;
            let rows: Vec<MailboxRow> = match state.manager_project() {
                Some(project) => {
                    let mut stmt = c
                        .prepare(
                            "SELECT m.id, m.sender, m.text, m.kind, m.structured_payload,
                                    m.telegram_msg_id
                             FROM messages m
                             WHERE m.id > ?1
                               AND m.recipient = 'user:telegram'
                               AND m.acked_at IS NULL
                               AND m.project_id = ?2
                             ORDER BY m.id",
                        )
                        .unwrap();
                    stmt.query_map(params![last_msg_id, project], MailboxRow::from_row)
                        .unwrap()
                        .flatten()
                        .collect()
                }
                None => {
                    let mut stmt = c
                        .prepare(
                            "SELECT m.id, m.sender, m.text, m.kind, m.structured_payload,
                                    m.telegram_msg_id
                             FROM messages m
                             WHERE m.id > ?1
                               AND m.recipient = 'user:telegram'
                               AND m.acked_at IS NULL
                             ORDER BY m.id",
                        )
                        .unwrap();
                    stmt.query_map(params![last_msg_id], MailboxRow::from_row)
                        .unwrap()
                        .flatten()
                        .collect()
                }
            };
            rows
        };
        for row in forwardable {
            last_msg_id = last_msg_id.max(row.id);
            // Per-manager scoping: only forward replies whose sender rolls up
            // to *this* bot's manager. Without this, every bot in the project
            // forwarded every reply (e.g. eng_lead's reply landing in pm and
            // marketing chats too). Unscoped bots take the back-compat path.
            let route_ok = {
                let c = state.conn.lock().await;
                should_route(state.manager.as_deref(), &row.sender, &c)
            };
            if !route_ok {
                continue;
            }
            forward_row(&bot, chat, &row).await;
            let c = state.conn.lock().await;
            let _ = c.execute(
                "UPDATE messages SET acked_at = strftime('%s','now') WHERE id = ?1",
                params![row.id],
            );
        }
    }
}

/// One mailbox row in the shape the outbound loop forwards. `kind` is `None`
/// for legacy text rows; structured kinds (image, file) carry the JSON
/// payload describing source + value + optional caption. `telegram_msg_id`
/// (T-086-B) is the Telegram message id this row should reply to — when
/// `Some`, the dispatcher attaches `reply_parameters` so the outbound
/// message visually nests under the operator's earlier message.
#[derive(Debug, Clone)]
struct MailboxRow {
    id: i64,
    sender: String,
    text: String,
    kind: Option<String>,
    payload: Option<String>,
    telegram_msg_id: Option<i64>,
}

impl MailboxRow {
    fn from_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
        Ok(Self {
            id: r.get(0)?,
            sender: r.get(1)?,
            text: r.get(2)?,
            kind: r.get(3)?,
            payload: r.get(4)?,
            telegram_msg_id: r.get(5)?,
        })
    }
}

/// Build a teloxide `ReplyParameters` from a stored Telegram message id, or
/// `None` when no threading is requested. Pulled out so unit tests pin the
/// presence/absence call without spinning up a real `Bot` — the `i32` cast
/// is safe because Telegram message ids stay within `i32` range.
fn reply_parameters_for(telegram_msg_id: Option<i64>) -> Option<ReplyParameters> {
    telegram_msg_id.map(|id| ReplyParameters::new(MessageId(id as i32)))
}

/// Parsed structured payload — `source` ("path"|"url"), `value` (the path or
/// URL), optional caption. `parse_payload` turns the JSON string into this
/// shape; failure cases fall back to text rendering with the raw payload
/// surfaced so the operator still sees something.
struct MediaPayload {
    source: String,
    value: String,
    caption: Option<String>,
}

fn parse_payload(payload: &str) -> Option<MediaPayload> {
    let v: serde_json::Value = serde_json::from_str(payload).ok()?;
    let source = v.get("source")?.as_str()?.to_string();
    let value = v.get("value")?.as_str()?.to_string();
    let caption = v
        .get("caption")
        .and_then(|c| c.as_str())
        .map(|s| s.to_string());
    Some(MediaPayload {
        source,
        value,
        caption,
    })
}

/// Build a teloxide `InputFile` from a parsed payload's source + value.
/// `path` resolves to a local file; `url` parses the value as a URL the
/// Telegram servers fetch directly.
fn input_file_from(payload: &MediaPayload) -> Option<InputFile> {
    match payload.source.as_str() {
        "path" => Some(InputFile::file(&payload.value)),
        "url" => Some(InputFile::url(payload.value.parse().ok()?)),
        _ => None,
    }
}

/// Decision the dispatcher makes for a row's `kind`. Kept as a plain enum so
/// it's testable without instantiating a teloxide `Bot`; the actual API call
/// happens in `forward_row` once the decision is made.
#[derive(Debug, PartialEq, Eq)]
enum DispatchKind {
    Text,
    Image,
    File,
    /// T-086-E: outbound reaction. Payload carries `{telegram_msg_id, emoji}`;
    /// the dispatcher routes through `setMessageReaction` rather than
    /// sending a chat message.
    Reaction,
    /// Structured row whose payload didn't parse — surface as a text
    /// fallback so the operator sees the raw payload rather than nothing.
    UnknownFallback,
}

fn classify_kind(kind: Option<&str>) -> DispatchKind {
    match kind {
        None | Some("text") | Some("") => DispatchKind::Text,
        Some("image") => DispatchKind::Image,
        Some("file") => DispatchKind::File,
        Some("reaction") => DispatchKind::Reaction,
        _ => DispatchKind::UnknownFallback,
    }
}

/// Parsed reaction payload (T-086-E). The MCP layer writes
/// `{"telegram_msg_id": <i64>, "emoji": "<str>"}`; this turns it back into a
/// typed pair the dispatcher hands to `setMessageReaction`. Returns `None`
/// when either field is missing or the wrong shape — the dispatcher's
/// fallback then logs and skips rather than calling Telegram with bogus
/// args.
struct ReactionPayload {
    telegram_msg_id: i64,
    emoji: String,
}

fn parse_reaction_payload(payload: &str) -> Option<ReactionPayload> {
    let v: serde_json::Value = serde_json::from_str(payload).ok()?;
    let telegram_msg_id = v.get("telegram_msg_id")?.as_i64()?;
    let emoji = v.get("emoji")?.as_str()?.to_string();
    Some(ReactionPayload {
        telegram_msg_id,
        emoji,
    })
}

async fn forward_row(bot: &Bot, chat: ChatId, row: &MailboxRow) {
    let kind = classify_kind(row.kind.as_deref());
    let attribution = format!("\n\n— replied by {}", row.sender);
    let reply = reply_parameters_for(row.telegram_msg_id);
    match kind {
        DispatchKind::Text => {
            let mut req =
                bot.send_message(chat, format!("{}{attribution}", render_plain(&row.text)));
            if let Some(rp) = reply.clone() {
                req = req.reply_parameters(rp);
            }
            let _ = req.await;
        }
        DispatchKind::Image | DispatchKind::File => {
            let Some(payload) = row.payload.as_deref().and_then(parse_payload) else {
                let _ = bot
                    .send_message(
                        chat,
                        format!(
                            "{} (media payload unparseable){attribution}",
                            render_plain(&row.text)
                        ),
                    )
                    .await;
                return;
            };
            let Some(input) = input_file_from(&payload) else {
                let _ = bot
                    .send_message(
                        chat,
                        format!(
                            "{} (unsupported media source `{}`){attribution}",
                            render_plain(&row.text),
                            payload.source
                        ),
                    )
                    .await;
                return;
            };
            let caption_text = payload
                .caption
                .as_deref()
                .map(|c| format!("{}{attribution}", render_plain(c)))
                .unwrap_or_else(|| attribution.trim_start().to_string());
            let result = match kind {
                DispatchKind::Image => {
                    let mut req = bot.send_photo(chat, input).caption(caption_text);
                    if let Some(rp) = reply.clone() {
                        req = req.reply_parameters(rp);
                    }
                    req.await.err()
                }
                DispatchKind::File => {
                    let mut req = bot.send_document(chat, input).caption(caption_text);
                    if let Some(rp) = reply.clone() {
                        req = req.reply_parameters(rp);
                    }
                    req.await.err()
                }
                _ => unreachable!(),
            };
            if let Some(e) = result {
                tracing::warn!(
                    "send_{} failed for mailbox row {}: {e}",
                    if kind == DispatchKind::Image {
                        "photo"
                    } else {
                        "document"
                    },
                    row.id
                );
            }
        }
        DispatchKind::Reaction => {
            // T-086-E: reactions ride the existing kind discriminator; the
            // dispatcher routes through `setMessageReaction` instead of a
            // send-message call. Failure-mode (unparseable payload) logs +
            // skips — no operator-visible chat noise, since a reaction is
            // a soft signal anyway. Telegram-side rejection (not in chat,
            // emoji disallowed, etc.) bubbles up via `tracing::warn!`.
            let Some(reaction) = row.payload.as_deref().and_then(parse_reaction_payload) else {
                tracing::warn!(
                    "reaction payload unparseable for mailbox row {} (skipping)",
                    row.id
                );
                return;
            };
            let result = bot
                .set_message_reaction(chat, MessageId(reaction.telegram_msg_id as i32))
                .reaction(vec![ReactionType::Emoji {
                    emoji: reaction.emoji,
                }])
                .await
                .err();
            if let Some(e) = result {
                tracing::warn!("set_message_reaction failed for row {}: {e}", row.id);
            }
        }
        DispatchKind::UnknownFallback => {
            let _ = bot
                .send_message(chat, format!("{}{attribution}", render_plain(&row.text)))
                .await;
        }
    }
}

async fn current_max(state: &Arc<State>, table: &str) -> i64 {
    let sql = format!("SELECT COALESCE(MAX(id), 0) FROM {table}");
    let c = state.conn.lock().await;
    c.query_row(&sql, [], |r| r.get(0)).unwrap_or(0)
}

/// Resolve the `<project>:<manager>` an agent rolls up to, used by T-027 to
/// route an approval to exactly one Telegram bot. Managers report to themselves
/// (no walk needed); non-managers resolve via `agents.reports_to`. Returns
/// `None` if the agent isn't registered.
fn manager_of(conn: &Connection, agent_id: &str) -> Option<String> {
    let row: Option<(String, i64, Option<String>)> = conn
        .query_row(
            "SELECT project_id, is_manager, reports_to FROM agents WHERE id = ?1",
            params![agent_id],
            |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
        )
        .ok();
    let (project, is_manager, reports_to) = row?;
    if is_manager == 1 {
        return Some(agent_id.to_string());
    }
    let role = reports_to?;
    Some(format!("{project}:{role}"))
}

/// Route an approval row to *this* bot iff:
/// - `scoped` is `None` (unscoped bot — back-compat fallback for setups
///   that predate per-manager scoping; surface every approval), or
/// - `scoped` is `Some(<project>:<manager>)` and the agent that filed
///   the approval rolls up to that manager (per `manager_of`).
///
/// Pulled out as a free function so the unscoped-vs-scoped semantics
/// are unit-testable without spinning up an async tokio runtime.
fn should_route(scoped: Option<&str>, agent_id: &str, conn: &Connection) -> bool {
    let Some(scoped) = scoped else {
        return true;
    };
    let routed = manager_of(conn, agent_id).unwrap_or_else(|| agent_id.to_string());
    routed == scoped
}

/// Look up the registered runtime for an agent. Used by slash-passthrough
/// (T-086-G) to feature-gate the chord on `runtime: claude-code` and by
/// the setMyCommands registration (T-086-H) to pick the per-runtime
/// command list. Returns `None` if the agent isn't in the mailbox's
/// `agents` table.
fn agent_runtime(conn: &Connection, agent_id: &str) -> Option<String> {
    conn.query_row(
        "SELECT runtime FROM agents WHERE id = ?1",
        params![agent_id],
        |r| r.get::<_, String>(0),
    )
    .ok()
}

/// Decision returned by `slash_outcome` — either we have a tmux session to
/// type the slash command into, or a user-facing rejection message.
#[derive(Debug, PartialEq, Eq)]
enum SlashOutcome {
    Passthrough { session: String },
    Reject { reason: String },
}

/// Pure decision: given the manager id (`<project>:<role>`), the manager's
/// runtime, and the configured tmux prefix, decide whether slash-passthrough
/// fires and against which tmux session. Non-Claude-Code runtimes are
/// rejected per Decision 6 (manager-only / CC-only routing); the rejection
/// message names the actual runtime so the operator sees why.
fn slash_outcome(manager: &str, runtime: &str, tmux_prefix: &str) -> SlashOutcome {
    if runtime != "claude-code" {
        return SlashOutcome::Reject {
            reason: format!(
                "slash-passthrough is only supported on Claude Code agents \
                 (this manager runs `{runtime}`)."
            ),
        };
    }
    let (project, role) = match manager.split_once(':') {
        Some((p, r)) => (p, r),
        None => {
            return SlashOutcome::Reject {
                reason: format!("malformed manager id `{manager}` (expected `project:role`)."),
            };
        }
    };
    SlashOutcome::Passthrough {
        session: format!("{tmux_prefix}{project}-{role}"),
    }
}

/// Argv for the tmux send-keys invocation. Pulled out so unit tests pin the
/// exact arg shape without spinning up tmux. The literal `Enter` keyword is
/// what tells tmux to fire a Return after the body, which is what triggers
/// the Claude Code prompt to actually process the slash command.
fn tmux_send_keys_argv<'a>(session: &'a str, body: &'a str) -> [&'a str; 5] {
    ["send-keys", "-t", session, body, "Enter"]
}

/// Real-world tmux send-keys wrapper. On failure, returns the verbatim error
/// (R12 family — surface the cause to the operator rather than silent drop).
fn tmux_send_keys(session: &str, body: &str) -> Result<(), String> {
    let argv = tmux_send_keys_argv(session, body);
    let output = Command::new("tmux")
        .args(argv)
        .output()
        .map_err(|e| format!("invoke tmux: {e}"))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        let trimmed = stderr.trim();
        if trimmed.is_empty() {
            return Err(format!("tmux exit {}", output.status));
        }
        return Err(format!("tmux exit {}: {trimmed}", output.status));
    }
    Ok(())
}

/// Curated subset of Claude Code slash commands surfaced via Telegram's
/// `setMyCommands` API (T-086-H). Telegram restricts the `command` field to
/// lowercase letters, digits, and underscores — the hyphenated CC commands
/// (`output-style`, `pr-comments`, `release-notes`, `security-review`) are
/// excluded for that reason; operators can still type them manually and the
/// slash-passthrough lane (T-086-G) routes them to tmux just fine. Login
/// flows (`login`, `logout`, `upgrade`) are also excluded — those are
/// awkward over chat and rarely the daily-driver path.
///
/// **Maintenance note**: this list is hand-maintained on Claude Code
/// version bumps. Drift cost is bounded — the CC slash command set is
/// stable across patch releases. The dynamic-discovery alternative (parse
/// CC's `/help` output at startup) is heavier substrate for marginal gain.
/// Refresh in a polish-PR when CC ships a new minor version.
const CC_SLASH_COMMANDS: &[(&str, &str)] = &[
    ("clear", "Clear conversation history"),
    (
        "compact",
        "Compact conversation, optionally with focus instructions",
    ),
    ("cost", "Show token usage cost"),
    ("help", "Show available commands and shortcuts"),
    ("init", "Initialize a new CLAUDE.md file"),
    ("mcp", "Manage MCP servers"),
    ("model", "Set the AI model for Claude Code"),
    ("permissions", "View and edit permissions"),
    ("resume", "Resume a previous conversation"),
    ("review", "Review a pull request"),
    ("status", "Show Claude Code status"),
    ("vim", "Toggle between vim and default editing modes"),
];

/// Build the runtime-appropriate `BotCommand` list for `setMyCommands`. CC
/// managers get `CC_SLASH_COMMANDS`; everything else (codex, gemini,
/// unknown, unscoped) gets an empty list — clean degrade per Decision 6
/// (manager-only / CC-only routing). Pulled out as a free function so the
/// per-runtime mapping is unit-testable without a real Telegram bot.
fn commands_for_runtime(runtime: Option<&str>) -> Vec<BotCommand> {
    match runtime {
        Some("claude-code") => CC_SLASH_COMMANDS
            .iter()
            .map(|(c, d)| BotCommand::new(*c, *d))
            .collect(),
        _ => Vec::new(),
    }
}

// ── T-086-C inbound media ───────────────────────────────────────

/// Photo vs. document — used to label the mailbox row's `kind`. The disk
/// path naming is the same either way (`<row_id>.<ext>`), so this just
/// drives the discriminator the agent reads via `inbox_peek`.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum MediaKind {
    Image,
    File,
}

/// Resolved enough information to download and record an inbound media
/// message. `file_id` feeds `bot.get_file`; `extension` + `mime` ride into
/// the structured payload so the agent can pick a vision-content shape on
/// its own runtime.
struct MediaIntent {
    file_id: String,
    extension: String,
    mime: String,
    kind: MediaKind,
}

/// Pick the largest photo size or fall back to a document; returns `None`
/// when the message carries neither (caller should defer to the text path).
/// Pulled out of `handle_inbound_media` so the picking rule is unit-testable
/// without standing up a fake `Bot`.
fn classify_media_intent(msg: &Message) -> Option<MediaIntent> {
    if let Some(photos) = msg.photo() {
        // Telegram delivers photos as a list of `PhotoSize` thumbnails — pick
        // the largest by pixel count so the agent gets the highest fidelity
        // available. Telegram's photo storage is always JPEG regardless of
        // upload format, so we hard-code the extension + mime.
        let largest = photos
            .iter()
            .max_by_key(|p| (p.width as u64).saturating_mul(p.height as u64))?;
        return Some(MediaIntent {
            file_id: largest.file.id.clone(),
            extension: "jpg".into(),
            mime: "image/jpeg".into(),
            kind: MediaKind::Image,
        });
    }
    if let Some(doc) = msg.document() {
        let mime = doc
            .mime_type
            .as_ref()
            .map(|m| m.essence_str().to_string())
            .unwrap_or_else(|| "application/octet-stream".to_string());
        let extension = extension_for_document(doc.file_name.as_deref(), &mime);
        // Telegram users often upload PNG/GIF as document (which preserves
        // the original bytes vs. the jpeg recompression of `photo`); route
        // those as Image so the agent's vision plumbing still picks them up.
        let kind = if mime.starts_with("image/") {
            MediaKind::Image
        } else {
            MediaKind::File
        };
        return Some(MediaIntent {
            file_id: doc.file.id.clone(),
            extension,
            mime,
            kind,
        });
    }
    None
}

/// Pick the file extension to use for a document upload. Prefer the
/// uploaded filename's extension when it's a clean ASCII alphanumeric
/// suffix; fall back to the mime-type lookup table otherwise. Defensive
/// against names like `report.pdf.bak` (uses `bak`) or `evil/../traversal`
/// (the rsplit_once on '.' won't match a path separator on its own, but the
/// alphanumeric guard keeps the result tame).
fn extension_for_document(filename: Option<&str>, mime: &str) -> String {
    if let Some(name) = filename {
        if let Some((_, ext)) = name.rsplit_once('.') {
            if !ext.is_empty() && ext.len() <= 8 && ext.chars().all(|c| c.is_ascii_alphanumeric()) {
                return ext.to_ascii_lowercase();
            }
        }
    }
    extension_from_mime(mime).into()
}

/// Mime → file-extension lookup. Covers the common Telegram-deliverable
/// shapes; everything unknown falls to `bin` so the on-disk file still
/// exists and an agent can re-mime it via libmagic if it cares.
fn extension_from_mime(mime: &str) -> &'static str {
    match mime {
        "image/png" => "png",
        "image/jpeg" => "jpg",
        "image/webp" => "webp",
        "image/gif" => "gif",
        "application/pdf" => "pdf",
        "text/plain" => "txt",
        "text/csv" => "csv",
        "application/zip" => "zip",
        "application/json" => "json",
        _ => "bin",
    }
}

/// Compose the on-disk path for an inbound media row. `media_root` is the
/// directory configured at startup (defaults to `<mailbox-parent>/inbound-
/// media/`); the per-project subdirectory keeps a multi-project mailbox
/// from colliding row ids across projects.
fn inbound_media_path(media_root: &Path, project: &str, row_id: i64, extension: &str) -> PathBuf {
    media_root
        .join(project)
        .join(format!("{row_id}.{extension}"))
}

/// JSON shape for a successful media row. Empty captions are omitted so
/// agents reading the payload don't have to special-case the empty string.
fn media_success_payload(path: &Path, caption: &str, mime: &str, size_bytes: u64) -> String {
    let mut payload = serde_json::json!({
        "path": path.display().to_string(),
        "mime": mime,
        "size_bytes": size_bytes,
    });
    if !caption.is_empty() {
        payload["caption"] = serde_json::Value::String(caption.to_string());
    }
    payload.to_string()
}

/// JSON shape for a failed media row (R12 — no silent drops). Captures the
/// verbatim error so the agent can ack to the user with a real diagnostic.
fn media_error_payload(caption: &str, error: &str) -> String {
    let mut payload = serde_json::json!({ "error": error });
    if !caption.is_empty() {
        payload["caption"] = serde_json::Value::String(caption.to_string());
    }
    payload.to_string()
}

/// Stream a Telegram-hosted file to disk via `bot.get_file` + `bot.download_file`.
/// On any error returns a verbatim `String` so the caller can fold it into
/// the `media_error` mailbox row + the user-facing reply.
async fn download_to(bot: &Bot, file_id: &str, path: &Path, dir: &Path) -> Result<u64, String> {
    use tokio::io::AsyncWriteExt;
    tokio::fs::create_dir_all(dir)
        .await
        .map_err(|e| format!("create_dir_all `{}`: {e}", dir.display()))?;
    let file = bot
        .get_file(file_id)
        .await
        .map_err(|e| format!("get_file: {e}"))?;
    let mut handle = tokio::fs::File::create(path)
        .await
        .map_err(|e| format!("create file `{}`: {e}", path.display()))?;
    bot.download_file(&file.path, &mut handle)
        .await
        .map_err(|e| format!("download_file: {e}"))?;
    handle.flush().await.ok();
    drop(handle);
    let meta = tokio::fs::metadata(path)
        .await
        .map_err(|e| format!("metadata: {e}"))?;
    Ok(meta.len())
}

/// Branch from `handle_message` for inbound photo/document. The two-phase
/// SQL pattern (insert placeholder → download → UPDATE on success or error)
/// keeps the row visible to the agent's `inbox_peek` from the moment the
/// message arrives — so an agent can see "media pending" while the download
/// races a slow link, rather than nothing for an unbounded stretch.
async fn handle_inbound_media(bot: &Bot, msg: &Message, state: &State) -> ResponseResult<()> {
    let Some(manager) = state.manager.as_deref() else {
        bot.send_message(
            msg.chat.id,
            "media uploads need a manager-scoped bot. \
             Run `teamctl bot up` to attach this bot to a manager.",
        )
        .await?;
        return Ok(());
    };
    let Some((project, _)) = manager.split_once(':') else {
        // `bot setup` validates this — defensive only.
        return Ok(());
    };
    let Some(intent) = classify_media_intent(msg) else {
        return Ok(());
    };
    let caption = msg.caption().unwrap_or("").to_string();

    // Insert a `media_pending` row first so we have a stable rowid to name
    // the disk file with. Caller will UPDATE the row to `image`/`file` (or
    // `media_error`) once the download resolves.
    let placeholder_payload = serde_json::json!({ "caption": caption }).to_string();
    let row_id_opt = {
        let c = state.conn.lock().await;
        match c.execute(
            "INSERT INTO messages
                (project_id, sender, recipient, text, sent_at, kind, structured_payload)
             VALUES (?1, 'user:telegram', ?2, ?3, strftime('%s','now'),
                     'media_pending', ?4)",
            params![project, manager, &caption, placeholder_payload],
        ) {
            Ok(_) => Some(c.last_insert_rowid()),
            Err(e) => {
                tracing::error!("inbound media: failed to insert placeholder row: {e}");
                None
            }
        }
    };
    let Some(row_id) = row_id_opt else {
        bot.send_message(
            msg.chat.id,
            "internal error: could not record the message; please retry.",
        )
        .await?;
        return Ok(());
    };

    let path = inbound_media_path(&state.media_root, project, row_id, &intent.extension);
    let dir = path.parent().unwrap_or(&state.media_root).to_path_buf();
    match download_to(bot, &intent.file_id, &path, &dir).await {
        Ok(size_bytes) => {
            let payload = media_success_payload(&path, &caption, &intent.mime, size_bytes);
            let kind = match intent.kind {
                MediaKind::Image => "image",
                MediaKind::File => "file",
            };
            let c = state.conn.lock().await;
            let _ = c.execute(
                "UPDATE messages SET kind = ?1, structured_payload = ?2 WHERE id = ?3",
                params![kind, payload, row_id],
            );
            drop(c);
            bot.send_message(msg.chat.id, format!("{manager}"))
                .await?;
        }
        Err(err) => {
            let payload = media_error_payload(&caption, &err);
            let c = state.conn.lock().await;
            let _ = c.execute(
                "UPDATE messages SET kind = 'media_error', structured_payload = ?1 WHERE id = ?2",
                params![payload, row_id],
            );
            drop(c);
            bot.send_message(msg.chat.id, format!("media download failed: {err}"))
                .await?;
        }
    }
    Ok(())
}

/// Strip lightweight markdown so Telegram renders clean prose with emoji
/// accents instead of literal `**bold**` / `_italic_` / `- bullet` syntax.
/// We deliberately do not translate to MarkdownV2 — Alireza prefers plain
/// text, and stripping is failure-mode-symmetric (no escaping landmines).
fn render_plain(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for (idx, line) in s.lines().enumerate() {
        if idx > 0 {
            out.push('\n');
        }
        let trimmed = line.trim_start();
        let leading = &line[..line.len() - trimmed.len()];
        let body = if let Some(rest) = trimmed
            .strip_prefix("- ")
            .or_else(|| trimmed.strip_prefix("* "))
            .or_else(|| trimmed.strip_prefix("+ "))
        {
            format!("{rest}")
        } else {
            trimmed.to_string()
        };
        out.push_str(leading);
        out.push_str(&strip_inline_markdown(&body));
    }
    out
}

/// Drop `**`, `__`, single `*` / `_` emphasis, and inline-code backticks.
/// Keeps URL text intact (we never see `[label](url)` rendered as a link
/// anyway in plain Telegram messages).
fn strip_inline_markdown(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if (c == '*' || c == '_') && chars.peek() == Some(&c) {
            // Paired `**` / `__` emphasis → drop both.
            chars.next();
            continue;
        }
        if c == '*' || c == '_' || c == '`' {
            continue;
        }
        out.push(c);
    }
    out
}

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

    fn seed(conn: &Connection) {
        team_core::mailbox::ensure(conn).unwrap();
        conn.execute(
            "INSERT OR IGNORE INTO projects (id, name) VALUES ('p','P')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT OR IGNORE INTO agents (id, project_id, role, runtime, is_manager, reports_to)
             VALUES ('p:eng_lead','p','eng_lead','claude-code',1,NULL)",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT OR IGNORE INTO agents (id, project_id, role, runtime, is_manager, reports_to)
             VALUES ('p:dev1','p','dev1','claude-code',0,'eng_lead')",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT OR IGNORE INTO agents (id, project_id, role, runtime, is_manager, reports_to)
             VALUES ('p:pm','p','pm','claude-code',1,NULL)",
            [],
        )
        .unwrap();
    }

    #[test]
    fn manager_of_returns_self_for_a_manager() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        assert_eq!(
            manager_of(&conn, "p:eng_lead").as_deref(),
            Some("p:eng_lead")
        );
        assert_eq!(manager_of(&conn, "p:pm").as_deref(), Some("p:pm"));
    }

    #[test]
    fn manager_of_resolves_reports_to_for_a_worker() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        assert_eq!(manager_of(&conn, "p:dev1").as_deref(), Some("p:eng_lead"));
    }

    #[test]
    fn manager_of_returns_none_for_unknown_agent() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        assert!(manager_of(&conn, "p:ghost").is_none());
    }

    // ── T-086-A dispatch tests ──────────────────────────────────

    #[test]
    fn classify_kind_treats_null_and_empty_as_text() {
        // Back-compat pin: rows from before T-086-A migration have NULL
        // kind; rows inserted via legacy `send_dm` still leave it NULL.
        // Both must dispatch as plain text — otherwise older databases
        // would suddenly fail the unknown-kind path.
        assert_eq!(classify_kind(None), DispatchKind::Text);
        assert_eq!(classify_kind(Some("text")), DispatchKind::Text);
        assert_eq!(classify_kind(Some("")), DispatchKind::Text);
    }

    #[test]
    fn classify_kind_routes_image_and_file() {
        assert_eq!(classify_kind(Some("image")), DispatchKind::Image);
        assert_eq!(classify_kind(Some("file")), DispatchKind::File);
    }

    #[test]
    fn classify_kind_falls_back_for_unknown_kinds() {
        // Forward-compat: kinds the binary doesn't recognise surface as
        // a text fallback rather than panicking. T-086-A's prophetic
        // example ("reaction") landed in T-086-E and now routes to its
        // own arm (covered by `classify_kind_routes_reaction`); the
        // fallback test stays useful by pinning truly-unknown strings.
        assert_eq!(
            classify_kind(Some("garbage")),
            DispatchKind::UnknownFallback
        );
        assert_eq!(classify_kind(Some("custom")), DispatchKind::UnknownFallback);
    }

    #[test]
    fn parse_payload_extracts_source_value_and_caption() {
        let p = parse_payload(r#"{"source":"path","value":"/tmp/x.png","caption":"hi"}"#)
            .expect("payload parses");
        assert_eq!(p.source, "path");
        assert_eq!(p.value, "/tmp/x.png");
        assert_eq!(p.caption.as_deref(), Some("hi"));
    }

    #[test]
    fn parse_payload_handles_missing_caption() {
        let p = parse_payload(r#"{"source":"url","value":"https://x.test/a.png"}"#)
            .expect("payload parses");
        assert_eq!(p.source, "url");
        assert!(p.caption.is_none());
    }

    #[test]
    fn parse_payload_returns_none_on_garbage() {
        assert!(parse_payload("not json").is_none());
        assert!(
            parse_payload(r#"{"value":"x"}"#).is_none(),
            "missing source"
        );
        assert!(
            parse_payload(r#"{"source":"path"}"#).is_none(),
            "missing value"
        );
    }

    #[test]
    fn input_file_from_path_and_url_both_construct() {
        // We can't easily assert teloxide internals, but we can pin that
        // both branches return Some() — the negative case (unknown
        // source) is the regression risk and is covered by the next
        // test.
        let p = parse_payload(r#"{"source":"path","value":"/tmp/x.png"}"#).unwrap();
        assert!(input_file_from(&p).is_some());
        let p = parse_payload(r#"{"source":"url","value":"https://x.test/a.png"}"#).unwrap();
        assert!(input_file_from(&p).is_some());
    }

    #[test]
    fn input_file_from_unknown_source_returns_none() {
        let p = MediaPayload {
            source: "bytes".into(),
            value: "abc".into(),
            caption: None,
        };
        assert!(input_file_from(&p).is_none());
    }

    #[allow(clippy::too_many_arguments)]
    fn insert_row(
        conn: &Connection,
        sender: &str,
        text: &str,
        kind: Option<&str>,
        payload: Option<&str>,
        telegram_msg_id: Option<i64>,
    ) -> i64 {
        let project = sender.split_once(':').map(|(p, _)| p).unwrap_or("p");
        conn.execute(
            "INSERT INTO messages
                (project_id, sender, recipient, text, sent_at,
                 kind, structured_payload, telegram_msg_id)
             VALUES (?1, ?2, 'user:telegram', ?3, strftime('%s','now'), ?4, ?5, ?6)",
            params![project, sender, text, kind, payload, telegram_msg_id],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    /// SELECT shape `outbound_loop` runs — kept in sync with the production
    /// query so MailboxRow's column ordering stays asserted.
    const OUTBOUND_SELECT: &str =
        "SELECT m.id, m.sender, m.text, m.kind, m.structured_payload, m.telegram_msg_id
         FROM messages m
         WHERE m.id > ?1
           AND m.recipient = 'user:telegram'
           AND m.acked_at IS NULL
         ORDER BY m.id";

    #[test]
    fn outbound_select_returns_kind_and_payload_for_structured_rows() {
        // Pins the SELECT-shape contract: outbound_loop's enriched query
        // surfaces both new columns so the dispatcher can route on them.
        // Without this, a structured row would still be fetched but with
        // text-row defaults — silently degrading image/file to text.
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let id = insert_row(
            &conn,
            "p:eng_lead",
            "shot",
            Some("image"),
            Some(r#"{"source":"path","value":"/tmp/a.png"}"#),
            None,
        );
        let mut stmt = conn.prepare(OUTBOUND_SELECT).unwrap();
        let rows: Vec<MailboxRow> = stmt
            .query_map(params![0i64], MailboxRow::from_row)
            .unwrap()
            .flatten()
            .collect();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, id);
        assert_eq!(rows[0].kind.as_deref(), Some("image"));
        assert!(rows[0].payload.as_deref().unwrap().contains("/tmp/a.png"));
    }

    #[test]
    fn outbound_select_returns_null_kind_for_legacy_text_rows() {
        // Pre-T-086-A rows (and rows written by `send_dm`, which leaves
        // kind NULL) still surface in the SELECT — the dispatcher's
        // classify_kind treats NULL as Text, completing the back-compat
        // round-trip.
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let id = insert_row(&conn, "p:eng_lead", "hello", None, None, None);
        let mut stmt = conn.prepare(OUTBOUND_SELECT).unwrap();
        let rows: Vec<MailboxRow> = stmt
            .query_map(params![0i64], MailboxRow::from_row)
            .unwrap()
            .flatten()
            .collect();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, id);
        assert!(rows[0].kind.is_none());
        assert!(rows[0].payload.is_none());
        assert!(rows[0].telegram_msg_id.is_none());
        assert_eq!(classify_kind(rows[0].kind.as_deref()), DispatchKind::Text);
    }

    #[test]
    fn outbound_select_returns_telegram_msg_id_when_set_for_threaded_rows() {
        // T-086-B: outbound rows written with a `reply_to_message_id` carry
        // it forward via `telegram_msg_id`. The dispatcher reads this and
        // attaches `reply_parameters` on send. Pinning the round-trip
        // guards against future SELECT shape regressions silently dropping
        // the threading column.
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let id = insert_row(&conn, "p:eng_lead", "ack", None, None, Some(7777));
        let mut stmt = conn.prepare(OUTBOUND_SELECT).unwrap();
        let rows: Vec<MailboxRow> = stmt
            .query_map(params![0i64], MailboxRow::from_row)
            .unwrap()
            .flatten()
            .collect();
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].id, id);
        assert_eq!(rows[0].telegram_msg_id, Some(7777));
    }

    #[test]
    fn render_plain_strips_paired_emphasis() {
        assert_eq!(render_plain("**bold** text"), "bold text");
        assert_eq!(render_plain("__also bold__"), "also bold");
        assert_eq!(render_plain("plain `code` here"), "plain code here");
    }

    #[test]
    fn render_plain_strips_single_emphasis() {
        assert_eq!(render_plain("*italic* text"), "italic text");
        assert_eq!(render_plain("_underscored_"), "underscored");
    }

    #[test]
    fn render_plain_translates_list_bullets() {
        let input = "- one\n- two\n  * nested\n+ three";
        let expected = "• one\n• two\n  • nested\n• three";
        assert_eq!(render_plain(input), expected);
    }

    #[test]
    fn render_plain_preserves_emoji_and_plain_prose() {
        let input = "🔐 deploy\nrouting prompt to one channel — the **right** one";
        let expected = "🔐 deploy\nrouting prompt to one channel — the right one";
        assert_eq!(render_plain(input), expected);
    }

    /// T-036 — exercise the SQL ordering pattern used by `handle_callback`
    /// (and by `cmd::approval::decide` in teamctl) directly against a
    /// `Connection` so the ordering invariant has a unit-testable home.
    /// Asserts: a stale tap on an `undeliverable` row does *not* flip
    /// `delivered_at` (preserving the invariant
    /// `undeliverable ↔ delivered_at IS NULL`), and a live tap on a
    /// `pending` row flips both fields atomically.
    fn decide_sql(conn: &Connection, id: i64, approved: bool) -> bool {
        let status = if approved { "approved" } else { "denied" };
        let n = conn
            .execute(
                "UPDATE approvals SET status=?1, decided_at=strftime('%s','now'), decided_by='user:telegram'
                 WHERE id=?2 AND status='pending'",
                params![status, id],
            )
            .map(|n| n > 0)
            .unwrap_or(false);
        if n {
            let _ = conn.execute(
                "UPDATE approvals SET delivered_at=strftime('%s','now')
                 WHERE id=?1 AND delivered_at IS NULL",
                params![id],
            );
        }
        n
    }

    fn insert_approval(conn: &Connection, status: &str, delivered_at: Option<f64>) -> i64 {
        conn.execute(
            "INSERT INTO approvals (project_id, agent_id, action, summary, status,
                                    requested_at, expires_at, delivered_at)
             VALUES ('p', 'eng_lead', 'publish', 's', ?1, 0.0, 999999999.0, ?2)",
            params![status, delivered_at],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    #[test]
    fn stale_tap_on_undeliverable_does_not_flip_delivered_at() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let id = insert_approval(&conn, "undeliverable", None);

        let decided = decide_sql(&conn, id, true);
        assert!(!decided, "stale tap should report no live decision");

        let (status, delivered_at): (String, Option<f64>) = conn
            .query_row(
                "SELECT status, delivered_at FROM approvals WHERE id = ?1",
                params![id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(status, "undeliverable");
        assert!(
            delivered_at.is_none(),
            "delivered_at must stay NULL on undeliverable row (invariant)"
        );
    }

    #[test]
    fn live_tap_on_pending_flips_status_and_delivered_at() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let id = insert_approval(&conn, "pending", None);

        let decided = decide_sql(&conn, id, true);
        assert!(decided, "live tap should report decision");

        let (status, delivered_at): (String, Option<f64>) = conn
            .query_row(
                "SELECT status, delivered_at FROM approvals WHERE id = ?1",
                params![id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(status, "approved");
        assert!(
            delivered_at.is_some(),
            "live decision implies delivery acknowledgement"
        );
    }

    /// T-039 — unscoped bot's back-compat path: when `state.manager` is
    /// `None`, every approval routes to this bot regardless of which
    /// agent filed it. The fallback is what makes pre-T-027 setups
    /// (single team-wide bot) keep working after per-manager scoping
    /// landed.
    #[test]
    fn unscoped_bot_routes_every_approval() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        // Worker, manager, and an unknown id all route through.
        assert!(should_route(None, "p:dev1", &conn));
        assert!(should_route(None, "p:eng_lead", &conn));
        assert!(should_route(None, "p:ghost", &conn));
        // Even agents from a different (unseeded) project route through —
        // the unscoped bot is intentionally undiscriminating.
        assert!(should_route(None, "other:agent", &conn));
    }

    #[test]
    fn scoped_bot_routes_only_its_managers_chain() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        // Bot scoped to p:eng_lead. dev1 reports to eng_lead → routes.
        assert!(should_route(Some("p:eng_lead"), "p:dev1", &conn));
        // The manager themselves routes (manager_of returns self).
        assert!(should_route(Some("p:eng_lead"), "p:eng_lead", &conn));
        // pm is a sibling manager — does NOT route to eng_lead's bot.
        assert!(!should_route(Some("p:eng_lead"), "p:pm", &conn));
    }

    #[test]
    fn scoped_bot_with_unknown_agent_falls_back_to_self_routing() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        // Unknown agent: manager_of returns None → routed = agent_id;
        // routed != scoped → does not route. This pins the fallback rule
        // (don't surface unknown rows to a scoped bot) so a future
        // change can't silently relax it.
        assert!(!should_route(Some("p:eng_lead"), "p:ghost", &conn));
    }

    fn insert_reply(conn: &Connection, sender: &str, text: &str) -> i64 {
        let project = sender.split_once(':').map(|(p, _)| p).unwrap_or("p");
        conn.execute(
            "INSERT INTO messages (project_id, sender, recipient, text, sent_at)
             VALUES (?1, ?2, 'user:telegram', ?3, strftime('%s','now'))",
            params![project, sender, text],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    /// Regression: when two managers (`p:pm`, `p:eng_lead`) live in the same
    /// project and each has its own scoped bot, a `reply_to_user` from one
    /// manager must surface in *that* manager's bot only — not in sibling
    /// bots. Pre-fix the project-id SQL filter was the only filter so all
    /// in-project bots fanned out the same reply.
    #[test]
    fn reply_routes_only_to_its_senders_bot() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let pm_msg = insert_reply(&conn, "p:pm", "from pm");
        let eng_msg = insert_reply(&conn, "p:eng_lead", "from eng");

        // Pull the project-scoped pre-filter rows the way outbound_loop does.
        let mut stmt = conn
            .prepare(
                "SELECT m.id, m.sender, m.text FROM messages m
                 WHERE m.id > 0
                   AND m.recipient = 'user:telegram'
                   AND m.acked_at IS NULL
                   AND m.project_id = 'p'
                 ORDER BY m.id",
            )
            .unwrap();
        let rows: Vec<(i64, String, String)> = stmt
            .query_map([], |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)))
            .unwrap()
            .flatten()
            .collect();
        assert_eq!(rows.len(), 2, "both replies share the project pre-filter");

        // pm bot keeps only the pm reply.
        let pm_routed: Vec<i64> = rows
            .iter()
            .filter(|(_, sender, _)| should_route(Some("p:pm"), sender, &conn))
            .map(|(id, _, _)| *id)
            .collect();
        assert_eq!(pm_routed, vec![pm_msg]);

        // eng_lead bot keeps only the eng_lead reply.
        let eng_routed: Vec<i64> = rows
            .iter()
            .filter(|(_, sender, _)| should_route(Some("p:eng_lead"), sender, &conn))
            .map(|(id, _, _)| *id)
            .collect();
        assert_eq!(eng_routed, vec![eng_msg]);

        // Unscoped bot back-compat: forwards both.
        let unscoped: Vec<i64> = rows
            .iter()
            .filter(|(_, sender, _)| should_route(None, sender, &conn))
            .map(|(id, _, _)| *id)
            .collect();
        assert_eq!(unscoped, vec![pm_msg, eng_msg]);
    }

    #[test]
    fn live_tap_keeps_existing_delivered_at_unchanged() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        let id = insert_approval(&conn, "pending", Some(1234.5));

        let decided = decide_sql(&conn, id, false);
        assert!(decided);

        let delivered_at: f64 = conn
            .query_row(
                "SELECT delivered_at FROM approvals WHERE id = ?1",
                params![id],
                |r| r.get(0),
            )
            .unwrap();
        assert!(
            (delivered_at - 1234.5).abs() < 1e-6,
            "previously-set delivered_at must not be overwritten ({delivered_at})"
        );
    }

    // ── T-086-G slash-passthrough ─────────────────────────────────

    #[test]
    fn agent_runtime_returns_runtime_for_known_agent() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        // `seed` inserts p:eng_lead (manager, runtime "claude-code"),
        // p:pm (manager), and p:dev1 (worker).
        assert_eq!(
            agent_runtime(&conn, "p:eng_lead"),
            Some("claude-code".into())
        );
    }

    #[test]
    fn agent_runtime_returns_runtime_when_runtime_varies() {
        // Hand-extend the seed with a non-CC manager so the lookup
        // path is exercised against a runtime that the slash-passthrough
        // gate would later reject.
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        conn.execute(
            "INSERT OR IGNORE INTO agents (id, project_id, role, runtime, is_manager, reports_to)
             VALUES ('p:codex_mgr','p','codex_mgr','codex',1,NULL)",
            [],
        )
        .unwrap();
        assert_eq!(agent_runtime(&conn, "p:codex_mgr"), Some("codex".into()));
    }

    #[test]
    fn agent_runtime_returns_none_for_unknown_agent() {
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        assert_eq!(agent_runtime(&conn, "p:ghost"), None);
    }

    #[test]
    fn slash_outcome_passes_through_for_claude_code_runtime() {
        let outcome = slash_outcome("writing:manager", "claude-code", "t-");
        assert_eq!(
            outcome,
            SlashOutcome::Passthrough {
                session: "t-writing-manager".into(),
            }
        );
    }

    #[test]
    fn slash_outcome_honours_custom_tmux_prefix() {
        // `compose.global.supervisor.tmux_prefix` is operator-configurable.
        // The session formatter must concatenate verbatim — no hidden
        // dash-or-anything between prefix and project segment.
        let outcome = slash_outcome("news:head_editor", "claude-code", "a-");
        assert_eq!(
            outcome,
            SlashOutcome::Passthrough {
                session: "a-news-head_editor".into(),
            }
        );
    }

    #[test]
    fn slash_outcome_rejects_codex_runtime_with_named_runtime() {
        // Decision 6 ratify: non-CC managers reject slash-passthrough
        // and the rejection message must name the actual runtime so the
        // operator sees why nothing fired.
        let outcome = slash_outcome("writing:manager", "codex", "t-");
        let SlashOutcome::Reject { reason } = outcome else {
            panic!("non-CC runtime must reject");
        };
        assert!(
            reason.contains("Claude Code"),
            "rejection should reference Claude Code: {reason}"
        );
        assert!(
            reason.contains("codex"),
            "rejection should name the actual runtime: {reason}"
        );
    }

    #[test]
    fn slash_outcome_rejects_gemini_runtime_with_named_runtime() {
        let outcome = slash_outcome("writing:manager", "gemini", "t-");
        let SlashOutcome::Reject { reason } = outcome else {
            panic!("non-CC runtime must reject");
        };
        assert!(reason.contains("gemini"), "names the runtime: {reason}");
    }

    #[test]
    fn slash_outcome_rejects_malformed_manager_id() {
        // Defence in depth: if state.manager somehow lost the `:` (CLI
        // misuse, hand-edited env), refuse to type into a session
        // computed from a half-id rather than guess.
        let outcome = slash_outcome("not-a-manager-id", "claude-code", "t-");
        let SlashOutcome::Reject { reason } = outcome else {
            panic!("malformed manager id must reject");
        };
        assert!(reason.contains("malformed"), "names the failure: {reason}");
    }

    #[test]
    fn tmux_send_keys_argv_pins_send_keys_target_body_enter_shape() {
        // Pinning the argv shape so a future refactor that drops the
        // trailing literal `Enter` (which is what makes Claude Code
        // actually process the slash command) shows up as a test fail
        // rather than a silent passthrough that types but never submits.
        let argv = tmux_send_keys_argv("t-writing-manager", "/clear");
        assert_eq!(
            argv,
            ["send-keys", "-t", "t-writing-manager", "/clear", "Enter"]
        );
    }

    #[test]
    fn tmux_send_keys_argv_passes_body_verbatim_no_quote_munging() {
        // `Command::args` doesn't shell-quote — argv positions are passed
        // straight through. Tests pin that bodies with spaces / quotes
        // travel as a single arg without our code adding quoting that
        // tmux would then take literally.
        let argv = tmux_send_keys_argv("sess", "/compact focus on the cascade");
        assert_eq!(argv[3], "/compact focus on the cascade");
        assert_eq!(argv[4], "Enter");
    }

    // ── T-086-H setMyCommands registration ────────────────────────

    #[test]
    fn commands_for_runtime_returns_full_cc_list_for_claude_code() {
        let cmds = commands_for_runtime(Some("claude-code"));
        assert_eq!(
            cmds.len(),
            CC_SLASH_COMMANDS.len(),
            "CC manager registers the full curated list"
        );
        let names: Vec<&str> = cmds.iter().map(|c| c.command.as_str()).collect();
        // Spot-check a few representative entries — adding/removing
        // entries from CC_SLASH_COMMANDS should consciously update
        // these spot-checks rather than silently drift.
        assert!(names.contains(&"clear"), "must include /clear: {names:?}");
        assert!(
            names.contains(&"compact"),
            "must include /compact: {names:?}"
        );
        assert!(names.contains(&"help"), "must include /help: {names:?}");
    }

    #[test]
    fn commands_for_runtime_returns_empty_for_codex() {
        // Decision 6 manager-only / CC-only routing: non-CC managers
        // register no autocomplete. Operator can still type slashes
        // manually but won't see the CC menu.
        assert!(commands_for_runtime(Some("codex")).is_empty());
    }

    #[test]
    fn commands_for_runtime_returns_empty_for_gemini() {
        assert!(commands_for_runtime(Some("gemini")).is_empty());
    }

    #[test]
    fn commands_for_runtime_returns_empty_for_unknown_runtime() {
        // Forward-compat: a future runtime ships before its
        // command-list does. The empty-list fallback means an old
        // team-bot binary against a new runtime degrades quietly.
        assert!(commands_for_runtime(Some("a-future-runtime")).is_empty());
    }

    #[test]
    fn commands_for_runtime_returns_empty_for_unscoped_bot() {
        // Unscoped bot (no `--manager`) → no runtime → no commands.
        // Slash-passthrough is gated on `state.manager.is_some()`
        // anyway, so the autocomplete would be misleading without it.
        assert!(commands_for_runtime(None).is_empty());
    }

    #[test]
    fn cc_slash_command_names_satisfy_telegram_constraints() {
        // Telegram restricts `BotCommand.command` to 1-32 chars,
        // lowercase letters / digits / underscores only. Pinning here
        // so a future CC slash-command-set update that adds a hyphen
        // (e.g. `output-style`) trips this test before hitting the
        // Telegram API and getting silently rejected.
        for (cmd, _desc) in CC_SLASH_COMMANDS {
            assert!(
                !cmd.is_empty() && cmd.len() <= 32,
                "command `{cmd}` violates 1-32 char limit"
            );
            assert!(
                cmd.chars()
                    .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'),
                "command `{cmd}` contains chars Telegram rejects (only [a-z0-9_])"
            );
        }
    }

    #[test]
    fn cc_slash_command_descriptions_satisfy_telegram_constraints() {
        // Telegram requires `BotCommand.description` to be 3-256 chars.
        // Pinning here for the same reason as the command-name test.
        for (cmd, desc) in CC_SLASH_COMMANDS {
            assert!(
                desc.len() >= 3 && desc.len() <= 256,
                "description for `{cmd}` violates 3-256 char limit (got {} chars: {desc:?})",
                desc.len()
            );
        }
    }

    // ── T-086-E reaction dispatch ────────────────────────────────

    #[test]
    fn classify_kind_routes_reaction() {
        // T-086-E adds a fourth kind alongside text/image/file. Future
        // refactors that drop this arm should fail this test rather
        // than silently degrading reactions to UnknownFallback (which
        // would surface as text noise rather than an actual reaction).
        assert_eq!(classify_kind(Some("reaction")), DispatchKind::Reaction);
    }

    #[test]
    fn classify_kind_unknown_fallback_unchanged_for_other_strings() {
        // Regression guard: T-086-E must not accidentally turn the
        // `UnknownFallback` arm into a reaction match — only the
        // exact string "reaction" routes to the new arm.
        assert_eq!(
            classify_kind(Some("reactions")),
            DispatchKind::UnknownFallback
        );
        assert_eq!(classify_kind(Some("react")), DispatchKind::UnknownFallback);
    }

    #[test]
    fn parse_reaction_payload_extracts_telegram_msg_id_and_emoji() {
        let p = parse_reaction_payload(r#"{"telegram_msg_id":4242,"emoji":"👀"}"#)
            .expect("payload parses");
        assert_eq!(p.telegram_msg_id, 4242);
        assert_eq!(p.emoji, "👀");
    }

    #[test]
    fn parse_reaction_payload_returns_none_on_missing_fields() {
        assert!(parse_reaction_payload("not json").is_none());
        assert!(
            parse_reaction_payload(r#"{"emoji":"👍"}"#).is_none(),
            "missing telegram_msg_id"
        );
        assert!(
            parse_reaction_payload(r#"{"telegram_msg_id":7}"#).is_none(),
            "missing emoji"
        );
    }

    #[test]
    fn parse_reaction_payload_returns_none_on_wrong_types() {
        // Defence-in-depth: a malformed payload (string in place of
        // i64) shouldn't crash, just return None so the dispatcher
        // falls back to the log-and-skip arm.
        assert!(
            parse_reaction_payload(r#"{"telegram_msg_id":"oops","emoji":"👍"}"#).is_none(),
            "string telegram_msg_id"
        );
        assert!(
            parse_reaction_payload(r#"{"telegram_msg_id":7,"emoji":42}"#).is_none(),
            "non-string emoji"
        );
    }

    // ── T-086-B reply_parameters dispatch ────────────────────────

    #[test]
    fn reply_parameters_for_returns_none_when_telegram_msg_id_is_none() {
        // Back-compat pin: rows without a threading target produce no
        // ReplyParameters so the dispatcher doesn't attach them and the
        // message lands as a fresh post.
        assert!(reply_parameters_for(None).is_none());
    }

    #[test]
    fn reply_parameters_for_returns_some_when_telegram_msg_id_is_set() {
        // Affirmative pin: present id → constructed `ReplyParameters`
        // ready for the teloxide builder. The actual MessageId carried
        // is asserted via the by-value PartialEq.
        let rp = reply_parameters_for(Some(12345)).expect("Some when set");
        assert_eq!(rp.message_id, MessageId(12345));
    }

    #[test]
    fn reply_parameters_for_safely_casts_within_i32_range() {
        // Telegram message ids are i32; Rust API takes i64 for SQLite
        // ergonomics. Pin that values comfortably within i32 range
        // round-trip exactly — guards against a future refactor that
        // drops the `as i32` cast and ends up with a wrap-around bug
        // on large but valid ids.
        let id: i64 = 2_000_000_000;
        let rp = reply_parameters_for(Some(id)).expect("Some when set");
        assert_eq!(rp.message_id, MessageId(id as i32));
    }

    // ── T-086-C inbound media helpers ─────────────────────────────

    #[test]
    fn extension_from_mime_covers_canonical_types() {
        assert_eq!(extension_from_mime("image/png"), "png");
        assert_eq!(extension_from_mime("image/jpeg"), "jpg");
        assert_eq!(extension_from_mime("image/webp"), "webp");
        assert_eq!(extension_from_mime("image/gif"), "gif");
        assert_eq!(extension_from_mime("application/pdf"), "pdf");
        assert_eq!(extension_from_mime("text/plain"), "txt");
        assert_eq!(extension_from_mime("application/zip"), "zip");
    }

    #[test]
    fn extension_from_mime_falls_back_to_bin_for_unknown() {
        // Forward-compat: a mime we haven't mapped still produces a real
        // file with a non-empty extension. The agent can re-mime via
        // libmagic if it cares; we don't pretend we know.
        assert_eq!(extension_from_mime("application/octet-stream"), "bin");
        assert_eq!(extension_from_mime("video/mp4"), "bin");
        assert_eq!(extension_from_mime(""), "bin");
    }

    #[test]
    fn extension_for_document_prefers_filename_extension() {
        // Filename's tail wins when it's a clean alphanumeric suffix —
        // even when it disagrees with the upload's mime type. Telegram
        // operators sometimes mislabel; trust the filename they typed.
        assert_eq!(
            extension_for_document(Some("report.pdf"), "application/octet-stream"),
            "pdf"
        );
        assert_eq!(
            extension_for_document(Some("snapshot.PNG"), "application/pdf"),
            "png",
            "case-folded to lowercase"
        );
    }

    #[test]
    fn extension_for_document_falls_back_to_mime_when_filename_missing() {
        assert_eq!(extension_for_document(None, "image/png"), "png");
        assert_eq!(
            extension_for_document(None, "application/octet-stream"),
            "bin"
        );
    }

    #[test]
    fn extension_for_document_rejects_funky_extensions() {
        // No extension → mime fallback.
        assert_eq!(extension_for_document(Some("README"), "text/plain"), "txt");
        // Empty extension after dot → mime fallback.
        assert_eq!(
            extension_for_document(Some("trailing."), "text/plain"),
            "txt"
        );
        // Non-alphanumeric chars → mime fallback (defends against weird
        // shell/fs metacharacters that could foul a path).
        assert_eq!(
            extension_for_document(Some("name.weird/ext"), "image/png"),
            "png"
        );
        // Over-long extension → mime fallback (sanity cap on what we'd
        // accept verbatim from a user-controlled filename).
        assert_eq!(
            extension_for_document(Some("name.thisistoolongatail"), "image/png"),
            "png"
        );
    }

    #[test]
    fn inbound_media_path_composes_root_project_rowid_extension() {
        let root = std::path::Path::new("/srv/.team/state/inbound-media");
        let path = inbound_media_path(root, "writing", 42, "jpg");
        assert_eq!(
            path,
            std::path::PathBuf::from("/srv/.team/state/inbound-media/writing/42.jpg")
        );
    }

    #[test]
    fn media_success_payload_includes_path_mime_size_and_omits_empty_caption() {
        let path = std::path::Path::new("/srv/.team/state/inbound-media/p/7.jpg");
        let s = media_success_payload(path, "", "image/jpeg", 1024);
        let v: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(v["path"], "/srv/.team/state/inbound-media/p/7.jpg");
        assert_eq!(v["mime"], "image/jpeg");
        assert_eq!(v["size_bytes"], 1024);
        assert!(
            v.get("caption").is_none(),
            "empty caption omitted from payload"
        );
    }

    #[test]
    fn media_success_payload_includes_caption_when_present() {
        let path = std::path::Path::new("/x.png");
        let s = media_success_payload(path, "look at this", "image/png", 32);
        let v: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(v["caption"], "look at this");
    }

    #[test]
    fn media_error_payload_carries_verbose_error_and_optional_caption() {
        // R12: media_error rows must surface the verbatim cause so the
        // agent can ack to the user with a real diagnostic.
        let s = media_error_payload("", "get_file: timed out");
        let v: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(v["error"], "get_file: timed out");
        assert!(v.get("caption").is_none());

        let s = media_error_payload("a screenshot", "create file: permission denied");
        let v: serde_json::Value = serde_json::from_str(&s).unwrap();
        assert_eq!(v["error"], "create file: permission denied");
        assert_eq!(v["caption"], "a screenshot");
    }

    #[test]
    fn placeholder_then_success_update_round_trip() {
        // Pin the two-phase SQL pattern: insert a `media_pending` row,
        // then UPDATE to `image` with the final payload. The kind +
        // structured_payload must reflect the final state and the row
        // id must remain stable so the on-disk filename matches.
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        conn.execute(
            "INSERT INTO messages
                (project_id, sender, recipient, text, sent_at, kind, structured_payload)
             VALUES ('p', 'user:telegram', 'p:eng_lead', 'cap',
                     strftime('%s','now'), 'media_pending', '{}')",
            [],
        )
        .unwrap();
        let id = conn.last_insert_rowid();

        // Simulated post-download UPDATE.
        let payload =
            media_success_payload(std::path::Path::new("/x/p/3.jpg"), "cap", "image/jpeg", 128);
        conn.execute(
            "UPDATE messages SET kind = ?1, structured_payload = ?2 WHERE id = ?3",
            params!["image", payload, id],
        )
        .unwrap();

        let (kind, sp): (Option<String>, Option<String>) = conn
            .query_row(
                "SELECT kind, structured_payload FROM messages WHERE id = ?1",
                params![id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(kind.as_deref(), Some("image"));
        let v: serde_json::Value = serde_json::from_str(sp.as_deref().unwrap()).unwrap();
        assert_eq!(v["mime"], "image/jpeg");
    }

    #[test]
    fn placeholder_then_error_update_writes_media_error_kind() {
        // Mirror of the success path for the failure mode (R12). After
        // the UPDATE the row's kind is `media_error` and the payload
        // carries the verbatim cause — operator's reply prompt has the
        // diagnostic in hand.
        let conn = Connection::open_in_memory().unwrap();
        seed(&conn);
        conn.execute(
            "INSERT INTO messages
                (project_id, sender, recipient, text, sent_at, kind, structured_payload)
             VALUES ('p', 'user:telegram', 'p:eng_lead', '',
                     strftime('%s','now'), 'media_pending', '{}')",
            [],
        )
        .unwrap();
        let id = conn.last_insert_rowid();

        let payload = media_error_payload("", "download_file: 502 bad gateway");
        conn.execute(
            "UPDATE messages SET kind = 'media_error', structured_payload = ?1 WHERE id = ?2",
            params![payload, id],
        )
        .unwrap();

        let (kind, sp): (Option<String>, Option<String>) = conn
            .query_row(
                "SELECT kind, structured_payload FROM messages WHERE id = ?1",
                params![id],
                |r| Ok((r.get(0)?, r.get(1)?)),
            )
            .unwrap();
        assert_eq!(kind.as_deref(), Some("media_error"));
        assert!(sp.unwrap().contains("502 bad gateway"));
    }
}