miden-debug-engine 0.8.1

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

use dap::prelude::*;
use miden_core::{
    Word,
    mast::{MastNode, MastNodeId},
    operations::{AssemblyOp, DebugOptions, DebugVarInfo, DebugVarLocation},
    precompile::PrecompileTranscript,
    program::Program,
};
use miden_processor::{
    BaseHost, ExecutionError, ExecutionOptions, ExecutionOutput, FastProcessor, FutureMaybeSend,
    Host, ProcessorState, ResumeContext, StackInputs, StackOutputs, TraceError,
    advice::{AdviceInputs, AdviceMutation},
    event::EventError,
    mast::MastForest,
    trace::RowIndex,
};

use super::{TraceEvent, state::extract_current_op};
use crate::debug::{
    DebugVarSnapshot, DebugVarTracker, FormatType, ReadMemoryExpr, resolve_variable_value,
    snapshot_transient_debug_values,
};

// DAP CONFIG
// ================================================================================================

static DAP_CONFIG: OnceLock<DapConfig> = OnceLock::new();

/// Configuration for the DAP debug server.
#[derive(Clone, Debug)]
pub struct DapConfig {
    /// The address to listen on, e.g. "127.0.0.1:4711".
    pub listen_addr: String,
    /// Source path prefixes passed from the compiler/debug plugin. If debug info
    /// stores paths after `-Ztrim-path-prefix`, clients may still send absolute
    /// editor paths; these prefixes describe that explicit mapping.
    source_path_prefixes: Vec<String>,
    /// Shared flag: set by the server when a Phase 2 restart (terminate-and-reconnect) is
    /// requested, read by the caller to decide whether to recompile and re-enter.
    restart_requested: Arc<AtomicBool>,
}

impl DapConfig {
    pub fn new(listen_addr: impl Into<String>) -> Self {
        Self {
            listen_addr: listen_addr.into(),
            source_path_prefixes: Vec::new(),
            restart_requested: Arc::new(AtomicBool::new(false)),
        }
    }

    pub fn with_source_path_prefixes(mut self, prefixes: Vec<PathBuf>) -> Self {
        self.source_path_prefixes = prefixes
            .into_iter()
            .map(|prefix| normalize_source_path(&prefix.to_string_lossy()))
            .filter(|prefix| !prefix.is_empty())
            .collect();
        self
    }

    /// Returns `true` if the server has signalled a Phase 2 restart.
    pub fn restart_requested(&self) -> bool {
        self.restart_requested.load(Ordering::Acquire)
    }

    /// Clear the restart flag (called by the caller after acting on it).
    pub fn reset_restart(&self) {
        self.restart_requested.store(false, Ordering::Release);
    }

    /// Set the global DAP configuration. Must be called before `execute_transaction()`.
    ///
    /// Only the first call takes effect; subsequent calls are ignored.
    pub fn set_global(config: DapConfig) {
        DAP_CONFIG.set(config).ok();
    }
}

impl Default for DapConfig {
    fn default() -> Self {
        Self::new("127.0.0.1:4711")
    }
}

// DAP HOST WRAPPER
// ================================================================================================

/// A single frame in the DAP call stack.
#[derive(Debug, Clone)]
struct DapCallFrame {
    name: String,
    source_path: Option<String>,
    line: i64,
    column: i64,
}

/// A host wrapper that intercepts trace events to track the call stack for DAP stack traces,
/// while delegating all other operations to the inner host.
struct DapHostWrapper<'a, H: Host> {
    inner: &'a mut H,
    call_depth: usize,
    frames: Vec<DapCallFrame>,
}

impl<'a, H: Host> DapHostWrapper<'a, H> {
    fn new(inner: &'a mut H) -> Self {
        Self {
            inner,
            call_depth: 0,
            frames: Vec::new(),
        }
    }
}

impl<H: Host> BaseHost for DapHostWrapper<'_, H> {
    fn get_label_and_source_file(
        &self,
        location: &miden_debug_types::Location,
    ) -> (miden_debug_types::SourceSpan, Option<Arc<miden_debug_types::SourceFile>>) {
        self.inner.get_label_and_source_file(location)
    }

    fn on_debug(
        &mut self,
        process: &ProcessorState<'_>,
        options: &DebugOptions,
    ) -> Result<(), miden_processor::DebugError> {
        self.inner.on_debug(process, options)
    }

    fn on_trace(&mut self, process: &ProcessorState<'_>, trace_id: u32) -> Result<(), TraceError> {
        let event = TraceEvent::from(trace_id);
        match event {
            TraceEvent::FrameStart => {
                self.call_depth += 1;
                self.frames.push(DapCallFrame {
                    name: String::new(),
                    source_path: None,
                    line: 0,
                    column: 0,
                });
            }
            TraceEvent::FrameEnd => {
                self.call_depth = self.call_depth.saturating_sub(1);
                self.frames.pop();
            }
            _ => {}
        }
        self.inner.on_trace(process, trace_id)
    }

    fn resolve_event(
        &self,
        event_id: miden_core::events::EventId,
    ) -> Option<&miden_core::events::EventName> {
        self.inner.resolve_event(event_id)
    }
}

impl<H: Host> Host for DapHostWrapper<'_, H> {
    fn get_mast_forest(&self, node_digest: &Word) -> impl FutureMaybeSend<Option<Arc<MastForest>>> {
        self.inner.get_mast_forest(node_digest)
    }

    fn on_event(
        &mut self,
        process: &ProcessorState<'_>,
    ) -> impl FutureMaybeSend<Result<Vec<AdviceMutation>, EventError>> {
        self.inner.on_event(process)
    }
}

// POLL IMMEDIATELY
// ================================================================================================

/// Resolve a future that is expected to complete immediately (synchronous host methods).
fn poll_immediately<T>(fut: impl std::future::Future<Output = T>) -> T {
    let waker = std::task::Waker::noop();
    let mut cx = std::task::Context::from_waker(waker);
    let mut fut = std::pin::pin!(fut);
    match fut.as_mut().poll(&mut cx) {
        std::task::Poll::Ready(val) => val,
        std::task::Poll::Pending => panic!("future was expected to complete immediately"),
    }
}

macro_rules! write_with_format_type {
    ($out:ident, $read_expr:ident, $value:expr) => {
        match $read_expr.format {
            FormatType::Decimal => write!(&mut $out, "{}", $value).unwrap(),
            FormatType::Hex => write!(&mut $out, "{:0x}", $value).unwrap(),
            FormatType::Binary => write!(&mut $out, "{:0b}", $value).unwrap(),
        }
    };
}

fn read_memory_at_current_state(
    processor: &mut FastProcessor,
    cycle: usize,
    expr: &ReadMemoryExpr,
) -> Result<String, String> {
    use core::fmt::Write;

    use miden_assembly_syntax::ast::types::Type;

    if expr.count > 1 {
        return Err("-count with value > 1 is not yet implemented".into());
    }

    let cycle = RowIndex::from(u32::try_from(cycle).map_err(|_| "cycle value overflowed u32")?);
    let ctx = processor.state().ctx();
    let mut output = String::new();

    if matches!(expr.ty, Type::Felt) {
        if !expr.addr.is_element_aligned() {
            return Err("read failed: type 'felt' must be aligned to an element boundary".into());
        }

        let felt = processor
            .memory()
            .read_element(
                ctx,
                miden_processor::Felt::new(u64::from(expr.addr.addr))
                    .expect("value exceeds field modulus"),
            )
            .ok()
            .unwrap_or(miden_processor::Felt::ZERO);
        write_with_format_type!(output, expr, felt.as_canonical_u64());
        return Ok(output);
    }

    if matches!(
        expr.ty,
        Type::Array(ref array_ty) if array_ty.element_type() == &Type::Felt && array_ty.len() == 4
    ) {
        if !expr.addr.is_word_aligned() {
            return Err("read failed: type 'word' must be aligned to a word boundary".into());
        }

        let word = processor
            .memory()
            .read_word(
                ctx,
                miden_processor::Felt::new(u64::from(expr.addr.addr))
                    .expect("value exceeds field modulus"),
                cycle,
            )
            .ok()
            .unwrap_or_default();

        output.push('[');
        for (i, elem) in word.iter().enumerate() {
            if i > 0 {
                output.push_str(", ");
            }
            write_with_format_type!(output, expr, elem.as_canonical_u64());
        }
        output.push(']');
        return Ok(output);
    }

    if !expr.addr.is_element_aligned() {
        return Err("invalid read: unaligned reads are not supported yet".into());
    }

    let mut elems = Vec::with_capacity(expr.ty.size_in_felts());
    for i in 0..expr.ty.size_in_felts() {
        let addr = expr
            .addr
            .addr
            .checked_add(u32::try_from(i).map_err(|_| "address overflow")?)
            .ok_or_else(|| {
                "invalid read: attempted to read beyond end of linear memory".to_string()
            })?;
        let felt = processor
            .memory()
            .read_element(
                ctx,
                miden_processor::Felt::new(u64::from(addr)).expect("value exceeds field modulus"),
            )
            .ok()
            .unwrap_or_default();
        elems.push(felt);
    }

    let mut bytes = Vec::with_capacity(expr.ty.size_in_bytes());
    let mut needed = expr.ty.size_in_bytes();
    for elem in elems {
        let elem_bytes = super::query::felt_to_le_bytes(elem);
        let take = core::cmp::min(needed, 4);
        bytes.extend(&elem_bytes[..take]);
        needed -= take;
    }

    match &expr.ty {
        Type::I1 => match expr.format {
            FormatType::Decimal => write!(&mut output, "{}", bytes[0] != 0).unwrap(),
            FormatType::Hex => write!(&mut output, "{:#0x}", (bytes[0] != 0) as u8).unwrap(),
            FormatType::Binary => write!(&mut output, "{:#0b}", (bytes[0] != 0) as u8).unwrap(),
        },
        Type::I8 => write_with_format_type!(output, expr, bytes[0] as i8),
        Type::U8 => write_with_format_type!(output, expr, bytes[0]),
        Type::I16 => {
            write_with_format_type!(output, expr, i16::from_le_bytes([bytes[0], bytes[1]]))
        }
        Type::U16 => {
            write_with_format_type!(output, expr, u16::from_le_bytes([bytes[0], bytes[1]]))
        }
        Type::I32 => write_with_format_type!(
            output,
            expr,
            i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
        ),
        Type::U32 => write_with_format_type!(
            output,
            expr,
            u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
        ),
        ty @ (Type::I64 | Type::U64) => {
            let val = u64::from_le_bytes(bytes[..8].try_into().unwrap());
            if matches!(ty, Type::I64) {
                write_with_format_type!(output, expr, val as i64);
            } else {
                write_with_format_type!(output, expr, val);
            }
        }
        ty => return Err(format!("support for reads of type '{ty}' are not implemented yet")),
    }

    Ok(output)
}

fn build_ui_state<H: Host>(
    processor: &mut FastProcessor,
    host: &DapHostWrapper<'_, H>,
    current_asmop: Option<&AssemblyOp>,
    cycle: usize,
) -> crate::exec::DapUiState {
    // Build callstack from the host's frame stack (bottom-to-top order, reversed so the
    // top-of-stack / most-recent frame comes first — matching DAP convention).
    let callstack: Vec<crate::exec::DapUiFrame> = if host.frames.is_empty() {
        // Fallback when no frames have been recorded yet.
        let (name, source_path, line) = match current_asmop {
            Some(asmop) => {
                let loc = resolve_asmop_location(asmop, host);
                let (source_path, line) = loc.map_or((None, 0), |(path, line)| (Some(path), line));
                (asmop.context_name().to_string(), source_path, line)
            }
            None => (format!("cycle {cycle}"), None, 0),
        };
        vec![crate::exec::DapUiFrame {
            name,
            source_path,
            line,
            column: 0,
        }]
    } else {
        host.frames
            .iter()
            .rev()
            .map(|frame| crate::exec::DapUiFrame {
                name: frame.name.clone(),
                source_path: frame.source_path.clone(),
                line: frame.line,
                column: frame.column,
            })
            .collect()
    };

    let current_stack = processor
        .state()
        .get_stack_state()
        .iter()
        .map(|felt| felt.as_canonical_u64())
        .collect();

    crate::exec::DapUiState {
        cycle,
        current_stack,
        callstack,
    }
}

// BREAKPOINT STORAGE
// ================================================================================================

/// A source breakpoint stored from a SetBreakpoints request.
#[derive(Debug, Clone)]
struct StoredBreakpoint {
    /// The source file path as sent by the client.
    path: String,
    /// 1-indexed line number.
    line: i64,
}

/// A function/pattern breakpoint stored from a SetFunctionBreakpoints request.
///
/// Matching is done in two ways:
/// 1. Glob pattern match against the full context name and source path
/// 2. Suffix match — the raw name is checked as a suffix of the context name
///    (e.g. `prologue::foo` matches `::$kernel::prologue::foo`)
#[derive(Debug, Clone)]
struct StoredFunctionBreakpoint {
    /// The raw name string for suffix matching.
    name: String,
    /// Compiled glob pattern for matching.
    pattern: glob::Pattern,
}

struct ContinueBreakpoints<'a> {
    source: &'a [StoredBreakpoint],
    function: &'a [StoredFunctionBreakpoint],
    source_path_prefixes: &'a [String],
}

// RESOLVE ASMOP LOCATION
// ================================================================================================

/// Resolve an `AssemblyOp`'s location to a (file_path, line_number) pair using the host.
fn resolve_asmop_location<H: Host>(asmop: &AssemblyOp, host: &H) -> Option<(String, i64)> {
    let location = asmop.location()?;
    let (span, source_file) = host.get_label_and_source_file(location);
    if let Some(source_file) = source_file {
        let file_line_col = source_file.location(span);
        let path = file_line_col.uri.as_ref().to_string();
        let line = file_line_col.line.to_u32() as i64;
        return Some((path, line));
    }

    crate::debug::resolve_location_from_filesystem(location)
        .map(|(path, line)| (path.display().to_string(), line as i64))
}

fn should_defer_function_breakpoint(resolved: Option<&(String, i64)>, context_name: &str) -> bool {
    !is_internal_procedure(context_name)
        && resolved.is_none_or(|(path, _)| {
            crate::debug::is_internal_source_uri(&miden_debug_types::Uri::new(path))
        })
}

fn is_internal_procedure(context_name: &str) -> bool {
    context_name.contains("::intrinsics::")
}

fn normalize_source_path(path: &str) -> String {
    let path = path.trim();
    let path = path.strip_prefix("file://").unwrap_or(path);
    let path = path.replace('\\', "/");

    let is_absolute = path.starts_with('/');
    let mut parts = Vec::new();
    for part in path.split('/') {
        match part {
            "" | "." => {}
            ".." => {
                if parts.last().is_some_and(|last| *last != "..") {
                    parts.pop();
                } else {
                    parts.push(part);
                }
            }
            _ => parts.push(part),
        }
    }

    let normalized = parts.join("/");
    if is_absolute && !normalized.is_empty() {
        format!("/{normalized}")
    } else {
        normalized
    }
}

fn strip_source_prefix(path: &str, prefix: &str) -> Option<String> {
    let path = path.trim_start_matches('/');
    let prefix = prefix.trim_start_matches('/').trim_end_matches('/');
    path.strip_prefix(prefix)
        .and_then(|rest| rest.strip_prefix('/'))
        .map(ToOwned::to_owned)
}

fn source_paths_match(left: &str, right: &str, trim_prefixes: &[String]) -> bool {
    let left = normalize_source_path(left);
    let right = normalize_source_path(right);
    if left.is_empty() || right.is_empty() {
        return false;
    }

    if left == right {
        return true;
    }

    for prefix in trim_prefixes {
        if strip_source_prefix(&left, prefix).is_some_and(|stripped| stripped == right) {
            return true;
        }
        if strip_source_prefix(&right, prefix).is_some_and(|stripped| stripped == left) {
            return true;
        }
    }

    false
}

fn breakable_source_lines<H: Host>(
    forest: &MastForest,
    host: &H,
    source_path: &str,
    trim_prefixes: &[String],
) -> BTreeSet<i64> {
    let mut lines = BTreeSet::new();

    for (node_idx, node) in forest.nodes().iter().enumerate() {
        let MastNode::Block(block) = node else {
            continue;
        };

        let node_id = MastNodeId::new_unchecked(node_idx as u32);
        for op_idx in 0..block.num_operations() as usize {
            let Some(asmop) = forest.get_assembly_op(node_id, Some(op_idx)) else {
                continue;
            };
            let Some((path, line)) = resolve_asmop_location(asmop, host) else {
                continue;
            };
            if source_paths_match(&path, source_path, trim_prefixes) {
                lines.insert(line);
            }
        }
    }

    lines
}

fn minimum_source_line_for_proc<H: Host>(
    forest: &MastForest,
    host: &H,
    procedure: &str,
    source_path: &str,
    trim_prefixes: &[String],
) -> Option<i64> {
    let mut min_line: Option<i64> = None;

    for (node_idx, node) in forest.nodes().iter().enumerate() {
        let MastNode::Block(block) = node else {
            continue;
        };

        let node_id = MastNodeId::new_unchecked(node_idx as u32);
        for op_idx in 0..block.num_operations() as usize {
            let Some(asmop) = forest.get_assembly_op(node_id, Some(op_idx)) else {
                continue;
            };
            if asmop.context_name() != procedure {
                continue;
            }
            let Some((path, line)) = resolve_asmop_location(asmop, host) else {
                continue;
            };
            if line > 1 && source_paths_match(&path, source_path, trim_prefixes) {
                min_line = Some(min_line.map_or(line, |current| current.min(line)));
            }
        }
    }

    min_line
}

fn resolve_breakpoint_line(lines: &BTreeSet<i64>, requested_line: i64) -> Option<i64> {
    if lines.contains(&requested_line) {
        return Some(requested_line);
    }

    lines
        .range(requested_line..)
        .next()
        .copied()
        .or_else(|| lines.range(..requested_line).next_back().copied())
}

fn debug_var_infos_for_context(ctx: &ResumeContext) -> Vec<DebugVarInfo> {
    let (_op, node_id, op_idx, _control) = extract_current_op(ctx);
    let Some(node_id) = node_id else {
        return Vec::new();
    };
    let Some(op_idx) = op_idx else {
        return Vec::new();
    };

    let forest = ctx.current_forest();
    forest
        .debug_vars_for_operation(node_id, op_idx)
        .iter()
        .filter_map(|var_id| forest.debug_var(*var_id).cloned())
        .collect()
}

fn record_debug_vars(
    debug_state: &mut DapDebugVarState,
    cycle: usize,
    debug_var_infos: Vec<DebugVarInfo>,
) {
    let clk = RowIndex::from(cycle as u32);
    debug_state.debug_vars.record_events(clk, debug_var_infos);
    debug_state.debug_vars.update_to_cycle(clk);
}

fn is_compiler_generated_name(name: &str) -> bool {
    let Some(suffix) = name.strip_prefix("local") else {
        return false;
    };
    !suffix.is_empty() && suffix.chars().all(|ch| ch.is_ascii_digit())
}

fn is_visible_source_var<H: Host>(
    var: &DebugVarSnapshot,
    current_asmop: Option<&AssemblyOp>,
    host: &DapHostWrapper<'_, H>,
    source_path_prefixes: &[String],
    show_all: bool,
) -> bool {
    if show_all {
        return true;
    }

    let name = var.info.name();
    if is_compiler_generated_name(name) {
        return false;
    }

    let Some(current) = current_asmop.and_then(|asmop| resolve_asmop_location(asmop, host)) else {
        return true;
    };

    let Some(var_loc) = var.info.location() else {
        return true;
    };

    source_var_location_is_visible(
        var_loc.uri.as_str(),
        i64::from(var_loc.line.to_u32()),
        &current.0,
        current.1,
        source_path_prefixes,
    )
}

fn source_var_location_is_visible(
    var_path: &str,
    var_line: i64,
    current_path: &str,
    current_line: i64,
    source_path_prefixes: &[String],
) -> bool {
    source_paths_match(var_path, current_path, source_path_prefixes) && var_line < current_line
}

fn resolve_debug_var_value(
    processor: &mut FastProcessor,
    location: &DebugVarLocation,
) -> Option<miden_processor::Felt> {
    let state = processor.state();
    let stack = state.get_stack_state();
    let context = state.ctx();

    let read_mem = |addr: u32| -> Option<miden_processor::Felt> {
        processor
            .memory()
            .read_element(
                context,
                miden_processor::Felt::new(u64::from(addr)).expect("value exceeds field modulus"),
            )
            .ok()
    };

    resolve_variable_value(location, &stack, read_mem, |offset| {
        let fmp_addr = miden_core::FMP_ADDR.as_canonical_u64() as u32;
        let fmp = read_mem(fmp_addr)?;
        let addr = (fmp.as_canonical_u64() as i64 + i64::from(offset)) as u32;
        read_mem(addr)
    })
}

fn debug_var_to_dap_variable(
    processor: &mut FastProcessor,
    var: &DebugVarSnapshot,
) -> types::Variable {
    let name = var.info.name().to_string();
    let location = var.info.value_location();
    let value = resolve_debug_var_value(processor, location)
        .map(|felt| felt.as_canonical_u64().to_string())
        .unwrap_or_else(|| location.to_string());

    types::Variable {
        name,
        value,
        type_field: Some("Felt".into()),
        variables_reference: 0,
        ..Default::default()
    }
}

fn debug_variables<H: Host>(
    processor: &mut FastProcessor,
    host: &DapHostWrapper<'_, H>,
    current_asmop: Option<&AssemblyOp>,
    debug_state: &DapDebugVarState,
    source_path_prefixes: &[String],
    show_all: bool,
) -> Vec<types::Variable> {
    debug_state
        .debug_vars
        .current_variables()
        .filter(|var| {
            is_visible_source_var(var, current_asmop, host, source_path_prefixes, show_all)
        })
        .map(|var| debug_var_to_dap_variable(processor, var))
        .collect()
}

fn format_debug_variables<H: Host>(
    processor: &mut FastProcessor,
    host: &DapHostWrapper<'_, H>,
    current_asmop: Option<&AssemblyOp>,
    debug_state: &DapDebugVarState,
    source_path_prefixes: &[String],
    show_all: bool,
) -> String {
    let variables = debug_variables(
        processor,
        host,
        current_asmop,
        debug_state,
        source_path_prefixes,
        show_all,
    );

    if variables.is_empty() {
        if show_all {
            "No debug variables tracked".into()
        } else {
            "No source-level variables (use 'vars all' to show compiler locals)".into()
        }
    } else {
        variables
            .into_iter()
            .map(|var| format!("{}={}", var.name, var.value))
            .collect::<Vec<_>>()
            .join(", ")
    }
}

fn evaluate_debug_variable<H: Host>(
    processor: &mut FastProcessor,
    host: &DapHostWrapper<'_, H>,
    current_asmop: Option<&AssemblyOp>,
    debug_state: &DapDebugVarState,
    source_path_prefixes: &[String],
    expression: &str,
) -> Option<types::Variable> {
    let var = debug_state.debug_vars.get_variable(expression)?;
    if !is_visible_source_var(var, current_asmop, host, source_path_prefixes, false) {
        return None;
    }
    Some(debug_var_to_dap_variable(processor, var))
}

/// Update the top frame on the host's frame stack with the current asmop's name and location.
///
/// If the frame stack is empty (e.g. before the first FrameStart trace event), a root frame
/// is pushed so there is always at least one frame visible in the stack trace.
fn update_top_frame<H: Host>(host: &mut DapHostWrapper<'_, H>, current_asmop: Option<&AssemblyOp>) {
    let (name, source_path, line) = match current_asmop {
        Some(asmop) => {
            let loc = resolve_asmop_location(asmop, &*host);
            let (source_path, line) = loc.map_or((None, 0), |(p, l)| (Some(p), l));
            (asmop.context_name().to_string(), source_path, line)
        }
        None => (String::new(), None, 0),
    };

    if host.frames.is_empty() {
        host.frames.push(DapCallFrame {
            name,
            source_path,
            line,
            column: 0,
        });
    } else if let Some(top) = host.frames.last_mut() {
        top.name = name;
        top.source_path = source_path;
        top.line = line;
    }
}

// DAP EXECUTOR
// ================================================================================================

/// A [`ProgramExecutor`] that starts a DAP TCP server and steps through the program
/// interactively.
///
/// When used with `TransactionExecutor`, instead of running to completion, `execute()` binds a TCP
/// listener and waits for a DAP client (e.g. VS Code) to connect. The client then controls
/// execution via standard DAP commands (continue, step, breakpoints, inspect stack/memory).
pub struct DapExecutor {
    stack_inputs: StackInputs,
    advice_inputs: AdviceInputs,
    options: ExecutionOptions,
    config: DapConfig,
}

/// Variables reference IDs for scopes.
const SCOPE_STACK: i64 = 1;
const SCOPE_MEMORY: i64 = 2;
const SCOPE_LOCALS: i64 = 3;

struct DapDebugVarState {
    debug_vars: DebugVarTracker,
}

impl DapDebugVarState {
    fn new() -> Self {
        Self {
            debug_vars: DebugVarTracker::new(Rc::new(RefCell::new(BTreeMap::new()))),
        }
    }
}

impl DapExecutor {
    pub fn new(
        stack_inputs: StackInputs,
        advice_inputs: AdviceInputs,
        options: ExecutionOptions,
    ) -> Self {
        let config = DAP_CONFIG.get().cloned().unwrap_or_default();
        DapExecutor {
            stack_inputs,
            advice_inputs,
            options,
            config,
        }
    }

    pub fn execute_async<H: Host + Send>(
        self,
        program: &Program,
        host: &mut H,
    ) -> impl FutureMaybeSend<Result<ExecutionOutput, ExecutionError>> {
        async move { self.run_dap_server(program, host) }
    }
}

impl DapExecutor {
    fn run_dap_server<H: Host>(
        self,
        program: &Program,
        host: &mut H,
    ) -> Result<ExecutionOutput, ExecutionError> {
        // Clone inputs so they can be reused across restarts.
        let stack_inputs = self.stack_inputs;
        let advice_inputs = self.advice_inputs;
        let options = self.options.with_debugging(true).with_tracing(true);

        // Bind TCP listener with SO_REUSEADDR to allow rebinding during Phase 2 restarts.
        let listener = {
            use std::net::ToSocketAddrs;

            use socket2::{Domain, Socket, Type};
            let addr: std::net::SocketAddr = self
                .config
                .listen_addr
                .to_socket_addrs()
                .unwrap_or_else(|e| {
                    panic!("invalid listen address '{}': {e}", self.config.listen_addr)
                })
                .next()
                .unwrap_or_else(|| {
                    panic!(
                        "listen address '{}' did not resolve to any address",
                        self.config.listen_addr
                    )
                });
            let socket = Socket::new(Domain::for_address(addr), Type::STREAM, None)
                .unwrap_or_else(|e| panic!("failed to create socket: {e}"));
            socket.set_reuse_address(true).ok();
            socket
                .bind(&addr.into())
                .unwrap_or_else(|e| panic!("DAP server failed to bind to {addr}: {e}"));
            socket
                .listen(1)
                .unwrap_or_else(|e| panic!("DAP server failed to listen on {addr}: {e}"));
            let listener: TcpListener = socket.into();
            listener
        };
        eprintln!(
            "DAP server listening on {}. Waiting for client connection...",
            self.config.listen_addr
        );

        // Accept one client connection (persists across restarts).
        let (stream, addr) =
            listener.accept().unwrap_or_else(|e| panic!("DAP server accept failed: {e}"));
        eprintln!("DAP client connected from {addr}");

        let reader = BufReader::new(
            stream.try_clone().unwrap_or_else(|e| panic!("Failed to clone TCP stream: {e}")),
        );
        let writer = BufWriter::new(stream);

        let mut server = Server::new(reader, writer);
        let mut breakpoints: Vec<StoredBreakpoint> = Vec::new();
        let mut function_breakpoints: Vec<StoredFunctionBreakpoint> = Vec::new();
        let mut is_restart = false;
        // VS Code's flow waits for `configurationDone` before stopping the VM at
        // the entry point; Zed's flow never sends `configurationDone`. Track
        // whether the entry stop has already been announced so it fires
        // exactly once regardless of which client we're talking to.
        let mut entry_announced = false;
        let restart_flag = self.config.restart_requested.clone();
        let source_path_prefixes = self.config.source_path_prefixes.clone();

        // Outer restart loop — on restart, the DapHostWrapper borrow is dropped,
        // a fresh FastProcessor is created, and the inner event loop re-enters.
        //
        // NOTE: The inner host `H` (e.g. from miden-client's transaction executor)
        // retains mutations from prior execution. A restarted session may therefore
        // diverge from a pristine fresh session. Phase 2 (terminate-and-reconnect)
        // solves this by creating a completely fresh host.
        loop {
            let mut processor =
                FastProcessor::new_with_options(stack_inputs, advice_inputs.clone(), options)
                    .expect("advice inputs should fit advice map limits");

            let resume_ctx = processor.get_initial_resume_context(program)?;
            let mut wrapper = DapHostWrapper::new(host);

            let mut resume_ctx = Some(resume_ctx);
            let mut cycle: usize = 0;
            let mut current_asmop: Option<AssemblyOp> = None;
            let mut debug_state = DapDebugVarState::new();

            // Extract initial asmop and populate the root frame.
            if let Some(ctx) = resume_ctx.as_ref() {
                let (_op, node_id, op_idx, _control) = extract_current_op(ctx);
                current_asmop = node_id
                    .and_then(|nid| ctx.current_forest().get_assembly_op(nid, op_idx).cloned());
            }
            update_top_frame(&mut wrapper, current_asmop.as_ref());

            // On restart, emit initial state immediately (no handshake needed).
            if is_restart {
                send_ui_state_snapshot(
                    &mut server,
                    &mut processor,
                    &wrapper,
                    current_asmop.as_ref(),
                    cycle,
                );
                server
                    .send_event(Event::Stopped(events::StoppedEventBody {
                        reason: types::StoppedEventReason::Entry,
                        description: Some("Restarted at program entry".into()),
                        thread_id: Some(1),
                        preserve_focus_hint: None,
                        text: None,
                        all_threads_stopped: Some(true),
                        hit_breakpoint_ids: None,
                    }))
                    .ok();
            }

            let mut restart_requested = false;
            let mut phase2_requested = false;

            loop {
                let req = match server.poll_request() {
                    Ok(Some(req)) => req,
                    Ok(None) => break,
                    Err(e) => {
                        eprintln!("DAP protocol error: {e:#?}");
                        break;
                    }
                };

                match req.command {
                    // --- Handshake ---
                    Command::Initialize(_) => {
                        let caps = types::Capabilities {
                            supports_configuration_done_request: Some(true),
                            supports_stepping_granularity: Some(true),
                            supports_restart_request: Some(true),
                            supports_function_breakpoints: Some(true),
                            supports_evaluate_for_hovers: Some(true),
                            ..Default::default()
                        };
                        let resp = req.success(ResponseBody::Initialize(caps));
                        server.respond(resp).ok();
                        server.send_event(Event::Initialized).ok();
                    }

                    Command::Launch(_) => {
                        server.respond(req.success(ResponseBody::Launch)).ok();
                        // Re-emit Initialized — some clients only listen for it after
                        // launch/attach has been acknowledged. VS Code tolerates the
                        // duplicate (it ignores Initialized after the first one).
                        server.send_event(Event::Initialized).ok();
                        announce_entry_stop(
                            &mut server,
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            cycle,
                            &mut entry_announced,
                        );
                    }

                    // VS Code's default flow issues `attach` when launch.json uses
                    // `request: "attach"`. The server is already bound to a TCP port and
                    // running against a compiled script, so there is nothing to do beyond
                    // acknowledging the request — mirror the `Launch` handling.
                    Command::Attach(_) => {
                        server.respond(req.success(ResponseBody::Attach)).ok();
                        // See the Launch arm — re-emit Initialized for clients that
                        // miss the first one.
                        server.send_event(Event::Initialized).ok();
                        // Zed never sends `configurationDone`, so announce the entry
                        // stop here as well. The `entry_announced` guard makes this
                        // a no-op when `configurationDone` later fires (VS Code path).
                        announce_entry_stop(
                            &mut server,
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            cycle,
                            &mut entry_announced,
                        );
                    }

                    Command::ConfigurationDone => {
                        if let Ok(resp) = req.ack() {
                            server.respond(resp).ok();
                        }
                        announce_entry_stop(
                            &mut server,
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            cycle,
                            &mut entry_announced,
                        );
                    }

                    Command::Restart(ref args) => {
                        // `args.is_some()` means the client sent a non-null
                        // `RestartArguments` envelope; `arguments.arguments.is_some()`
                        // means that envelope carries an explicit launch/attach payload.
                        // Only the latter signals "Phase 2: recompile from disk".
                        let has_arguments =
                            args.as_ref().and_then(|a| a.arguments.as_ref()).is_some();
                        server.respond(req.success(ResponseBody::Restart)).ok();
                        if has_arguments {
                            // Phase 2: terminate-and-reconnect for recompilation.
                            restart_flag.store(true, Ordering::Release);
                            server
                                .send_event(Event::Terminated(Some(events::TerminatedEventBody {
                                    restart: Some(serde_json::Value::Bool(true)),
                                })))
                                .ok();
                            phase2_requested = true;
                            break;
                        } else {
                            // Phase 1: in-process reset (same program, same host).
                            restart_requested = true;
                            break;
                        }
                    }

                    Command::Disconnect(_) => {
                        if let Ok(resp) = req.ack() {
                            server.respond(resp).ok();
                        }
                        break;
                    }

                    // --- Execution Control ---
                    Command::Continue(_) => {
                        let resp =
                            req.success(ResponseBody::Continue(responses::ContinueResponse {
                                all_threads_continued: Some(true),
                            }));
                        server.respond(resp).ok();

                        let continue_breakpoints = ContinueBreakpoints {
                            source: &breakpoints,
                            function: &function_breakpoints,
                            source_path_prefixes: &source_path_prefixes,
                        };
                        match step_until_breakpoint(
                            &mut processor,
                            &mut wrapper,
                            &mut resume_ctx,
                            &mut cycle,
                            &mut current_asmop,
                            &continue_breakpoints,
                            &mut debug_state,
                        ) {
                            StepResult::Stepped | StepResult::Breakpoint(_) => {
                                send_ui_state_snapshot(
                                    &mut server,
                                    &mut processor,
                                    &wrapper,
                                    current_asmop.as_ref(),
                                    cycle,
                                );
                                server
                                    .send_event(Event::Stopped(events::StoppedEventBody {
                                        reason: types::StoppedEventReason::Breakpoint,
                                        description: Some("Hit breakpoint".into()),
                                        thread_id: Some(1),
                                        preserve_focus_hint: None,
                                        text: None,
                                        all_threads_stopped: Some(true),
                                        hit_breakpoint_ids: None,
                                    }))
                                    .ok();
                            }
                            StepResult::Terminated => {
                                server.send_event(Event::Terminated(None)).ok();
                            }
                            StepResult::Error(e) => {
                                server.send_event(Event::Terminated(None)).ok();
                                return Err(e);
                            }
                        }
                    }

                    Command::Next(ref args) => {
                        let is_instruction_step = matches!(
                            args.granularity,
                            Some(types::SteppingGranularity::Instruction)
                        );
                        let resp = req.success(ResponseBody::Next);
                        server.respond(resp).ok();

                        let step_result = if is_instruction_step {
                            step_over(
                                &mut processor,
                                &mut wrapper,
                                &mut resume_ctx,
                                &mut cycle,
                                &mut current_asmop,
                                &mut debug_state,
                            )
                        } else {
                            step_next_line(
                                &mut processor,
                                &mut wrapper,
                                &mut resume_ctx,
                                &mut cycle,
                                &mut current_asmop,
                                &source_path_prefixes,
                                &mut debug_state,
                            )
                        };

                        match step_result {
                            StepResult::Stepped | StepResult::Breakpoint(_) => {
                                if resume_ctx.is_none() {
                                    server.send_event(Event::Terminated(None)).ok();
                                } else {
                                    send_ui_state_snapshot(
                                        &mut server,
                                        &mut processor,
                                        &wrapper,
                                        current_asmop.as_ref(),
                                        cycle,
                                    );
                                    send_stopped_step(&mut server);
                                }
                            }
                            StepResult::Terminated => {
                                server.send_event(Event::Terminated(None)).ok();
                            }
                            StepResult::Error(e) => {
                                server.send_event(Event::Terminated(None)).ok();
                                return Err(e);
                            }
                        }
                    }

                    Command::StepIn(_) => {
                        let resp = req.success(ResponseBody::StepIn);
                        server.respond(resp).ok();

                        match step_one(
                            &mut processor,
                            &mut wrapper,
                            &mut resume_ctx,
                            &mut cycle,
                            &mut current_asmop,
                            &mut debug_state,
                        ) {
                            StepResult::Stepped | StepResult::Breakpoint(_) => {
                                if resume_ctx.is_none() {
                                    server.send_event(Event::Terminated(None)).ok();
                                } else {
                                    send_ui_state_snapshot(
                                        &mut server,
                                        &mut processor,
                                        &wrapper,
                                        current_asmop.as_ref(),
                                        cycle,
                                    );
                                    send_stopped_step(&mut server);
                                }
                            }
                            StepResult::Terminated => {
                                server.send_event(Event::Terminated(None)).ok();
                            }
                            StepResult::Error(e) => {
                                server.send_event(Event::Terminated(None)).ok();
                                return Err(e);
                            }
                        }
                    }

                    Command::StepOut(_) => {
                        let resp = req.success(ResponseBody::StepOut);
                        server.respond(resp).ok();

                        match step_out(
                            &mut processor,
                            &mut wrapper,
                            &mut resume_ctx,
                            &mut cycle,
                            &mut current_asmop,
                            &mut debug_state,
                        ) {
                            StepResult::Stepped | StepResult::Breakpoint(_) => {
                                if resume_ctx.is_none() {
                                    server.send_event(Event::Terminated(None)).ok();
                                } else {
                                    send_ui_state_snapshot(
                                        &mut server,
                                        &mut processor,
                                        &wrapper,
                                        current_asmop.as_ref(),
                                        cycle,
                                    );
                                    send_stopped_step(&mut server);
                                }
                            }
                            StepResult::Terminated => {
                                server.send_event(Event::Terminated(None)).ok();
                            }
                            StepResult::Error(e) => {
                                server.send_event(Event::Terminated(None)).ok();
                                return Err(e);
                            }
                        }
                    }

                    // --- State Inspection ---
                    Command::Threads => {
                        let resp = req.success(ResponseBody::Threads(responses::ThreadsResponse {
                            threads: vec![types::Thread {
                                id: 1,
                                name: "main".into(),
                            }],
                        }));
                        server.respond(resp).ok();
                    }

                    Command::StackTrace(ref _args) => {
                        // Build stack frames from the host's frame stack (reversed: top-of-stack
                        // first, matching DAP convention).
                        let frames: Vec<types::StackFrame> = if wrapper.frames.is_empty() {
                            // Fallback when no frames have been recorded.
                            let (name, source, line) = if let Some(asmop) = current_asmop.as_ref() {
                                let loc = resolve_asmop_location(asmop, &wrapper);
                                let (path, line_num) =
                                    loc.unwrap_or_else(|| ("<unknown>".into(), 0));
                                let source = types::Source {
                                    name: Some(
                                        path.rsplit('/').next().unwrap_or(&path).to_string(),
                                    ),
                                    path: Some(path),
                                    ..Default::default()
                                };
                                (asmop.context_name().to_string(), Some(source), line_num)
                            } else {
                                (format!("cycle {cycle}"), None, 0)
                            };
                            vec![types::StackFrame {
                                id: 0,
                                name,
                                source,
                                line,
                                column: 0,
                                ..Default::default()
                            }]
                        } else {
                            wrapper
                                .frames
                                .iter()
                                .rev()
                                .enumerate()
                                .map(|(id, frame)| {
                                    let source =
                                        frame.source_path.as_ref().map(|path| types::Source {
                                            name: Some(
                                                path.rsplit('/').next().unwrap_or(path).to_string(),
                                            ),
                                            path: Some(path.clone()),
                                            ..Default::default()
                                        });
                                    types::StackFrame {
                                        id: id as i64,
                                        name: frame.name.clone(),
                                        source,
                                        line: frame.line,
                                        column: frame.column,
                                        ..Default::default()
                                    }
                                })
                                .collect()
                        };

                        let total = frames.len() as i64;
                        let resp =
                            req.success(ResponseBody::StackTrace(responses::StackTraceResponse {
                                stack_frames: frames,
                                total_frames: Some(total),
                            }));
                        server.respond(resp).ok();
                    }

                    Command::Scopes(ref _args) => {
                        let resp = req.success(ResponseBody::Scopes(responses::ScopesResponse {
                            scopes: vec![
                                types::Scope {
                                    name: "Local Variables".into(),
                                    variables_reference: SCOPE_LOCALS,
                                    presentation_hint: Some(types::ScopePresentationhint::Locals),
                                    named_variables: Some(
                                        debug_variables(
                                            &mut processor,
                                            &wrapper,
                                            current_asmop.as_ref(),
                                            &debug_state,
                                            &source_path_prefixes,
                                            false,
                                        )
                                        .len() as i64,
                                    ),
                                    expensive: false,
                                    ..Default::default()
                                },
                                types::Scope {
                                    name: "Operand Stack".into(),
                                    variables_reference: SCOPE_STACK,
                                    expensive: false,
                                    ..Default::default()
                                },
                                types::Scope {
                                    name: "Memory".into(),
                                    variables_reference: SCOPE_MEMORY,
                                    expensive: false,
                                    ..Default::default()
                                },
                            ],
                        }));
                        server.respond(resp).ok();
                    }

                    Command::Variables(ref args) => {
                        let variables = match args.variables_reference {
                            SCOPE_LOCALS => debug_variables(
                                &mut processor,
                                &wrapper,
                                current_asmop.as_ref(),
                                &debug_state,
                                &source_path_prefixes,
                                false,
                            ),
                            SCOPE_STACK => {
                                let state = processor.state();
                                let stack = state.get_stack_state();
                                stack
                                    .iter()
                                    .enumerate()
                                    .map(|(i, felt)| types::Variable {
                                        name: format!("[{i}]"),
                                        value: format!("{}", felt.as_canonical_u64()),
                                        type_field: Some("Felt".into()),
                                        variables_reference: 0,
                                        ..Default::default()
                                    })
                                    .collect()
                            }
                            SCOPE_MEMORY => {
                                let state = processor.state();
                                let ctx = state.ctx();
                                let mem = state.get_mem_state(ctx);
                                mem.iter()
                                    .map(|(addr, felt)| {
                                        let addr_u32: u32 = (*addr).into();
                                        types::Variable {
                                            name: format!("0x{addr_u32:08x}"),
                                            value: format!("{}", felt.as_canonical_u64()),
                                            type_field: Some("Felt".into()),
                                            variables_reference: 0,
                                            ..Default::default()
                                        }
                                    })
                                    .collect()
                            }
                            _ => Vec::new(),
                        };

                        let resp =
                            req.success(ResponseBody::Variables(responses::VariablesResponse {
                                variables,
                            }));
                        server.respond(resp).ok();
                    }

                    // --- Breakpoints ---
                    Command::SetBreakpoints(ref args) => {
                        let source_path = args.source.path.clone().unwrap_or_default();
                        breakpoints.retain(|bp| {
                            !source_paths_match(&bp.path, &source_path, &source_path_prefixes)
                        });
                        let breakable_lines = breakable_source_lines(
                            program.mast_forest(),
                            &wrapper,
                            &source_path,
                            &source_path_prefixes,
                        );

                        let mut confirmed = Vec::new();
                        if let Some(bps) = &args.breakpoints {
                            for sbp in bps {
                                let resolved_line =
                                    resolve_breakpoint_line(&breakable_lines, sbp.line);
                                let verified = resolved_line.is_some();
                                let actual_line = resolved_line.unwrap_or(sbp.line);
                                let message = match resolved_line {
                                    Some(line) if line != sbp.line => {
                                        Some(format!("Moved to executable line {line}."))
                                    }
                                    Some(_) => None,
                                    None => Some(
                                        "No executable Miden operation is mapped to this source \
                                         file."
                                            .into(),
                                    ),
                                };

                                if verified {
                                    breakpoints.push(StoredBreakpoint {
                                        path: source_path.clone(),
                                        line: actual_line,
                                    });
                                }

                                confirmed.push(types::Breakpoint {
                                    verified,
                                    message,
                                    line: Some(actual_line),
                                    source: Some(types::Source {
                                        path: Some(source_path.clone()),
                                        ..Default::default()
                                    }),
                                    ..Default::default()
                                });
                            }
                        }

                        let resp = req.success(ResponseBody::SetBreakpoints(
                            responses::SetBreakpointsResponse {
                                breakpoints: confirmed,
                            },
                        ));
                        server.respond(resp).ok();
                    }

                    Command::SetFunctionBreakpoints(ref args) => {
                        function_breakpoints.clear();
                        let mut confirmed = Vec::new();
                        for fbp in &args.breakpoints {
                            let verified = match glob::Pattern::new(&fbp.name) {
                                Ok(pattern) => {
                                    function_breakpoints.push(StoredFunctionBreakpoint {
                                        name: fbp.name.clone(),
                                        pattern,
                                    });
                                    true
                                }
                                Err(_) => false,
                            };
                            confirmed.push(types::Breakpoint {
                                verified,
                                ..Default::default()
                            });
                        }

                        let resp = req.success(ResponseBody::SetFunctionBreakpoints(
                            responses::SetFunctionBreakpointsResponse {
                                breakpoints: confirmed,
                            },
                        ));
                        server.respond(resp).ok();
                    }

                    // --- Evaluate (custom state query) ---
                    Command::Evaluate(ref args) if args.expression == "__miden_ui_state" => {
                        let state_json = serde_json::to_string(&build_ui_state(
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            cycle,
                        ))
                        .expect("bundled DAP UI state should serialize");
                        let resp =
                            req.success(ResponseBody::Evaluate(responses::EvaluateResponse {
                                result: state_json,
                                type_field: Some("json".into()),
                                presentation_hint: None,
                                variables_reference: 0,
                                named_variables: None,
                                indexed_variables: None,
                                memory_reference: None,
                            }));
                        server.respond(resp).ok();
                    }

                    Command::Evaluate(ref args)
                        if args.expression.starts_with("__miden_read_memory ") =>
                    {
                        let expr = args
                            .expression
                            .strip_prefix("__miden_read_memory ")
                            .expect("prefix checked above");

                        match expr.parse::<ReadMemoryExpr>().and_then(|expr| {
                            read_memory_at_current_state(&mut processor, cycle, &expr)
                        }) {
                            Ok(result) => {
                                let resp = req.success(ResponseBody::Evaluate(
                                    responses::EvaluateResponse {
                                        result,
                                        type_field: Some("string".into()),
                                        presentation_hint: None,
                                        variables_reference: 0,
                                        named_variables: None,
                                        indexed_variables: None,
                                        memory_reference: None,
                                    },
                                ));
                                server.respond(resp).ok();
                            }
                            Err(err) => {
                                server.respond(req.error(&err)).ok();
                            }
                        }
                    }

                    Command::Evaluate(ref args)
                        if args.expression == "vars" || args.expression == ":vars" =>
                    {
                        let result = format_debug_variables(
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            &debug_state,
                            &source_path_prefixes,
                            false,
                        );
                        let resp =
                            req.success(ResponseBody::Evaluate(responses::EvaluateResponse {
                                result,
                                type_field: Some("string".into()),
                                presentation_hint: None,
                                variables_reference: 0,
                                named_variables: None,
                                indexed_variables: None,
                                memory_reference: None,
                            }));
                        server.respond(resp).ok();
                    }

                    Command::Evaluate(ref args)
                        if args.expression == "vars all" || args.expression == ":vars all" =>
                    {
                        let result = format_debug_variables(
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            &debug_state,
                            &source_path_prefixes,
                            true,
                        );
                        let resp =
                            req.success(ResponseBody::Evaluate(responses::EvaluateResponse {
                                result,
                                type_field: Some("string".into()),
                                presentation_hint: None,
                                variables_reference: 0,
                                named_variables: None,
                                indexed_variables: None,
                                memory_reference: None,
                            }));
                        server.respond(resp).ok();
                    }

                    Command::Evaluate(ref args) => {
                        if let Some(variable) = evaluate_debug_variable(
                            &mut processor,
                            &wrapper,
                            current_asmop.as_ref(),
                            &debug_state,
                            &source_path_prefixes,
                            args.expression.as_str(),
                        ) {
                            let resp =
                                req.success(ResponseBody::Evaluate(responses::EvaluateResponse {
                                    result: variable.value,
                                    type_field: variable.type_field,
                                    presentation_hint: None,
                                    variables_reference: 0,
                                    named_variables: None,
                                    indexed_variables: None,
                                    memory_reference: None,
                                }));
                            server.respond(resp).ok();
                        } else {
                            server.respond(req.error("Unsupported expression")).ok();
                        }
                    }

                    // --- Unhandled ---
                    _ => {
                        server.respond(req.error("Unsupported command")).ok();
                    }
                }
            }

            if phase2_requested {
                eprintln!("DAP Phase 2 restart: returning from execute() for recompilation...");
                return Ok(ExecutionOutput {
                    stack: StackOutputs::new(&[]).expect("empty stack outputs"),
                    advice: Default::default(),
                    memory: Default::default(),
                    final_precompile_transcript: PrecompileTranscript::default(),
                });
            }

            if restart_requested {
                is_restart = true;
                eprintln!("DAP restart requested. Resetting processor...");
                // wrapper is dropped here, releasing the &mut H borrow.
                // The outer loop creates a fresh processor and wrapper.
                continue;
            }

            // Normal exit (disconnect or connection closed).
            eprintln!("DAP session ended. Building execution output...");

            // Run the program to completion if it hasn't finished.
            if let Some(ctx) = resume_ctx {
                let mut ctx = Some(ctx);
                while let Some(resume) = ctx.take() {
                    match poll_immediately(processor.step(&mut wrapper, resume)) {
                        Ok(Some(new_ctx)) => {
                            ctx = Some(new_ctx);
                        }
                        Ok(None) => break,
                        Err(e) => return Err(e),
                    }
                }
            }

            // Build ExecutionOutput from the processor's final state.
            let stack_top: Vec<_> = processor.stack_top().iter().rev().copied().collect();
            let stack = StackOutputs::new(&stack_top)
                .unwrap_or_else(|_| StackOutputs::new(&[]).expect("empty stack outputs"));

            let (advice, memory, final_precompile_transcript) = processor.into_parts();
            return Ok(ExecutionOutput {
                stack,
                advice,
                memory,
                final_precompile_transcript,
            });
        } // end outer restart loop
    }
}

// STEPPING HELPERS
// ================================================================================================

fn advance_one<H: Host>(
    processor: &mut FastProcessor,
    host: &mut DapHostWrapper<'_, H>,
    ctx: ResumeContext,
    cycle: &mut usize,
    current_asmop: &mut Option<AssemblyOp>,
    debug_state: &mut DapDebugVarState,
) -> Result<Option<ResumeContext>, ExecutionError> {
    let (_op, node_id, op_idx, _control) = extract_current_op(&ctx);
    let executed_asmop =
        node_id.and_then(|nid| ctx.current_forest().get_assembly_op(nid, op_idx).cloned());
    let mut debug_var_infos = debug_var_infos_for_context(&ctx);
    let pre_step_stack = processor.state().get_stack_state();
    snapshot_transient_debug_values(&mut debug_var_infos, &pre_step_stack);
    match poll_immediately(processor.step(host, ctx)) {
        Ok(Some(new_ctx)) => {
            *cycle += 1;
            record_debug_vars(debug_state, *cycle, debug_var_infos);
            *current_asmop = executed_asmop;
            Ok(Some(new_ctx))
        }
        Ok(None) => {
            *cycle += 1;
            *current_asmop = None;
            Ok(None)
        }
        Err(e) => Err(e),
    }
}

fn is_next_source_line(
    start_proc: Option<&str>,
    start_loc: Option<&(String, i64)>,
    current_proc: Option<&str>,
    current_loc: Option<&(String, i64)>,
    source_path_prefixes: &[String],
    minimum_source_line: Option<i64>,
) -> bool {
    let same_proc = match (start_proc, current_proc) {
        (Some(start), Some(current)) => start == current,
        (Some(_), None) => false,
        _ => true,
    };
    if !same_proc {
        return false;
    }

    if let (Some(minimum_source_line), Some(current)) = (minimum_source_line, current_loc)
        && current.1 < minimum_source_line
    {
        return false;
    }

    match (start_loc, current_loc) {
        (Some(start), Some(current)) => {
            source_paths_match(&start.0, &current.0, source_path_prefixes) && start.1 != current.1
        }
        (None, Some(_)) => true,
        _ => false,
    }
}

/// Execute a single VM step.
fn step_one<H: Host>(
    processor: &mut FastProcessor,
    host: &mut DapHostWrapper<'_, H>,
    resume_ctx: &mut Option<ResumeContext>,
    cycle: &mut usize,
    current_asmop: &mut Option<AssemblyOp>,
    debug_state: &mut DapDebugVarState,
) -> StepResult {
    let ctx = match resume_ctx.take() {
        Some(ctx) => ctx,
        None => return StepResult::Terminated,
    };

    match advance_one(processor, host, ctx, cycle, current_asmop, debug_state) {
        Ok(Some(new_ctx)) => {
            *resume_ctx = Some(new_ctx);
            update_top_frame(host, current_asmop.as_ref());
            StepResult::Stepped
        }
        Ok(None) => StepResult::Terminated,
        Err(e) => StepResult::Error(e),
    }
}

/// Step over: advance until the current assembly operation changes.
fn step_over<H: Host>(
    processor: &mut FastProcessor,
    host: &mut DapHostWrapper<'_, H>,
    resume_ctx: &mut Option<ResumeContext>,
    cycle: &mut usize,
    current_asmop: &mut Option<AssemblyOp>,
    debug_state: &mut DapDebugVarState,
) -> StepResult {
    let original_asmop = current_asmop.clone();

    loop {
        let ctx = match resume_ctx.take() {
            Some(ctx) => ctx,
            None => return StepResult::Terminated,
        };

        match advance_one(processor, host, ctx, cycle, current_asmop, debug_state) {
            Ok(Some(new_ctx)) => {
                *resume_ctx = Some(new_ctx);

                if *current_asmop != original_asmop {
                    update_top_frame(host, current_asmop.as_ref());
                    return StepResult::Stepped;
                }
            }
            Ok(None) => return StepResult::Terminated,
            Err(e) => return StepResult::Error(e),
        }
    }
}

/// Step over source lines: advance until the current source line changes.
fn step_next_line<H: Host>(
    processor: &mut FastProcessor,
    host: &mut DapHostWrapper<'_, H>,
    resume_ctx: &mut Option<ResumeContext>,
    cycle: &mut usize,
    current_asmop: &mut Option<AssemblyOp>,
    source_path_prefixes: &[String],
    debug_state: &mut DapDebugVarState,
) -> StepResult {
    let original_asmop = current_asmop.clone();
    let start_proc = original_asmop.as_ref().map(|asmop| asmop.context_name().to_string());
    let start_loc = original_asmop.as_ref().and_then(|asmop| resolve_asmop_location(asmop, host));
    let minimum_source_line = if let (Some(ctx), Some(proc), Some((source_path, _line))) =
        (resume_ctx.as_ref(), start_proc.as_deref(), start_loc.as_ref())
    {
        minimum_source_line_for_proc(
            ctx.current_forest(),
            host,
            proc,
            source_path,
            source_path_prefixes,
        )
    } else {
        None
    };

    loop {
        let ctx = match resume_ctx.take() {
            Some(ctx) => ctx,
            None => return StepResult::Terminated,
        };

        match advance_one(processor, host, ctx, cycle, current_asmop, debug_state) {
            Ok(Some(new_ctx)) => {
                *resume_ctx = Some(new_ctx);

                let current_proc =
                    current_asmop.as_ref().map(|asmop| asmop.context_name().to_string());
                let current_loc =
                    current_asmop.as_ref().and_then(|asmop| resolve_asmop_location(asmop, host));
                let has_source_context = start_loc.is_some() || current_loc.is_some();
                let reached_next = if has_source_context {
                    is_next_source_line(
                        start_proc.as_deref(),
                        start_loc.as_ref(),
                        current_proc.as_deref(),
                        current_loc.as_ref(),
                        source_path_prefixes,
                        minimum_source_line,
                    )
                } else {
                    *current_asmop != original_asmop
                };

                if reached_next {
                    update_top_frame(host, current_asmop.as_ref());
                    return StepResult::Stepped;
                }
            }
            Ok(None) => return StepResult::Terminated,
            Err(e) => return StepResult::Error(e),
        }
    }
}

/// Step out: advance until call depth decreases.
fn step_out<H: Host>(
    processor: &mut FastProcessor,
    host: &mut DapHostWrapper<'_, H>,
    resume_ctx: &mut Option<ResumeContext>,
    cycle: &mut usize,
    current_asmop: &mut Option<AssemblyOp>,
    debug_state: &mut DapDebugVarState,
) -> StepResult {
    let target_depth = host.call_depth.saturating_sub(1);

    loop {
        let ctx = match resume_ctx.take() {
            Some(ctx) => ctx,
            None => return StepResult::Terminated,
        };

        match advance_one(processor, host, ctx, cycle, current_asmop, debug_state) {
            Ok(Some(new_ctx)) => {
                *resume_ctx = Some(new_ctx);

                if host.call_depth <= target_depth {
                    update_top_frame(host, current_asmop.as_ref());
                    return StepResult::Stepped;
                }
            }
            Ok(None) => return StepResult::Terminated,
            Err(e) => return StepResult::Error(e),
        }
    }
}

/// Continue: step until a breakpoint is hit or the program terminates.
fn step_until_breakpoint<H: Host>(
    processor: &mut FastProcessor,
    host: &mut DapHostWrapper<'_, H>,
    resume_ctx: &mut Option<ResumeContext>,
    cycle: &mut usize,
    current_asmop: &mut Option<AssemblyOp>,
    breakpoints: &ContinueBreakpoints<'_>,
    debug_state: &mut DapDebugVarState,
) -> StepResult {
    loop {
        let ctx = match resume_ctx.take() {
            Some(ctx) => ctx,
            None => return StepResult::Terminated,
        };

        match advance_one(processor, host, ctx, cycle, current_asmop, debug_state) {
            Ok(Some(new_ctx)) => {
                *resume_ctx = Some(new_ctx);

                if let Some(asmop) = current_asmop.as_ref() {
                    let resolved = resolve_asmop_location(asmop, host);

                    // Check line breakpoints
                    if let Some((ref path, line)) = resolved {
                        for bp in breakpoints.source {
                            if bp.line == line
                                && source_paths_match(
                                    path,
                                    &bp.path,
                                    breakpoints.source_path_prefixes,
                                )
                            {
                                update_top_frame(host, current_asmop.as_ref());
                                return StepResult::Breakpoint(line);
                            }
                        }
                    }

                    // Check function/pattern breakpoints — match against context name and
                    // source file path. Context names may have a leading `::` (absolute
                    // paths like `::prologue::foo`), so we also try matching without it.
                    if !breakpoints.function.is_empty() {
                        let context_name = asmop.context_name();
                        let stripped_name = context_name.strip_prefix("::").unwrap_or(context_name);
                        for fbp in breakpoints.function {
                            // Match via glob pattern or suffix (e.g. "prologue::foo"
                            // matches "::$kernel::prologue::foo").
                            if fbp.pattern.matches(context_name)
                                || fbp.pattern.matches(stripped_name)
                                || context_name.ends_with(&fbp.name)
                                || stripped_name.ends_with(&fbp.name)
                            {
                                if should_defer_function_breakpoint(resolved.as_ref(), context_name)
                                {
                                    continue;
                                }
                                update_top_frame(host, current_asmop.as_ref());
                                let line = resolved.as_ref().map_or(0, |(_, l)| *l);
                                return StepResult::Breakpoint(line);
                            }
                            if let Some((ref path, line)) = resolved
                                && fbp.pattern.matches(path)
                            {
                                update_top_frame(host, current_asmop.as_ref());
                                return StepResult::Breakpoint(line);
                            }
                        }
                    }
                }
            }
            Ok(None) => return StepResult::Terminated,
            Err(e) => return StepResult::Error(e),
        }
    }
}

/// Push a `miden/uiState` snapshot event to the DAP client.
///
/// This custom event carries the bundled UI state (cycle, stack, callstack) so
/// the client can refresh without an extra evaluate round-trip. It is emitted
/// immediately before the standard `stopped` event because the DAP `stopped`
/// event itself does not carry VM state — it only signals that execution paused.
fn send_ui_state_snapshot<R: std::io::Read, W: std::io::Write, H: Host>(
    server: &mut Server<R, W>,
    processor: &mut FastProcessor,
    host: &DapHostWrapper<'_, H>,
    current_asmop: Option<&AssemblyOp>,
    cycle: usize,
) {
    let ui_state = build_ui_state(processor, host, current_asmop, cycle);
    if let Ok(json) = serde_json::to_value(&ui_state) {
        server.send_event(Event::MidenUiState(json)).ok();
    }
}

/// Announce the entry-point stop to the DAP client (UI snapshot + `Stopped(entry)`),
/// flipping `already_announced` so subsequent calls become no-ops.
///
/// Called from both `Attach`/`Launch` (so clients like Zed that skip
/// `configurationDone` still see the initial stop) and from `ConfigurationDone`
/// (the VS Code path).
fn announce_entry_stop<R: std::io::Read, W: std::io::Write, H: Host>(
    server: &mut Server<R, W>,
    processor: &mut FastProcessor,
    host: &DapHostWrapper<'_, H>,
    current_asmop: Option<&AssemblyOp>,
    cycle: usize,
    already_announced: &mut bool,
) {
    if *already_announced {
        return;
    }
    *already_announced = true;
    // Some DAP clients (Zed) only react to `stopped` events for thread IDs they
    // already know about; explicitly announce thread 1 as started before the
    // initial stop. VS Code tolerates the extra event.
    server
        .send_event(Event::Thread(events::ThreadEventBody {
            reason: types::ThreadEventReason::Started,
            thread_id: 1,
        }))
        .ok();
    send_ui_state_snapshot(server, processor, host, current_asmop, cycle);
    server
        .send_event(Event::Stopped(events::StoppedEventBody {
            reason: types::StoppedEventReason::Entry,
            description: Some("Paused at program entry".into()),
            thread_id: Some(1),
            preserve_focus_hint: None,
            text: None,
            all_threads_stopped: Some(true),
            hit_breakpoint_ids: None,
        }))
        .ok();
}

/// Send a "stopped(step)" event to the DAP client.
fn send_stopped_step<R: std::io::Read, W: std::io::Write>(server: &mut Server<R, W>) {
    server
        .send_event(Event::Stopped(events::StoppedEventBody {
            reason: types::StoppedEventReason::Step,
            description: None,
            thread_id: Some(1),
            preserve_focus_hint: None,
            text: None,
            all_threads_stopped: Some(true),
            hit_breakpoint_ids: None,
        }))
        .ok();
}

/// Result of a stepping operation.
#[allow(dead_code)]
enum StepResult {
    /// Successfully advanced one or more steps.
    Stepped,
    /// Hit a breakpoint at the given line.
    Breakpoint(i64),
    /// Program terminated normally.
    Terminated,
    /// An execution error occurred.
    Error(ExecutionError),
}

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

    #[test]
    fn source_paths_match_only_uses_declared_trim_prefixes() {
        let trim_prefixes = vec!["/workspace/compiler/examples/fibonacci".into()];

        assert!(source_paths_match(
            "/workspace/compiler/examples/fibonacci/src/lib.rs",
            "src/lib.rs",
            &trim_prefixes,
        ));
        assert!(source_paths_match(
            "file:///workspace/compiler/examples/fibonacci/src/lib.rs",
            "/workspace/compiler/examples/fibonacci/src/lib.rs",
            &[],
        ));
        assert!(!source_paths_match(
            "/workspace/compiler/examples/fibonacci/src/lib.rs",
            "src/lib.rs",
            &[],
        ));
        assert!(!source_paths_match(
            "/workspace/compiler/examples/fibonacci/src/lib.rs",
            "other/src/lib.rs",
            &trim_prefixes,
        ));
    }

    #[test]
    fn resolve_breakpoint_line_moves_to_next_executable_line() {
        let lines = BTreeSet::from([39, 40, 41]);

        assert_eq!(resolve_breakpoint_line(&lines, 38), Some(39));
        assert_eq!(resolve_breakpoint_line(&lines, 40), Some(40));
        assert_eq!(resolve_breakpoint_line(&lines, 99), Some(41));
        assert_eq!(resolve_breakpoint_line(&BTreeSet::new(), 38), None);
    }

    #[test]
    fn source_var_is_visible_after_its_declaration_line() {
        let prefixes = Vec::new();
        let path = "/tmp/src/lib.rs";

        assert!(!source_var_location_is_visible(path, 40, path, 39, &prefixes));
        assert!(!source_var_location_is_visible(path, 40, path, 40, &prefixes));
        assert!(source_var_location_is_visible(path, 40, path, 41, &prefixes));
    }

    #[test]
    fn next_source_line_ignores_pre_body_mappings() {
        let prefixes = Vec::new();
        let start = ("/tmp/src/lib.rs".to_string(), 39);
        let pre_body = ("/tmp/src/lib.rs".to_string(), 1);
        let body = ("/tmp/src/lib.rs".to_string(), 40);

        assert!(!is_next_source_line(
            Some("entrypoint"),
            Some(&start),
            Some("entrypoint"),
            Some(&pre_body),
            &prefixes,
            Some(39),
        ));
        assert!(is_next_source_line(
            Some("entrypoint"),
            Some(&start),
            Some("entrypoint"),
            Some(&body),
            &prefixes,
            Some(39),
        ));
    }
}