Skip to main content

logicaffeine_compile/
debug.rs

1//! The bytecode debugger bridge — drives the LOGOS VM one op at a time for the
2//! Studio debug drawer, with breakpoints, step-over / step-out, and **time-travel**
3//! (step backwards through executed ops). Single-task, bytecode tier (`tier: None`)
4//! so granularity is exactly one op and behaviour is identical to a normal run.
5//!
6//! ZERO production cost: nothing here is on the execution path. The stepping rides
7//! the VM's `STEPPED = true` monomorphization (the default `run_until_block` is
8//! byte-for-byte the old hot loop), and this whole module dead-strips from any
9//! binary that never constructs a [`Debugger`].
10//!
11//! Time-travel falls out of the architecture for free: the debugger owns the
12//! [`CompiledProgram`] and rebuilds a fresh VM each step from a saved state
13//! snapshot, so it keeps the full snapshot *history* — stepping back is just
14//! dropping the last snapshot.
15
16use std::collections::{BTreeSet, HashMap};
17
18use serde::Serialize;
19
20use crate::vm::{disassemble, CompiledProgram, DebugVmState, DisasmLine, Vm, VmStep};
21
22/// Browser-safety cap on a single Continue / Step-Over / Step-Out (an infinite loop
23/// must not hang the tab — the run pauses and reports it hit the limit).
24const STEP_LIMIT: usize = 5_000_000;
25
26/// One register in a [`DebugFrame`]. `name` is the source variable when known
27/// (filled by the compiler's debug-info pass; `None` ⇒ show `R{index}`).
28#[derive(Clone, Serialize)]
29pub struct DebugReg {
30    pub index: u16,
31    pub name: Option<String>,
32    /// The value's type — `Int`, `Float`, `List`, `Text`, … (teaches the type system).
33    pub kind: String,
34    pub value: String,
35    /// The value changed in the last executed op (drives the highlight / pulse).
36    pub changed: bool,
37}
38
39/// One call frame's registers. `function` is `None` for Main; `base` is the frame's
40/// start address in the linear register file (its stack base), for the Stack view.
41#[derive(Clone, Serialize)]
42pub struct DebugFrame {
43    pub function: Option<String>,
44    pub base: usize,
45    pub registers: Vec<DebugReg>,
46}
47
48/// One heap object for the Heap view: a list / map / set / struct / text reachable
49/// from a variable or global. `referenced_by` lists every root that points at it, so
50/// `shared` (more than one) makes aliasing visible — the thing assembly debuggers
51/// can't show because they only have raw bytes, not typed objects.
52#[derive(Clone, Serialize, Debug)]
53pub struct HeapObject {
54    /// A short stable label within this snapshot, e.g. `#1`.
55    pub id: String,
56    pub kind: String,
57    pub summary: String,
58    /// The underlying storage layout (`packed Vec<i64>`, `columnar`, …) — teaches how
59    /// the data is really laid out, not just its printed form.
60    pub storage: String,
61    /// Reference count (how many handles point at this allocation).
62    pub rc: usize,
63    pub referenced_by: Vec<String>,
64    /// Referenced by more than one root — an alias.
65    pub shared: bool,
66}
67
68/// A complete picture of the paused VM for the debug drawer (serde for the UI).
69#[derive(Clone, Serialize)]
70pub struct DebugSnapshot {
71    /// The pc the program is stopped at (the op about to execute).
72    pub pc: usize,
73    /// The disassembled current op (empty once finished).
74    pub op_text: String,
75    /// A plain-English description of the op about to run — the teaching narration
76    /// (e.g. "add x(6) + y(7) → R4"). Empty for the long-tail ops.
77    pub narration: String,
78    /// The first-order-logic semantics of the op about to run — the formal meaning of
79    /// this step (e.g. `sum = x + y`, `t ⟺ (i < n)`, `¬cond → goto 12`). Empty for the
80    /// long-tail ops.
81    pub fol: String,
82    /// A **Socratic** prompt for the step about to run — a guiding question that invites
83    /// the learner to predict the outcome before stepping ("x (6) and y (7) — what is
84    /// their sum?"). Empty for ops with nothing to anticipate (the UI then shows the
85    /// plain narration). Matches the engine's voice: concrete values, second person, `—`.
86    pub socratic: String,
87    /// Registers the current op reads / writes — drives the datapath animation.
88    pub op_reads: Vec<u16>,
89    pub op_writes: Option<u16>,
90    /// `"paused" | "done" | "blocked" | "error"`.
91    pub state: String,
92    pub error: Option<String>,
93    /// Position in the execution history (0 = before any op) — the time-travel cursor.
94    pub step: usize,
95    /// Highest step explored so far — the scrubber's maximum (>= `step`).
96    pub total_steps: usize,
97    /// Number of instructions in the program (the bytecode tape length).
98    pub total_ops: usize,
99    /// Call frames, Main first and the current frame last.
100    pub frames: Vec<DebugFrame>,
101    /// Heap objects reachable from the current frame + globals (the Heap view).
102    pub heap: Vec<HeapObject>,
103    /// Promoted globals (name → display value).
104    pub globals: Vec<(String, String)>,
105    /// Output emitted so far (the `Show` lines).
106    pub output: Vec<String>,
107    /// Whether execution is currently stopped on a breakpoint.
108    pub at_breakpoint: bool,
109}
110
111/// One variable's value over the whole recorded execution — a trace on the
112/// [`VarTimeline`] oscilloscope. `points[i]` is the value at explored step
113/// `timeline.start + i`.
114#[derive(Clone, Serialize)]
115pub struct VarTrace {
116    /// Main-frame register slot this variable lives in.
117    pub reg: u16,
118    pub name: String,
119    /// The value's type, sampled the first step it holds one (`Int`, `List`, …).
120    pub kind: String,
121    pub points: Vec<TimelinePoint>,
122}
123
124/// One sample on a [`VarTrace`]: the variable's display value at a single step, and
125/// whether it just changed (the waveform "edge").
126#[derive(Clone, Serialize)]
127pub struct TimelinePoint {
128    pub value: String,
129    /// The slot held a value at this step (always true for Main locals once the
130    /// frame exists; `false` before it is allocated).
131    pub present: bool,
132    /// Differs from the previous step's value — drives the waveform transition.
133    pub changed: bool,
134}
135
136/// A logic-analyzer view of the run: every Main-frame variable's value across the
137/// recorded history, with a playhead at the time-travel cursor. Deterministic replay
138/// makes this exact — it is the program's *entire* observable past, not a sample.
139#[derive(Clone, Serialize)]
140pub struct VarTimeline {
141    /// Step index of column 0 (non-zero only when the history was tail-windowed).
142    pub start: usize,
143    /// Number of columns (explored steps) in the window.
144    pub steps: usize,
145    /// The time-travel cursor's absolute step (place the playhead at `cursor - start`).
146    pub cursor: usize,
147    /// History longer than the window cap was tail-trimmed to the most recent steps.
148    pub truncated: bool,
149    pub vars: Vec<VarTrace>,
150}
151
152/// One variable's **observed invariants** — facts that held over the recorded run
153/// (constant, monotonic, range, distinct count). Dynamic likely-invariants, labelled
154/// as observed (not proven), the empirical companion to the Oracle's static facts.
155#[derive(Clone, Serialize)]
156pub struct VarInsight {
157    pub name: String,
158    pub kind: String,
159    pub facts: Vec<String>,
160}
161
162/// A variable's program-wide **proven** facts (from the Oracle's static abstract
163/// interpretation): a finite integer range, non-negativity, a concrete scalar type.
164/// Every field is a sound guarantee that holds on *every* run — the static companion
165/// to [`VarInsight`]'s observed-this-run facts.
166#[derive(Clone, Serialize, Default)]
167pub struct ProvenFacts {
168    pub scalar: Option<String>,
169    pub int_range: Option<(i64, i64)>,
170    pub nonneg: bool,
171}
172
173impl From<crate::optimize::VarProvenFacts> for ProvenFacts {
174    fn from(v: crate::optimize::VarProvenFacts) -> Self {
175        ProvenFacts {
176            scalar: v.scalar.map(|s| format!("{s:?}")),
177            int_range: v.int_range,
178            nonneg: v.nonneg,
179        }
180    }
181}
182
183impl ProvenFacts {
184    /// Human-readable proven facts, e.g. `["∈ [0, 9]", "type Int"]`. A finite range
185    /// subsumes non-negativity, so `≥ 0` is shown only when the upper bound is open.
186    fn labels(&self) -> Vec<String> {
187        let mut out = Vec::new();
188        match self.int_range {
189            Some((lo, hi)) => out.push(format!("\u{2208} [{lo}, {hi}]")),
190            None if self.nonneg => out.push("\u{2265} 0".to_string()),
191            None => {}
192        }
193        if let Some(s) = &self.scalar {
194            out.push(format!("type {s}"));
195        }
196        out
197    }
198}
199
200/// One variable's proven invariants, pre-rendered for the UI (mirrors [`VarInsight`]).
201#[derive(Clone, Serialize)]
202pub struct ProvenInsight {
203    pub name: String,
204    pub facts: Vec<String>,
205}
206
207/// The verdict of a **live proof** at a breakpoint — whether a predicate is statically
208/// guaranteed across every run (`ProvenTrue`), statically refuted (`ProvenFalse`), or
209/// undecided from the proven facts (`Unknown`, where only the concrete check speaks).
210#[derive(Clone, Serialize, PartialEq, Debug)]
211pub enum ProofVerdict {
212    ProvenTrue,
213    ProvenFalse,
214    Unknown,
215}
216
217/// The result of asserting a predicate at the cursor — the dual lens the debugger is
218/// built for: what is true **now** (concrete, from live values) and what is **proven**
219/// for every run (from the Oracle's static facts, kernel-style interval entailment, no
220/// Z3). `now` is `None` when a term has no live integer value; the verdict is `Unknown`
221/// when a term has no proven range.
222#[derive(Clone, Serialize)]
223pub struct AssertionResult {
224    pub query: String,
225    /// Whether the predicate parsed as a comparison (`a < b`, `x >= 0`, …).
226    pub parsed: bool,
227    /// Concrete truth at the current state (`None` if a term isn't a live integer).
228    pub now: Option<bool>,
229    pub now_detail: String,
230    /// Static guarantee over every run.
231    pub verdict: ProofVerdict,
232    pub verdict_detail: String,
233}
234
235/// One side of a comparison: a variable reference or an integer literal.
236enum Operand {
237    Var(String),
238    Int(i64),
239}
240
241#[derive(Clone, Copy)]
242enum Cmp {
243    Lt,
244    Le,
245    Gt,
246    Ge,
247    Eq,
248    Ne,
249}
250
251/// A node in a **causal provenance tree** — the exact op that produced a value, and
252/// (recursively) the ops that produced its inputs. Because execution is deterministic
253/// and fully recorded, this lineage is exact, not heuristic: the answer to "why is
254/// this value here?" with no guessing.
255#[derive(Clone, Serialize)]
256pub struct CausalNode {
257    /// Explored step whose op produced this value (`0` ⇒ an initial/never-written slot).
258    pub step: usize,
259    /// The producing op's pc, its disassembly, and its English narration.
260    pub pc: usize,
261    pub op_text: String,
262    pub narration: String,
263    /// The slot, its source name if any, and the value it ended up holding.
264    pub reg: u16,
265    pub name: Option<String>,
266    pub kind: String,
267    pub value: String,
268    /// The values this op consumed — each itself traced to where it came from.
269    pub inputs: Vec<CausalNode>,
270}
271
272/// Tail-window cap on the oscilloscope (a runaway loop must not force a million VM
273/// rebuilds nor an unviewable waveform — the most recent steps are what you watch).
274const TIMELINE_MAX_STEPS: usize = 512;
275
276/// Depth / breadth caps on a provenance walk so a deep dependency chain stays a
277/// readable tree rather than an explosion.
278const PROVENANCE_MAX_DEPTH: usize = 24;
279const PROVENANCE_MAX_NODES: usize = 96;
280
281/// Per-frame terminal status (the program is deterministic, so each explored op has
282/// exactly one outcome that travels with its history entry — seeking back to it
283/// correctly reads "paused", not the program's final "done").
284#[derive(Clone)]
285enum Outcome {
286    Running,
287    Done,
288    Blocked,
289    Error(String),
290}
291
292/// One explored point in the execution: the VM state plus its outcome.
293struct Frame {
294    state: DebugVmState,
295    outcome: Outcome,
296}
297
298/// A self-contained stepping debugger over one compiled program.
299///
300/// Execution is deterministic, so `history` is the single execution prefix explored
301/// so far and `cursor` is simply where you are looking. Step / step-back / seek /
302/// restart all just move the cursor; a new VM op is only ever computed when the
303/// cursor reaches the unexplored frontier. That makes step-back, restart, redo, and
304/// the time-travel scrubber instant, and reverse-continue a pure cursor walk.
305pub struct Debugger {
306    program: CompiledProgram,
307    disasm: Vec<DisasmLine>,
308    history: Vec<Frame>,
309    cursor: usize,
310    breakpoints: BTreeSet<usize>,
311    /// Program-wide PROVEN facts per variable name, from the Oracle's abstract
312    /// interpretation (computed once at compile, then read-only). The static
313    /// counterpart to the dynamic [`Debugger::observed_invariants`].
314    proven: HashMap<String, ProvenFacts>,
315}
316
317impl Debugger {
318    /// Compile `src` (exactly as the Studio "Run" path does) and arm a debugger at
319    /// the program's entry. The program is debugged on the bytecode tier with no
320    /// JIT, so stepping is per-op and output matches a normal run.
321    pub fn from_source(src: &str) -> Result<Debugger, String> {
322        let (program, proven) = compile_source(src)?;
323        let disasm = disassemble(&program);
324        let initial = Vm::new(&program).save_debug_state();
325        Ok(Debugger {
326            program,
327            disasm,
328            history: vec![Frame {
329                state: initial,
330                outcome: Outcome::Running,
331            }],
332            cursor: 0,
333            breakpoints: BTreeSet::new(),
334            proven,
335        })
336    }
337
338    /// Execute exactly one op (Step Into).
339    pub fn step(&mut self) {
340        self.run_one();
341    }
342
343    /// Execute one op, but run any function it calls to completion (Step Over).
344    pub fn step_over(&mut self) {
345        let start = self.current_depth();
346        if !self.run_one() {
347            return;
348        }
349        let mut budget = STEP_LIMIT;
350        while self.is_paused() && self.current_depth() > start {
351            if self.at_breakpoint() {
352                break;
353            }
354            if !self.run_one() {
355                break;
356            }
357            budget -= 1;
358            if budget == 0 {
359                break;
360            }
361        }
362    }
363
364    /// Run until the current function returns (Step Out); from Main, runs to the end.
365    pub fn step_out(&mut self) {
366        let start = self.current_depth();
367        let mut budget = STEP_LIMIT;
368        loop {
369            if !self.is_paused() || self.current_depth() < start {
370                break;
371            }
372            if !self.run_one() {
373                break;
374            }
375            if self.at_breakpoint() {
376                break;
377            }
378            budget -= 1;
379            if budget == 0 {
380                break;
381            }
382        }
383    }
384
385    /// Run until the next breakpoint, a block, completion, or the step limit (Continue).
386    pub fn resume(&mut self) {
387        let mut budget = STEP_LIMIT;
388        loop {
389            if !self.is_paused() {
390                break;
391            }
392            if !self.run_one() {
393                break;
394            }
395            if self.at_breakpoint() {
396                break;
397            }
398            budget -= 1;
399            if budget == 0 {
400                break;
401            }
402        }
403    }
404
405    /// Run BACKWARD to the previous breakpoint, or the program entry — reverse
406    /// continue. Pure cursor motion over the recorded history, a time-travel feature
407    /// almost no debugger has.
408    pub fn reverse_resume(&mut self) {
409        while self.cursor > 0 {
410            self.cursor -= 1;
411            if self.breakpoints.contains(&self.current().pc()) {
412                break;
413            }
414        }
415    }
416
417    /// Undo the last executed op — time-travel one step backwards.
418    pub fn step_back(&mut self) {
419        self.cursor = self.cursor.saturating_sub(1);
420    }
421
422    /// Jump the time-travel cursor to any already-explored step (the scrubber).
423    pub fn seek(&mut self, step: usize) {
424        self.cursor = step.min(self.history.len().saturating_sub(1));
425    }
426
427    /// Rewind to the program entry, keeping the explored history (re-stepping is then
428    /// instant) and the breakpoints.
429    pub fn restart(&mut self) {
430        self.cursor = 0;
431    }
432
433    /// Toggle a breakpoint on a bytecode pc.
434    pub fn toggle_breakpoint(&mut self, pc: usize) {
435        if !self.breakpoints.remove(&pc) {
436            self.breakpoints.insert(pc);
437        }
438    }
439
440    pub fn set_breakpoint(&mut self, pc: usize) {
441        self.breakpoints.insert(pc);
442    }
443
444    pub fn clear_breakpoint(&mut self, pc: usize) {
445        self.breakpoints.remove(&pc);
446    }
447
448    pub fn breakpoints(&self) -> Vec<usize> {
449        self.breakpoints.iter().copied().collect()
450    }
451
452    /// The full disassembly (the bytecode tape).
453    pub fn disassembly(&self) -> &[DisasmLine] {
454        &self.disasm
455    }
456
457    /// Whether the program is still paused mid-execution at the current cursor (cheap,
458    /// no snapshot build). `false` once it has finished, blocked, or errored here.
459    pub fn is_running(&self) -> bool {
460        self.is_paused()
461    }
462
463    /// What the program has printed up to the cursor — the snapshot's `output`, read from the
464    /// recorded state without rebuilding a VM.
465    pub fn output(&self) -> &[String] {
466        self.current().lines()
467    }
468
469    /// The runtime error the program stopped on at the cursor, if it stopped on one.
470    pub fn error(&self) -> Option<&str> {
471        match &self.cur().outcome {
472            Outcome::Error(message) => Some(message),
473            _ => None,
474        }
475    }
476
477    /// Build a serde snapshot of the current paused state for the UI.
478    pub fn snapshot(&self) -> DebugSnapshot {
479        let (view, heap_raw) = self.view_and_heap(self.current());
480        // The previous step's innermost-frame registers, to mark what just changed —
481        // but ONLY when the frame context is the same (same call depth). Crossing into
482        // or out of a function changes which frame is innermost, so comparing by index
483        // would flag unrelated registers; suppress it across that boundary.
484        let prev_inner: HashMap<u16, String> = if self.cursor >= 1 {
485            let pv = self.view_of(&self.history[self.cursor - 1].state);
486            if pv.frames.len() == view.frames.len() {
487                pv.frames
488                    .last()
489                    .map(|f| {
490                        f.registers
491                            .iter()
492                            .map(|(idx, _kind, val)| (*idx, val.clone()))
493                            .collect()
494                    })
495                    .unwrap_or_default()
496            } else {
497                HashMap::new()
498            }
499        } else {
500            HashMap::new()
501        };
502        // Variable names (`R0` → `x`) for Main and each function, captured by the debug
503        // compile path.
504        let frame_names = |func: Option<u16>| -> HashMap<u16, String> {
505            match func {
506                None => self.program.reg_names.iter().cloned().collect(),
507                Some(i) => self
508                    .program
509                    .fn_debug
510                    .get(i as usize)
511                    .map(|f| f.reg_names.iter().cloned().collect())
512                    .unwrap_or_default(),
513            }
514        };
515        let function_name = |i: u16| {
516            self.program
517                .fn_debug
518                .get(i as usize)
519                .map(|f| f.name.clone())
520                .filter(|n| !n.is_empty())
521                .unwrap_or_else(|| format!("fn#{i}"))
522        };
523        let n = view.frames.len();
524        let frames: Vec<DebugFrame> = view
525            .frames
526            .iter()
527            .enumerate()
528            .map(|(fi, f)| {
529                let inner = fi + 1 == n;
530                let names = frame_names(f.func);
531                DebugFrame {
532                    function: f.func.map(function_name),
533                    base: f.base,
534                    registers: f
535                        .registers
536                        .iter()
537                        .map(|(idx, kind, val)| DebugReg {
538                            index: *idx,
539                            name: names.get(idx).cloned(),
540                            kind: kind.clone(),
541                            value: val.clone(),
542                            changed: inner
543                                && prev_inner.get(idx).map(|p| p != val).unwrap_or(false),
544                        })
545                        .collect(),
546                }
547            })
548            .collect();
549        let (state, error) = match &self.cur().outcome {
550            Outcome::Running => ("paused", None),
551            Outcome::Done => ("done", None),
552            Outcome::Blocked => ("blocked", None),
553            Outcome::Error(e) => ("error", Some(e.clone())),
554        };
555        let op_text = self
556            .disasm
557            .get(view.pc)
558            .map(|d| d.text.clone())
559            .unwrap_or_default();
560        // Teaching narration + the registers this op touches (for the datapath).
561        let inner_regs: HashMap<u16, (Option<String>, String)> = frames
562            .last()
563            .map(|f: &DebugFrame| {
564                f.registers
565                    .iter()
566                    .map(|r| (r.index, (r.name.clone(), r.value.clone())))
567                    .collect()
568            })
569            .unwrap_or_default();
570        let cur_op = self.program.code.get(view.pc).copied();
571        let (narration, op_reads, op_writes) = match (&self.cur().outcome, cur_op) {
572            (Outcome::Error(e), _) => (format!("error: {e}"), Vec::new(), None),
573            (Outcome::Done, _) => ("the program has finished".to_string(), Vec::new(), None),
574            (Outcome::Blocked, _) => (
575                "waiting on a concurrency operation".to_string(),
576                Vec::new(),
577                None,
578            ),
579            (Outcome::Running, Some(op)) => {
580                let io = crate::vm::op_io(&op);
581                (
582                    narrate(&op, &inner_regs, &self.program),
583                    io.reads,
584                    io.writes,
585                )
586            }
587            _ => (String::new(), Vec::new(), None),
588        };
589        let fol = match (&self.cur().outcome, cur_op) {
590            (Outcome::Running, Some(op)) => fol_of_op(&op, &inner_regs, &self.program),
591            _ => String::new(),
592        };
593        let socratic = match (&self.cur().outcome, cur_op) {
594            (Outcome::Running, Some(op)) => socratic_of_op(&op, &inner_regs),
595            (Outcome::Done, _) => {
596                "The program has finished — did the result match what you expected?".to_string()
597            }
598            _ => String::new(),
599        };
600        let heap: Vec<HeapObject> = heap_raw
601            .iter()
602            .enumerate()
603            .map(|(i, o)| HeapObject {
604                id: format!("#{}", i + 1),
605                kind: o.kind.clone(),
606                summary: o.summary.clone(),
607                storage: o.storage.clone(),
608                rc: o.rc,
609                referenced_by: o.referenced_by.clone(),
610                shared: o.referenced_by.len() > 1,
611            })
612            .collect();
613        DebugSnapshot {
614            pc: view.pc,
615            op_text,
616            narration,
617            fol,
618            socratic,
619            op_reads,
620            op_writes,
621            state: state.to_string(),
622            error,
623            step: self.cursor,
624            total_steps: self.history.len().saturating_sub(1),
625            total_ops: self.disasm.len(),
626            frames,
627            heap,
628            globals: view.globals.clone(),
629            output: view.output.clone(),
630            at_breakpoint: self.at_breakpoint(),
631        }
632    }
633
634    /// The **variable oscilloscope**: every Main-frame variable's value across the
635    /// recorded execution, with a playhead at the cursor. On-demand (only the Timeline
636    /// tab calls it), tail-windowed to the most recent `TIMELINE_MAX_STEPS` steps so
637    /// a long loop stays cheap and viewable.
638    pub fn variable_timeline(&self) -> VarTimeline {
639        let names = self.main_names();
640        let total = self.history.len();
641        let start = total.saturating_sub(TIMELINE_MAX_STEPS);
642        let truncated = start > 0;
643        let window = &self.history[start..];
644        let n = window.len();
645
646        let mut order: Vec<u16> = names.keys().copied().collect();
647        order.sort_unstable();
648        // (kind, value) per (reg, column); None before the slot exists at that step.
649        let mut series: HashMap<u16, Vec<Option<(String, String)>>> =
650            order.iter().map(|r| (*r, vec![None; n])).collect();
651        for (col, frame) in window.iter().enumerate() {
652            let view = self.view_of(&frame.state);
653            if let Some(main) = view.frames.iter().find(|f| f.func.is_none()) {
654                for (idx, kind, val) in &main.registers {
655                    if let Some(slot) = series.get_mut(idx) {
656                        slot[col] = Some((kind.clone(), val.clone()));
657                    }
658                }
659            }
660        }
661
662        let vars = order
663            .iter()
664            .map(|reg| {
665                let name = names.get(reg).cloned().unwrap_or_else(|| format!("R{reg}"));
666                let raw = &series[reg];
667                let mut kind = String::new();
668                let mut points = Vec::with_capacity(n);
669                let mut prev: Option<String> = None;
670                for cell in raw {
671                    match cell {
672                        Some((k, v)) => {
673                            // The settled type: a slot reads `Nothing` before assignment,
674                            // so the last meaningful kind is the variable's real type.
675                            if k != "Nothing" || kind.is_empty() {
676                                kind = k.clone();
677                            }
678                            // An "edge" needs a prior present value to differ from — the
679                            // first time a variable appears is not a transition.
680                            let changed = matches!(&prev, Some(p) if p != v);
681                            points.push(TimelinePoint {
682                                value: v.clone(),
683                                present: true,
684                                changed,
685                            });
686                            prev = Some(v.clone());
687                        }
688                        None => {
689                            points.push(TimelinePoint {
690                                value: String::new(),
691                                present: false,
692                                changed: false,
693                            });
694                            prev = None;
695                        }
696                    }
697                }
698                VarTrace {
699                    reg: *reg,
700                    name,
701                    kind,
702                    points,
703                }
704            })
705            // A variable never observed in the window is noise; drop it.
706            .filter(|t| t.points.iter().any(|p| p.present))
707            .collect();
708
709        VarTimeline {
710            start,
711            steps: n,
712            cursor: self.cursor,
713            truncated,
714            vars,
715        }
716    }
717
718    /// **Observed invariants** (Daikon-style dynamic detection): for each variable,
719    /// reduce its recorded trace into the facts that held over *this run* — constant,
720    /// monotonic, value range, distinct count. Dynamic, not a static proof (the
721    /// formally-proven counterpart comes from the Oracle), but exact for what happened.
722    pub fn observed_invariants(&self) -> Vec<VarInsight> {
723        let tl = self.variable_timeline();
724        tl.vars
725            .iter()
726            .filter_map(|v| {
727                // Sample only from the variable's first real assignment (its first edge)
728                // — before that the slot is uninitialised and would pollute the facts.
729                let first = v.points.iter().position(|p| p.present && p.changed)?;
730                let vals: Vec<&str> = v.points[first..]
731                    .iter()
732                    .filter(|p| p.present)
733                    .map(|p| p.value.as_str())
734                    .collect();
735                if vals.is_empty() {
736                    return None;
737                }
738                let distinct: BTreeSet<&str> = vals.iter().copied().collect();
739                let nums: Option<Vec<f64>> = vals.iter().map(|s| s.parse::<f64>().ok()).collect();
740                let mut facts = Vec::new();
741                if distinct.len() == 1 {
742                    facts.push(format!("constant {}", vals[0]));
743                } else {
744                    if let Some(ns) = &nums {
745                        let min = ns.iter().cloned().fold(f64::INFINITY, f64::min);
746                        let max = ns.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
747                        facts.push(format!("range [{}, {}]", fmt_num(min), fmt_num(max)));
748                        if ns.windows(2).all(|w| w[1] >= w[0]) {
749                            facts.push("only increases".to_string());
750                        } else if ns.windows(2).all(|w| w[1] <= w[0]) {
751                            facts.push("only decreases".to_string());
752                        }
753                    }
754                    facts.push(format!("{} distinct values", distinct.len()));
755                }
756                Some(VarInsight {
757                    name: v.name.clone(),
758                    kind: v.kind.clone(),
759                    facts,
760                })
761            })
762            .collect()
763    }
764
765    /// **Proven invariants**: the Oracle's statically-verified facts per variable
766    /// (range, non-negativity, scalar type) — guarantees that hold on *every* run, not
767    /// just this one. The formal companion to [`Debugger::observed_invariants`]. Only
768    /// variables with at least one non-trivial proven fact are returned, sorted by name.
769    pub fn proven_invariants(&self) -> Vec<ProvenInsight> {
770        let mut out: Vec<ProvenInsight> = self
771            .proven
772            .iter()
773            .filter_map(|(name, pf)| {
774                let facts = pf.labels();
775                if facts.is_empty() {
776                    None
777                } else {
778                    Some(ProvenInsight {
779                        name: name.clone(),
780                        facts,
781                    })
782                }
783            })
784            .collect();
785        out.sort_by(|a, b| a.name.cmp(&b.name));
786        out
787    }
788
789    /// **Live proof at a breakpoint**: assert a comparison predicate (`x < y`, `x >= 0`,
790    /// `sum == 13`) and get both lenses — whether it holds **now** (concretely, from the
791    /// live values) and whether it is **proven for every run** (from the Oracle's proven
792    /// ranges, by sound interval entailment; pure Rust, no Z3). The dual answer is the
793    /// point: a thing can be true now yet unproven in general, or proven yet about a value
794    /// not yet reached.
795    pub fn assert_at_cursor(&self, predicate: &str) -> AssertionResult {
796        let query = predicate.trim().to_string();
797        let Some((lhs, cmp, rhs)) = parse_comparison(&query) else {
798            return AssertionResult {
799                query,
800                parsed: false,
801                now: None,
802                now_detail: "couldn't parse \u{2014} try a comparison like `x < y` or `x >= 0`"
803                    .to_string(),
804                verdict: ProofVerdict::Unknown,
805                verdict_detail: String::new(),
806            };
807        };
808
809        // Concrete: resolve each side to its live integer value at the cursor.
810        let frame = self.snapshot();
811        let live = |o: &Operand| -> Option<i64> {
812            match o {
813                Operand::Int(c) => Some(*c),
814                Operand::Var(name) => frame
815                    .frames
816                    .last()
817                    .and_then(|f| {
818                        f.registers
819                            .iter()
820                            .find(|r| r.name.as_deref() == Some(name.as_str()))
821                    })
822                    .and_then(|r| r.value.parse::<i64>().ok()),
823            }
824        };
825        let now = match (live(&lhs), live(&rhs)) {
826            (Some(a), Some(b)) => Some(apply_cmp(a, cmp, b)),
827            _ => None,
828        };
829        let now_detail = {
830            let mut parts = Vec::new();
831            for o in [&lhs, &rhs] {
832                if let Operand::Var(name) = o {
833                    match live(o) {
834                        Some(v) => parts.push(format!("{name} = {v}")),
835                        None => parts.push(format!("{name} = ?")),
836                    }
837                }
838            }
839            parts.join(", ")
840        };
841
842        // Static: resolve each side to its proven range and check entailment.
843        let prange = |o: &Operand| -> Option<(i64, i64)> {
844            match o {
845                Operand::Int(c) => Some((*c, *c)),
846                Operand::Var(name) => self.proven.get(name).and_then(|pf| pf.int_range),
847            }
848        };
849        let (verdict, verdict_detail) = match (prange(&lhs), prange(&rhs)) {
850            (Some(a), Some(b)) => {
851                let v = entail(a, cmp, b);
852                let mut srcs = Vec::new();
853                if let Operand::Var(n) = &lhs {
854                    srcs.push(format!("{n} \u{2208} [{}, {}]", a.0, a.1));
855                }
856                if let Operand::Var(n) = &rhs {
857                    srcs.push(format!("{n} \u{2208} [{}, {}]", b.0, b.1));
858                }
859                let detail = match v {
860                    ProofVerdict::Unknown => "the proven ranges don't decide it".to_string(),
861                    _ => format!("from {}", srcs.join(", ")),
862                };
863                (v, detail)
864            }
865            _ => (
866                ProofVerdict::Unknown,
867                "no proven range for one of the terms".to_string(),
868            ),
869        };
870
871        AssertionResult {
872            query,
873            parsed: true,
874            now,
875            now_detail,
876            verdict,
877            verdict_detail,
878        }
879    }
880
881    /// **Causal provenance**: trace the value currently in innermost-frame register
882    /// `reg` back to the exact op that produced it, and recursively the ops that
883    /// produced *that* op's inputs — the precise answer to "why is this value here?".
884    /// Returns `None` only if the register holds nothing at the cursor.
885    pub fn provenance(&self, reg: u16) -> Option<CausalNode> {
886        let mut budget = PROVENANCE_MAX_NODES;
887        self.trace_value(reg, self.cursor, PROVENANCE_MAX_DEPTH, &mut budget)
888    }
889
890    /// Walk back from `at_step` to the most recent op (at or before it) that wrote
891    /// `reg`, then recurse on that op's source registers as of *its* input state.
892    /// Strictly decreasing `at_step` guarantees termination.
893    fn trace_value(
894        &self,
895        reg: u16,
896        at_step: usize,
897        depth: usize,
898        budget: &mut usize,
899    ) -> Option<CausalNode> {
900        let (name, kind, value) = self.reg_value_at(at_step, reg)?;
901        if *budget == 0 || depth == 0 {
902            return Some(CausalNode {
903                step: 0,
904                pc: 0,
905                op_text: String::new(),
906                narration: String::new(),
907                reg,
908                name,
909                kind,
910                value,
911                inputs: Vec::new(),
912            });
913        }
914        *budget -= 1;
915
916        // Find the producing op: stepping from state[i-1] runs the op at state[i-1].pc()
917        // and lands its write in state[i]. Scan back for the latest write of `reg`.
918        for i in (1..=at_step).rev() {
919            let producer_pc = self.history[i - 1].state.pc();
920            let Some(op) = self.program.code.get(producer_pc).copied() else {
921                continue;
922            };
923            let io = crate::vm::op_io(&op);
924            if io.writes != Some(reg) {
925                continue;
926            }
927            // A `Move` is a compiler-inserted copy (temp → named slot). It carries no
928            // computation, so fold it: the value's real lineage is its source's, just
929            // relabelled as this destination — the tree then matches the SOURCE data
930            // flow ("w = z + x"), not the bytecode's temp shuffles.
931            if let crate::vm::Op::Move { src, .. } = op {
932                if let Some(mut child) = self.trace_value(src, i - 1, depth, budget) {
933                    if let Some((nm, k, v)) = self.reg_value_at(i, reg) {
934                        child.reg = reg;
935                        child.name = nm;
936                        child.kind = k;
937                        child.value = v;
938                    }
939                    return Some(child);
940                }
941            }
942            // Resolve this op's value as of the step it produced, its inputs as of the
943            // input state (i-1) — register numbers are frame-relative to each state.
944            let (pname, pkind, pvalue) = self
945                .reg_value_at(i, reg)
946                .unwrap_or_else(|| (name.clone(), kind.clone(), value.clone()));
947            let inner = self.input_regs(i - 1);
948            let narration = narrate(&op, &inner, &self.program);
949            let op_text = self
950                .disasm
951                .get(producer_pc)
952                .map(|d| d.text.clone())
953                .unwrap_or_default();
954            let inputs = io
955                .reads
956                .iter()
957                .filter_map(|r| self.trace_value(*r, i - 1, depth - 1, budget))
958                .collect();
959            return Some(CausalNode {
960                step: i,
961                pc: producer_pc,
962                op_text,
963                narration,
964                reg,
965                name: pname,
966                kind: pkind,
967                value: pvalue,
968                inputs,
969            });
970        }
971
972        // No op in history wrote this slot — it is an initial / constant / parameter.
973        Some(CausalNode {
974            step: 0,
975            pc: 0,
976            op_text: String::new(),
977            narration: String::new(),
978            reg,
979            name,
980            kind,
981            value,
982            inputs: Vec::new(),
983        })
984    }
985
986    // ── internals ────────────────────────────────────────────────────────────
987
988    /// Main-frame variable names (`R0` → `x`), as captured by the debug compile pass.
989    fn main_names(&self) -> HashMap<u16, String> {
990        self.program.reg_names.iter().cloned().collect()
991    }
992
993    /// The `(name, kind, value)` of innermost-frame register `reg` at explored `step`,
994    /// or `None` if the slot is absent there. Names are applied for the Main frame.
995    fn reg_value_at(&self, step: usize, reg: u16) -> Option<(Option<String>, String, String)> {
996        let frame = self.history.get(step)?;
997        let view = self.view_of(&frame.state);
998        let f = view.frames.last()?;
999        let is_main = f.func.is_none();
1000        f.registers
1001            .iter()
1002            .find(|(idx, _, _)| *idx == reg)
1003            .map(|(idx, kind, val)| {
1004                let name = if is_main {
1005                    self.main_names().get(idx).cloned()
1006                } else {
1007                    None
1008                };
1009                (name, kind.clone(), val.clone())
1010            })
1011    }
1012
1013    /// The innermost-frame `(reg → (name, value))` map at `step`, for narrating an op
1014    /// in terms of the operands it actually read.
1015    fn input_regs(&self, step: usize) -> HashMap<u16, (Option<String>, String)> {
1016        let names = self.main_names();
1017        let Some(frame) = self.history.get(step) else {
1018            return HashMap::new();
1019        };
1020        let view = self.view_of(&frame.state);
1021        let Some(f) = view.frames.last() else {
1022            return HashMap::new();
1023        };
1024        let is_main = f.func.is_none();
1025        f.registers
1026            .iter()
1027            .map(|(idx, _, val)| {
1028                let name = if is_main {
1029                    names.get(idx).cloned()
1030                } else {
1031                    None
1032                };
1033                (*idx, (name, val.clone()))
1034            })
1035            .collect()
1036    }
1037
1038    fn cur(&self) -> &Frame {
1039        &self.history[self.cursor]
1040    }
1041
1042    fn current(&self) -> &DebugVmState {
1043        &self.cur().state
1044    }
1045
1046    fn is_paused(&self) -> bool {
1047        matches!(self.cur().outcome, Outcome::Running)
1048    }
1049
1050    fn current_depth(&self) -> usize {
1051        self.current().call_depth()
1052    }
1053
1054    fn at_breakpoint(&self) -> bool {
1055        self.is_paused() && self.breakpoints.contains(&self.current().pc())
1056    }
1057
1058    /// Rebuild a `tier: None` VM in `st`'s state and read its debug view.
1059    fn view_of(&self, st: &DebugVmState) -> crate::vm::DebugView {
1060        let mut vm = Vm::new(&self.program);
1061        vm.restore_debug_state(st.clone());
1062        vm.debug_view()
1063    }
1064
1065    /// Like [`view_of`], plus the heap objects reachable from that state (one VM
1066    /// rebuild for both).
1067    fn view_and_heap(
1068        &self,
1069        st: &DebugVmState,
1070    ) -> (crate::vm::DebugView, Vec<crate::vm::HeapObjView>) {
1071        let mut vm = Vm::new(&self.program);
1072        vm.restore_debug_state(st.clone());
1073        (vm.debug_view(), vm.debug_heap())
1074    }
1075
1076    /// Advance the cursor by one op. When the cursor is rewound into already-explored
1077    /// history this just steps it forward — execution is deterministic, so the cached
1078    /// frame is exactly what re-running would produce. At the frontier it computes and
1079    /// records the next frame. Returns whether the new position is still running.
1080    fn run_one(&mut self) -> bool {
1081        if !self.is_paused() {
1082            return false;
1083        }
1084        if self.cursor + 1 < self.history.len() {
1085            self.cursor += 1;
1086            return self.is_paused();
1087        }
1088        let cur_state = self.current().clone();
1089        let mut vm = Vm::new(&self.program);
1090        vm.restore_debug_state(cur_state.clone());
1091        let frame = match vm.run_steps(1) {
1092            Ok(VmStep::Paused) => Frame {
1093                state: vm.save_debug_state(),
1094                outcome: Outcome::Running,
1095            },
1096            Ok(VmStep::Done(_)) => Frame {
1097                state: vm.save_debug_state(),
1098                outcome: Outcome::Done,
1099            },
1100            Ok(VmStep::Blocked) => Frame {
1101                state: vm.save_debug_state(),
1102                outcome: Outcome::Blocked,
1103            },
1104            // Keep the pre-error state so the snapshot shows the failing op's pc.
1105            Err(e) => Frame {
1106                state: cur_state,
1107                outcome: Outcome::Error(e),
1108            },
1109        };
1110        self.history.push(frame);
1111        self.cursor += 1;
1112        self.is_paused()
1113    }
1114}
1115
1116/// A plain-English description of the op about to run, using variable names and live
1117/// values where available (e.g. `add x(6) + y(7) → R4`). The teaching narration; empty
1118/// for ops with no pedagogical value, so the UI falls back to the disassembly.
1119fn narrate(
1120    op: &crate::vm::Op,
1121    regs: &HashMap<u16, (Option<String>, String)>,
1122    prog: &CompiledProgram,
1123) -> String {
1124    use crate::vm::Op;
1125    let name = |r: u16| {
1126        regs.get(&r)
1127            .and_then(|(n, _)| n.clone())
1128            .unwrap_or_else(|| format!("R{r}"))
1129    };
1130    let operand = |r: u16| match regs.get(&r) {
1131        Some((_, v)) if !v.is_empty() => format!("{}({})", name(r), v),
1132        _ => name(r),
1133    };
1134    match *op {
1135        Op::LoadConst { dst, idx } => {
1136            format!(
1137                "load {} into {}",
1138                crate::vm::format_constant(prog, idx),
1139                name(dst)
1140            )
1141        }
1142        Op::Move { dst, src } => format!("copy {} into {}", operand(src), name(dst)),
1143        Op::Add { dst, lhs, rhs } => format!(
1144            "add {} + {} \u{2192} {}",
1145            operand(lhs),
1146            operand(rhs),
1147            name(dst)
1148        ),
1149        Op::Sub { dst, lhs, rhs } => format!(
1150            "subtract {} - {} \u{2192} {}",
1151            operand(lhs),
1152            operand(rhs),
1153            name(dst)
1154        ),
1155        Op::Mul { dst, lhs, rhs } => format!(
1156            "multiply {} \u{00d7} {} \u{2192} {}",
1157            operand(lhs),
1158            operand(rhs),
1159            name(dst)
1160        ),
1161        Op::Div { dst, lhs, rhs } | Op::ExactDiv { dst, lhs, rhs } => {
1162            format!(
1163                "divide {} \u{00f7} {} \u{2192} {}",
1164                operand(lhs),
1165                operand(rhs),
1166                name(dst)
1167            )
1168        }
1169        Op::Mod { dst, lhs, rhs } => format!(
1170            "{} mod {} \u{2192} {}",
1171            operand(lhs),
1172            operand(rhs),
1173            name(dst)
1174        ),
1175        Op::Lt { dst, lhs, rhs } => format!(
1176            "is {} < {}? \u{2192} {}",
1177            operand(lhs),
1178            operand(rhs),
1179            name(dst)
1180        ),
1181        Op::Gt { dst, lhs, rhs } => format!(
1182            "is {} > {}? \u{2192} {}",
1183            operand(lhs),
1184            operand(rhs),
1185            name(dst)
1186        ),
1187        Op::LtEq { dst, lhs, rhs } => format!(
1188            "is {} <= {}? \u{2192} {}",
1189            operand(lhs),
1190            operand(rhs),
1191            name(dst)
1192        ),
1193        Op::GtEq { dst, lhs, rhs } => format!(
1194            "is {} >= {}? \u{2192} {}",
1195            operand(lhs),
1196            operand(rhs),
1197            name(dst)
1198        ),
1199        Op::Eq { dst, lhs, rhs } => format!(
1200            "is {} == {}? \u{2192} {}",
1201            operand(lhs),
1202            operand(rhs),
1203            name(dst)
1204        ),
1205        Op::NotEq { dst, lhs, rhs } => format!(
1206            "is {} != {}? \u{2192} {}",
1207            operand(lhs),
1208            operand(rhs),
1209            name(dst)
1210        ),
1211        Op::AddAssign { dst, src } => format!("append {} onto {}", operand(src), name(dst)),
1212        Op::Not { dst, src } => format!("negate {} \u{2192} {}", operand(src), name(dst)),
1213        Op::Show { src } => format!("print {}", operand(src)),
1214        Op::Return { src } => format!("return {}", operand(src)),
1215        Op::ReturnNothing => "return".to_string(),
1216        Op::Jump { target } => format!("jump to step {target}"),
1217        Op::JumpIfFalse { cond, target } => {
1218            format!("if {} is false, jump to {target}", operand(cond))
1219        }
1220        Op::JumpIfTrue { cond, target } => {
1221            format!("if {} is true, jump to {target}", operand(cond))
1222        }
1223        Op::Index {
1224            dst,
1225            collection,
1226            index,
1227        }
1228        | Op::IndexUnchecked {
1229            dst,
1230            collection,
1231            index,
1232        } => {
1233            format!(
1234                "read {}[{}] \u{2192} {}",
1235                name(collection),
1236                operand(index),
1237                name(dst)
1238            )
1239        }
1240        Op::SetIndex {
1241            collection,
1242            index,
1243            value,
1244        }
1245        | Op::SetIndexUnchecked {
1246            collection,
1247            index,
1248            value,
1249        } => {
1250            format!(
1251                "set {}[{}] = {}",
1252                name(collection),
1253                operand(index),
1254                operand(value)
1255            )
1256        }
1257        Op::Length { dst, collection } => {
1258            format!("count {} \u{2192} {}", name(collection), name(dst))
1259        }
1260        Op::ListPush { list, value } => format!("push {} onto {}", operand(value), name(list)),
1261        Op::NewEmptyList { dst } | Op::NewEmptyListI32 { dst } => {
1262            format!("make an empty list \u{2192} {}", name(dst))
1263        }
1264        Op::NewEmptyListFixed { dst, capacity } => {
1265            format!(
1266                "make an empty list with capacity {capacity} \u{2192} {}",
1267                name(dst)
1268            )
1269        }
1270        Op::NewEmptyListWithCapacity { dst, capacity } => {
1271            format!(
1272                "make an empty list with capacity {} \u{2192} {}",
1273                operand(capacity),
1274                name(dst)
1275            )
1276        }
1277        Op::NewEmptyMapWithCapacity { dst, capacity } => {
1278            format!(
1279                "make an empty map with capacity {} \u{2192} {}",
1280                operand(capacity),
1281                name(dst)
1282            )
1283        }
1284        Op::Call { .. } => "call a function".to_string(),
1285        Op::Halt => "halt \u{2014} the program is done".to_string(),
1286        _ => String::new(),
1287    }
1288}
1289
1290/// The **first-order-logic semantics** of the op about to run — its formal meaning as
1291/// a formula over the (named) registers: an assignment `dst = lhs + rhs`, a boolean
1292/// definition `dst ⟺ (lhs < rhs)`, a guarded jump `¬cond → goto L`. Symbolic (names,
1293/// not live values), so it reads as the verification condition the step establishes.
1294/// Empty for ops with no crisp logical reading (the UI then falls back to narration).
1295fn fol_of_op(
1296    op: &crate::vm::Op,
1297    regs: &HashMap<u16, (Option<String>, String)>,
1298    prog: &CompiledProgram,
1299) -> String {
1300    use crate::vm::Op;
1301    let name = |r: u16| {
1302        regs.get(&r)
1303            .and_then(|(n, _)| n.clone())
1304            .unwrap_or_else(|| format!("R{r}"))
1305    };
1306    match *op {
1307        Op::LoadConst { dst, idx } => {
1308            format!("{} = {}", name(dst), crate::vm::format_constant(prog, idx))
1309        }
1310        Op::Move { dst, src } => format!("{} = {}", name(dst), name(src)),
1311        Op::Add { dst, lhs, rhs } => format!("{} = {} + {}", name(dst), name(lhs), name(rhs)),
1312        Op::Sub { dst, lhs, rhs } => {
1313            format!("{} = {} \u{2212} {}", name(dst), name(lhs), name(rhs))
1314        }
1315        Op::Mul { dst, lhs, rhs } => {
1316            format!("{} = {} \u{00d7} {}", name(dst), name(lhs), name(rhs))
1317        }
1318        Op::Div { dst, lhs, rhs } | Op::ExactDiv { dst, lhs, rhs } => {
1319            format!("{} = {} \u{00f7} {}", name(dst), name(lhs), name(rhs))
1320        }
1321        Op::Mod { dst, lhs, rhs } => format!("{} = {} mod {}", name(dst), name(lhs), name(rhs)),
1322        Op::Lt { dst, lhs, rhs } => {
1323            format!("{} \u{27fa} ({} < {})", name(dst), name(lhs), name(rhs))
1324        }
1325        Op::Gt { dst, lhs, rhs } => {
1326            format!("{} \u{27fa} ({} > {})", name(dst), name(lhs), name(rhs))
1327        }
1328        Op::LtEq { dst, lhs, rhs } => format!(
1329            "{} \u{27fa} ({} \u{2264} {})",
1330            name(dst),
1331            name(lhs),
1332            name(rhs)
1333        ),
1334        Op::GtEq { dst, lhs, rhs } => format!(
1335            "{} \u{27fa} ({} \u{2265} {})",
1336            name(dst),
1337            name(lhs),
1338            name(rhs)
1339        ),
1340        Op::Eq { dst, lhs, rhs } => {
1341            format!("{} \u{27fa} ({} = {})", name(dst), name(lhs), name(rhs))
1342        }
1343        Op::NotEq { dst, lhs, rhs } => format!(
1344            "{} \u{27fa} ({} \u{2260} {})",
1345            name(dst),
1346            name(lhs),
1347            name(rhs)
1348        ),
1349        Op::Not { dst, src } => format!("{} \u{27fa} \u{00ac}{}", name(dst), name(src)),
1350        Op::AddAssign { dst, src } => format!(
1351            "{} \u{2254} {} \u{29fa} {}",
1352            name(dst),
1353            name(dst),
1354            name(src)
1355        ),
1356        Op::Index {
1357            dst,
1358            collection,
1359            index,
1360        }
1361        | Op::IndexUnchecked {
1362            dst,
1363            collection,
1364            index,
1365        } => {
1366            format!("{} = {}[{}]", name(dst), name(collection), name(index))
1367        }
1368        Op::SetIndex {
1369            collection,
1370            index,
1371            value,
1372        }
1373        | Op::SetIndexUnchecked {
1374            collection,
1375            index,
1376            value,
1377        } => {
1378            format!(
1379                "{}[{}] \u{2254} {}",
1380                name(collection),
1381                name(index),
1382                name(value)
1383            )
1384        }
1385        Op::Length { dst, collection } => format!("{} = |{}|", name(dst), name(collection)),
1386        Op::ListPush { list, value } => format!(
1387            "{} \u{2254} {} \u{2295} {}",
1388            name(list),
1389            name(list),
1390            name(value)
1391        ),
1392        Op::NewEmptyList { dst }
1393        | Op::NewEmptyListI32 { dst }
1394        | Op::NewEmptyListFixed { dst, .. }
1395        | Op::NewEmptyListWithCapacity { dst, .. } => format!("{} = \u{2205}", name(dst)),
1396        Op::NewEmptyMapWithCapacity { dst, .. } => format!("{} = \u{2205}", name(dst)),
1397        Op::Return { src } => format!("result = {}", name(src)),
1398        Op::Jump { target } => format!("goto {target}"),
1399        Op::JumpIfFalse { cond, target } => {
1400            format!("\u{00ac}{} \u{2192} goto {target}", name(cond))
1401        }
1402        Op::JumpIfTrue { cond, target } => format!("{} \u{2192} goto {target}", name(cond)),
1403        _ => String::new(),
1404    }
1405}
1406
1407/// A **Socratic** prompt for the op about to run — the "ask before telling" move: a
1408/// guiding question grounded in the live operand values that invites the learner to
1409/// predict the outcome, which stepping then reveals. Returns empty for ops with nothing
1410/// to anticipate (a literal load, a bare jump), so the UI falls back to the narration.
1411/// Matches the Socratic engine's voice (concrete values, second person, em-dash).
1412fn socratic_of_op(op: &crate::vm::Op, regs: &HashMap<u16, (Option<String>, String)>) -> String {
1413    use crate::vm::Op;
1414    let name = |r: u16| {
1415        regs.get(&r)
1416            .and_then(|(n, _)| n.clone())
1417            .unwrap_or_else(|| format!("R{r}"))
1418    };
1419    // "x (6)" when a live value is known, else just the name.
1420    let nv = |r: u16| match regs.get(&r) {
1421        Some((_, v)) if !v.is_empty() => format!("{} ({})", name(r), v),
1422        _ => name(r),
1423    };
1424    match *op {
1425        Op::Add { lhs, rhs, .. } => {
1426            format!("{} and {} \u{2014} what is their sum?", nv(lhs), nv(rhs))
1427        }
1428        Op::Sub { lhs, rhs, .. } => format!("{} minus {} \u{2014} what's left?", nv(lhs), nv(rhs)),
1429        Op::Mul { lhs, rhs, .. } => {
1430            format!("{} times {} \u{2014} what do you get?", nv(lhs), nv(rhs))
1431        }
1432        Op::Div { lhs, rhs, .. } | Op::ExactDiv { lhs, rhs, .. } => {
1433            format!(
1434                "{} divided by {} \u{2014} what is the quotient?",
1435                nv(lhs),
1436                nv(rhs)
1437            )
1438        }
1439        Op::Mod { lhs, rhs, .. } => {
1440            format!("What remains when {} is divided by {}?", nv(lhs), nv(rhs))
1441        }
1442        Op::Lt { lhs, rhs, .. } => format!("Is {} less than {}?", nv(lhs), nv(rhs)),
1443        Op::Gt { lhs, rhs, .. } => format!("Is {} greater than {}?", nv(lhs), nv(rhs)),
1444        Op::LtEq { lhs, rhs, .. } => format!("Is {} at most {}?", nv(lhs), nv(rhs)),
1445        Op::GtEq { lhs, rhs, .. } => format!("Is {} at least {}?", nv(lhs), nv(rhs)),
1446        Op::Eq { lhs, rhs, .. } => format!("Does {} equal {}?", nv(lhs), nv(rhs)),
1447        Op::NotEq { lhs, rhs, .. } => format!("Are {} and {} different?", nv(lhs), nv(rhs)),
1448        Op::Not { src, .. } => format!("{} \u{2014} what is its negation?", nv(src)),
1449        Op::JumpIfFalse { cond, .. } => {
1450            format!(
1451                "{} \u{2014} will the program take this branch, or fall through?",
1452                nv(cond)
1453            )
1454        }
1455        Op::JumpIfTrue { cond, .. } => {
1456            format!(
1457                "{} \u{2014} is the condition met, so the program jumps?",
1458                nv(cond)
1459            )
1460        }
1461        Op::Index {
1462            collection, index, ..
1463        }
1464        | Op::IndexUnchecked {
1465            collection, index, ..
1466        } => {
1467            format!(
1468                "What sits at position {} of {}?",
1469                nv(index),
1470                name(collection)
1471            )
1472        }
1473        Op::Length { collection, .. } => format!("How many items does {} hold?", name(collection)),
1474        Op::Return { src } => {
1475            format!(
1476                "The result is about to be {} \u{2014} is that what you predicted?",
1477                nv(src)
1478            )
1479        }
1480        _ => String::new(),
1481    }
1482}
1483
1484/// Parse a comparison predicate `<term> <op> <term>` (e.g. `x < y`, `sum >= 0`). Two-
1485/// char operators are tried before single-char so `<=` isn't read as `<`. A term is an
1486/// integer literal or a variable name. `None` if it isn't a single comparison.
1487fn parse_comparison(s: &str) -> Option<(Operand, Cmp, Operand)> {
1488    for (sym, cmp) in [
1489        ("<=", Cmp::Le),
1490        (">=", Cmp::Ge),
1491        ("==", Cmp::Eq),
1492        ("!=", Cmp::Ne),
1493    ] {
1494        if let Some(i) = s.find(sym) {
1495            return build_cmp(&s[..i], &s[i + sym.len()..], cmp);
1496        }
1497    }
1498    for (sym, cmp) in [('<', Cmp::Lt), ('>', Cmp::Gt), ('=', Cmp::Eq)] {
1499        if let Some(i) = s.find(sym) {
1500            return build_cmp(&s[..i], &s[i + 1..], cmp);
1501        }
1502    }
1503    None
1504}
1505
1506fn build_cmp(l: &str, r: &str, cmp: Cmp) -> Option<(Operand, Cmp, Operand)> {
1507    Some((operand_of(l)?, cmp, operand_of(r)?))
1508}
1509
1510fn operand_of(s: &str) -> Option<Operand> {
1511    let t = s.trim();
1512    if t.is_empty() {
1513        return None;
1514    }
1515    Some(match t.parse::<i64>() {
1516        Ok(n) => Operand::Int(n),
1517        Err(_) => Operand::Var(t.to_string()),
1518    })
1519}
1520
1521fn apply_cmp(a: i64, cmp: Cmp, b: i64) -> bool {
1522    match cmp {
1523        Cmp::Lt => a < b,
1524        Cmp::Le => a <= b,
1525        Cmp::Gt => a > b,
1526        Cmp::Ge => a >= b,
1527        Cmp::Eq => a == b,
1528        Cmp::Ne => a != b,
1529    }
1530}
1531
1532/// Decide a comparison between two PROVEN ranges `a ∈ [al, ah]`, `b ∈ [bl, bh]`. Sound:
1533/// `ProvenTrue`/`ProvenFalse` are returned only when the relation holds (resp. fails) for
1534/// EVERY pair in the ranges; overlapping ranges that don't settle it give `Unknown`.
1535fn entail((al, ah): (i64, i64), cmp: Cmp, (bl, bh): (i64, i64)) -> ProofVerdict {
1536    use ProofVerdict::{ProvenFalse, ProvenTrue, Unknown};
1537    let singleton_eq = al == ah && bl == bh && al == bl;
1538    let disjoint = ah < bl || bh < al;
1539    match cmp {
1540        Cmp::Lt => {
1541            if ah < bl {
1542                ProvenTrue
1543            } else if al >= bh {
1544                ProvenFalse
1545            } else {
1546                Unknown
1547            }
1548        }
1549        Cmp::Le => {
1550            if ah <= bl {
1551                ProvenTrue
1552            } else if al > bh {
1553                ProvenFalse
1554            } else {
1555                Unknown
1556            }
1557        }
1558        Cmp::Gt => {
1559            if al > bh {
1560                ProvenTrue
1561            } else if ah <= bl {
1562                ProvenFalse
1563            } else {
1564                Unknown
1565            }
1566        }
1567        Cmp::Ge => {
1568            if al >= bh {
1569                ProvenTrue
1570            } else if ah < bl {
1571                ProvenFalse
1572            } else {
1573                Unknown
1574            }
1575        }
1576        Cmp::Eq => {
1577            if singleton_eq {
1578                ProvenTrue
1579            } else if disjoint {
1580                ProvenFalse
1581            } else {
1582                Unknown
1583            }
1584        }
1585        Cmp::Ne => {
1586            if disjoint {
1587                ProvenTrue
1588            } else if singleton_eq {
1589                ProvenFalse
1590            } else {
1591                Unknown
1592            }
1593        }
1594    }
1595}
1596
1597/// Format an observed numeric bound without a spurious `.0` on whole numbers, so a
1598/// range over integers reads `[1, 5]`, not `[1.0, 5.0]`.
1599fn fmt_num(n: f64) -> String {
1600    if n.fract() == 0.0 && n.abs() < 9.007e15 {
1601        format!("{}", n as i64)
1602    } else {
1603        format!("{n}")
1604    }
1605}
1606
1607/// Compile `src` to **un-optimized** bytecode — faithful to the source so the
1608/// debugger steps `Let`, the arithmetic, and the `Show` as written, rather than the
1609/// run-path optimizer's folded form (which would erase the very variables you are
1610/// debugging). Output is identical either way (optimizations are semantics-
1611/// preserving), so stepping still matches a normal run.
1612///
1613/// Also runs the Oracle's abstract interpretation ONCE here and rolls its per-
1614/// occurrence facts up by variable name — the proven invariants the debugger shows.
1615/// This is the only caller of that rollup, so it is **zero cost** for every non-debug
1616/// compile (the production VM/JIT/AOT paths never touch it).
1617fn compile_source(src: &str) -> Result<(CompiledProgram, HashMap<String, ProvenFacts>), String> {
1618    crate::ui_bridge::with_parsed_program(src, |parsed, interner| {
1619        let (stmts, types, _policies) = parsed?;
1620        let program = crate::vm::Compiler::compile_for_debug(stmts, interner, Some(types))?;
1621        let facts = crate::optimize::oracle_analyze_with(stmts, interner);
1622        let proven = facts
1623            .summarize_variables(stmts)
1624            .into_iter()
1625            .map(|(sym, vf)| (interner.resolve(sym).to_string(), ProvenFacts::from(vf)))
1626            .collect();
1627        Ok((program, proven))
1628    })
1629}
1630
1631#[cfg(test)]
1632#[path = "../../logicaffeine_tests/unit/logicaffeine_compile/debug/tests.rs"]
1633mod tests;