dirge-agent 0.18.4

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

#[allow(unused_imports)]
use crate::sync_util::LockExt;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::Mutex as StdMutex;
use std::time::Duration;

use serde_json::Value;
use tokio::sync::{Mutex, mpsc};

use crate::agent::agent_loop::tool::AbortSignal;
use crate::agent::tools::ToolError;
use crate::dap::client::{DapClient, RpcError};

#[cfg(test)]
use crate::dap::client::DapRpc;
use crate::dap::types::*;
use crate::permission::checker::PermCheck;

/// Global DAP session manager — set during `DebugTool` construction,
/// read by the UI loop for debug panel snapshots. Uses a std Mutex
/// (not tokio) so it can be written from sync constructors and read
/// from the UI loop without an async context.
pub static DAP_MANAGER: StdMutex<Option<std::sync::Arc<DapSessionManager>>> = StdMutex::new(None);

/// Global DAP permission checker — set during `DebugTool` construction
/// alongside `DAP_MANAGER`. Read by the Janet FFI bridge to gate
/// expression evaluation (`dap/eval`) through the same permission
/// engine the agent tool path uses. Ask results from the engine are
/// treated as denial (no dialog in the bridge task).
pub static DAP_PERM_CHECK: StdMutex<Option<PermCheck>> = StdMutex::new(None);

// ---------------------------------------------------------------------------
// Output cap
// ---------------------------------------------------------------------------

/// Maximum bytes of accumulated output we retain per session.
const MAX_OUTPUT_BYTES: usize = 128 * 1024;

/// dirge-p3r7: how long `attach` waits for an initial stopped event before
/// concluding the debuggee is running. Attaching rarely produces a stop, so
/// this is a short grace window — not the full request timeout, which would
/// stall the attach and race the bridge command timeout.
const ATTACH_STOP_GRACE: Duration = Duration::from_secs(1);

// ---------------------------------------------------------------------------
// Per-session event channels
// ---------------------------------------------------------------------------

/// Bundled receivers for DAP events during a session.
struct EventReceivers {
    stopped: mpsc::UnboundedReceiver<StoppedEventBody>,
    output: mpsc::UnboundedReceiver<OutputEventBody>,
    terminated: mpsc::UnboundedReceiver<TerminatedEventBody>,
    exited: mpsc::UnboundedReceiver<ExitedEventBody>,
}

impl EventReceivers {
    /// A placeholder set of receivers whose senders are already dropped.
    /// dirge-acgj: `continue_` swaps the live receivers out from behind the
    /// `active` lock while it parks on the stop-wait, leaving this dead set
    /// in the session so the lock can be released. `try_recv` on these is a
    /// harmless no-op; a concurrent waiter is deflected earlier by the
    /// `stop_wait_in_flight` guard, so it never blocks on them.
    fn dead() -> Self {
        let (_, stopped) = mpsc::unbounded_channel();
        let (_, output) = mpsc::unbounded_channel();
        let (_, terminated) = mpsc::unbounded_channel();
        let (_, exited) = mpsc::unbounded_channel();
        EventReceivers {
            stopped,
            output,
            terminated,
            exited,
        }
    }
}

/// Register handlers on `client` that forward events into channels.
async fn register_event_channels(client: &DapClient) -> EventReceivers {
    let (stopped_tx, stopped_rx) = mpsc::unbounded_channel();
    let (output_tx, output_rx) = mpsc::unbounded_channel();
    let (terminated_tx, terminated_rx) = mpsc::unbounded_channel();
    let (exited_tx, exited_rx) = mpsc::unbounded_channel();

    client
        .on_event(
            "stopped",
            Box::new(move |v| {
                if let Ok(body) = serde_json::from_value::<StoppedEventBody>(v) {
                    let _ = stopped_tx.send(body);
                }
            }),
        )
        .await;
    client
        .on_event(
            "output",
            Box::new(move |v| {
                if let Ok(body) = serde_json::from_value::<OutputEventBody>(v) {
                    let _ = output_tx.send(body);
                }
            }),
        )
        .await;
    client
        .on_event(
            "terminated",
            Box::new(move |v| {
                if let Ok(body) = serde_json::from_value::<TerminatedEventBody>(v) {
                    let _ = terminated_tx.send(body);
                }
            }),
        )
        .await;
    client
        .on_event(
            "exited",
            Box::new(move |v| {
                if let Ok(body) = serde_json::from_value::<ExitedEventBody>(v) {
                    let _ = exited_tx.send(body);
                }
            }),
        )
        .await;

    EventReceivers {
        stopped: stopped_rx,
        output: output_rx,
        terminated: terminated_rx,
        exited: exited_rx,
    }
}

// ---------------------------------------------------------------------------
// DapSession — active debug session state
// ---------------------------------------------------------------------------

struct DapSession {
    id: String,
    client: DapClient,
    status: SessionStatus,
    breakpoints: HashMap<PathBuf, Vec<BreakpointRecord>>,
    function_breakpoints: Vec<FunctionBreakpoint>,
    output: String,
    output_truncated: bool,
    exit_code: Option<u32>,
    events: EventReceivers,
    /// Cached for TUI debug panel snapshots.
    cached_threads: Vec<Thread>,
    /// Cached for TUI debug panel snapshots.
    cached_frames: Vec<StackFrame>,
    /// Cached for TUI debug panel snapshots (last variables request).
    cached_variables: Vec<Variable>,
    /// dirge-vept: threadId from the most recent stopped event. The Janet
    /// bridge calls step/continue/stackTrace with thread_id 0 (unspecified);
    /// strict adapters (debugpy) reject an id of 0 with "thread not found", so
    /// the session substitutes this last stopped thread when a caller passes 0.
    last_stopped_thread_id: Option<u32>,
    languages: Vec<String>,
    /// dirge-acgj: true while `continue_` has handed the event receivers off
    /// and is parked on the stop-wait with the `active` lock released. A
    /// concurrent step/pause that reaches the session in this window has its
    /// own request issued but must not also wait for the stop — the parked
    /// `continue_` owns the event stream and will report the resulting stop.
    stop_wait_in_flight: bool,
}

impl DapSession {
    fn summary(&self) -> SessionSummary {
        SessionSummary {
            id: self.id.clone(),
            adapter_name: self.client.adapter_name.clone(),
            program: None,
            status: self.status.clone(),
            breakpoint_count: self.breakpoints.values().map(|v| v.len()).sum(),
            function_breakpoint_count: self.function_breakpoints.len(),
            stop_reason: None,
            thread_id: None,
            output: String::new(),
            output_truncated: false,
            exit_code: None,
            capabilities: self
                .client
                .capabilities
                .try_lock()
                .ok()
                .and_then(|g| g.clone()),
            languages: self.languages.clone(),
        }
    }

    /// Drain all pending output events into the output buffer.
    fn drain_output(&mut self) {
        while let Ok(evt) = self.events.output.try_recv() {
            // Stop appending once at the cap (keep draining the channel so a
            // flooding adapter can't back it up), so the buffer can't grow
            // unbounded before the post-hoc truncate.
            if self.output.len() >= MAX_OUTPUT_BYTES {
                self.output_truncated = true;
                continue;
            }
            self.output.push_str(&evt.output);
        }
        if self.output.len() > MAX_OUTPUT_BYTES {
            // `String::truncate` panics if the index isn't on a char
            // boundary, and `evt.output` is adapter-controlled — back off to
            // the nearest boundary at or below the cap.
            let mut cut = MAX_OUTPUT_BYTES;
            while cut > 0 && !self.output.is_char_boundary(cut) {
                cut -= 1;
            }
            self.output.truncate(cut);
            self.output_truncated = true;
        }
    }

    /// dirge-un0g: discard any stopped events left queued from a previous
    /// stop before issuing the next step/continue/pause. The stopped channel
    /// is unbounded and drained only on demand, so a stale event (e.g. a
    /// second thread that halted alongside the first) would otherwise satisfy
    /// the next wait instantly — reporting the previous stop's reason/thread
    /// and skewing every following op by one. Mirrors `drain_output`.
    fn drain_stopped(&mut self) {
        while self.events.stopped.try_recv().is_ok() {}
    }

    /// Drain queued stopped events, returning the most recent one. `pause`
    /// uses this instead of the plain drain: a queued stop with no waiter can
    /// be a genuine never-reported halt (e.g. a breakpoint hit after a
    /// timed-out continue, status still Running). Pausing an already-stopped
    /// program produces no new event, so discarding the drained stop would
    /// lose it — the wait times out and the status sticks at Running.
    fn drain_stopped_latest(&mut self) -> Option<StoppedEventBody> {
        let mut latest = None;
        while let Ok(evt) = self.events.stopped.try_recv() {
            latest = Some(evt);
        }
        latest
    }

    /// Drain and check for terminated/exited events.
    fn drain_termination(&mut self) {
        if self.events.terminated.try_recv().is_ok() {
            self.status = SessionStatus::Terminated;
        }
        if let Ok(evt) = self.events.exited.try_recv() {
            self.exit_code = Some(evt.exit_code as u32);
        }
    }

    /// Wait for a stopped event with timeout.
    async fn wait_for_stopped(&mut self, timeout: Duration) -> Result<StoppedEventBody, ToolError> {
        // dirge-acgj: a `continue_` is parked on the stop-wait with the event
        // receivers handed off; this session's copy is a dead placeholder.
        // Don't block on it — our request already reached the adapter and the
        // parked continue will report the stop it induces.
        if self.stop_wait_in_flight {
            return Err(ToolError::Msg(
                "a continue is already waiting for the next stop; its result will reflect this request".into(),
            ));
        }
        let stopped = tokio::time::timeout(timeout, self.events.stopped.recv())
            .await
            .map_err(|_| {
                ToolError::Msg(format!(
                    "timed out after {timeout:?} waiting for stopped event"
                ))
            })?
            .ok_or_else(|| ToolError::Msg("debug adapter disconnected".into()))?;
        self.record_stopped_thread(&stopped);
        Ok(stopped)
    }

    /// dirge-vept: remember the thread the adapter last stopped on, so a
    /// later step/continue/stackTrace with the 0 sentinel can target it.
    fn record_stopped_thread(&mut self, stopped: &StoppedEventBody) {
        if let Some(tid) = stopped.thread_id {
            self.last_stopped_thread_id = Some(tid as u32);
        }
    }

    /// dirge-vept: resolve a caller-supplied thread id. A `requested` of 0
    /// means "unspecified" (the Janet bridge hardcodes it); fall back to the
    /// last stopped thread. A non-zero id is honored verbatim.
    fn resolve_thread_id(&self, requested: u32) -> u32 {
        if requested == 0 {
            self.last_stopped_thread_id.unwrap_or(requested)
        } else {
            requested
        }
    }
}

// ---------------------------------------------------------------------------
// DapSessionManager — public API
// ---------------------------------------------------------------------------

pub struct DapSessionManager {
    /// In an `Arc` so `continue_` can hand the stop-wait (phases 2+3) to a
    /// spawned task that outlives a cancelled caller — see dirge-acgj notes
    /// in `continue_`.
    active: Arc<Mutex<Option<DapSession>>>,
    next_id: std::sync::atomic::AtomicU64,
    /// Last successfully-built panel snapshot. The session methods hold
    /// `active` across their adapter round-trip, so the UI's `try_lock` in
    /// `debug_snapshot` fails for that whole window — returning this cached
    /// copy keeps the debug panel showing the last-known state instead of
    /// blanking out. A plain `std::sync::Mutex`, never held across `.await`.
    last_snapshot: std::sync::Mutex<Option<DebugPanelData>>,
}

impl DapSessionManager {
    pub fn new() -> Self {
        Self {
            active: Arc::new(Mutex::new(None)),
            next_id: std::sync::atomic::AtomicU64::new(1),
            last_snapshot: std::sync::Mutex::new(None),
        }
    }

    fn next_id(&self) -> String {
        use std::sync::atomic::Ordering;
        let n = self.next_id.fetch_add(1, Ordering::SeqCst);
        format!("dap-{n}")
    }

    /// Launch a debug session.
    ///
    /// Terminates any existing active session first.
    /// Returns a summary once the program is stopped (on entry or breakpoint).
    #[allow(clippy::too_many_arguments)]
    pub async fn launch(
        &self,
        adapter_name: &str,
        adapter_cmd: &str,
        adapter_args: &[String],
        cwd: &str,
        program: Option<&str>,
        module: Option<&str>,
        program_args: &[String],
        stop_on_entry: Option<bool>,
        launch_extra: Option<serde_json::Value>,
        signal: &AbortSignal,
        timeout: Duration,
        languages: Vec<String>,
    ) -> Result<SessionSummary, ToolError> {
        self.terminate_active().await;

        let client = DapClient::spawn_stdio(
            adapter_name,
            Path::new(adapter_cmd),
            adapter_args,
            Path::new(cwd),
        )
        .await
        .map_err(|e| ToolError::Msg(format!("failed to spawn adapter: {e}")))?;

        self.launch_with_client(
            adapter_name,
            cwd,
            program,
            module,
            program_args,
            stop_on_entry,
            launch_extra,
            signal,
            client,
            timeout,
            languages,
        )
        .await
    }

    /// Core launch logic — used by both public launch and tests.
    ///
    /// `_signal` is reserved for future cancellation integration — when wired,
    /// a `tokio::select!` on `signal.received()` will abort the initial-stop
    /// wait so a user can cancel a hung launch.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn launch_with_client(
        &self,
        adapter_name: &str,
        cwd: &str,
        program: Option<&str>,
        module: Option<&str>,
        program_args: &[String],
        stop_on_entry: Option<bool>,
        launch_extra: Option<serde_json::Value>,
        _signal: &AbortSignal,
        client: DapClient,
        timeout: Duration,
        languages: Vec<String>,
    ) -> Result<SessionSummary, ToolError> {
        // Register event handlers.
        let mut events = register_event_channels(&client).await;

        // Initialize handshake.
        let init_args = InitializeArgs {
            adapter_id: adapter_name.to_string(),
            ..Default::default()
        };

        let caps: Capabilities = client
            .request("initialize", &init_args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        *client.capabilities.lock().await = Some(caps.clone());

        // Build launch arguments.
        let mut launch_args = LaunchArgs {
            program: program.map(|s| s.to_string()),
            module: module.map(|s| s.to_string()),
            cwd: Some(cwd.to_string()),
            args: Some(program_args.to_vec()),
            stop_on_entry,
            ..Default::default()
        };

        if let Some(extra) = launch_extra {
            launch_args.extra = extra;
        }

        // Send launch request as fire-and-forget — some adapters (debugpy)
        // won't respond to launch until configurationDone is received. We must
        // send configurationDone immediately to avoid a deadlock.
        //
        // Tradeoff: launch errors (bad program path, permissions) from adapters
        // that don't reply to launch-notify surface only as a stopped-event
        // timeout rather than a direct failure response. This is a protocol
        // limitation — the adapter won't respond to launch until we signal
        // configurationDone, and by then the launch is already in flight.
        client
            .notify("launch", &launch_args)
            .await
            .map_err(rpc_to_tool_error)?;

        // Send configurationDone if adapter supports it.
        if caps.supports_configuration_done_request.unwrap_or(false) {
            client
                .notify("configurationDone", &ConfigurationDoneArgs::default())
                .await
                .map_err(rpc_to_tool_error)?;
        }

        // Wait for the initial stopped event (stopOnEntry).
        // events is moved into DapSession later, so we destructure carefully.
        let stopped = tokio::time::timeout(timeout, events.stopped.recv())
            .await
            .map_err(|_| {
                ToolError::Msg(format!(
                    "timed out after {timeout:?} waiting for initial stop"
                ))
            })?
            .ok_or_else(|| {
                ToolError::Msg("debug adapter disconnected before stopped event".into())
            })?;

        let id = self.next_id();
        let mut session = DapSession {
            id: id.clone(),
            status: SessionStatus::Stopped,
            breakpoints: HashMap::new(),
            function_breakpoints: Vec::new(),
            output: String::new(),
            output_truncated: false,
            exit_code: None,
            events,
            client,
            cached_threads: Vec::new(),
            cached_frames: Vec::new(),
            cached_variables: Vec::new(),
            last_stopped_thread_id: stopped.thread_id.map(|id| id as u32),
            languages,
            stop_wait_in_flight: false,
        };
        session.drain_output();

        let mut summary = session.summary();
        summary.stop_reason = Some(stopped.reason.as_str().to_string());
        summary.thread_id = stopped.thread_id.map(|id| id as u32);
        *self.active.lock().await = Some(session);

        Ok(summary)
    }

    /// Attach to a running process.
    ///
    /// `_signal` is reserved for future cancellation integration.
    #[allow(clippy::too_many_arguments)]
    pub async fn attach(
        &self,
        adapter_name: &str,
        adapter_cmd: &str,
        adapter_args: &[String],
        cwd: &str,
        pid: Option<u32>,
        port: Option<u16>,
        host: Option<String>,
        attach_extra: Option<serde_json::Value>,
        _signal: &AbortSignal,
        timeout: Duration,
        languages: Vec<String>,
    ) -> Result<SessionSummary, ToolError> {
        self.terminate_active().await;

        let client = DapClient::spawn_stdio(
            adapter_name,
            Path::new(adapter_cmd),
            adapter_args,
            Path::new(cwd),
        )
        .await
        .map_err(|e| ToolError::Msg(format!("failed to spawn adapter: {e}")))?;

        self.attach_with_client(
            adapter_name,
            cwd,
            pid,
            port,
            host,
            attach_extra,
            _signal,
            client,
            timeout,
            languages,
        )
        .await
    }

    /// Core attach logic — used by both public attach and tests.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn attach_with_client(
        &self,
        adapter_name: &str,
        cwd: &str,
        pid: Option<u32>,
        port: Option<u16>,
        host: Option<String>,
        attach_extra: Option<serde_json::Value>,
        _signal: &AbortSignal,
        client: DapClient,
        timeout: Duration,
        languages: Vec<String>,
    ) -> Result<SessionSummary, ToolError> {
        let mut events = register_event_channels(&client).await;

        let init_args = InitializeArgs {
            adapter_id: adapter_name.to_string(),
            ..Default::default()
        };
        let caps: Capabilities = client
            .request("initialize", &init_args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        *client.capabilities.lock().await = Some(caps.clone());

        let mut attach_args = AttachArgs {
            pid,
            port,
            host,
            cwd: Some(cwd.to_string()),
            ..Default::default()
        };

        if let Some(extra) = attach_extra {
            attach_args.extra = extra;
        }

        client
            .request::<_, Value>("attach", &attach_args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        if caps.supports_configuration_done_request.unwrap_or(false) {
            client
                .notify("configurationDone", &ConfigurationDoneArgs::default())
                .await
                .map_err(rpc_to_tool_error)?;
        }

        // dirge-p3r7: attaching to an already-running process usually yields
        // no stopped event at all. Waiting the full request timeout here
        // stalls ~30s and races the Janet bridge's own DAP_CMD_TIMEOUT; then
        // recording Stopped unconditionally makes the debug panel and
        // summaries misreport a live debuggee as halted. Wait only a short
        // grace period, and set the status from what actually arrived.
        let grace = ATTACH_STOP_GRACE.min(timeout);
        let stopped = match tokio::time::timeout(grace, events.stopped.recv()).await {
            Ok(Some(body)) => Some(body),
            _ => None,
        };
        let status = if stopped.is_some() {
            SessionStatus::Stopped
        } else {
            SessionStatus::Running
        };

        let id = self.next_id();
        let mut session = DapSession {
            id: id.clone(),
            status,
            breakpoints: HashMap::new(),
            function_breakpoints: Vec::new(),
            output: String::new(),
            output_truncated: false,
            exit_code: None,
            events,
            client,
            cached_threads: Vec::new(),
            cached_frames: Vec::new(),
            cached_variables: Vec::new(),
            last_stopped_thread_id: stopped
                .as_ref()
                .and_then(|s| s.thread_id)
                .map(|id| id as u32),
            languages,
            stop_wait_in_flight: false,
        };
        session.drain_output();

        let mut summary = session.summary();
        if let Some(stopped) = stopped {
            summary.stop_reason = Some(stopped.reason.as_str().to_string());
            summary.thread_id = stopped.thread_id.map(|id| id as u32);
        }

        *self.active.lock().await = Some(session);
        Ok(summary)
    }

    /// Set file breakpoints for the active session.
    pub async fn set_breakpoints(
        &self,
        file: &str,
        breakpoints: Vec<SourceBreakpoint>,
        timeout: Duration,
    ) -> Result<Vec<Breakpoint>, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let source = Source {
            path: Some(file.to_string()),
            ..Default::default()
        };

        let args = SetBreakpointsArgs {
            source,
            breakpoints: Some(breakpoints.clone()),
            breakpoints_deprecated: None,
            source_modified: None,
        };

        let response: SetBreakpointsResponse = session
            .client
            .request("setBreakpoints", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        let path = PathBuf::from(file);
        session.breakpoints.insert(
            path,
            vec![BreakpointRecord {
                file: file.to_string(),
                breakpoints,
                verified: Some(response.breakpoints.clone()),
            }],
        );

        Ok(response.breakpoints)
    }

    /// Set function breakpoints.
    #[allow(dead_code)] // reserved for future agent tool action
    pub async fn set_function_breakpoints(
        &self,
        breakpoints: Vec<FunctionBreakpoint>,
        timeout: Duration,
    ) -> Result<Vec<Breakpoint>, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let args = SetFunctionBreakpointsArgs {
            breakpoints: breakpoints.clone(),
        };

        let response: SetFunctionBreakpointsResponse = session
            .client
            .request("setFunctionBreakpoints", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        session.function_breakpoints = breakpoints;
        Ok(response.breakpoints)
    }

    /// Continue execution and wait for the next stop event.
    pub async fn continue_(
        &self,
        thread_id: u32,
        _signal: &AbortSignal,
        timeout: Duration,
    ) -> Result<ContinueOutcome, ToolError> {
        // Phase 1: under the lock, issue the continue and hand the event
        // receivers off. dirge-acgj: the wait below used to run with `active`
        // held, so a pause meant to interrupt a free-running program blocked
        // on the mutex for this continue's full timeout — the one window where
        // pause is meaningful. Take the receivers out and release the lock so
        // concurrent requests (pause, evaluate) can reach the adapter.
        // dirge-8gdv: capture the session identity under the lock so phase 3 can
        // detect that a launch/attach replaced `active` while we were parked,
        // and refuse to restore our stale receivers into the new session.
        let (mut receivers, session_id) = {
            let mut active = self.active.lock().await;
            let session = active
                .as_mut()
                .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

            // A previous continue is still parked on its stop-wait and owns
            // the event stream; the session holds the dead placeholder.
            // Proceeding would issue a real continue, park on the dead
            // receivers (instant false "disconnected"), and clear
            // `stop_wait_in_flight` out from under the first waiter.
            if session.stop_wait_in_flight {
                return Err(ToolError::Msg(
                    "a continue is already waiting for the next stop; its result will reflect this request".into(),
                ));
            }

            // dirge-un0g: clear stops queued from a prior halt so we wait for
            // the fresh one this continue induces, not a stale event.
            session.drain_stopped();

            let args = ContinueArgs {
                thread_id: session.resolve_thread_id(thread_id),
                single_thread: None,
            };

            session
                .client
                .request::<_, ContinueResponse>("continue", &args, timeout)
                .await
                .map_err(rpc_to_tool_error)?;

            session.status = SessionStatus::Running;
            session.stop_wait_in_flight = true;
            let session_id = session.id.clone();
            (
                std::mem::replace(&mut session.events, EventReceivers::dead()),
                session_id,
            )
        };

        // Phases 2+3 run in a spawned task so they survive caller drop: the
        // agent tool executor drops the tool future on cancel, and a drop
        // mid-park would destroy the live receivers and leave
        // `stop_wait_in_flight` set forever — every later step/pause
        // deflected by the guard, every continue parked on dead channels.
        // Dropping the JoinHandle below merely detaches the task; it still
        // restores the receivers and clears the flag whenever the adapter
        // eventually stops, terminates, or the timeout fires.
        let active = Arc::clone(&self.active);
        let park = tokio::spawn(async move {
            // Phase 2: wait for the stop with the lock released.
            enum StopOutcome {
                Stopped(StoppedEventBody),
                Terminated,
                Disconnected,
                TimedOut,
            }
            let outcome = tokio::select! {
                s = receivers.stopped.recv() => match s {
                    Some(stopped) => StopOutcome::Stopped(stopped),
                    None => StopOutcome::Disconnected,
                },
                _ = receivers.terminated.recv() => StopOutcome::Terminated,
                _ = tokio::time::sleep(timeout) => StopOutcome::TimedOut,
            };

            // Phase 3: re-acquire, restore the receivers, record the result.
            let mut active = active.lock().await;
            let session = active
                .as_mut()
                .ok_or_else(|| ToolError::Msg("debug session ended during continue".into()))?;
            // dirge-8gdv: if a launch/attach replaced the active session while
            // we were parked, the session now in `active` is a different one.
            // Restoring our (taken, now-stale) receivers into it would clobber
            // the new session's live event channels and stomp its
            // stop_wait_in_flight/status — it would then never see another
            // event. Bail instead: drop the stale receivers and leave the
            // replacement untouched.
            if session.id != session_id {
                return Err(ToolError::Msg(
                    "debug session replaced during continue".into(),
                ));
            }
            session.events = receivers;
            session.stop_wait_in_flight = false;

            let (stop_reason, stop_thread_id) = match outcome {
                StopOutcome::Stopped(stopped) => {
                    session.status = SessionStatus::Stopped;
                    session.record_stopped_thread(&stopped);
                    (
                        Some(stopped.reason.as_str().to_string()),
                        stopped.thread_id.map(|id| id as u32),
                    )
                }
                StopOutcome::Terminated => {
                    session.status = SessionStatus::Terminated;
                    (Some("terminated".into()), None)
                }
                StopOutcome::Disconnected => {
                    return Err(ToolError::Msg("debug adapter disconnected".into()));
                }
                StopOutcome::TimedOut => {
                    return Err(ToolError::Msg(format!(
                        "timed out after {timeout:?} waiting for stop after continue"
                    )));
                }
            };

            session.drain_output();
            session.drain_termination();

            Ok(ContinueOutcome {
                status: session.status.clone(),
                output: session.output.clone(),
                output_truncated: session.output_truncated,
                exit_code: session.exit_code,
                stop_reason,
                thread_id: stop_thread_id,
            })
        });

        park.await
            .map_err(|e| ToolError::Msg(format!("continue stop-wait task failed: {e}")))?
    }

    /// Step over (next).
    pub async fn step_over(
        &self,
        thread_id: u32,
        _signal: &AbortSignal,
        timeout: Duration,
    ) -> Result<SessionSummary, ToolError> {
        self.step("next", thread_id, timeout).await
    }

    /// Step into.
    pub async fn step_in(
        &self,
        thread_id: u32,
        _signal: &AbortSignal,
        timeout: Duration,
    ) -> Result<SessionSummary, ToolError> {
        self.step("stepIn", thread_id, timeout).await
    }

    /// Step out.
    pub async fn step_out(
        &self,
        thread_id: u32,
        _signal: &AbortSignal,
        timeout: Duration,
    ) -> Result<SessionSummary, ToolError> {
        self.step("stepOut", thread_id, timeout).await
    }

    async fn step(
        &self,
        command: &str,
        thread_id: u32,
        timeout: Duration,
    ) -> Result<SessionSummary, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        // dirge-un0g: clear stops queued from a prior halt so this step waits
        // for the fresh one it induces, not a stale event.
        session.drain_stopped();

        // dirge-vept: substitute the last stopped thread when the bridge
        // passes the 0 sentinel.
        let thread_id = session.resolve_thread_id(thread_id);
        let args = match command {
            "next" => serde_json::to_value(NextArgs {
                thread_id,
                single_thread: None,
                granularity: None,
            })
            .unwrap(),
            "stepIn" => serde_json::to_value(StepInArgs {
                thread_id,
                single_thread: None,
                granularity: None,
                target_id: None,
            })
            .unwrap(),
            "stepOut" => serde_json::to_value(StepOutArgs {
                thread_id,
                single_thread: None,
                granularity: None,
            })
            .unwrap(),
            _ => return Err(ToolError::Msg(format!("unknown step command: {command}"))),
        };
        session
            .client
            .request::<_, Value>(command, &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        session.status = SessionStatus::Running;

        let stopped = session.wait_for_stopped(timeout).await?;
        session.status = SessionStatus::Stopped;
        session.drain_output();
        session.drain_termination();

        let mut summary = session.summary();
        summary.stop_reason = Some(stopped.reason.as_str().to_string());
        summary.thread_id = stopped.thread_id.map(|id| id as u32);
        Ok(summary)
    }

    /// Pause execution.
    pub async fn pause(
        &self,
        thread_id: u32,
        timeout: Duration,
    ) -> Result<SessionSummary, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        // A queued stop here can be a genuine never-reported halt (breakpoint
        // hit after a timed-out continue, with nothing waiting on the
        // channel). Pausing an already-stopped program yields no new event,
        // so the plain dirge-un0g drain would eat the stop and the wait below
        // would time out with the status stuck at Running. Treat the most
        // recent drained stop as the pause result instead.
        if let Some(stopped) = session.drain_stopped_latest() {
            session.status = SessionStatus::Stopped;
            session.record_stopped_thread(&stopped);
            session.drain_output();
            session.drain_termination();

            let mut summary = session.summary();
            summary.stop_reason = Some(stopped.reason.as_str().to_string());
            summary.thread_id = stopped.thread_id.map(|id| id as u32);
            return Ok(summary);
        }

        let args = PauseArgs { thread_id };
        session
            .client
            .request::<_, Value>("pause", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        let stopped = session.wait_for_stopped(timeout).await?;
        session.status = SessionStatus::Stopped;
        session.drain_output();
        session.drain_termination();

        let mut summary = session.summary();
        summary.stop_reason = Some(stopped.reason.as_str().to_string());
        summary.thread_id = stopped.thread_id.map(|id| id as u32);
        Ok(summary)
    }

    /// Get stack trace.
    pub async fn stack_trace(
        &self,
        thread_id: u32,
        levels: Option<u32>,
        timeout: Duration,
    ) -> Result<Vec<StackFrame>, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let args = StackTraceArgs {
            // dirge-vept: 0 from the bridge means the last stopped thread.
            thread_id: session.resolve_thread_id(thread_id),
            start_frame: None,
            levels,
            format: None,
        };

        let response: StackTraceResponse = session
            .client
            .request("stackTrace", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        session.cached_frames = response.stack_frames.clone();
        Ok(response.stack_frames)
    }

    /// Get scopes for a frame.
    pub async fn scopes(&self, frame_id: u32, timeout: Duration) -> Result<Vec<Scope>, ToolError> {
        let active = self.active.lock().await;
        let session = active
            .as_ref()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let args = ScopesArgs { frame_id };
        let response: ScopesResponse = session
            .client
            .request("scopes", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        Ok(response.scopes)
    }

    /// Get variables.
    pub async fn variables(
        &self,
        variables_reference: u32,
        timeout: Duration,
    ) -> Result<Vec<Variable>, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let args = VariablesArgs {
            variables_reference,
            filter: None,
            start: None,
            count: None,
            format: None,
        };

        let response: VariablesResponse = session
            .client
            .request("variables", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        session.cached_variables = response.variables.clone();
        Ok(response.variables)
    }

    /// Evaluate expression.
    pub async fn evaluate(
        &self,
        expression: &str,
        frame_id: Option<u32>,
        context: Option<&str>,
        timeout: Duration,
    ) -> Result<EvaluateResponse, ToolError> {
        let active = self.active.lock().await;
        let session = active
            .as_ref()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let args = EvaluateArgs {
            expression: expression.to_string(),
            frame_id,
            context: context.map(|s| s.to_string()),
            format: None,
        };

        let response: EvaluateResponse = session
            .client
            .request("evaluate", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        Ok(response)
    }

    /// List threads.
    pub async fn threads(&self, timeout: Duration) -> Result<Vec<Thread>, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let response: ThreadsResponse = session
            .client
            .request("threads", &ThreadsArgs {}, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        session.cached_threads = response.threads.clone();
        Ok(response.threads)
    }

    /// Terminate the debuggee.
    pub async fn terminate(&self, timeout: Duration) -> Result<SessionSummary, ToolError> {
        let mut active = self.active.lock().await;
        let session = active
            .as_mut()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        session
            .client
            .request::<_, Value>("terminate", &TerminateArgs::default(), timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        session.drain_output();
        session.drain_termination();
        session.status = SessionStatus::Terminated;

        Ok(session.summary())
    }

    /// Disconnect from the debug adapter.
    pub async fn disconnect(&self, restart: bool, timeout: Duration) -> Result<(), ToolError> {
        let mut active = self.active.lock().await;
        if let Some(session) = active.as_mut() {
            let args = DisconnectArgs {
                restart: Some(restart),
                terminate_debuggee: None,
                extra: Default::default(),
            };
            session
                .client
                .request::<_, Value>("disconnect", &args, timeout)
                .await
                .map_err(rpc_to_tool_error)?;
            session.status = SessionStatus::Terminated;
        }
        *active = None;
        Ok(())
    }

    /// Restart a stack frame — re-execute from the beginning of the frame.
    /// Useful for edit-and-continue workflows after modifying source code.
    pub async fn restart_frame(&self, frame_id: u32, timeout: Duration) -> Result<(), ToolError> {
        let active = self.active.lock().await;
        let session = active
            .as_ref()
            .ok_or_else(|| ToolError::Msg("no active debug session".into()))?;

        let args = RestartFrameArgs { frame_id };
        session
            .client
            .request::<_, Value>("restartFrame", &args, timeout)
            .await
            .map_err(rpc_to_tool_error)?;

        Ok(())
    }

    /// Return a summary of the active session, if any.
    pub async fn active_summary(&self) -> Option<SessionSummary> {
        let active = self.active.lock().await;
        active.as_ref().map(|s| s.summary())
    }

    /// Build a `DebugPanelData` snapshot from the active session's
    /// cached state. Non-async — uses `try_lock` so the UI loop
    /// never blocks waiting for a DAP tool call. Returns `None`
    /// when no session is active or the lock is held by a tool.
    pub fn debug_snapshot(&self) -> Option<DebugPanelData> {
        // If `active` is locked (an op is mid-round-trip), fall back to the
        // last cached snapshot so the panel doesn't blank out for the whole
        // call. On a successful lock, rebuild and refresh the cache.
        let active = match self.active.try_lock() {
            Ok(active) => active,
            Err(_) => {
                return self.last_snapshot.lock_ignore_poison().clone();
            }
        };
        let snapshot = active.as_ref().map(|session| DebugPanelData {
            adapter: session.client.adapter_name.clone(),
            status: session.status.clone(),
            session_summary: Some(session.summary()),
            threads: session.cached_threads.clone(),
            frames: session.cached_frames.clone(),
            variables: session.cached_variables.clone(),
            scopes: Vec::new(),
            breakpoints: session.breakpoints.values().flatten().cloned().collect(),
            output: session.output.clone(),
            output_truncated: session.output_truncated,
            exit_code: session.exit_code,
        });
        *self.last_snapshot.lock_ignore_poison() = snapshot.clone();
        snapshot
    }

    /// Force-terminate the active session (drop = kill_on_drop).
    async fn terminate_active(&self) {
        let mut active = self.active.lock().await;
        if let Some(session) = active.as_mut() {
            // Best-effort graceful disconnect (terminate the debuggee) before
            // dropping, which otherwise hard-SIGKILLs the process group. Short
            // timeout; errors are ignored — the drop is the fallback.
            let args = DisconnectArgs {
                restart: Some(false),
                terminate_debuggee: Some(true),
                extra: Default::default(),
            };
            let _ = session
                .client
                .request::<_, Value>("disconnect", &args, Duration::from_secs(2))
                .await;
        }
        *active = None;
    }
}

/// Best-effort teardown of the active DAP session at process exit
/// (dirge-ixcw). [`DAP_MANAGER`] is a `static`, so its `Drop` never runs
/// on a normal exit — without an explicit call here a `setsid()`-isolated
/// adapter + debuggee in their own process group could be orphaned. Mirrors
/// the LSP `close_all_files` shutdown step. Force-terminates (the manager's
/// `terminate_active` already attempts a 2s graceful disconnect, then drops
/// to `kill_on_drop`) rather than blocking the exit on a slow adapter.
pub async fn shutdown_active_session() {
    let mgr = DAP_MANAGER.lock().ok().and_then(|guard| guard.clone());
    if let Some(mgr) = mgr {
        mgr.terminate_active().await;
    }
}

impl Default for DapSessionManager {
    fn default() -> Self {
        Self::new()
    }
}

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

fn rpc_to_tool_error(e: RpcError) -> ToolError {
    match &e {
        RpcError::Server(msg) => ToolError::Msg(format!("adapter error: {msg}")),
        other => ToolError::Msg(other.to_string()),
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::jsonrpc_framing::{decode_frame, encode_frame};
    use serde_json::Value;
    use tokio::io::{AsyncBufRead, AsyncWrite};

    /// A fake DAP adapter that handles:
    /// 1. initialize request → capabilities response
    /// 2. launch request → success response → stopped event
    /// 3. configurationDone request → success response
    async fn fake_launch_adapter(
        mut reader: impl AsyncBufRead + Unpin,
        mut writer: impl AsyncWrite + Unpin,
    ) {
        // --- initialize ---
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "initialize");
        let seq = msg["seq"].as_u64().unwrap();

        let resp = serde_json::json!({
            "type": "response",
            "seq": 1,
            "request_seq": seq,
            "success": true,
            "command": "initialize",
            "body": {
                "supportsConfigurationDoneRequest": true,
                "supportsFunctionBreakpoints": false,
            }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();

        // --- launch ---
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "launch");
        let seq = msg["seq"].as_u64().unwrap();

        let resp = serde_json::json!({
            "type": "response",
            "seq": 2,
            "request_seq": seq,
            "success": true,
            "command": "launch",
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();

        // Stopped event (stopOnEntry).
        let evt = serde_json::json!({
            "type": "event",
            "seq": 3,
            "event": "stopped",
            "body": {
                "reason": "entry",
                "threadId": 1,
            }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&evt).unwrap())
            .await
            .unwrap();

        // --- configurationDone ---
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "configurationDone");
        let seq = msg["seq"].as_u64().unwrap();

        let resp = serde_json::json!({
            "type": "response",
            "seq": 4,
            "request_seq": seq,
            "success": true,
            "command": "configurationDone",
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();

        // --- setBreakpoints ---
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "setBreakpoints");
        let seq = msg["seq"].as_u64().unwrap();

        let resp = serde_json::json!({
            "type": "response",
            "seq": 5,
            "request_seq": seq,
            "success": true,
            "command": "setBreakpoints",
            "body": {
                "breakpoints": [
                    {"id": 1, "verified": true, "line": 10}
                ]
            }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();

        // --- continue ---
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "continue");
        let seq = msg["seq"].as_u64().unwrap();

        let resp = serde_json::json!({
            "type": "response",
            "seq": 6,
            "request_seq": seq,
            "success": true,
            "command": "continue",
            "body": { "allThreadsContinued": true }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();

        // Stopped event (breakpoint hit).
        let evt = serde_json::json!({
            "type": "event",
            "seq": 7,
            "event": "stopped",
            "body": {
                "reason": "breakpoint",
                "threadId": 1,
            }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&evt).unwrap())
            .await
            .unwrap();

        // --- terminate ---
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "terminate");
        let seq = msg["seq"].as_u64().unwrap();

        let resp = serde_json::json!({
            "type": "response",
            "seq": 8,
            "request_seq": seq,
            "success": true,
            "command": "terminate",
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();
    }

    /// Build a DapClient over duplex channels connected to a fake adapter.
    fn client_with_fake_adapter() -> DapClient {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);

        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);

        tokio::spawn(async move {
            fake_launch_adapter(tokio::io::BufReader::new(server_read), server_write).await;
        });

        DapClient::from_rpc(rpc, "fake-adapter")
    }

    /// Full launch → setBreakpoints → continue → terminate flow over duplex.
    #[tokio::test]
    async fn launch_breakpoint_continue_terminate() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_fake_adapter();

        let summary = mgr
            .launch_with_client(
                "fake-adapter",
                "/tmp",
                Some("test-program"),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                Duration::from_secs(5),
                vec![],
            )
            .await
            .unwrap();

        assert_eq!(summary.status, SessionStatus::Stopped);
        assert_eq!(summary.stop_reason.as_deref(), Some("entry"));
        assert_eq!(summary.thread_id, Some(1));

        // set breakpoints
        let bps = mgr
            .set_breakpoints(
                "/tmp/test.rs",
                vec![SourceBreakpoint {
                    line: 10,
                    column: None,
                    condition: None,
                    hit_condition: None,
                    log_message: None,
                }],
                Duration::from_secs(5),
            )
            .await
            .unwrap();

        assert_eq!(bps.len(), 1);
        assert_eq!(bps[0].id, Some(1));
        assert!(bps[0].verified);

        // continue → wait for breakpoint hit
        let outcome = mgr
            .continue_(1, &signal, Duration::from_secs(5))
            .await
            .unwrap();

        assert_eq!(outcome.status, SessionStatus::Stopped);
        assert_eq!(outcome.stop_reason.as_deref(), Some("breakpoint"));

        // terminate
        let term = mgr.terminate(Duration::from_secs(5)).await.unwrap();
        assert_eq!(term.status, SessionStatus::Terminated);
    }

    /// dirge-vept: a fake adapter that stops on thread 42 at entry, then on
    /// `continue` echoes back the `threadId` it actually received (in the next
    /// stopped event's threadId). Lets a test observe what thread id the
    /// manager sent, proving the 0-sentinel was substituted.
    async fn fake_echo_thread_adapter(
        mut reader: impl AsyncBufRead + Unpin,
        mut writer: impl AsyncWrite + Unpin,
    ) {
        // initialize
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        let seq = msg["seq"].as_u64().unwrap();
        let resp = serde_json::json!({
            "type": "response", "seq": 1, "request_seq": seq, "success": true,
            "command": "initialize",
            "body": { "supportsConfigurationDoneRequest": true }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();

        // launch → success → stopped on thread 42
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        let seq = msg["seq"].as_u64().unwrap();
        let resp = serde_json::json!({
            "type": "response", "seq": 2, "request_seq": seq, "success": true,
            "command": "launch",
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();
        let evt = serde_json::json!({
            "type": "event", "seq": 3, "event": "stopped",
            "body": { "reason": "entry", "threadId": 42 }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&evt).unwrap())
            .await
            .unwrap();

        // configurationDone (notify — no response)
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "configurationDone");

        // continue → echo the received threadId into the next stopped event.
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "continue");
        let seq = msg["seq"].as_u64().unwrap();
        let received_tid = msg["arguments"]["threadId"].as_u64().unwrap();
        let resp = serde_json::json!({
            "type": "response", "seq": 4, "request_seq": seq, "success": true,
            "command": "continue", "body": { "allThreadsContinued": true }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&resp).unwrap())
            .await
            .unwrap();
        let evt = serde_json::json!({
            "type": "event", "seq": 5, "event": "stopped",
            "body": { "reason": "breakpoint", "threadId": received_tid }
        });
        encode_frame(&mut writer, &serde_json::to_vec(&evt).unwrap())
            .await
            .unwrap();
    }

    fn client_with_echo_thread_adapter() -> DapClient {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);
        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);
        tokio::spawn(async move {
            fake_echo_thread_adapter(tokio::io::BufReader::new(server_read), server_write).await;
        });
        DapClient::from_rpc(rpc, "fake-adapter")
    }

    /// dirge-vept: the Janet bridge calls `continue_(0, …)`. A `thread_id` of
    /// 0 is the "unspecified" sentinel and must be substituted with the last
    /// stopped thread (42 here), or strict adapters (debugpy) reject it with
    /// "thread not found". The echo adapter reports the id it received.
    #[tokio::test]
    async fn continue_with_zero_thread_substitutes_last_stopped() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_echo_thread_adapter();

        let summary = mgr
            .launch_with_client(
                "fake-adapter",
                "/tmp",
                Some("p"),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                Duration::from_secs(5),
                vec![],
            )
            .await
            .unwrap();
        assert_eq!(summary.thread_id, Some(42));

        // Bridge passes 0; the manager must send the last stopped thread.
        let outcome = mgr
            .continue_(0, &signal, Duration::from_secs(5))
            .await
            .unwrap();
        assert_eq!(
            outcome.thread_id,
            Some(42),
            "continue(0) must target the last stopped thread, not 0"
        );
    }

    /// Session summary reflects the active session.
    #[tokio::test]
    async fn active_summary_after_launch() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_fake_adapter();

        let summary = mgr
            .launch_with_client(
                "fake-adapter",
                "/tmp",
                Some("hello"),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                Duration::from_secs(5),
                vec![],
            )
            .await
            .unwrap();

        assert_eq!(summary.status, SessionStatus::Stopped);

        let active = mgr.active_summary().await;
        assert!(active.is_some());
        assert_eq!(active.unwrap().id, summary.id);
    }

    /// Single-session enforcement: launching a new session drops the old one.
    #[tokio::test]
    async fn second_launch_replaces_first() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_fake_adapter();

        let first = mgr
            .launch_with_client(
                "fake-adapter",
                "/tmp",
                Some("first"),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                Duration::from_secs(5),
                vec![],
            )
            .await
            .unwrap();

        let first_id = first.id;

        let active = mgr.active_summary().await;
        assert!(active.is_some());
        assert_eq!(active.unwrap().id, first_id);

        // Manually clear to verify terminate_active works
        mgr.terminate_active().await;
        assert!(mgr.active_summary().await.is_none());
    }

    /// E2E: DapSessionManager::launch_with_client against real debugpy.
    /// Reproduces dirge-go4b timeout bug.
    #[tokio::test]
    async fn e2e_debugpy_launch_with_client() {
        if std::process::Command::new("python3")
            .args(["-c", "import debugpy"])
            .output()
            .map_or(true, |o| !o.status.success())
        {
            eprintln!("SKIP: debugpy not installed");
            return;
        }

        let fixture = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("tests")
            .join("dap")
            .join("fixtures")
            .join("test_program.py");
        assert!(fixture.exists(), "test_program.py must exist");

        let client = DapClient::spawn_stdio(
            "debugpy",
            std::path::Path::new("python3"),
            &["-m".to_string(), "debugpy.adapter".to_string()],
            std::path::Path::new("."),
        )
        .await
        .expect("debugpy adapter should spawn");

        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();

        let summary = mgr
            .launch_with_client(
                "debugpy",
                ".",
                Some(fixture.to_str().unwrap()),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                std::time::Duration::from_secs(15),
                vec!["python".into()],
            )
            .await
            .expect("launch_with_client should succeed");

        assert_eq!(summary.status, SessionStatus::Stopped);
        assert!(summary.stop_reason.is_some(), "should have stop reason");

        // Terminate and disconnect.
        mgr.terminate(std::time::Duration::from_secs(10))
            .await
            .expect("terminate should succeed");

        mgr.disconnect(false, std::time::Duration::from_secs(10))
            .await
            .expect("disconnect should succeed");
    }

    /// Launch a Python module (python -m test_mod) via debugpy using
    /// launch_with_client and exercise the full session-manager lifecycle.
    #[cfg(feature = "dap")]
    #[tokio::test]
    async fn e2e_debugpy_launch_module() {
        if std::process::Command::new("python3")
            .args(["-c", "import debugpy"])
            .output()
            .map_or(true, |o| !o.status.success())
        {
            eprintln!("SKIP: debugpy not installed");
            return;
        }

        let fixtures_dir = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("src")
            .join("tests")
            .join("dap")
            .join("fixtures");
        assert!(
            fixtures_dir.join("test_mod").exists(),
            "test_mod package must exist"
        );

        let client = DapClient::spawn_stdio(
            "debugpy",
            std::path::Path::new("python3"),
            &["-m".to_string(), "debugpy.adapter".to_string()],
            std::path::Path::new("."),
        )
        .await
        .expect("debugpy adapter should spawn");

        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();

        // launch with module instead of program — debugpy runs python -m test_mod
        let summary = mgr
            .launch_with_client(
                "debugpy",
                fixtures_dir.to_str().unwrap(),
                None,             // program: None
                Some("test_mod"), // module: Some("test_mod")
                &[],
                Some(true), // stop_on_entry
                None,
                &signal,
                client,
                std::time::Duration::from_secs(15),
                vec!["python".into()],
            )
            .await
            .expect("launch_with_client should succeed");

        assert_eq!(summary.status, SessionStatus::Stopped);
        assert!(summary.stop_reason.is_some(), "should have stop reason");

        // Terminate and disconnect.
        mgr.terminate(std::time::Duration::from_secs(10))
            .await
            .expect("terminate should succeed");

        mgr.disconnect(false, std::time::Duration::from_secs(10))
            .await
            .expect("disconnect should succeed");
    }

    // -----------------------------------------------------------------------
    // dirge-un0g: stale queued stopped events must be drained before the next
    // continue/step/pause, or they satisfy the wait instantly and every op is
    // reported one stop behind.
    // -----------------------------------------------------------------------

    /// Launch handshake (init → launch → stopped(entry, 1) → configurationDone)
    /// then queues a STALE stopped event before answering `continue` with a
    /// fresh breakpoint stop on thread 1.
    async fn fake_stale_stop_adapter(
        mut reader: impl AsyncBufRead + Unpin,
        mut writer: impl AsyncWrite + Unpin,
    ) {
        // initialize
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        let seq = msg["seq"].as_u64().unwrap();
        encode_frame(
            &mut writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "response", "seq": 1, "request_seq": seq, "success": true,
                "command": "initialize",
                "body": { "supportsConfigurationDoneRequest": true }
            }))
            .unwrap(),
        )
        .await
        .unwrap();

        // launch (notify) → stopped on entry, thread 1
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "launch");
        encode_frame(
            &mut writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "event", "seq": 2, "event": "stopped",
                "body": { "reason": "entry", "threadId": 1 }
            }))
            .unwrap(),
        )
        .await
        .unwrap();

        // configurationDone (notify)
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "configurationDone");

        // A stale stopped event, as if a second thread halted alongside the
        // first. Nothing has consumed it — it sits queued in the channel.
        encode_frame(
            &mut writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "event", "seq": 3, "event": "stopped",
                "body": { "reason": "step", "threadId": 99 }
            }))
            .unwrap(),
        )
        .await
        .unwrap();

        // continue → respond, then send the genuine fresh stop.
        let frame = decode_frame(&mut reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "continue");
        let seq = msg["seq"].as_u64().unwrap();
        encode_frame(
            &mut writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "response", "seq": 4, "request_seq": seq, "success": true,
                "command": "continue", "body": { "allThreadsContinued": true }
            }))
            .unwrap(),
        )
        .await
        .unwrap();
        encode_frame(
            &mut writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "event", "seq": 5, "event": "stopped",
                "body": { "reason": "breakpoint", "threadId": 1 }
            }))
            .unwrap(),
        )
        .await
        .unwrap();
    }

    fn client_with_stale_stop_adapter() -> DapClient {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);
        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);
        tokio::spawn(async move {
            fake_stale_stop_adapter(tokio::io::BufReader::new(server_read), server_write).await;
        });
        DapClient::from_rpc(rpc, "fake-adapter")
    }

    #[tokio::test]
    async fn continue_drains_stale_stopped_and_reports_the_fresh_stop() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_stale_stop_adapter();

        let summary = mgr
            .launch_with_client(
                "fake-adapter",
                "/tmp",
                Some("p"),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                Duration::from_secs(5),
                vec![],
            )
            .await
            .unwrap();
        assert_eq!(summary.stop_reason.as_deref(), Some("entry"));

        // Let the stale stopped event land in the channel before we continue.
        tokio::time::sleep(Duration::from_millis(150)).await;

        let outcome = mgr
            .continue_(1, &signal, Duration::from_secs(5))
            .await
            .unwrap();

        // Without draining, the queued step/thread-99 event would satisfy the
        // wait instantly. The fix drains it and reports the fresh breakpoint.
        assert_eq!(
            outcome.stop_reason.as_deref(),
            Some("breakpoint"),
            "continue must report the fresh stop, not a stale queued one"
        );
        assert_eq!(outcome.thread_id, Some(1));
    }

    // -----------------------------------------------------------------------
    // dirge-p3r7: attach must not stall the full request timeout waiting for a
    // stop that a running process never sends, nor record a running debuggee
    // as Stopped.
    // -----------------------------------------------------------------------

    async fn attach_handshake(
        reader: &mut (impl AsyncBufRead + Unpin),
        writer: &mut (impl AsyncWrite + Unpin),
    ) {
        // initialize
        let frame = decode_frame(reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        let seq = msg["seq"].as_u64().unwrap();
        encode_frame(
            writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "response", "seq": 1, "request_seq": seq, "success": true,
                "command": "initialize",
                "body": { "supportsConfigurationDoneRequest": true }
            }))
            .unwrap(),
        )
        .await
        .unwrap();

        // attach (request) → success
        let frame = decode_frame(reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "attach");
        let seq = msg["seq"].as_u64().unwrap();
        encode_frame(
            writer,
            &serde_json::to_vec(&serde_json::json!({
                "type": "response", "seq": 2, "request_seq": seq, "success": true,
                "command": "attach"
            }))
            .unwrap(),
        )
        .await
        .unwrap();

        // configurationDone (notify)
        let frame = decode_frame(reader).await.unwrap();
        let msg: Value = serde_json::from_slice(&frame).unwrap();
        assert_eq!(msg["command"], "configurationDone");
    }

    fn client_with_attach_adapter<F, Fut>(body: F) -> DapClient
    where
        F: FnOnce(
                tokio::io::BufReader<tokio::io::ReadHalf<tokio::io::DuplexStream>>,
                tokio::io::WriteHalf<tokio::io::DuplexStream>,
            ) -> Fut
            + Send
            + 'static,
        Fut: std::future::Future<Output = ()> + Send,
    {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);
        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);
        tokio::spawn(async move {
            body(tokio::io::BufReader::new(server_read), server_write).await;
        });
        DapClient::from_rpc(rpc, "fake-adapter")
    }

    #[tokio::test]
    async fn attach_to_running_process_returns_promptly_as_running() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        // Adapter completes the handshake but never sends a stopped event, then
        // holds the connection open past the grace window.
        let client = client_with_attach_adapter(|mut reader, mut writer| async move {
            attach_handshake(&mut reader, &mut writer).await;
            tokio::time::sleep(Duration::from_secs(5)).await;
        });

        // A generous request timeout — the fix must not wait it out.
        let summary = tokio::time::timeout(
            Duration::from_secs(3),
            mgr.attach_with_client(
                "fake-adapter",
                "/tmp",
                Some(1234),
                None,
                None,
                None,
                &signal,
                client,
                Duration::from_secs(30),
                vec![],
            ),
        )
        .await
        .expect("attach must return within the grace window, not the full timeout")
        .unwrap();

        assert_eq!(
            summary.status,
            SessionStatus::Running,
            "a running debuggee with no stop event must be reported Running, not Stopped"
        );
        assert!(summary.stop_reason.is_none());
    }

    #[tokio::test]
    async fn attach_that_stops_immediately_reports_stopped() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_attach_adapter(|mut reader, mut writer| async move {
            attach_handshake(&mut reader, &mut writer).await;
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 3, "event": "stopped",
                    "body": { "reason": "breakpoint", "threadId": 7 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();
            tokio::time::sleep(Duration::from_secs(5)).await;
        });

        let summary = mgr
            .attach_with_client(
                "fake-adapter",
                "/tmp",
                Some(1234),
                None,
                None,
                None,
                &signal,
                client,
                Duration::from_secs(30),
                vec![],
            )
            .await
            .unwrap();

        assert_eq!(summary.status, SessionStatus::Stopped);
        assert_eq!(summary.stop_reason.as_deref(), Some("breakpoint"));
        assert_eq!(summary.thread_id, Some(7));
    }

    // -----------------------------------------------------------------------
    // dirge-acgj: continue must not hold the `active` lock across its stop-wait,
    // or a concurrent request (pause, snapshot) blocks for continue's whole
    // timeout — exactly the window where interrupting a free-running program
    // matters.
    // -----------------------------------------------------------------------

    /// Launch handshake, then answers `continue` but withholds the stop until
    /// `release` fires — simulating a free-running program.
    fn client_with_free_running_adapter(release: tokio::sync::oneshot::Receiver<()>) -> DapClient {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);
        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);
        tokio::spawn(async move {
            let mut reader = tokio::io::BufReader::new(server_read);
            let mut writer = server_write;

            // initialize
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            let seq = msg["seq"].as_u64().unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "response", "seq": 1, "request_seq": seq, "success": true,
                    "command": "initialize",
                    "body": { "supportsConfigurationDoneRequest": true }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // launch → stopped(entry, 1)
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "launch");
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 2, "event": "stopped",
                    "body": { "reason": "entry", "threadId": 1 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // configurationDone
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "configurationDone");

            // continue → respond, but withhold the stop until released.
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "continue");
            let seq = msg["seq"].as_u64().unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "response", "seq": 3, "request_seq": seq, "success": true,
                    "command": "continue", "body": { "allThreadsContinued": true }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            let _ = release.await;
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 4, "event": "stopped",
                    "body": { "reason": "breakpoint", "threadId": 1 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();
        });
        DapClient::from_rpc(rpc, "fake-adapter")
    }

    #[tokio::test]
    async fn continue_does_not_hold_the_active_lock_while_parked() {
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let mgr = std::sync::Arc::new(DapSessionManager::new());
        let signal = AbortSignal::new();
        let client = client_with_free_running_adapter(release_rx);

        mgr.launch_with_client(
            "fake-adapter",
            "/tmp",
            Some("p"),
            None,
            &[],
            Some(true),
            None,
            &signal,
            client,
            Duration::from_secs(5),
            vec![],
        )
        .await
        .unwrap();

        // Park a continue that will not return until we release the stop.
        let mgr2 = mgr.clone();
        let cont = tokio::spawn(async move {
            let signal = AbortSignal::new();
            mgr2.continue_(1, &signal, Duration::from_secs(5)).await
        });

        // Let continue issue its request and reach the parked stop-wait.
        tokio::time::sleep(Duration::from_millis(200)).await;

        // The active lock must be free while continue parks — a concurrent
        // request completes instead of blocking for continue's full timeout.
        let summary = tokio::time::timeout(Duration::from_secs(1), mgr.active_summary())
            .await
            .expect("active_summary must not block while continue is parked (dirge-acgj)")
            .expect("a session is active");
        assert_eq!(summary.status, SessionStatus::Running);

        // Release the stop; continue completes normally.
        release_tx.send(()).unwrap();
        let outcome = cont.await.unwrap().unwrap();
        assert_eq!(outcome.stop_reason.as_deref(), Some("breakpoint"));
    }

    /// A second continue issued while the first is parked on its stop-wait
    /// must be rejected in phase 1, under the lock, before any request
    /// reaches the adapter — otherwise it swaps out the dead placeholder as
    /// its "receivers" (instant false disconnect) and clears
    /// `stop_wait_in_flight` out from under the first waiter.
    #[tokio::test]
    async fn second_continue_while_parked_is_rejected() {
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let mgr = std::sync::Arc::new(DapSessionManager::new());
        let signal = AbortSignal::new();
        let client = client_with_free_running_adapter(release_rx);

        mgr.launch_with_client(
            "fake-adapter",
            "/tmp",
            Some("p"),
            None,
            &[],
            Some(true),
            None,
            &signal,
            client,
            Duration::from_secs(5),
            vec![],
        )
        .await
        .unwrap();

        // Park the first continue.
        let mgr2 = mgr.clone();
        let cont = tokio::spawn(async move {
            let signal = AbortSignal::new();
            mgr2.continue_(1, &signal, Duration::from_secs(5)).await
        });
        tokio::time::sleep(Duration::from_millis(200)).await;

        // The second continue must bail with the guard error, quickly.
        let err = mgr
            .continue_(1, &signal, Duration::from_secs(1))
            .await
            .expect_err("a second concurrent continue must be rejected");
        assert!(
            err.to_string().contains("already waiting"),
            "unexpected error: {err}"
        );

        // The first continue is unaffected: release the stop, it reports it.
        release_tx.send(()).unwrap();
        let outcome = cont.await.unwrap().unwrap();
        assert_eq!(outcome.stop_reason.as_deref(), Some("breakpoint"));
    }

    /// dirge-8gdv: a `continue_` parked in phase 2 must not, in phase 3,
    /// restore its taken receivers / clear `stop_wait_in_flight` / record the
    /// stop into a session that was replaced (launch/attach) while it was
    /// parked. Phase 3 must check session identity and bail when the active
    /// session is no longer the one the continue started under — otherwise it
    /// overwrites the new session's live event receivers with the old client's
    /// channels and the new session never sees another event.
    #[tokio::test]
    async fn continue_does_not_clobber_a_replacement_session() {
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let mgr = std::sync::Arc::new(DapSessionManager::new());
        let signal = AbortSignal::new();
        let client = client_with_free_running_adapter(release_rx);

        // Install session #1 (id "dap-1"), stopped on entry.
        mgr.launch_with_client(
            "fake-adapter",
            "/tmp",
            Some("p"),
            None,
            &[],
            Some(true),
            None,
            &signal,
            client,
            Duration::from_secs(5),
            vec![],
        )
        .await
        .unwrap();

        // Park a continue_ on session #1: the free-running adapter responds to
        // `continue` and withholds the stop until `release_tx` fires, so phase
        // 2 parks with the `active` lock released.
        let mgr2 = mgr.clone();
        let cont = tokio::spawn(async move {
            let signal = AbortSignal::new();
            mgr2.continue_(1, &signal, Duration::from_secs(5)).await
        });
        tokio::time::sleep(Duration::from_millis(200)).await;

        // While continue_ is parked, simulate a launch/attach swapping in a
        // FRESH session with a different id and its own live event receivers.
        // Take session #1 out of `active` without dropping it so its
        // client/senders stay alive and the parked continue wakes on the real
        // stop (not a disconnect) — the race the fix targets.
        let (stopped_tx_new, stopped_rx_new) = mpsc::unbounded_channel::<StoppedEventBody>();
        let (_output_tx, output_rx) = mpsc::unbounded_channel();
        let (_terminated_tx, terminated_rx) = mpsc::unbounded_channel();
        let (_exited_tx, exited_rx) = mpsc::unbounded_channel();
        let replacement = DapSession {
            id: mgr.next_id(), // "dap-2", differs from the parked session's "dap-1"
            client: client_with_fake_adapter(),
            status: SessionStatus::Running,
            breakpoints: HashMap::new(),
            function_breakpoints: Vec::new(),
            output: String::new(),
            output_truncated: false,
            exit_code: None,
            events: EventReceivers {
                stopped: stopped_rx_new,
                output: output_rx,
                terminated: terminated_rx,
                exited: exited_rx,
            },
            cached_threads: Vec::new(),
            cached_frames: Vec::new(),
            cached_variables: Vec::new(),
            last_stopped_thread_id: None,
            languages: Vec::new(),
            stop_wait_in_flight: false,
        };
        let _parked_session = {
            let mut active = mgr.active.lock().await;
            let old = active.take();
            *active = Some(replacement);
            old
        };

        // Drive the parked continue_ to completion by releasing session #1's
        // stop. After the fix it bails on the id mismatch; before the fix it
        // clobbers the replacement first. The return value is not the point —
        // the invariant checked below is.
        release_tx.send(()).unwrap();
        let _ = cont.await;

        // The replacement session must be completely untouched.
        let mut active = mgr.active.lock().await;
        let session = active.as_mut().expect("replacement session still active");
        assert_eq!(session.id, "dap-2", "replacement id must be unchanged");
        assert!(
            !session.stop_wait_in_flight,
            "replacement's stop_wait_in_flight must stay clear"
        );
        assert_eq!(
            session.status,
            SessionStatus::Running,
            "replacement status must be unchanged"
        );
        let stop_body: StoppedEventBody = serde_json::from_value(serde_json::json!({
            "reason": "breakpoint",
            "threadId": 1
        }))
        .unwrap();
        let send_ok = stopped_tx_new.send(stop_body).is_ok();
        assert!(
            send_ok,
            "replacement's stopped receiver was dropped/clobbered by phase 3"
        );
        assert!(
            session.events.stopped.try_recv().is_ok(),
            "replacement's live receivers must still receive an event \
             (phase 3 must not have swapped in the old client's channels)"
        );
    }

    /// Launch handshake, then `continue` (respond, withhold the stop until
    /// `release` fires), then a `next` step (respond → stopped(step)). Lets a
    /// test cancel the parked continue and verify the session recovers once
    /// the adapter finally stops.
    fn client_with_cancel_recovery_adapter(
        release: tokio::sync::oneshot::Receiver<()>,
    ) -> DapClient {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);
        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);
        tokio::spawn(async move {
            let mut reader = tokio::io::BufReader::new(server_read);
            let mut writer = server_write;

            // initialize
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            let seq = msg["seq"].as_u64().unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "response", "seq": 1, "request_seq": seq, "success": true,
                    "command": "initialize",
                    "body": { "supportsConfigurationDoneRequest": true }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // launch → stopped(entry, 1)
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "launch");
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 2, "event": "stopped",
                    "body": { "reason": "entry", "threadId": 1 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // configurationDone
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "configurationDone");

            // continue → respond, withhold the stop until released.
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "continue");
            let seq = msg["seq"].as_u64().unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "response", "seq": 3, "request_seq": seq, "success": true,
                    "command": "continue", "body": { "allThreadsContinued": true }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            let _ = release.await;
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 4, "event": "stopped",
                    "body": { "reason": "breakpoint", "threadId": 1 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // A later step must still work: next → respond → stopped(step).
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "next");
            let seq = msg["seq"].as_u64().unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "response", "seq": 5, "request_seq": seq, "success": true,
                    "command": "next"
                }))
                .unwrap(),
            )
            .await
            .unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 6, "event": "stopped",
                    "body": { "reason": "step", "threadId": 1 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // Hold the connection open.
            tokio::time::sleep(Duration::from_secs(5)).await;
        });
        DapClient::from_rpc(rpc, "fake-adapter")
    }

    /// The agent tool executor drops the tool future on cancel. Dropping a
    /// parked `continue_` must not destroy the live event receivers or leave
    /// `stop_wait_in_flight` set — the detached stop-wait must still restore
    /// state when the adapter eventually stops, and a later step must work.
    #[tokio::test]
    async fn cancelled_continue_leaves_session_usable() {
        let (release_tx, release_rx) = tokio::sync::oneshot::channel();
        let mgr = std::sync::Arc::new(DapSessionManager::new());
        let signal = AbortSignal::new();
        let client = client_with_cancel_recovery_adapter(release_rx);

        mgr.launch_with_client(
            "fake-adapter",
            "/tmp",
            Some("p"),
            None,
            &[],
            Some(true),
            None,
            &signal,
            client,
            Duration::from_secs(5),
            vec![],
        )
        .await
        .unwrap();

        // Park a continue, then drop its future mid-park (what the tool
        // executor's cancel race does).
        let mgr2 = mgr.clone();
        let cont = tokio::spawn(async move {
            let signal = AbortSignal::new();
            mgr2.continue_(1, &signal, Duration::from_secs(5)).await
        });
        tokio::time::sleep(Duration::from_millis(200)).await;
        cont.abort();
        let _ = cont.await;

        // Adapter finally reports the stop the continue induced.
        release_tx.send(()).unwrap();

        // The detached stop-wait must consume it, restore the receivers, and
        // clear stop_wait_in_flight. Poll until the status flips.
        let deadline = tokio::time::Instant::now() + Duration::from_secs(3);
        loop {
            let summary = mgr.active_summary().await.expect("session still active");
            if summary.status == SessionStatus::Stopped {
                break;
            }
            assert!(
                tokio::time::Instant::now() < deadline,
                "stop never recorded after cancelled continue; session wedged"
            );
            tokio::time::sleep(Duration::from_millis(25)).await;
        }

        // A later step must succeed — not deflected by a stuck
        // stop_wait_in_flight, not parked on dead receivers.
        let summary = mgr
            .step_over(1, &signal, Duration::from_secs(3))
            .await
            .expect("step after a cancelled continue must succeed");
        assert_eq!(summary.stop_reason.as_deref(), Some("step"));
    }

    /// Launch handshake, then queues a never-reported stopped event
    /// (breakpoint on thread 5). If a pause request arrives anyway (the buggy
    /// path), respond success but send no event so the wait times out instead
    /// of hanging.
    fn client_with_queued_stop_adapter() -> DapClient {
        let (client_side, server_side) = tokio::io::duplex(4096);
        let (client_read, client_write) = tokio::io::split(client_side);
        let (server_read, server_write) = tokio::io::split(server_side);
        let client_reader = tokio::io::BufReader::new(client_read);
        let (rpc, _read_task) = DapRpc::new(client_reader, client_write);
        tokio::spawn(async move {
            let mut reader = tokio::io::BufReader::new(server_read);
            let mut writer = server_write;

            // initialize
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            let seq = msg["seq"].as_u64().unwrap();
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "response", "seq": 1, "request_seq": seq, "success": true,
                    "command": "initialize",
                    "body": { "supportsConfigurationDoneRequest": true }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // launch → stopped(entry, 1)
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "launch");
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 2, "event": "stopped",
                    "body": { "reason": "entry", "threadId": 1 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // configurationDone
            let frame = decode_frame(&mut reader).await.unwrap();
            let msg: Value = serde_json::from_slice(&frame).unwrap();
            assert_eq!(msg["command"], "configurationDone");

            // A genuine stop nobody waited for (e.g. breakpoint hit after a
            // timed-out continue). It sits queued in the stopped channel.
            encode_frame(
                &mut writer,
                &serde_json::to_vec(&serde_json::json!({
                    "type": "event", "seq": 3, "event": "stopped",
                    "body": { "reason": "breakpoint", "threadId": 5 }
                }))
                .unwrap(),
            )
            .await
            .unwrap();

            // Buggy path only: answer a pause but never send a stop, so the
            // wait times out rather than hanging the test.
            if let Ok(frame) = decode_frame(&mut reader).await {
                let msg: Value = serde_json::from_slice(&frame).unwrap();
                if msg["command"] == "pause" {
                    let seq = msg["seq"].as_u64().unwrap();
                    let _ = encode_frame(
                        &mut writer,
                        &serde_json::to_vec(&serde_json::json!({
                            "type": "response", "seq": 4, "request_seq": seq,
                            "success": true, "command": "pause"
                        }))
                        .unwrap(),
                    )
                    .await;
                }
            }
            tokio::time::sleep(Duration::from_secs(5)).await;
        });
        DapClient::from_rpc(rpc, "fake-adapter")
    }

    /// A stop queued with no waiter (status still Running) must not be eaten
    /// by pause's stale-stop drain: pausing an already-stopped program yields
    /// no new event, so the drained stop IS the pause result.
    #[tokio::test]
    async fn pause_returns_a_drained_never_reported_stop() {
        let mgr = DapSessionManager::new();
        let signal = AbortSignal::new();
        let client = client_with_queued_stop_adapter();

        let summary = mgr
            .launch_with_client(
                "fake-adapter",
                "/tmp",
                Some("p"),
                None,
                &[],
                Some(true),
                None,
                &signal,
                client,
                Duration::from_secs(5),
                vec![],
            )
            .await
            .unwrap();
        assert_eq!(summary.stop_reason.as_deref(), Some("entry"));

        // Let the never-reported stop land in the channel.
        tokio::time::sleep(Duration::from_millis(150)).await;

        let summary = mgr
            .pause(1, Duration::from_secs(2))
            .await
            .expect("pause must report the drained stop, not time out");
        assert_eq!(summary.status, SessionStatus::Stopped);
        assert_eq!(summary.stop_reason.as_deref(), Some("breakpoint"));
        assert_eq!(summary.thread_id, Some(5));
    }
} // mod tests