harn-dap 0.7.11

Debug Adapter Protocol implementation for Harn
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
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;

use harn_vm::llm::{enable_tracing, take_agent_trace, AgentTraceEvent};
use harn_vm::{
    clear_host_call_bridge, register_http_builtins, register_llm_builtins, register_vm_stdlib,
    set_host_call_bridge, DebugAction, DebugState, Vm, VmError, VmValue,
};
use serde_json::json;

use crate::host_bridge::DapHostBridge;
use crate::protocol::*;

/// Execution state for stepping.
#[derive(Debug, Clone, PartialEq)]
pub enum StepMode {
    /// Run until a breakpoint or end.
    Continue,
    /// Stop at the next line.
    StepOver,
    /// Stop at the next statement (step into functions).
    StepIn,
    /// Run until returning from the current function.
    StepOut,
}

/// Program state.
enum ProgramState {
    /// Not yet started.
    NotStarted,
    /// Running (VM is initialized).
    Running,
    /// Stopped at a debug point.
    Stopped,
    /// Program has terminated.
    Terminated,
}

/// A segment in an expression path for evaluation.
enum PathSegment {
    Field(String),
    Index(i64),
}

/// The debug adapter implementation.
pub struct Debugger {
    seq: i64,
    source_path: Option<String>,
    source_content: Option<String>,
    breakpoints: Vec<Breakpoint>,
    next_bp_id: i64,
    vm: Option<Vm>,
    /// Variables captured at the current stop point.
    variables: BTreeMap<String, VmValue>,
    /// Current execution state.
    stopped: bool,
    /// Current line in the source.
    current_line: i64,
    /// Step mode.
    step_mode: StepMode,
    /// Output captured during execution.
    output: String,
    /// Program state.
    program_state: ProgramState,
    /// Structured variable references: reference_id → children
    var_refs: BTreeMap<i64, Vec<(String, VmValue)>>,
    /// Tokio runtime for async VM execution.
    runtime: tokio::runtime::Runtime,
    /// Next variable reference ID (start at 100 to avoid conflict with scope refs).
    next_var_ref: i64,
    /// Whether to break on thrown exceptions.
    break_on_exceptions: bool,
    /// Latest VM debug snapshot captured through the VM debug hook.
    latest_debug_state: Rc<RefCell<Option<DebugState>>>,
    /// Optional bridge that round-trips unhandled `host_call` ops to the
    /// DAP client as reverse requests. When `None`, scripts only see the
    /// harn-vm fallbacks.
    host_bridge: Option<DapHostBridge>,
    /// True when the VM is in a "should keep stepping" state (after
    /// continue/next/stepIn/stepOut/configurationDone). The main loop
    /// drives one VM step per iteration while this is set, draining any
    /// pending DAP messages between steps so pause/disconnect/etc. get
    /// serviced mid-run instead of being starved.
    running: bool,
    /// Snapshotted breakpoint conditions for the active run. Refreshed
    /// each time we transition idle→running so condition edits between
    /// runs take effect.
    bp_conditions: Vec<(i64, Option<String>)>,
    /// Set by handle_pause; the next VM step honors it by emitting a
    /// stopped event with reason="pause" and clearing the flag.
    pending_pause: bool,
    /// progressId of the in-flight DAP progressStart, if any. The IDE
    /// uses it to display a "still working" indicator and reset its own
    /// per-request timeouts. Cleared on stop/terminate via progressEnd.
    active_progress_id: Option<String>,
    /// Number of VM steps taken since the most recent progressStart;
    /// used to throttle progressUpdate emission to one per ~256 steps
    /// so we don't flood the IDE with no-op events.
    steps_since_progress_update: u32,
}

impl Debugger {
    pub fn new() -> Self {
        Self {
            seq: 1,
            source_path: None,
            source_content: None,
            breakpoints: Vec::new(),
            next_bp_id: 1,
            vm: None,
            variables: BTreeMap::new(),
            stopped: false,
            current_line: 0,
            step_mode: StepMode::Continue,
            output: String::new(),
            program_state: ProgramState::NotStarted,
            var_refs: BTreeMap::new(),
            next_var_ref: 100,
            runtime: tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap(),
            break_on_exceptions: false,
            latest_debug_state: Rc::new(RefCell::new(None)),
            host_bridge: None,
            running: false,
            bp_conditions: Vec::new(),
            pending_pause: false,
            active_progress_id: None,
            steps_since_progress_update: 0,
        }
    }

    /// End any in-flight progress event. Called whenever the VM stops
    /// (breakpoint, pause, terminate, error) so the IDE clears its
    /// "Running…" indicator.
    fn end_progress(&mut self, responses: &mut Vec<DapResponse>) {
        if let Some(id) = self.active_progress_id.take() {
            let seq = self.next_seq();
            responses.push(DapResponse::event(
                seq,
                "progressEnd",
                Some(json!({ "progressId": id })),
            ));
        }
        self.steps_since_progress_update = 0;
    }

    /// Emit a progressUpdate roughly every 256 steps so the IDE sees
    /// liveness ticks during long runs and can extend its own timeouts.
    /// Cheap when there's no active progress (early return).
    fn maybe_progress_update(&mut self, responses: &mut Vec<DapResponse>) {
        if self.active_progress_id.is_none() {
            return;
        }
        self.steps_since_progress_update = self.steps_since_progress_update.wrapping_add(1);
        if self.steps_since_progress_update & 0xFF != 0 {
            return;
        }
        let id = self.active_progress_id.clone().unwrap();
        let line = self.current_line;
        let seq = self.next_seq();
        responses.push(DapResponse::event(
            seq,
            "progressUpdate",
            Some(json!({
                "progressId": id,
                "message": format!("line {}", line),
            })),
        ));
    }

    /// True when the main loop should keep stepping this debugger's VM.
    /// Drives the message-interleave loop in `main.rs` — when false, the
    /// loop blocks on `request_rx.recv()` instead of busy-stepping.
    pub fn is_running(&self) -> bool {
        self.running && self.vm.is_some()
    }

    /// Install a host bridge. Cloned into an `Rc` and registered with
    /// harn-vm via `set_host_call_bridge` whenever a fresh VM is built.
    pub fn attach_host_bridge(&mut self, bridge: std::sync::Arc<DapHostBridge>) {
        self.host_bridge = Some((*bridge).clone());
    }

    fn next_seq(&mut self) -> i64 {
        let s = self.seq;
        self.seq += 1;
        s
    }

    pub fn handle_message(&mut self, msg: DapMessage) -> Vec<DapResponse> {
        let command = msg.command.as_deref().unwrap_or("");
        match command {
            "initialize" => self.handle_initialize(&msg),
            "launch" => self.handle_launch(&msg),
            "setBreakpoints" => self.handle_set_breakpoints(&msg),
            "configurationDone" => self.handle_configuration_done(&msg),
            "continue" => self.handle_continue(&msg),
            "next" => self.handle_next(&msg),
            "stepIn" => self.handle_step_in(&msg),
            "stepOut" => self.handle_step_out(&msg),
            "pause" => self.handle_pause(&msg),
            "threads" => self.handle_threads(&msg),
            "stackTrace" => self.handle_stack_trace(&msg),
            "scopes" => self.handle_scopes(&msg),
            "variables" => self.handle_variables(&msg),
            "evaluate" => self.handle_evaluate(&msg),
            "setExceptionBreakpoints" => self.handle_set_exception_breakpoints(&msg),
            "disconnect" => self.handle_disconnect(&msg),
            "harnPing" => self.handle_ping(&msg),
            _ => {
                vec![DapResponse::success(
                    self.next_seq(),
                    msg.seq,
                    command,
                    None,
                )]
            }
        }
    }

    fn handle_initialize(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let caps = Capabilities::default();
        let seq = self.next_seq();
        let response = DapResponse::success(seq, msg.seq, "initialize", Some(json!(caps)));

        let event_seq = self.next_seq();
        let event = DapResponse::event(event_seq, "initialized", None);

        vec![response, event]
    }

    fn handle_launch(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let mut responses = Vec::new();

        if let Some(args) = &msg.arguments {
            if let Some(program) = args.get("program").and_then(|p| p.as_str()) {
                self.source_path = Some(program.to_string());
                match std::fs::read_to_string(program) {
                    Ok(source) => {
                        self.source_content = Some(source.clone());
                        match self.compile_program(&source) {
                            Ok(()) => {
                                self.program_state = ProgramState::Running;
                            }
                            Err(e) => {
                                let seq = self.next_seq();
                                responses.push(DapResponse::event(
                                    seq,
                                    "output",
                                    Some(json!({
                                        "category": "stderr",
                                        "output": format!("Compilation error: {e}\n"),
                                    })),
                                ));
                            }
                        }
                    }
                    Err(e) => {
                        let seq = self.next_seq();
                        responses.push(DapResponse::event(
                            seq,
                            "output",
                            Some(json!({
                                "category": "stderr",
                                "output": format!("Failed to read {program}: {e}\n"),
                            })),
                        ));
                    }
                }
            }
        }

        let seq = self.next_seq();
        responses.push(DapResponse::success(seq, msg.seq, "launch", None));
        responses
    }

    fn compile_program(&mut self, source: &str) -> Result<(), String> {
        let chunk = harn_vm::compile_source(source)?;

        let mut vm = Vm::new();
        register_vm_stdlib(&mut vm);
        register_http_builtins(&mut vm);
        register_llm_builtins(&mut vm);
        // Enable LLM trace collection so the debugger can surface llm_call
        // telemetry to the IDE via DAP `output` events with category=telemetry.
        enable_tracing();

        // Reset any prior bridge from a previous launch, then install the
        // current one (if any) so unhandled host_call ops route to the
        // DAP client via reverse requests instead of erroring out.
        clear_host_call_bridge();
        if let Some(bridge) = &self.host_bridge {
            set_host_call_bridge(Rc::new(bridge.clone()));
        }

        if let Some(ref path) = self.source_path {
            if let Some(parent) = std::path::Path::new(path).parent() {
                if !parent.as_os_str().is_empty() {
                    vm.set_source_dir(parent);
                }
            }
        }

        // Hand the VM each file's breakpoint set keyed by source path so
        // imports don't accidentally match the main script's lines.
        let mut by_file: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        for bp in &self.breakpoints {
            let key = bp
                .source
                .as_ref()
                .and_then(|s| s.path.clone())
                .unwrap_or_default();
            by_file.entry(key).or_default().push(bp.line as usize);
        }
        for (key, lines) in &by_file {
            vm.set_breakpoints_for_file(key, lines.clone());
        }
        *self.latest_debug_state.borrow_mut() = None;
        let latest_debug_state = Rc::clone(&self.latest_debug_state);
        vm.set_debug_hook(move |state| {
            *latest_debug_state.borrow_mut() = Some(state.clone());
            DebugAction::Continue
        });

        // Push the initial frame but don't run — the first continue/step drives execution.
        vm.start(&chunk);
        *self.latest_debug_state.borrow_mut() = Some(vm.debug_state());
        self.vm = Some(vm);
        Ok(())
    }

    fn handle_set_breakpoints(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        // Per DAP spec, each setBreakpoints request is the *complete* set
        // of breakpoints for one source file. We must therefore drop any
        // existing breakpoints for that file before re-adding, but
        // *preserve* breakpoints from other files (multi-file pipelines).
        let request_path = msg
            .arguments
            .as_ref()
            .and_then(|a| a.get("source"))
            .and_then(|s| s.get("path"))
            .and_then(|p| p.as_str())
            .map(|s| s.to_string());

        if let Some(ref path) = request_path {
            self.breakpoints
                .retain(|bp| bp.source.as_ref().and_then(|s| s.path.as_ref()) != Some(path));
        } else {
            // Source-less request — legacy behavior, clear everything.
            self.breakpoints.clear();
        }

        if let Some(args) = &msg.arguments {
            if let Some(bps) = args.get("breakpoints").and_then(|b| b.as_array()) {
                for bp in bps {
                    if let Some(line) = bp.get("line").and_then(|l| l.as_i64()) {
                        let id = self.next_bp_id;
                        self.next_bp_id += 1;
                        let condition = bp
                            .get("condition")
                            .and_then(|c| c.as_str())
                            .map(|s| s.to_string())
                            .filter(|s| !s.is_empty());
                        self.breakpoints.push(Breakpoint {
                            id,
                            verified: true,
                            line,
                            source: request_path.clone().map(|p| Source {
                                name: None,
                                path: Some(p),
                            }),
                            condition,
                        });
                    }
                }
            }
        }

        if let Some(vm) = &mut self.vm {
            // Push per-file breakpoint sets so the VM can match
            // (file, line) precisely instead of treating the lines as
            // global wildcards.
            let mut by_file: BTreeMap<String, Vec<usize>> = BTreeMap::new();
            for bp in &self.breakpoints {
                let key = bp
                    .source
                    .as_ref()
                    .and_then(|s| s.path.clone())
                    .unwrap_or_default();
                by_file.entry(key).or_default().push(bp.line as usize);
            }
            // Clear stale files first by setting empty for every file we
            // know about — covers the case where the user removed all
            // breakpoints from a file that previously had some.
            let known_keys: Vec<String> = by_file.keys().cloned().collect();
            for key in known_keys.iter() {
                vm.set_breakpoints_for_file(key, by_file[key].clone());
            }
        }

        let seq = self.next_seq();
        vec![DapResponse::success(
            seq,
            msg.seq,
            "setBreakpoints",
            Some(json!({ "breakpoints": self.breakpoints })),
        )]
    }

    fn handle_configuration_done(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let seq = self.next_seq();
        let response = DapResponse::success(seq, msg.seq, "configurationDone", None);
        self.enter_running();
        // Emit a progressStart event so the IDE shows "Running…" while
        // the VM works through its first step batch. We end the progress
        // when the VM stops (next breakpoint, terminates, or pause). DAP
        // spec: progressStart/progressUpdate/progressEnd, identified by
        // a stable progressId we hold for the lifetime of the run.
        let progress_seq = self.next_seq();
        self.active_progress_id = Some(format!("run-{}", progress_seq));
        let progress = DapResponse::event(
            progress_seq,
            "progressStart",
            Some(json!({
                "progressId": self.active_progress_id.clone().unwrap(),
                "title": "Running script",
                "cancellable": false,
            })),
        );
        vec![response, progress]
    }

    /// Drain agent trace events the VM has accumulated and serialize the
    /// LLM-call entries as DAP `output` events with `category: "telemetry"`.
    /// Other event kinds (tool execution, phase change, etc.) are skipped
    /// for now — the IDE consumes only LLM telemetry. Keeping this here
    /// rather than in harn-vm preserves the rule that DAP wire-format
    /// concerns belong in harn-dap.
    fn drain_telemetry_events(&mut self) -> Vec<DapResponse> {
        let events = take_agent_trace();
        if events.is_empty() {
            return Vec::new();
        }
        let mut out = Vec::new();
        for event in events {
            if let AgentTraceEvent::LlmCall {
                call_id,
                model,
                input_tokens,
                output_tokens,
                cache_tokens,
                duration_ms,
                iteration,
            } = event
            {
                let payload = json!({
                    "call_id": call_id,
                    "model": model,
                    "prompt_tokens": input_tokens,
                    "completion_tokens": output_tokens,
                    "cache_tokens": cache_tokens,
                    "total_ms": duration_ms,
                    "iteration": iteration,
                });
                let body_str = serde_json::to_string(&payload).unwrap_or_default();
                let seq = self.next_seq();
                out.push(DapResponse::event(
                    seq,
                    "output",
                    Some(json!({
                        "category": "telemetry",
                        "output": body_str,
                    })),
                ));
            }
        }
        out
    }

    /// Transition idle → running. Snapshots breakpoint conditions and
    /// resets per-run state. Caller sets the appropriate `step_mode` and
    /// VM step flag separately. Returns nothing — actual stepping happens
    /// later when `main` polls `step_running_vm` between message drains.
    fn enter_running(&mut self) {
        self.bp_conditions = self
            .breakpoints
            .iter()
            .map(|bp| (bp.line, bp.condition.clone()))
            .collect();
        self.var_refs.clear();
        self.next_var_ref = 100;
        self.running = self.vm.is_some();
    }

    /// Take ONE VM step and return any DAP events the step produced.
    /// Stops the run (sets `running = false`) when the program hits a
    /// breakpoint, terminates, or errors. Designed to be called in a
    /// tight loop by main, interleaved with `request_rx.try_recv()` so
    /// pause/disconnect/setBreakpoints get handled mid-run instead of
    /// being starved by a blocking inner loop.
    pub fn step_running_vm(&mut self) -> Vec<DapResponse> {
        if !self.running || self.vm.is_none() {
            return Vec::new();
        }

        // Honor a pending pause request before taking the step — we
        // don't actually advance the VM, just stop with reason="pause".
        if self.pending_pause {
            self.pending_pause = false;
            return self.handle_pause_stop();
        }

        let mut responses = Vec::new();
        let step_result = {
            let vm = self.vm.as_mut().unwrap();
            self.runtime.block_on(async { vm.step_execute().await })
        };

        for tele in self.drain_telemetry_events() {
            responses.push(tele);
        }
        self.maybe_progress_update(&mut responses);

        match step_result {
            Ok(Some((_val, stopped))) if stopped => {
                let state = self.current_debug_state();
                let current_line = state.line as i64;
                let vars = state.variables;
                if !check_condition(&self.bp_conditions, current_line, &vars) {
                    return responses;
                }
                self.stopped = true;
                self.running = false;
                self.current_line = current_line;
                self.variables = vars;
                self.program_state = ProgramState::Stopped;
                self.flush_output_into(&mut responses);
                self.end_progress(&mut responses);
                let seq = self.next_seq();
                responses.push(DapResponse::event(
                    seq,
                    "stopped",
                    Some(json!({
                        "reason": "breakpoint",
                        "threadId": 1,
                        "allThreadsStopped": true,
                    })),
                ));
            }
            Ok(Some((_val, _))) => {
                // Program reached its natural end.
                self.flush_output_into(&mut responses);
                self.program_state = ProgramState::Terminated;
                self.running = false;
                self.end_progress(&mut responses);
                let seq = self.next_seq();
                responses.push(DapResponse::event(seq, "terminated", None));
            }
            Ok(None) => {
                // Mid-instruction continuation; just keep stepping.
            }
            Err(e) => {
                self.running = false;
                self.end_progress(&mut responses);
                if self.break_on_exceptions && matches!(&e, VmError::Thrown(_)) {
                    let error_msg = e.to_string();
                    let state = self.current_debug_state();
                    self.stopped = true;
                    self.current_line = state.line as i64;
                    self.variables = state.variables;
                    self.program_state = ProgramState::Stopped;
                    let seq = self.next_seq();
                    responses.push(DapResponse::event(
                        seq,
                        "output",
                        Some(json!({
                            "category": "stderr",
                            "output": format!("Exception: {error_msg}\n"),
                        })),
                    ));
                    let seq = self.next_seq();
                    responses.push(DapResponse::event(
                        seq,
                        "stopped",
                        Some(json!({
                            "reason": "exception",
                            "description": error_msg,
                            "threadId": 1,
                            "allThreadsStopped": true,
                        })),
                    ));
                    return responses;
                }
                let seq = self.next_seq();
                responses.push(DapResponse::event(
                    seq,
                    "output",
                    Some(json!({
                        "category": "stderr",
                        "output": format!("Error: {e}\n"),
                    })),
                ));
                self.program_state = ProgramState::Terminated;
                let seq = self.next_seq();
                responses.push(DapResponse::event(seq, "terminated", None));
            }
        }

        responses
    }

    /// Honor a deferred pause request: stop on the current instruction
    /// without advancing, emit a stopped event with reason="pause".
    fn handle_pause_stop(&mut self) -> Vec<DapResponse> {
        let mut responses = Vec::new();
        let state = self.current_debug_state();
        self.stopped = true;
        self.running = false;
        self.current_line = state.line as i64;
        self.variables = state.variables;
        self.program_state = ProgramState::Stopped;
        self.flush_output_into(&mut responses);
        self.end_progress(&mut responses);
        let seq = self.next_seq();
        responses.push(DapResponse::event(
            seq,
            "stopped",
            Some(json!({
                "reason": "pause",
                "threadId": 1,
                "allThreadsStopped": true,
            })),
        ));
        responses
    }

    /// Drain any new VM stdout into `output` DAP events. Used by the
    /// stop/terminate paths so the IDE doesn't lose trailing print()s.
    fn flush_output_into(&mut self, responses: &mut Vec<DapResponse>) {
        let output = self.vm.as_ref().unwrap().output().to_string();
        if !output.is_empty() && output != self.output {
            let new_output = output[self.output.len()..].to_string();
            if !new_output.is_empty() {
                let seq = self.next_seq();
                responses.push(DapResponse::event(
                    seq,
                    "output",
                    Some(json!({
                        "category": "stdout",
                        "output": new_output,
                    })),
                ));
            }
            self.output = output;
        }
    }

    fn handle_continue(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        self.step_mode = StepMode::Continue;
        self.stopped = false;
        let seq = self.next_seq();
        let response = DapResponse::success(
            seq,
            msg.seq,
            "continue",
            Some(json!({ "allThreadsContinued": true })),
        );
        self.enter_running();
        vec![response]
    }

    fn handle_next(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        self.step_mode = StepMode::StepOver;
        if let Some(vm) = &mut self.vm {
            vm.set_step_over();
        }
        let seq = self.next_seq();
        let response = DapResponse::success(seq, msg.seq, "next", None);
        self.enter_running();
        vec![response]
    }

    fn handle_step_in(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        self.step_mode = StepMode::StepIn;
        if let Some(vm) = &mut self.vm {
            vm.set_step_mode(true);
        }
        let seq = self.next_seq();
        let response = DapResponse::success(seq, msg.seq, "stepIn", None);
        self.enter_running();
        vec![response]
    }

    fn handle_step_out(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        self.step_mode = StepMode::StepOut;
        if let Some(vm) = &mut self.vm {
            vm.set_step_out();
        }
        let seq = self.next_seq();
        let response = DapResponse::success(seq, msg.seq, "stepOut", None);
        self.enter_running();
        vec![response]
    }

    /// Break into the currently running program at the next VM step.
    ///
    /// With message interleaving, this works even mid-run: main.rs drains
    /// the message channel between VM steps, so a pause request lands
    /// while the VM is in flight. We set `pending_pause` so the next
    /// `step_running_vm` call honors it without advancing the VM.
    fn handle_pause(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let seq = self.next_seq();
        let mut responses = vec![DapResponse::success(seq, msg.seq, "pause", None)];

        if self.stopped {
            // Already stopped — just emit a stopped event so the IDE
            // updates its UI immediately.
            let stop_seq = self.next_seq();
            responses.push(DapResponse::event(
                stop_seq,
                "stopped",
                Some(json!({
                    "reason": "pause",
                    "threadId": 1,
                    "allThreadsStopped": true,
                })),
            ));
        } else {
            // Defer: next step_running_vm tick will stop with reason=pause.
            self.pending_pause = true;
            self.step_mode = StepMode::StepIn;
            if let Some(vm) = &mut self.vm {
                vm.set_step_mode(true);
            }
        }

        responses
    }

    fn handle_threads(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let seq = self.next_seq();
        vec![DapResponse::success(
            seq,
            msg.seq,
            "threads",
            Some(json!({
                "threads": [{
                    "id": 1,
                    "name": "main"
                }]
            })),
        )]
    }

    fn handle_stack_trace(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let frames: Vec<StackFrame> = if let Some(vm) = &self.vm {
            vm.debug_stack_frames()
                .into_iter()
                .enumerate()
                .map(|(i, (name, line))| StackFrame {
                    id: (i + 1) as i64,
                    name,
                    line: line.max(1) as i64,
                    column: 1,
                    source: self.source_path.as_ref().map(|p| Source {
                        name: std::path::Path::new(p)
                            .file_name()
                            .map(|f| f.to_string_lossy().into_owned()),
                        path: Some(p.clone()),
                    }),
                })
                .collect()
        } else {
            vec![StackFrame {
                id: 1,
                name: "pipeline".to_string(),
                line: self.current_line.max(1),
                column: 1,
                source: self.source_path.as_ref().map(|p| Source {
                    name: std::path::Path::new(p)
                        .file_name()
                        .map(|f| f.to_string_lossy().into_owned()),
                    path: Some(p.clone()),
                }),
            }]
        };

        let total = frames.len();
        let seq = self.next_seq();
        vec![DapResponse::success(
            seq,
            msg.seq,
            "stackTrace",
            Some(json!({
                "stackFrames": frames,
                "totalFrames": total,
            })),
        )]
    }

    fn handle_scopes(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let scopes = vec![Scope {
            name: "Locals".to_string(),
            variables_reference: 1,
            expensive: false,
        }];

        let seq = self.next_seq();
        vec![DapResponse::success(
            seq,
            msg.seq,
            "scopes",
            Some(json!({ "scopes": scopes })),
        )]
    }

    fn current_debug_state(&self) -> DebugState {
        self.latest_debug_state
            .borrow()
            .clone()
            .or_else(|| self.vm.as_ref().map(|vm| vm.debug_state()))
            .unwrap_or(DebugState {
                line: self.current_line.max(0) as usize,
                variables: self.variables.clone(),
                frame_name: "pipeline".to_string(),
                frame_depth: 0,
            })
    }

    fn alloc_var_ref(&mut self, children: Vec<(String, VmValue)>) -> i64 {
        let id = self.next_var_ref;
        self.next_var_ref += 1;
        self.var_refs.insert(id, children);
        id
    }

    fn make_variable(&mut self, name: String, val: &VmValue) -> Variable {
        let (var_ref, display) = match val {
            VmValue::List(items) => {
                let children: Vec<(String, VmValue)> = items
                    .iter()
                    .enumerate()
                    .map(|(i, v)| (format!("[{i}]"), v.clone()))
                    .collect();
                let display = format!("list<{}>", items.len());
                if children.is_empty() {
                    (0, display)
                } else {
                    (self.alloc_var_ref(children), display)
                }
            }
            VmValue::Dict(map) => {
                let children: Vec<(String, VmValue)> =
                    map.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
                let display = format!("dict<{}>", map.len());
                if children.is_empty() {
                    (0, display)
                } else {
                    (self.alloc_var_ref(children), display)
                }
            }
            VmValue::StructInstance {
                struct_name,
                fields,
            } => {
                let children: Vec<(String, VmValue)> =
                    fields.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
                let display = struct_name.clone();
                if children.is_empty() {
                    (0, display)
                } else {
                    (self.alloc_var_ref(children), display)
                }
            }
            VmValue::EnumVariant {
                enum_name,
                variant,
                fields,
            } => {
                if fields.is_empty() {
                    (0, format!("{enum_name}.{variant}"))
                } else {
                    let children: Vec<(String, VmValue)> = fields
                        .iter()
                        .enumerate()
                        .map(|(i, v)| (format!("field_{i}"), v.clone()))
                        .collect();
                    let display = format!("{enum_name}.{variant}(...)");
                    (self.alloc_var_ref(children), display)
                }
            }
            other => (0, other.display()),
        };
        Variable {
            name,
            value: display,
            var_type: vm_type_name(val).to_string(),
            variables_reference: var_ref,
        }
    }

    fn handle_variables(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let ref_id = msg
            .arguments
            .as_ref()
            .and_then(|a| a.get("variablesReference"))
            .and_then(|v| v.as_i64())
            .unwrap_or(1);

        // Ref IDs ≥ 100 index `self.var_refs` (children of composite values).
        if ref_id >= 100 {
            if let Some(children) = self.var_refs.get(&ref_id).cloned() {
                let vars: Vec<Variable> = children
                    .iter()
                    .map(|(name, val)| self.make_variable(name.clone(), val))
                    .collect();
                let seq = self.next_seq();
                return vec![DapResponse::success(
                    seq,
                    msg.seq,
                    "variables",
                    Some(json!({ "variables": vars })),
                )];
            }
        }

        // Fallback: scope 1 is the locals map.
        let variable_list: Vec<(String, VmValue)> = self.variables.clone().into_iter().collect();
        let vars: Vec<Variable> = variable_list
            .iter()
            .map(|(name, val)| self.make_variable(name.clone(), val))
            .collect();

        let seq = self.next_seq();
        vec![DapResponse::success(
            seq,
            msg.seq,
            "variables",
            Some(json!({ "variables": vars })),
        )]
    }

    fn handle_evaluate(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let expression = msg
            .arguments
            .as_ref()
            .and_then(|a| a.get("expression"))
            .and_then(|e| e.as_str())
            .unwrap_or("");

        // DAP context is one of "watch", "repl", "hover", "clipboard"; we ignore it.
        let _context = msg
            .arguments
            .as_ref()
            .and_then(|a| a.get("context"))
            .and_then(|c| c.as_str())
            .unwrap_or("watch");

        match self.resolve_expression(expression) {
            Some(val) => {
                let variable = self.make_variable(expression.to_string(), &val);
                let seq = self.next_seq();
                vec![DapResponse::success(
                    seq,
                    msg.seq,
                    "evaluate",
                    Some(json!({
                        "result": variable.value,
                        "type": variable.var_type,
                        "variablesReference": variable.variables_reference,
                    })),
                )]
            }
            None => {
                let seq = self.next_seq();
                vec![DapResponse {
                    seq,
                    msg_type: "response".to_string(),
                    request_seq: Some(msg.seq),
                    success: Some(false),
                    command: Some("evaluate".to_string()),
                    message: Some(format!(
                        "Cannot evaluate '{expression}': only variable lookups and dot-access \
                         property paths are supported in the debugger"
                    )),
                    body: None,
                    event: None,
                }]
            }
        }
    }

    /// Resolve an expression string against the current variable state.
    /// Supports: variable names ("x"), dot-access ("x.foo.bar"),
    /// subscript access ("x[0]", "x[\"key\"]"), len(x), type_of(x).
    fn resolve_expression(&self, expression: &str) -> Option<VmValue> {
        let expr = expression.trim();

        if let Some(inner) = expr.strip_prefix("len(").and_then(|s| s.strip_suffix(')')) {
            let val = self.resolve_expression(inner)?;
            return match &val {
                VmValue::String(s) => Some(VmValue::Int(s.len() as i64)),
                VmValue::List(l) => Some(VmValue::Int(l.len() as i64)),
                VmValue::Dict(d) => Some(VmValue::Int(d.len() as i64)),
                _ => None,
            };
        }
        if let Some(inner) = expr
            .strip_prefix("type_of(")
            .and_then(|s| s.strip_suffix(')'))
        {
            let val = self.resolve_expression(inner)?;
            let type_name = match &val {
                VmValue::Int(_) => "int",
                VmValue::Float(_) => "float",
                VmValue::String(_) => "string",
                VmValue::Bool(_) => "bool",
                VmValue::Nil => "nil",
                VmValue::List(_) => "list",
                VmValue::Dict(_) => "dict",
                _ => "unknown",
            };
            return Some(VmValue::String(std::rc::Rc::from(type_name)));
        }

        // Tokenize into a path of `Field(name)` and `Index(n)` segments.
        let mut segments = Vec::new();
        let mut chars = expr.chars().peekable();
        let mut name = String::new();
        while let Some(&c) = chars.peek() {
            if c.is_alphanumeric() || c == '_' {
                name.push(c);
                chars.next();
            } else {
                break;
            }
        }
        if name.is_empty() {
            return None;
        }
        segments.push(PathSegment::Field(name));

        while let Some(&c) = chars.peek() {
            match c {
                '.' => {
                    chars.next();
                    let mut field = String::new();
                    while let Some(&c) = chars.peek() {
                        if c.is_alphanumeric() || c == '_' {
                            field.push(c);
                            chars.next();
                        } else {
                            break;
                        }
                    }
                    if field.is_empty() {
                        return None;
                    }
                    segments.push(PathSegment::Field(field));
                }
                '[' => {
                    chars.next();
                    let mut idx = String::new();
                    while let Some(&c) = chars.peek() {
                        if c == ']' {
                            chars.next();
                            break;
                        }
                        idx.push(c);
                        chars.next();
                    }
                    let idx = idx.trim().trim_matches('"').trim_matches('\'');
                    if let Ok(n) = idx.parse::<i64>() {
                        segments.push(PathSegment::Index(n));
                    } else {
                        segments.push(PathSegment::Field(idx.to_string()));
                    }
                }
                _ => return None,
            }
        }

        let root_name = match &segments[0] {
            PathSegment::Field(n) => n.as_str(),
            _ => return None,
        };
        let mut current = self.variables.get(root_name)?.clone();

        for seg in &segments[1..] {
            current = match seg {
                PathSegment::Field(f) => match &current {
                    VmValue::Dict(map) => map.get(f.as_str())?.clone(),
                    VmValue::StructInstance { fields, .. } => fields.get(f.as_str())?.clone(),
                    _ => return None,
                },
                PathSegment::Index(i) => match &current {
                    VmValue::List(list) => {
                        let idx = if *i < 0 {
                            (list.len() as i64 + i) as usize
                        } else {
                            *i as usize
                        };
                        list.get(idx)?.clone()
                    }
                    VmValue::Dict(map) => map.get(&i.to_string())?.clone(),
                    _ => return None,
                },
            };
        }

        Some(current)
    }

    fn handle_set_exception_breakpoints(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        self.break_on_exceptions = msg
            .arguments
            .as_ref()
            .and_then(|a| a.get("filters"))
            .and_then(|f| f.as_array())
            .map(|filters| filters.iter().any(|f| f.as_str() == Some("all")))
            .unwrap_or(false);

        let seq = self.next_seq();
        vec![DapResponse::success(
            seq,
            msg.seq,
            "setExceptionBreakpoints",
            None,
        )]
    }

    /// Lightweight liveness check the IDE pings us with periodically.
    /// Replies with the current run-state so the IDE can distinguish
    /// "wedged" from "actively stepping" without having to emit
    /// progress events (which we already do for active runs).
    fn handle_ping(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        let seq = self.next_seq();
        let state_str = match self.program_state {
            ProgramState::NotStarted => "not_started",
            ProgramState::Running => "running",
            ProgramState::Stopped => "stopped",
            ProgramState::Terminated => "terminated",
        };
        vec![DapResponse::success(
            seq,
            msg.seq,
            "harnPing",
            Some(json!({
                "state": state_str,
                "running": self.running,
                "stopped": self.stopped,
            })),
        )]
    }

    fn handle_disconnect(&mut self, msg: &DapMessage) -> Vec<DapResponse> {
        // Stop the VM and release any reverse-request waiters. Without
        // the cancellation step, a host_call in flight via DapHostBridge
        // would block until its 60s timeout — leaving the script (and
        // any tokio task driving step_execute) stuck for a minute after
        // the IDE walks away.
        self.running = false;
        if let Some(bridge) = &self.host_bridge {
            bridge.cancel_all_pending("disconnect");
        }
        self.vm = None;
        self.program_state = ProgramState::Terminated;
        let mut responses = Vec::new();
        self.end_progress(&mut responses);
        let seq = self.next_seq();
        responses.push(DapResponse::success(seq, msg.seq, "disconnect", None));
        responses
    }
}

fn vm_type_name(val: &VmValue) -> &'static str {
    val.type_name()
}

/// Check if a conditional breakpoint should fire.
fn check_condition(
    bp_conditions: &[(i64, Option<String>)],
    line: i64,
    variables: &BTreeMap<String, VmValue>,
) -> bool {
    let condition = bp_conditions
        .iter()
        .find(|(l, _)| *l == line)
        .and_then(|(_, c)| c.as_deref());

    let condition = match condition {
        Some(c) => c.trim(),
        None => return true,
    };

    // Minimal evaluator: `var <op> val` for comparison ops, or bare `var` for truthy.
    for op in &["==", "!=", ">=", "<=", ">", "<"] {
        if let Some((lhs, rhs)) = condition.split_once(op) {
            let lhs = lhs.trim();
            let rhs = rhs.trim().trim_matches('"');
            let lhs_val = variables.get(lhs).map(|v| v.display()).unwrap_or_default();
            return match *op {
                "==" => lhs_val == rhs,
                "!=" => lhs_val != rhs,
                ">=" => lhs_val.parse::<f64>().unwrap_or(0.0) >= rhs.parse::<f64>().unwrap_or(0.0),
                "<=" => lhs_val.parse::<f64>().unwrap_or(0.0) <= rhs.parse::<f64>().unwrap_or(0.0),
                ">" => lhs_val.parse::<f64>().unwrap_or(0.0) > rhs.parse::<f64>().unwrap_or(0.0),
                "<" => lhs_val.parse::<f64>().unwrap_or(0.0) < rhs.parse::<f64>().unwrap_or(0.0),
                _ => true,
            };
        }
    }

    if let Some(val) = variables.get(condition) {
        return val.is_truthy();
    }

    true
}

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

    fn make_request(seq: i64, command: &str, args: Option<serde_json::Value>) -> DapMessage {
        DapMessage {
            seq,
            msg_type: "request".to_string(),
            command: Some(command.to_string()),
            arguments: args,
            request_seq: None,
            success: None,
            message: None,
            body: None,
        }
    }

    #[test]
    fn test_initialize() {
        let mut dbg = Debugger::new();
        let responses = dbg.handle_message(make_request(1, "initialize", None));
        assert_eq!(responses.len(), 2);
        assert_eq!(responses[0].command.as_deref(), Some("initialize"));
        assert_eq!(responses[0].success, Some(true));
        assert_eq!(responses[1].event.as_deref(), Some("initialized"));
    }

    #[test]
    fn test_threads() {
        let mut dbg = Debugger::new();
        let responses = dbg.handle_message(make_request(1, "threads", None));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        let threads = body["threads"].as_array().unwrap();
        assert_eq!(threads.len(), 1);
        assert_eq!(threads[0]["name"], "main");
    }

    #[test]
    fn test_set_breakpoints() {
        let mut dbg = Debugger::new();
        let responses = dbg.handle_message(make_request(
            1,
            "setBreakpoints",
            Some(json!({
                "source": {"path": "test.harn"},
                "breakpoints": [{"line": 5}, {"line": 10}]
            })),
        ));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        let bps = body["breakpoints"].as_array().unwrap();
        assert_eq!(bps.len(), 2);
        assert_eq!(bps[0]["line"], 5);
        assert_eq!(bps[1]["line"], 10);
        assert_eq!(bps[0]["verified"], true);
    }

    #[test]
    fn test_launch_and_run() {
        let mut dbg = Debugger::new();

        let dir = std::env::temp_dir().join("harn_dap_test");
        std::fs::create_dir_all(&dir).ok();
        let file = dir.join("test.harn");
        std::fs::write(&file, "pipeline test(task) { log(42) }").unwrap();

        dbg.handle_message(make_request(1, "initialize", None));
        dbg.handle_message(make_request(
            2,
            "launch",
            Some(json!({"program": file.to_string_lossy()})),
        ));

        // configurationDone transitions the debugger into "running" and
        // returns immediately; the main loop drives step_running_vm
        // between message drains. In tests we drain manually until the
        // program terminates.
        let mut responses = dbg.handle_message(make_request(3, "configurationDone", None));
        while dbg.is_running() {
            responses.extend(dbg.step_running_vm());
        }
        assert!(responses.len() >= 2);

        let output_event = responses.iter().find(|r| {
            r.event.as_deref() == Some("output")
                && r.body
                    .as_ref()
                    .map(|b| b["category"] == "stdout")
                    .unwrap_or(false)
        });

        if let Some(evt) = output_event {
            let output = evt.body.as_ref().unwrap()["output"].as_str().unwrap();
            assert!(output.contains("[harn] 42"));
        }

        let terminated = responses
            .iter()
            .find(|r| r.event.as_deref() == Some("terminated"));
        assert!(terminated.is_some());

        std::fs::remove_file(&file).ok();
        std::fs::remove_dir(&dir).ok();
    }

    #[test]
    fn test_scopes_and_variables() {
        let mut dbg = Debugger::new();
        dbg.variables.insert("x".to_string(), VmValue::Int(42));
        dbg.variables
            .insert("name".to_string(), VmValue::String("hello".into()));

        let responses = dbg.handle_message(make_request(
            1,
            "variables",
            Some(json!({"variablesReference": 1})),
        ));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        let vars = body["variables"].as_array().unwrap();
        assert_eq!(vars.len(), 2);
    }

    #[test]
    fn test_evaluate() {
        let mut dbg = Debugger::new();
        dbg.variables.insert("x".to_string(), VmValue::Int(42));

        let responses = dbg.handle_message(make_request(
            1,
            "evaluate",
            Some(json!({"expression": "x"})),
        ));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        assert_eq!(body["result"], "42");
        assert_eq!(body["variablesReference"], 0);
    }

    #[test]
    fn test_evaluate_dot_access() {
        use std::rc::Rc;

        let mut dbg = Debugger::new();
        let mut inner = BTreeMap::new();
        inner.insert("bar".to_string(), VmValue::Int(99));
        dbg.variables
            .insert("foo".to_string(), VmValue::Dict(Rc::new(inner)));

        let responses = dbg.handle_message(make_request(
            1,
            "evaluate",
            Some(json!({"expression": "foo.bar"})),
        ));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        assert_eq!(body["result"], "99");
        assert_eq!(body["variablesReference"], 0);
    }

    #[test]
    fn test_evaluate_nested_dot_access() {
        use std::rc::Rc;

        let mut dbg = Debugger::new();
        let mut inner = BTreeMap::new();
        inner.insert("c".to_string(), VmValue::String("deep".into()));
        let mut outer = BTreeMap::new();
        outer.insert("b".to_string(), VmValue::Dict(Rc::new(inner)));
        dbg.variables
            .insert("a".to_string(), VmValue::Dict(Rc::new(outer)));

        let responses = dbg.handle_message(make_request(
            1,
            "evaluate",
            Some(json!({"expression": "a.b.c"})),
        ));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        assert_eq!(body["result"], "deep");
    }

    #[test]
    fn test_evaluate_complex_value_has_var_ref() {
        use std::rc::Rc;

        let mut dbg = Debugger::new();
        let mut map = BTreeMap::new();
        map.insert("key".to_string(), VmValue::Int(1));
        dbg.variables
            .insert("d".to_string(), VmValue::Dict(Rc::new(map)));

        let responses = dbg.handle_message(make_request(
            1,
            "evaluate",
            Some(json!({"expression": "d"})),
        ));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        assert!(body["variablesReference"].as_i64().unwrap() > 0);
    }

    #[test]
    fn test_evaluate_undefined_returns_error() {
        let mut dbg = Debugger::new();

        let responses = dbg.handle_message(make_request(
            1,
            "evaluate",
            Some(json!({"expression": "nonexistent"})),
        ));
        assert_eq!(responses.len(), 1);
        assert_eq!(responses[0].success, Some(false));
        assert!(responses[0]
            .message
            .as_ref()
            .unwrap()
            .contains("nonexistent"));
    }

    #[test]
    fn test_evaluate_with_context() {
        let mut dbg = Debugger::new();
        dbg.variables.insert("x".to_string(), VmValue::Int(7));

        for ctx in &["watch", "repl", "hover"] {
            let responses = dbg.handle_message(make_request(
                1,
                "evaluate",
                Some(json!({"expression": "x", "context": ctx})),
            ));
            assert_eq!(responses.len(), 1);
            let body = responses[0].body.as_ref().unwrap();
            assert_eq!(body["result"], "7");
        }
    }

    #[test]
    fn test_set_exception_breakpoints_enable() {
        let mut dbg = Debugger::new();
        assert!(!dbg.break_on_exceptions);

        let responses = dbg.handle_message(make_request(
            1,
            "setExceptionBreakpoints",
            Some(json!({"filters": ["all"]})),
        ));
        assert_eq!(responses.len(), 1);
        assert_eq!(responses[0].success, Some(true));
        assert!(dbg.break_on_exceptions);
    }

    #[test]
    fn test_set_exception_breakpoints_disable() {
        let mut dbg = Debugger::new();
        dbg.break_on_exceptions = true;

        let responses = dbg.handle_message(make_request(
            1,
            "setExceptionBreakpoints",
            Some(json!({"filters": []})),
        ));
        assert_eq!(responses.len(), 1);
        assert_eq!(responses[0].success, Some(true));
        assert!(!dbg.break_on_exceptions);
    }

    #[test]
    fn test_initialize_has_exception_breakpoint_filters() {
        let mut dbg = Debugger::new();
        let responses = dbg.handle_message(make_request(1, "initialize", None));
        let body = responses[0].body.as_ref().unwrap();
        assert_eq!(body["supportsExceptionBreakpointFilters"], true);
        let filters = body["exceptionBreakpointFilters"].as_array().unwrap();
        assert_eq!(filters.len(), 1);
        assert_eq!(filters[0]["filter"], "all");
        assert_eq!(filters[0]["label"], "All Exceptions");
        assert_eq!(filters[0]["default"], false);
    }

    #[test]
    fn test_step_commands() {
        let mut dbg = Debugger::new();

        let r = dbg.handle_message(make_request(1, "next", None));
        assert!(r[0].success == Some(true));
        assert_eq!(dbg.step_mode, StepMode::StepOver);

        let r = dbg.handle_message(make_request(2, "stepIn", None));
        assert!(r[0].success == Some(true));
        assert_eq!(dbg.step_mode, StepMode::StepIn);

        let r = dbg.handle_message(make_request(3, "stepOut", None));
        assert!(r[0].success == Some(true));
        assert_eq!(dbg.step_mode, StepMode::StepOut);

        let r = dbg.handle_message(make_request(4, "continue", None));
        assert!(r[0].success == Some(true));
        assert_eq!(dbg.step_mode, StepMode::Continue);
    }

    #[test]
    fn test_disconnect() {
        let mut dbg = Debugger::new();
        let r = dbg.handle_message(make_request(1, "disconnect", None));
        assert_eq!(r[0].success, Some(true));
    }

    #[test]
    fn test_stack_trace() {
        let mut dbg = Debugger::new();
        dbg.source_path = Some("test.harn".to_string());
        dbg.current_line = 5;

        let r = dbg.handle_message(make_request(1, "stackTrace", None));
        let body = r[0].body.as_ref().unwrap();
        let frames = body["stackFrames"].as_array().unwrap();
        assert_eq!(frames.len(), 1);
    }

    #[test]
    fn test_breakpoint_stop() {
        let mut dbg = Debugger::new();

        let dir = std::env::temp_dir().join("harn_dap_bp_test");
        std::fs::create_dir_all(&dir).ok();
        let file = dir.join("test_bp.harn");
        std::fs::write(
            &file,
            "pipeline test(task) {\n  let x = 1\n  let y = 2\n  log(x + y)\n}",
        )
        .unwrap();

        dbg.handle_message(make_request(1, "initialize", None));
        dbg.handle_message(make_request(
            2,
            "setBreakpoints",
            Some(json!({
                "source": {"path": file.to_string_lossy()},
                "breakpoints": [{"line": 3}]
            })),
        ));
        dbg.handle_message(make_request(
            3,
            "launch",
            Some(json!({"program": file.to_string_lossy()})),
        ));

        let mut responses = dbg.handle_message(make_request(4, "configurationDone", None));
        while dbg.is_running() {
            responses.extend(dbg.step_running_vm());
        }

        let has_stopped = responses
            .iter()
            .any(|r| r.event.as_deref() == Some("stopped"));
        let has_terminated = responses
            .iter()
            .any(|r| r.event.as_deref() == Some("terminated"));

        // Either we stopped at the breakpoint or the VM raced ahead to completion;
        // both outcomes are acceptable since execution is single-threaded here.
        assert!(has_stopped || has_terminated);

        std::fs::remove_file(&file).ok();
        std::fs::remove_dir(&dir).ok();
    }

    #[test]
    fn test_pause_interrupts_running_vm() {
        let mut dbg = Debugger::new();

        let dir = std::env::temp_dir().join("harn_dap_pause_test");
        std::fs::create_dir_all(&dir).ok();
        let file = dir.join("test_pause.harn");
        std::fs::write(
            &file,
            "pipeline test(task) {\n  let x = 1\n  let y = 2\n  let z = 3\n}",
        )
        .unwrap();

        dbg.handle_message(make_request(1, "initialize", None));
        dbg.handle_message(make_request(
            2,
            "launch",
            Some(json!({"program": file.to_string_lossy()})),
        ));
        dbg.handle_message(make_request(3, "configurationDone", None));
        assert!(dbg.is_running());

        // Pause the in-flight VM before draining; the next step tick
        // must honor the pending pause and emit stopped/reason=pause.
        dbg.handle_message(make_request(4, "pause", None));
        let step_responses = dbg.step_running_vm();
        let paused = step_responses.iter().any(|r| {
            r.event.as_deref() == Some("stopped")
                && r.body
                    .as_ref()
                    .map(|b| b["reason"] == "pause")
                    .unwrap_or(false)
        });
        assert!(paused, "expected a stopped event with reason=pause");
        assert!(!dbg.is_running());

        std::fs::remove_file(&file).ok();
        std::fs::remove_dir(&dir).ok();
    }

    #[test]
    fn test_harn_ping_reports_state() {
        let mut dbg = Debugger::new();
        let responses = dbg.handle_message(make_request(1, "harnPing", None));
        assert_eq!(responses.len(), 1);
        let body = responses[0].body.as_ref().unwrap();
        assert_eq!(body["state"], "not_started");
        assert_eq!(body["running"], false);
        assert_eq!(body["stopped"], false);
    }
}