1use crate::cli::DebugMode;
44use pounce_algorithm::debug::{
45 BLOCK_NAMES, DebugCtx, IterateSnapshot, ResidKind, Residual, is_live_tolerance,
46};
47use pounce_algorithm::debug_rank::{RankReport, RankRow};
48use pounce_common::debug::{Checkpoint, DebugAction, DebugHook, DebugState};
49use pounce_common::reg_options::{DefaultValue, OptionType, RegisteredOptions};
50use pounce_nlp::ipopt_nlp::SplitNames;
51use pounce_presolve::dulmage_mendelsohn::DulmageMendelsohnPartition;
52use pounce_presolve::incidence::EqualityIncidence;
53use pounce_presolve::matching::hopcroft_karp;
54use rustyline::completion::{Completer, Pair};
55use rustyline::error::ReadlineError;
56use rustyline::history::FileHistory;
57use rustyline::{Context, Editor, Helper, Highlighter, Hinter, Validator};
58use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
59use std::io::{IsTerminal, Write};
60use std::path::PathBuf;
61use std::rc::Rc;
62
63const COMMANDS: &[&str] = &[
65 "help",
66 "info",
67 "print",
68 "step",
69 "stepi",
70 "continue",
71 "run",
72 "break",
73 "tbreak",
74 "watchpoint",
75 "commands",
76 "stop-at",
77 "set",
78 "get",
79 "opt",
80 "complete",
81 "viz",
82 "save",
83 "load",
84 "sweep",
85 "multistart",
86 "goto",
87 "restart",
88 "resolve",
89 "ask",
90 "watch",
91 "diff",
92 "diagnose",
93 "source",
94 "progress",
95 "detach",
96 "quit",
97];
98
99const EVENTS: &[&str] = &[
102 "resto_entered",
103 "resto_exited",
104 "regularized",
105 "tiny_step",
106 "ls_rejected",
107 "mu_stalled",
108 "nan",
109];
110
111const MU_STALL_ITERS: u32 = 3;
114
115#[derive(Clone)]
118struct WatchPoint {
119 raw: String,
121 block: String,
122 idx: Option<usize>,
123 threshold: f64,
124 last: Option<Vec<f64>>,
126}
127
128const CHECKPOINTS: &[&str] = &[
130 "iter_start",
131 "after_mu",
132 "after_search_dir",
133 "after_step",
134 "step_rejected",
135 "pre_restoration_entry",
136 "post_restoration_exit",
137 "terminated",
138];
139
140pub struct RestartRequest {
144 pub seed_x: Vec<f64>,
147 pub options: Vec<(String, String)>,
149 pub warm: Option<IterateSnapshot>,
155}
156
157pub type RestartCell = Rc<std::cell::RefCell<Option<RestartRequest>>>;
160
161#[derive(Clone)]
163struct SweepRecord {
164 idx: usize,
166 seed: Vec<f64>,
168 status: String,
170 objective: f64,
172 inf_pr: f64,
174 iters: i32,
176}
177
178struct SweepState {
183 queue: VecDeque<Vec<f64>>,
185 current: Option<Vec<f64>>,
187 records: Vec<SweepRecord>,
189 total: usize,
191 saved_pause_iters: bool,
194}
195
196const SNAPSHOT_CAP: usize = 2000;
199
200fn is_success_status(s: &str) -> bool {
203 matches!(s, "Success" | "StopAtAcceptablePoint")
204}
205
206fn parse_floats(s: &str) -> Result<Vec<f64>, String> {
210 s.split(|c: char| c == ',' || c.is_whitespace())
211 .filter(|t| !t.is_empty())
212 .map(|t| t.parse::<f64>().map_err(|_| format!("bad number `{t}`")))
213 .collect()
214}
215
216fn splitmix_unit(state: &mut u64) -> f64 {
219 *state = state.wrapping_add(0x9E37_79B9_7F4A_7C15);
220 let mut z = *state;
221 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
222 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
223 z ^= z >> 31;
224 ((z >> 11) as f64 / (1u64 << 53) as f64) * 2.0 - 1.0
226}
227
228fn seed_for(k: usize) -> u64 {
230 0x9E37_79B9_7F4A_7C15u64
231 ^ (k as u64)
232 .wrapping_mul(0xD1B5_4A32_D192_ED03)
233 .wrapping_add(1)
234}
235
236fn sample_start(base: &[f64], bounds: Option<(&[f64], &[f64])>, rel: f64, k: usize) -> Vec<f64> {
242 if k == 0 {
243 return base.to_vec();
244 }
245 let mut state = seed_for(k);
246 base.iter()
247 .enumerate()
248 .map(|(i, &xi)| {
249 let unit = splitmix_unit(&mut state); if let Some((lo, hi)) = bounds {
251 let (l, u) = (lo[i], hi[i]);
252 if l.is_finite() && u.is_finite() && u > l {
253 return l + (u - l) * (unit * 0.5 + 0.5);
255 }
256 }
257 xi + rel * (xi.abs() + 1.0) * unit
258 })
259 .collect()
260}
261
262#[cfg(test)]
264fn jitter(base: &[f64], rel: f64, k: usize) -> Vec<f64> {
265 sample_start(base, None, rel, k)
266}
267
268pub mod interrupt {
279 use std::sync::atomic::{AtomicBool, Ordering};
280
281 static PENDING: AtomicBool = AtomicBool::new(false);
282 #[cfg(unix)]
283 static INSTALLED: AtomicBool = AtomicBool::new(false);
284
285 #[cfg(unix)]
286 extern "C" fn handler(_sig: nix::libc::c_int) {
287 if PENDING.swap(true, Ordering::SeqCst) {
290 unsafe { nix::libc::_exit(130) };
292 }
293 }
294
295 #[cfg(unix)]
298 pub fn install() {
299 use nix::sys::signal::{self, SigHandler, Signal};
300 if INSTALLED.swap(true, Ordering::SeqCst) {
301 return;
302 }
303 unsafe {
305 let _ = signal::signal(Signal::SIGINT, SigHandler::Handler(handler));
306 }
307 }
308
309 #[cfg(not(unix))]
314 pub fn install() {}
315
316 pub fn take() -> bool {
318 PENDING.swap(false, Ordering::SeqCst)
319 }
320
321 #[cfg(test)]
323 pub fn set_pending_for_test() {
324 PENDING.store(true, Ordering::SeqCst);
325 }
326}
327
328#[derive(Clone, Copy)]
330enum Flow {
331 Stay,
333 Resume,
335 Stop,
337}
338
339struct CmdOut {
341 ok: bool,
342 lines: Vec<String>,
343 data: Option<serde_json::Value>,
344 flow: Flow,
345}
346
347impl CmdOut {
348 fn ok(lines: Vec<String>) -> Self {
349 Self {
350 ok: true,
351 lines,
352 data: None,
353 flow: Flow::Stay,
354 }
355 }
356 fn err(msg: impl Into<String>) -> Self {
357 Self {
358 ok: false,
359 lines: vec![msg.into()],
360 data: None,
361 flow: Flow::Stay,
362 }
363 }
364 fn with_data(mut self, data: serde_json::Value) -> Self {
365 self.data = Some(data);
366 self
367 }
368 fn flow(mut self, flow: Flow) -> Self {
369 self.flow = flow;
370 self
371 }
372}
373
374const METRICS: &[&str] = &[
381 "iter",
382 "mu",
383 "objective",
384 "inf_pr",
385 "inf_du",
386 "nlp_error",
387 "complementarity",
388];
389
390#[derive(Clone, Copy, Debug, PartialEq, Eq)]
392enum Metric {
393 Mu,
394 InfPr,
395 InfDu,
396 Obj,
397 NlpError,
398 Compl,
399 Iter,
400}
401
402impl Metric {
403 fn parse(s: &str) -> Option<Metric> {
404 Some(match s {
405 "mu" => Metric::Mu,
406 "inf_pr" => Metric::InfPr,
407 "inf_du" => Metric::InfDu,
408 "obj" | "objective" => Metric::Obj,
409 "err" | "nlp_error" => Metric::NlpError,
410 "compl" | "complementarity" => Metric::Compl,
411 "iter" => Metric::Iter,
412 _ => return None,
413 })
414 }
415 fn eval(self, ctx: &dyn DebugState) -> f64 {
416 match self {
417 Metric::Mu => ctx.mu(),
418 Metric::InfPr => ctx.inf_pr(),
419 Metric::InfDu => ctx.inf_du(),
420 Metric::Obj => ctx.objective(),
421 Metric::NlpError => ctx.nlp_error(),
422 Metric::Compl => ctx.complementarity(),
423 Metric::Iter => ctx.iter() as f64,
424 }
425 }
426}
427
428fn metric_fields(ctx: &dyn DebugState) -> Vec<(&'static str, serde_json::Value)> {
444 METRICS
445 .iter()
446 .map(|&name| {
447 let value = if name == "iter" {
448 serde_json::json!(ctx.iter())
449 } else {
450 let metric = Metric::parse(name)
451 .expect("every METRICS entry must have a matching Metric arm");
452 serde_json::json!(metric.eval(ctx))
453 };
454 (name, value)
455 })
456 .collect()
457}
458
459fn insert_metric_fields(ev: &mut serde_json::Value, ctx: &dyn DebugState) {
461 if let serde_json::Value::Object(map) = ev {
462 for (name, value) in metric_fields(ctx) {
463 map.insert(name.to_string(), value);
464 }
465 }
466}
467
468#[derive(Clone, Copy, Debug, PartialEq, Eq)]
470enum CmpOp {
471 Lt,
472 Le,
473 Gt,
474 Ge,
475 Eq,
476}
477
478impl CmpOp {
479 fn eval(self, lhs: f64, rhs: f64) -> bool {
480 match self {
481 CmpOp::Lt => lhs < rhs,
482 CmpOp::Le => lhs <= rhs,
483 CmpOp::Gt => lhs > rhs,
484 CmpOp::Ge => lhs >= rhs,
485 CmpOp::Eq => (lhs - rhs).abs() <= 1e-12 * rhs.abs().max(1.0),
491 }
492 }
493}
494
495#[derive(Clone, Debug)]
497struct Atom {
498 metric: Metric,
499 op: CmpOp,
500 rhs: f64,
501}
502
503impl Atom {
504 fn parse(expr: &str) -> Result<Atom, String> {
507 let expr = expr.trim();
508 let mut found: Option<(&str, usize, usize)> = None;
513 for (i, _) in expr.char_indices() {
514 let rest = &expr[i..];
515 if rest.starts_with("<=") || rest.starts_with(">=") || rest.starts_with("==") {
516 found = Some((&expr[i..i + 2], i, 2));
517 break;
518 }
519 if rest.starts_with('<') || rest.starts_with('>') {
520 found = Some((&expr[i..i + 1], i, 1));
521 break;
522 }
523 }
524 let (op, pos, oplen) = found
525 .ok_or_else(|| format!("no comparison operator in `{expr}` (use < <= > >= ==)"))?;
526 let metric_s = expr[..pos].trim();
527 let rhs_s = expr[pos + oplen..].trim();
528 let metric = Metric::parse(metric_s)
529 .ok_or_else(|| format!("unknown metric `{metric_s}` (one of {METRICS:?})"))?;
530 let rhs = rhs_s
531 .parse::<f64>()
532 .map_err(|_| format!("bad threshold `{rhs_s}`"))?;
533 let cmp = match op {
534 "<" => CmpOp::Lt,
535 "<=" => CmpOp::Le,
536 ">" => CmpOp::Gt,
537 ">=" => CmpOp::Ge,
538 "==" => CmpOp::Eq,
539 _ => unreachable!(),
540 };
541 Ok(Atom {
542 metric,
543 op: cmp,
544 rhs,
545 })
546 }
547
548 fn holds(&self, ctx: &dyn DebugState) -> bool {
549 self.op.eval(self.metric.eval(ctx), self.rhs)
550 }
551}
552
553#[derive(Clone, Copy, Debug, PartialEq, Eq)]
555enum Join {
556 And,
557 Or,
558}
559
560#[derive(Clone, Debug)]
565struct Condition {
566 first: Atom,
567 rest: Vec<(Join, Atom)>,
568 raw: String,
570}
571
572impl Condition {
573 fn parse(expr: &str) -> Result<Condition, String> {
574 let cleaned: String = expr.chars().filter(|c| !matches!(c, '(' | ')')).collect();
576 let mut atoms: Vec<(Option<Join>, &str)> = Vec::new();
578 let bytes = cleaned.as_bytes();
579 let mut start = 0usize;
580 let mut i = 0usize;
581 let mut pending: Option<Join> = None;
582 while i + 1 < bytes.len() {
583 let two = &cleaned[i..i + 2];
584 let join = match two {
585 "&&" => Some(Join::And),
586 "||" => Some(Join::Or),
587 _ => None,
588 };
589 if let Some(j) = join {
590 atoms.push((pending, &cleaned[start..i]));
591 pending = Some(j);
592 i += 2;
593 start = i;
594 } else {
595 i += 1;
596 }
597 }
598 atoms.push((pending, &cleaned[start..]));
599
600 let mut iter = atoms.into_iter();
601 let Some((_, first_s)) = iter.next() else {
602 return Err("empty condition".into());
603 };
604 let first = Atom::parse(first_s)?;
605 let mut rest = Vec::new();
606 for (join, s) in iter {
607 let join = join.ok_or("malformed compound condition (dangling &&/||)")?;
608 rest.push((join, Atom::parse(s)?));
609 }
610 Ok(Condition {
612 first,
613 rest,
614 raw: cleaned,
615 })
616 }
617
618 fn holds(&self, ctx: &dyn DebugState) -> bool {
619 let mut acc = self.first.holds(ctx);
620 for (join, atom) in &self.rest {
621 let v = atom.holds(ctx);
622 acc = match join {
623 Join::And => acc && v,
624 Join::Or => acc || v,
625 };
626 }
627 acc
628 }
629}
630
631fn path_candidates(word: &str) -> Vec<String> {
641 let (dir, prefix) = match word.rfind('/') {
643 Some(i) => (&word[..=i], &word[i + 1..]), None => ("", word),
645 };
646 let read_from = if dir.is_empty() { "." } else { dir };
647 let Ok(entries) = std::fs::read_dir(read_from) else {
648 return Vec::new();
649 };
650 let mut out: Vec<String> = Vec::new();
651 for e in entries.flatten() {
652 let name = e.file_name().to_string_lossy().into_owned();
653 if !name.starts_with(prefix) {
654 continue;
655 }
656 if name.starts_with('.') && !prefix.starts_with('.') {
657 continue;
658 }
659 let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
660 let mut cand = format!("{dir}{name}");
661 if is_dir {
662 cand.push('/');
663 }
664 out.push(cand);
665 }
666 out.sort();
667 out
668}
669
670fn completion_candidates(reg: Option<&RegisteredOptions>, before: &str, word: &str) -> Vec<String> {
671 let toks: Vec<&str> = before.split_whitespace().collect();
672 let starts = |opts: &[&str]| -> Vec<String> {
673 opts.iter()
674 .filter(|c| c.starts_with(word))
675 .map(|c| c.to_string())
676 .collect()
677 };
678 let opt_names = || -> Vec<String> {
679 reg.map(|r| {
680 r.registered_options_in_order()
681 .iter()
682 .map(|o| o.name.clone())
683 .filter(|n| n.starts_with(word))
684 .collect()
685 })
686 .unwrap_or_default()
687 };
688 match toks.as_slice() {
689 [] => starts(COMMANDS),
690 ["set"] => {
691 let mut v = starts(&["mu", "opt"]);
692 v.extend(starts(&BLOCK_NAMES));
693 v
694 }
695 ["set", "opt"] | ["get", "opt"] | ["get"] | ["opt"] | ["options"] => opt_names(),
696 ["set", "opt", name] => reg
698 .and_then(|r| r.get_option(name))
699 .map(|o| {
700 o.valid_strings
701 .iter()
702 .map(|e| e.value.clone())
703 .filter(|v| v.starts_with(word) && v != "*")
704 .collect()
705 })
706 .unwrap_or_default(),
707 ["stop-at"] | ["stopat"] => starts(CHECKPOINTS),
708 ["break", "if"] | ["b", "if"] => starts(METRICS),
709 ["break", "on"] | ["b", "on"] => starts(EVENTS),
710 ["break"] | ["b"] => starts(&["if", "on", "clear", "del"]),
711 ["watchpoint"] | ["wp"] => starts(&BLOCK_NAMES),
712 ["print"] | ["p"] | ["watch"] | ["display"] => {
713 let mut v = starts(&BLOCK_NAMES);
714 v.extend(starts(&[
715 "mu",
716 "obj",
717 "inf_pr",
718 "inf_du",
719 "err",
720 "compl",
721 "iter",
722 "kkt",
723 "active",
724 "inactive",
725 "residuals",
726 "equation",
727 "rank",
728 ]));
729 v
730 }
731 ["viz"] | ["plot"] => {
732 let mut v = starts(&BLOCK_NAMES);
733 v.extend(starts(&["kkt", "L"]));
734 v
735 }
736 ["complete"] => starts(COMMANDS),
737 ["save"] | ["load"] | ["sweep"] | ["source"] => path_candidates(word),
739 ["load", _] => starts(&BLOCK_NAMES),
741 _ => Vec::new(),
742 }
743}
744
745#[derive(Helper, Hinter, Highlighter, Validator)]
749struct DbgHelper {
750 reg: Option<Rc<RegisteredOptions>>,
751}
752
753impl Completer for DbgHelper {
754 type Candidate = Pair;
755 fn complete(
756 &self,
757 line: &str,
758 pos: usize,
759 _ctx: &Context<'_>,
760 ) -> rustyline::Result<(usize, Vec<Pair>)> {
761 let before = &line[..pos];
762 let start = before
763 .rfind(char::is_whitespace)
764 .map(|i| i + 1)
765 .unwrap_or(0);
766 let word = &before[start..];
767 let cands = completion_candidates(self.reg.as_deref(), &before[..start], word);
768 let pairs = cands
769 .into_iter()
770 .map(|c| Pair {
771 display: c.clone(),
772 replacement: c,
773 })
774 .collect();
775 Ok((start, pairs))
776 }
777}
778
779pub struct EquationBook {
789 names: Vec<String>,
792 equations: Vec<String>,
794}
795
796impl EquationBook {
797 pub fn new(names: Vec<String>, equations: Vec<String>) -> Self {
800 Self { names, equations }
801 }
802
803 pub fn len(&self) -> usize {
805 self.equations.len()
806 }
807
808 pub fn is_empty(&self) -> bool {
810 self.equations.is_empty()
811 }
812
813 fn label(&self, i: usize) -> String {
816 match self.names.get(i) {
817 Some(n) if !n.is_empty() => n.clone(),
818 _ => format!("c[{i}]"),
819 }
820 }
821
822 fn resolve(&self, key: &str) -> Option<usize> {
825 if let Some(i) = self.names.iter().position(|n| n == key) {
826 return Some(i);
827 }
828 key.parse::<usize>()
829 .ok()
830 .filter(|&i| i < self.equations.len())
831 }
832}
833
834const MAX_STRUCT_NAMES: usize = 10;
839
840const MAX_SINGULAR_VALUES_SHOWN: usize = 16;
843
844const MAX_RANK_CULPRITS: usize = 12;
847
848pub struct StructureBook {
866 inc: EqualityIncidence,
869 con_names: Vec<String>,
872 var_names: Vec<String>,
875}
876
877impl StructureBook {
878 pub fn new(inc: EqualityIncidence, con_names: Vec<String>, var_names: Vec<String>) -> Self {
884 Self {
885 inc,
886 con_names,
887 var_names,
888 }
889 }
890
891 fn con_label(&self, eq_row: usize) -> String {
894 let orig = self.inc.eq_row_inner_idx[eq_row];
895 match self.con_names.get(orig) {
896 Some(n) if !n.is_empty() => n.clone(),
897 _ => format!("c[{orig}]"),
898 }
899 }
900
901 fn var_label(&self, v: usize) -> String {
904 match self.var_names.get(v) {
905 Some(n) if !n.is_empty() => n.clone(),
906 _ => format!("x[{v}]"),
907 }
908 }
909
910 fn join_capped(labels: &[String]) -> String {
913 if labels.len() <= MAX_STRUCT_NAMES {
914 labels.join(", ")
915 } else {
916 let head = labels[..MAX_STRUCT_NAMES].join(", ");
917 let more = labels.len() - MAX_STRUCT_NAMES;
918 format!("{head}, … (+{more} more)")
919 }
920 }
921
922 fn findings(&self) -> Vec<(&'static str, &'static str, String)> {
932 let mut out = Vec::new();
933 if self.inc.n_eq_rows() == 0 {
934 return out;
935 }
936 let matching = hopcroft_karp(&self.inc);
937 let dm = DulmageMendelsohnPartition::from_matching(&self.inc, &matching);
938 if dm.over_rows.is_empty() {
939 return out;
940 }
941
942 let excess = dm.over_rows.len().saturating_sub(dm.over_cols.len());
946 let eq_labels: Vec<String> = dm.over_rows.iter().map(|&r| self.con_label(r)).collect();
947 let var_labels: Vec<String> = dm.over_cols.iter().map(|&v| self.var_label(v)).collect();
948 let eqs = Self::join_capped(&eq_labels);
949 let shared = if var_labels.is_empty() {
950 "no variables".to_string()
951 } else {
952 Self::join_capped(&var_labels)
953 };
954 out.push((
955 "warning",
956 "structural_singularity",
957 format!(
958 "Constraint Jacobian is structurally singular (Dulmage–Mendelsohn): {} equation(s) \
959 over-determine the {} variable(s) they jointly touch ({}), so ≥{} of them must be \
960 redundant or mutually inconsistent (LICQ fails on this block). Candidate \
961 dependent equations: {}. Inspect them with `print equation <name>`; this names \
962 the rows behind any δ_c dual-regularization / wrong-inertia signal.",
963 dm.over_rows.len(),
964 dm.over_cols.len(),
965 shared,
966 excess.max(1),
967 eqs
968 ),
969 ));
970 out
971 }
972}
973
974pub struct SolverDebugger {
975 mode: DebugMode,
976 reg: Option<Rc<RegisteredOptions>>,
977 step: bool,
979 run_to: Option<i32>,
981 breaks: Vec<i32>,
983 temp_breaks: Vec<i32>,
985 bp_commands: HashMap<i32, Vec<String>>,
988 conds: Vec<Condition>,
990 watchpoints: Vec<WatchPoint>,
992 last_mu: Option<f64>,
994 mu_stall: u32,
995 in_restoration: bool,
998 detached: bool,
1000 hello_sent: bool,
1003 pause_iters: bool,
1006 pause_terminal: bool,
1008 terminal_only_on_error: bool,
1010 interruptible: bool,
1012 emit_progress: bool,
1015 sub_step: bool,
1018 stop_at: HashSet<&'static str>,
1020 break_events: HashSet<&'static str>,
1022 snapshots: BTreeMap<i32, Box<dyn pounce_common::debug::IterSnapshot>>,
1025 restart: Option<RestartCell>,
1028 editor: Option<Editor<DbgHelper, FileHistory>>,
1032 hist_path: Option<PathBuf>,
1034 pump: Option<StdinPump>,
1037 watches: Vec<String>,
1040 pending_script: Option<String>,
1043 staged: Vec<(String, String)>,
1047 sweep: Option<SweepState>,
1050 prompt_interrupts: u8,
1055 equation_book: Option<EquationBook>,
1060 structure_book: Option<StructureBook>,
1065 script_queue: Option<SharedScript>,
1071}
1072
1073pub type SharedScript = Rc<std::cell::RefCell<VecDeque<String>>>;
1077
1078impl SolverDebugger {
1079 pub fn new(mode: DebugMode, reg: Option<Rc<RegisteredOptions>>) -> Self {
1082 Self {
1083 mode,
1084 reg,
1085 step: true,
1088 run_to: None,
1089 breaks: Vec::new(),
1090 temp_breaks: Vec::new(),
1091 bp_commands: HashMap::new(),
1092 conds: Vec::new(),
1093 watchpoints: Vec::new(),
1094 last_mu: None,
1095 mu_stall: 0,
1096 in_restoration: false,
1097 detached: false,
1098 hello_sent: false,
1099 pause_iters: true,
1100 pause_terminal: true,
1101 terminal_only_on_error: false,
1102 interruptible: true,
1103 emit_progress: true,
1104 sub_step: false,
1105 stop_at: HashSet::new(),
1106 break_events: HashSet::new(),
1107 snapshots: BTreeMap::new(),
1108 restart: None,
1109 editor: None,
1110 hist_path: None,
1111 pump: None,
1112 watches: Vec::new(),
1113 pending_script: None,
1114 staged: Vec::new(),
1115 sweep: None,
1116 prompt_interrupts: 0,
1117 equation_book: None,
1118 structure_book: None,
1119 script_queue: None,
1120 }
1121 }
1122
1123 pub fn quiet(mode: DebugMode, reg: Option<Rc<RegisteredOptions>>) -> Self {
1129 let mut d = Self::new(mode, reg);
1130 d.step = false;
1131 d.pause_iters = false;
1132 d.pause_terminal = false;
1133 d.detached = true;
1134 d
1135 }
1136
1137 pub fn with_script(mut self, path: String) -> Self {
1139 self.pending_script = Some(path);
1140 self
1141 }
1142
1143 pub fn set_equation_book(&mut self, book: EquationBook) {
1147 self.equation_book = Some(book);
1148 }
1149
1150 pub fn set_structure_book(&mut self, book: StructureBook) {
1156 self.structure_book = Some(book);
1157 }
1158
1159 pub fn with_shared_script(mut self, queue: SharedScript) -> Self {
1163 self.script_queue = Some(queue);
1164 self
1165 }
1166
1167 pub fn with_restart(mut self, cell: RestartCell) -> Self {
1170 self.restart = Some(cell);
1171 self
1172 }
1173
1174 pub fn on_error(mode: DebugMode, reg: Option<Rc<RegisteredOptions>>) -> Self {
1177 Self {
1178 step: false,
1179 pause_iters: false,
1180 terminal_only_on_error: true,
1181 ..Self::new(mode, reg)
1182 }
1183 }
1184
1185 pub fn on_interrupt(mode: DebugMode, reg: Option<Rc<RegisteredOptions>>) -> Self {
1189 Self {
1190 step: false,
1191 pause_iters: false,
1192 pause_terminal: false,
1193 ..Self::new(mode, reg)
1194 }
1195 }
1196
1197 pub fn staged_options(&self) -> &[(String, String)] {
1200 &self.staged
1201 }
1202
1203 fn should_pause(&mut self, iter: i32) -> bool {
1204 if self.detached {
1205 return false;
1206 }
1207 if self.step {
1208 return true;
1209 }
1210 if let Some(t) = self.run_to {
1211 if iter >= t {
1212 self.run_to = None;
1213 return true;
1214 }
1215 }
1216 if self.breaks.contains(&iter) {
1217 return true;
1218 }
1219 if let Some(pos) = self.temp_breaks.iter().position(|&b| b == iter) {
1221 self.temp_breaks.remove(pos);
1222 return true;
1223 }
1224 false
1225 }
1226
1227 fn matched_condition(&self, ctx: &dyn DebugState) -> Option<String> {
1230 if self.detached {
1231 return None;
1232 }
1233 self.conds
1234 .iter()
1235 .find(|c| c.holds(ctx))
1236 .map(|c| c.raw.clone())
1237 }
1238
1239 fn matched_event(&self, ctx: &dyn DebugState) -> Option<&'static str> {
1243 if self.detached || self.break_events.is_empty() {
1244 return None;
1245 }
1246 let cp = ctx.checkpoint();
1247 let tiny = 1e-10;
1249 EVENTS.iter().copied().find(|&e| {
1250 self.break_events.contains(e)
1251 && match e {
1252 "resto_entered" => cp == Checkpoint::PreRestoration,
1253 "resto_exited" => cp == Checkpoint::PostRestoration,
1254 "regularized" => {
1255 cp == Checkpoint::AfterSearchDirection && ctx.regularization() > 0.0
1256 }
1257 "tiny_step" => {
1258 cp == Checkpoint::AfterSearchDirection
1259 && ctx
1260 .delta_block("x")
1261 .map(|v| v.iter().fold(0.0_f64, |m, &x| m.max(x.abs())) < tiny)
1262 .unwrap_or(false)
1263 }
1264 "ls_rejected" => cp == Checkpoint::AfterStep && ctx.ls_count() > 1,
1265 "mu_stalled" => cp == Checkpoint::IterStart && self.mu_stall >= MU_STALL_ITERS,
1266 "nan" => !ctx.nlp_error().is_finite() || !ctx.objective().is_finite(),
1267 _ => false,
1268 }
1269 })
1270 }
1271
1272 fn update_mu_stall(&mut self, mu: f64) {
1274 if let Some(last) = self.last_mu {
1275 if (mu - last).abs() <= 1e-12 * last.abs().max(1.0) {
1276 self.mu_stall += 1;
1277 } else {
1278 self.mu_stall = 0;
1279 }
1280 }
1281 self.last_mu = Some(mu);
1282 }
1283
1284 fn matched_watchpoint(&mut self, ctx: &dyn DebugState) -> Option<String> {
1287 if self.detached {
1288 return None;
1289 }
1290 let mut hit = None;
1291 for wp in self.watchpoints.iter_mut() {
1292 let Some(full) = ctx.block(&wp.block) else {
1293 continue;
1294 };
1295 let cur: Vec<f64> = match wp.idx {
1296 Some(i) => match full.get(i) {
1297 Some(&v) => vec![v],
1298 None => continue,
1299 },
1300 None => full,
1301 };
1302 if let Some(prev) = &wp.last {
1303 if prev.len() == cur.len() {
1304 let changed = prev
1305 .iter()
1306 .zip(&cur)
1307 .any(|(p, c)| (p - c).abs() > wp.threshold);
1308 if changed && hit.is_none() {
1309 hit = Some(wp.raw.clone());
1310 }
1311 }
1312 }
1313 wp.last = Some(cur);
1314 }
1315 hit
1316 }
1317
1318 fn dispatch(&mut self, line: &str, ctx: &mut dyn DebugState) -> CmdOut {
1321 let owned = tokenize_quoted(line);
1325 let toks: Vec<&str> = owned.iter().map(String::as_str).collect();
1326 let Some(&verb) = toks.first() else {
1327 return CmdOut::ok(vec![]); };
1329 let rest = &toks[1..];
1330 match verb {
1331 "help" | "h" | "?" => self.cmd_help(),
1332 "info" | "i" => self.cmd_info(ctx),
1333 "print" | "p" => self.cmd_print(rest, ctx),
1334 "step" | "s" | "n" | "next" if rest.first() == Some(&"sub") => {
1337 self.sub_step = true;
1338 CmdOut::ok(vec![
1339 "stepping to the next checkpoint (sub-iteration)".into(),
1340 ])
1341 .flow(Flow::Resume)
1342 }
1343 "step" | "s" | "n" | "next" => {
1344 self.step = true;
1345 CmdOut::ok(vec!["stepping one iteration".into()]).flow(Flow::Resume)
1346 }
1347 "stepi" | "si" => {
1348 self.sub_step = true;
1349 CmdOut::ok(vec![
1350 "stepping to the next checkpoint (sub-iteration)".into(),
1351 ])
1352 .flow(Flow::Resume)
1353 }
1354 "continue" | "c" | "cont" => {
1355 self.step = false;
1356 self.sub_step = false;
1357 self.run_to = None;
1358 CmdOut::ok(vec!["continuing".into()]).flow(Flow::Resume)
1359 }
1360 "run" | "r" => self.cmd_run(rest),
1361 "break" | "b" => self.cmd_break(rest),
1362 "tbreak" | "tb" => match rest.first().and_then(|s| s.parse::<i32>().ok()) {
1363 Some(n) => {
1364 if !self.temp_breaks.contains(&n) {
1365 self.temp_breaks.push(n);
1366 }
1367 CmdOut::ok(vec![format!("temporary breakpoint at iteration {n}")])
1368 }
1369 None => CmdOut::err("usage: tbreak <iteration>"),
1370 },
1371 "watchpoint" | "wp" => self.cmd_watchpoint(rest, ctx),
1372 "commands" => self.cmd_commands(rest),
1373 "stop-at" | "stopat" => self.cmd_stop_at(rest),
1374 "progress" => match rest.first().copied() {
1375 Some("on") | None => {
1376 self.emit_progress = true;
1377 CmdOut::ok(vec!["progress events on".into()])
1378 }
1379 Some("off") => {
1380 self.emit_progress = false;
1381 CmdOut::ok(vec!["progress events off".into()])
1382 }
1383 _ => CmdOut::err("usage: progress [on|off]"),
1384 },
1385 "set" => self.cmd_set(rest, ctx),
1386 "get" => self.cmd_get(rest),
1387 "opt" | "options" => self.cmd_opt(rest),
1388 "complete" => self.cmd_complete(rest),
1389 "viz" | "plot" => self.cmd_viz(rest, ctx),
1390 "save" => self.cmd_save(rest, ctx),
1391 "load" => match as_nlp_mut(ctx) {
1392 Some(c) => self.cmd_load(rest, c),
1393 None => nlp_only("load"),
1394 },
1395 "sweep" => match as_nlp_mut(ctx) {
1396 Some(c) => self.cmd_sweep(rest, c),
1397 None => nlp_only("sweep"),
1398 },
1399 "multistart" => match as_nlp_mut(ctx) {
1400 Some(c) => self.cmd_multistart(rest, c),
1401 None => nlp_only("multistart"),
1402 },
1403 "goto" | "jump" => self.cmd_goto(rest, ctx),
1404 "restart" => match self.snapshots.keys().next().copied() {
1405 Some(k) => self.restore_to(k, ctx),
1406 None => CmdOut::err("no snapshots captured yet"),
1407 },
1408 "resolve" | "re-solve" => match as_nlp(ctx) {
1409 Some(c) => self.cmd_resolve(c),
1410 None => nlp_only("resolve"),
1411 },
1412 "ask" | "explain" | "claude" => self.cmd_ask(rest, ctx),
1413 "watch" | "display" => self.cmd_watch(rest),
1414 "diff" => self.cmd_diff(ctx),
1415 "diagnose" | "diag" => match as_nlp(ctx) {
1416 Some(c) => self.cmd_diagnose(c),
1417 None => nlp_only("diagnose"),
1418 },
1419 "source" => self.cmd_source(rest, ctx),
1420 "detach" => {
1421 self.detached = true;
1422 self.step = false;
1423 self.run_to = None;
1424 CmdOut::ok(vec!["detached — solving to completion".into()]).flow(Flow::Resume)
1425 }
1426 "pause" => CmdOut::ok(vec!["already paused".into()]),
1429 "coffee" | "brew" | "espresso" => self.cmd_coffee(),
1431 "quit" | "q" | "exit" => CmdOut::ok(vec!["stopping solve".into()]).flow(Flow::Stop),
1432 other => CmdOut::err(format!("unknown command `{other}` (try `help`)")),
1433 }
1434 }
1435
1436 fn cmd_coffee(&self) -> CmdOut {
1440 let color = matches!(self.mode, DebugMode::Repl)
1441 && std::io::stderr().is_terminal()
1442 && std::env::var_os("NO_COLOR").is_none();
1443 let paint = |r: u8, g: u8, b: u8, s: &str| -> String {
1444 if color {
1445 format!("\x1b[38;2;{r};{g};{b}m{s}\x1b[0m")
1446 } else {
1447 s.to_string()
1448 }
1449 };
1450 let cup = |s: &str| paint(0xEC, 0xEC, 0xEF, s);
1452 let dark = |s: &str| paint(0x5A, 0x32, 0x1E, s);
1453 let brew = |s: &str| paint(0x96, 0x5F, 0x37, s);
1454 let steam = |s: &str| paint(0xB4, 0xB9, 0xC3, s);
1455 let lines = vec![
1456 String::new(),
1457 format!(" {}", steam(") ) )")),
1458 format!(" {}", steam("( ( (")),
1459 format!(" {}", cup("._________.")),
1460 format!(" {}{}{}", cup("|"), dark("~~~~~~~~"), cup("|_")),
1461 format!(" {}{}{}", cup("| "), brew("COFFEE"), cup("| |")),
1462 format!(" {}{}{}", cup("| "), dark("~~~~~~"), cup("| |")),
1463 format!(" {}", cup("|________|_|")),
1464 format!(" {}", cup("\\________/")),
1465 format!(" {}", brew("a fresh cup for a stuck solve")),
1466 String::new(),
1467 ];
1468 CmdOut::ok(lines).with_data(serde_json::json!({"easter_egg": "coffee"}))
1469 }
1470
1471 fn cmd_help(&self) -> CmdOut {
1472 let lines = vec![
1473 "commands:".into(),
1474 " info | i summary of the current iterate".into(),
1475 " print | p <what> x|s|y_c|y_d|z_l|z_u|v_l|v_u | dx (step) |".into(),
1476 " mu|obj|inf_pr|inf_du|err|compl|iter | kkt | active | inactive".into(),
1477 " print residuals [pr|du] [k] top-k largest-magnitude residuals (default k=10)".into(),
1478 " print equation [name|row] source algebra of a constraint, by model name or row".into(),
1479 " print rank SVD rank of the equality Jacobian; names dependent equations".into(),
1480 " step | s | n run one iteration, pause again".into(),
1481 " stepi | si | step sub run to the next checkpoint (into sub-iteration phases)".into(),
1482 " progress [on|off] toggle per-iteration progress events (JSON mode)".into(),
1483 " stop-at <cp> always pause at a checkpoint: after_mu|after_search_dir|after_step".into(),
1484 " continue | c run to the next breakpoint".into(),
1485 " run | r <N> run until iteration N".into(),
1486 " break | b [N|clear|del N] set/list/clear breakpoints".into(),
1487 " break if <m><op><v> conditional bp; m in mu|inf_pr|inf_du|obj|err|iter,".into(),
1488 " op in < <= > >= == (e.g. break if inf_pr<1e-6)".into(),
1489 " break on <event> event bp: resto_entered|resto_exited|regularized|".into(),
1490 " tiny_step|ls_rejected|mu_stalled|nan".into(),
1491 " tbreak <N> one-shot breakpoint (deletes after firing)".into(),
1492 " watchpoint <blk>[<i>] [τ] pause when a value changes by > τ (alias wp)".into(),
1493 " commands <N> <c>;<c>… auto-run commands when iter N's breakpoint hits".into(),
1494 " set mu <v> overwrite the barrier parameter".into(),
1495 " set <blk>[<i>] <v> overwrite one component (e.g. set x[2] 1.5)".into(),
1496 " set <blk> <v0,v1,...> overwrite a whole block".into(),
1497 " set opt <name> <value> stage a solver option (validated)".into(),
1498 " get opt <name> show an option's effective value (staged or default)".into(),
1499 " opt [filter] list solver options (name/type/default)".into(),
1500 " complete <prefix> completion candidates (commands + options)".into(),
1501 " viz <x|s|dx|...|kkt|L> open the artifact in an external viewer".into(),
1502 " save [path] write the current iterate + residuals to JSON".into(),
1503 " load <file> [block] read a block (default x) from a save artifact / numeric file".into(),
1504 " sweep <file> one solve per start in <file>; tabulate outcomes".into(),
1505 " multistart <N> [rel] N restarts (uniform in each finite box; jitter else)".into(),
1506 " goto <k> | restart rewind to a captured iteration (primal-dual only)".into(),
1507 " resolve re-solve from the current x with staged `set opt`s".into(),
1508 " ask [question] ask an LLM about the state (default Claude Code; set".into(),
1509 " POUNCE_DBG_LLM=claude|codex|gemini|llm or a command template)".into(),
1510 " watch [target|clear|del] auto-print a `print` target at every pause".into(),
1511 " diff what changed in the iterate since the last iteration".into(),
1512 " diagnose | diag live health report: named culprit residuals, KKT inertia, stalls".into(),
1513 " source <file> run debugger commands from a file".into(),
1514 " detach stop pausing; solve to completion".into(),
1515 " quit | q stop the solve now".into(),
1516 ];
1517 CmdOut::ok(lines)
1518 }
1519
1520 fn cmd_info(&self, ctx: &dyn DebugState) -> CmdOut {
1521 let dims: Vec<_> = ctx.block_dims();
1522 let dims_json: serde_json::Map<String, serde_json::Value> = dims
1523 .iter()
1524 .map(|(n, d)| ((*n).to_string(), serde_json::json!(d)))
1525 .collect();
1526 let lines = vec![
1527 format!("iter = {}", ctx.iter()),
1528 format!("mu = {:.6e}", ctx.mu()),
1529 format!("objective = {:.8e}", ctx.objective()),
1530 format!("inf_pr = {:.6e}", ctx.inf_pr()),
1531 format!("inf_du = {:.6e}", ctx.inf_du()),
1532 format!("nlp_error = {:.6e}", ctx.nlp_error()),
1533 format!(
1534 "dims = {}",
1535 dims.iter()
1536 .map(|(n, d)| format!("{n}:{d}"))
1537 .collect::<Vec<_>>()
1538 .join(" ")
1539 ),
1540 ];
1541 let mut data = serde_json::json!({ "dims": dims_json });
1542 insert_metric_fields(&mut data, ctx);
1546 CmdOut::ok(lines).with_data(data)
1547 }
1548
1549 fn cmd_print(&self, rest: &[&str], ctx: &dyn DebugState) -> CmdOut {
1550 let Some(&what) = rest.first() else {
1551 return self.cmd_info(ctx);
1552 };
1553 if what == "kkt" {
1560 return match as_nlp(ctx) {
1561 Some(_) => self.cmd_print_kkt(ctx),
1562 None => nlp_only("print kkt"),
1563 };
1564 }
1565 if what == "active" || what == "inactive" {
1566 return match as_nlp(ctx) {
1567 Some(_) => self.cmd_print_bounds(ctx, what == "active"),
1568 None => nlp_only(&format!("print {what}")),
1569 };
1570 }
1571 if what == "residuals" || what == "resid" {
1572 return match as_nlp(ctx) {
1573 Some(_) => self.cmd_print_residuals(&rest[1..], ctx),
1574 None => nlp_only("print residuals"),
1575 };
1576 }
1577 if what == "equation" || what == "eqn" || what == "eq" {
1578 return self.cmd_print_equation(&rest[1..]);
1579 }
1580 if what == "rank" {
1581 return match as_nlp(ctx) {
1582 Some(c) => self.cmd_print_rank(c),
1583 None => nlp_only("print rank"),
1584 };
1585 }
1586 let delta = what.strip_prefix("d").filter(|b| is_block(ctx, b));
1588 if is_block(ctx, what) {
1589 match ctx.block(what) {
1590 Some(v) => CmdOut::ok(vec![fmt_vec(what, &v)])
1591 .with_data(serde_json::json!({"name": what, "values": v})),
1592 None => CmdOut::err(format!("no iterate yet for block `{what}`")),
1593 }
1594 } else if let Some(blk) = delta {
1595 match ctx.delta_block(blk) {
1596 Some(v) => CmdOut::ok(vec![fmt_vec(&format!("d{blk}"), &v)])
1597 .with_data(serde_json::json!({"name": format!("d{blk}"), "values": v})),
1598 None => CmdOut::err(format!("no search direction available for `d{blk}` yet")),
1599 }
1600 } else {
1601 let val = match what {
1602 "mu" => ctx.mu(),
1603 "obj" | "objective" => ctx.objective(),
1604 "inf_pr" => ctx.inf_pr(),
1605 "inf_du" => ctx.inf_du(),
1606 "err" | "nlp_error" => ctx.nlp_error(),
1607 "compl" | "complementarity" => ctx.complementarity(),
1608 "iter" => ctx.iter() as f64,
1609 _ => {
1610 return CmdOut::err(format!(
1611 "don't know how to print `{what}` (try a block name or mu|obj|inf_pr|inf_du|err|compl|iter)"
1612 ));
1613 }
1614 };
1615 CmdOut::ok(vec![format!("{what} = {val:.10e}")])
1616 .with_data(serde_json::json!({"name": what, "value": val}))
1617 }
1618 }
1619
1620 fn cmd_print_bounds(&self, ctx: &dyn DebugState, active: bool) -> CmdOut {
1626 let tol = 1e-6;
1627 let mut lines = Vec::new();
1628 let mut cats = serde_json::Map::new();
1629 for cat in ["x_l", "x_u", "s_l", "s_u"] {
1630 let Some(sl) = ctx.bound_slack(cat) else {
1631 continue;
1632 };
1633 if sl.is_empty() {
1634 continue;
1635 }
1636 let n = sl.len();
1637 if active {
1638 let min = sl.iter().copied().fold(f64::INFINITY, f64::min);
1639 let near = sl.iter().filter(|&&s| s.abs() < tol).count();
1640 lines.push(format!(
1641 "{cat}: {n} bound(s), {near} near-active (slack<{tol:.0e}), min slack {min:.3e}"
1642 ));
1643 cats.insert(
1644 cat.to_string(),
1645 serde_json::json!({"n": n, "near_active": near, "min_slack": min}),
1646 );
1647 } else {
1648 let max = sl.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1649 let far = sl.iter().filter(|&&s| s.abs() >= tol).count();
1650 lines.push(format!(
1651 "{cat}: {n} bound(s), {far} inactive (slack≥{tol:.0e}), max slack {max:.3e}"
1652 ));
1653 cats.insert(
1654 cat.to_string(),
1655 serde_json::json!({"n": n, "inactive": far, "max_slack": max}),
1656 );
1657 }
1658 }
1659 if lines.is_empty() {
1660 lines.push("no bounded variables or inequality slacks".into());
1661 }
1662 CmdOut::ok(lines).with_data(serde_json::json!({"tol": tol, "categories": cats}))
1663 }
1664
1665 fn cmd_print_residuals(&self, rest: &[&str], ctx: &dyn DebugState) -> CmdOut {
1672 let mut k: Option<usize> = None;
1673 let mut filter: Option<bool> = None; for &arg in rest {
1675 if let Ok(n) = arg.parse::<usize>() {
1676 k = Some(n);
1677 } else {
1678 match arg {
1679 "primal" | "pr" => filter = Some(true),
1680 "dual" | "du" => filter = Some(false),
1681 other => {
1682 return CmdOut::err(format!(
1683 "usage: print residuals [primal|dual] [k] (got `{other}`)"
1684 ));
1685 }
1686 }
1687 }
1688 }
1689 let k = k.unwrap_or(10);
1690
1691 let mut all = Vec::new();
1692 if filter != Some(false) {
1693 let Some(primal) = ctx.constraint_residuals() else {
1694 return CmdOut::err("no iterate yet — residuals unavailable");
1695 };
1696 all.extend(primal);
1697 }
1698 if filter != Some(true) {
1699 let Some(dual) = ctx.dual_residuals() else {
1700 return CmdOut::err("no iterate yet — residuals unavailable");
1701 };
1702 all.extend(dual);
1703 }
1704
1705 let total = all.len();
1706 let top = rank_residuals(all, k);
1707 if top.is_empty() {
1708 return CmdOut::ok(vec!["no residuals at this iterate".into()])
1709 .with_data(serde_json::json!({"k": k, "total": total, "top": []}));
1710 }
1711
1712 let names = ctx
1720 .as_any()
1721 .and_then(|a| a.downcast_ref::<DebugCtx>())
1722 .and_then(|c| c.split_names());
1723 let name_of = |r: &Residual| resid_name(r, &names);
1724
1725 let lines = top
1726 .iter()
1727 .map(|r| {
1728 let label = match name_of(r) {
1729 Some(name) => format!("{}[{}]", r.kind.tag(), name),
1730 None => format!("{}[{}]", r.kind.tag(), r.index),
1731 };
1732 format!("{:>8} = {:+.6e} |{:.3e}|", label, r.value, r.value.abs())
1733 })
1734 .collect();
1735 let data: Vec<_> = top
1736 .iter()
1737 .map(|r| {
1738 serde_json::json!({
1739 "space": r.kind.tag(),
1740 "primal": r.kind.is_primal(),
1741 "index": r.index,
1742 "name": name_of(r),
1743 "value": r.value,
1744 })
1745 })
1746 .collect();
1747 CmdOut::ok(lines).with_data(serde_json::json!({"k": k, "total": total, "top": data}))
1748 }
1749
1750 fn cmd_print_equation(&self, rest: &[&str]) -> CmdOut {
1759 let Some(book) = self.equation_book.as_ref() else {
1760 return CmdOut::err(
1761 "no equation source — `print equation` needs an .nl model (none was loaded)",
1762 );
1763 };
1764 if book.is_empty() {
1765 return CmdOut::err("the model has no constraint equations to print");
1766 }
1767 let Some(&key) = rest.first() else {
1768 return CmdOut::ok(vec![format!(
1769 "{} constraint equation(s) — `print equation <name|row>` to show one",
1770 book.len()
1771 )])
1772 .with_data(serde_json::json!({"count": book.len()}));
1773 };
1774 let Some(i) = book.resolve(key) else {
1775 return CmdOut::err(format!(
1776 "no constraint named or indexed `{key}` (have {} equation(s); try a name or 0..{})",
1777 book.len(),
1778 book.len().saturating_sub(1)
1779 ));
1780 };
1781 let label = book.label(i);
1782 let Some(eq) = book.equations.get(i) else {
1785 return CmdOut::err(format!(
1786 "constraint `{key}` has no source algebra (index {i} out of range)"
1787 ));
1788 };
1789 CmdOut::ok(vec![format!("{label}: {eq}")]).with_data(serde_json::json!({
1790 "index": i,
1791 "name": book.names.get(i).filter(|n| !n.is_empty()),
1792 "equation": eq,
1793 }))
1794 }
1795
1796 fn cmd_diagnose(&self, ctx: &DebugCtx) -> CmdOut {
1811 const TOL: f64 = 1e-6;
1812 let names = ctx.split_names();
1813 let mut f: Vec<(&'static str, &'static str, String)> = Vec::new();
1815
1816 let inf_pr = ctx.inf_pr();
1818 if inf_pr > TOL {
1819 if let Some(resids) = ctx.constraint_residuals() {
1820 if let Some((label, val)) = worst_named(resids, &names) {
1821 let sev = if inf_pr > 1e-2 { "error" } else { "warning" };
1822 f.push((
1823 sev,
1824 "primal_infeasible",
1825 format!(
1826 "Primal infeasibility {inf_pr:.2e}; worst constraint residual is \
1827 {label} = {val:+.3e}. Inspect this equation's feasibility and scaling \
1828 at the current point (`print equation {label}`)."
1829 ),
1830 ));
1831 }
1832 }
1833 }
1834
1835 let inf_du = ctx.inf_du();
1837 if inf_du > TOL {
1838 if let Some(resids) = ctx.dual_residuals() {
1839 if let Some((label, val)) = worst_named(resids, &names) {
1840 f.push((
1841 "warning",
1842 "dual_infeasible",
1843 format!(
1844 "Dual infeasibility {inf_du:.2e}; largest stationarity residual is \
1845 {label} = {val:+.3e}."
1846 ),
1847 ));
1848 }
1849 }
1850 }
1851
1852 if let Some(k) = ctx.kkt() {
1854 if k.provides_inertia && !k.inertia_correct {
1855 f.push((
1856 "warning",
1857 "inertia_wrong",
1858 format!(
1859 "KKT inertia is wrong (n-={} vs expected {}): the system was \
1860 indefinite/singular and the step had to be stabilized. A persistent \
1861 mismatch points at a rank-deficient Jacobian or an indefinite Hessian.",
1862 k.n_neg, k.expected_neg
1863 ),
1864 ));
1865 }
1866 if k.delta_w > 1e-4 {
1867 f.push((
1868 "info",
1869 "heavy_regularization",
1870 format!(
1871 "Primal regularization δ_w={:.2e} applied — the Hessian was indefinite at \
1872 this step. Normal near saddle points; persistent large δ_w suggests a \
1873 problematic Hessian.",
1874 k.delta_w
1875 ),
1876 ));
1877 }
1878 if k.delta_c > 0.0 {
1879 f.push((
1880 "warning",
1881 "dual_regularization",
1882 format!(
1883 "Dual regularization δ_c={:.2e} applied — the constraint Jacobian is (near) \
1884 rank-deficient (linearly dependent or redundant equalities). Inspect the \
1885 equality residuals by name (`print residuals primal`).",
1886 k.delta_c
1887 ),
1888 ));
1889 }
1890 }
1891
1892 if let Some(book) = self.structure_book.as_ref() {
1896 f.extend(book.findings());
1897 }
1898
1899 if let Some(rep) = ctx.rank_report() {
1905 if rep.is_rank_deficient() {
1906 let culprits: Vec<String> = rep
1907 .culprits
1908 .iter()
1909 .take(MAX_RANK_CULPRITS)
1910 .map(|c| rank_row_label(&rep.rows[c.row], &names))
1911 .collect();
1912 let named = if culprits.is_empty() {
1913 String::new()
1914 } else {
1915 format!(" Implicated equations: {}.", culprits.join(", "))
1916 };
1917 f.push((
1918 "warning",
1919 "rank_deficient_jacobian",
1920 format!(
1921 "Equality Jacobian J_c is numerically rank-deficient at this iterate: \
1922 rank {}/{} (deficiency {}), σ_min={:.2e}, cond={}. Linearly dependent \
1923 or redundant equality constraints — the root cause behind δ_c \
1924 regularization / wrong inertia.{named}",
1925 rep.rank,
1926 rep.n_rows(),
1927 rep.deficiency(),
1928 rep.sigma_min(),
1929 fmt_cond(rep.cond),
1930 ),
1931 ));
1932 }
1933 }
1934
1935 let mut max_mult = 0.0_f64;
1937 for blk in ["y_c", "y_d", "z_l", "z_u", "v_l", "v_u"] {
1938 if let Some(v) = ctx.block(blk) {
1939 max_mult = v.iter().fold(max_mult, |m, &x| m.max(x.abs()));
1940 }
1941 }
1942 if max_mult > 1e8 {
1943 f.push((
1944 "warning",
1945 "large_multipliers",
1946 format!(
1947 "Largest multiplier magnitude is {max_mult:.2e}. Very large multipliers signal a \
1948 constraint-qualification failure or poor scaling — consider rescaling the \
1949 offending rows."
1950 ),
1951 ));
1952 }
1953
1954 let mut pinned = 0usize;
1956 for cat in ["x_l", "x_u"] {
1957 if let Some(sl) = ctx.bound_slack(cat) {
1958 pinned += sl.iter().filter(|&&s| s.abs() < TOL).count();
1959 }
1960 }
1961 if pinned > 0 {
1962 f.push((
1963 "info",
1964 "bounds_pinned",
1965 format!(
1966 "{pinned} variable bound(s) are active (slack < {TOL:.0e}). Active bounds are \
1967 expected at a solution, but a large count early can throttle the line search."
1968 ),
1969 ));
1970 }
1971
1972 let (alpha_pr, _) = ctx.alpha();
1974 if ctx.iter() > 0 && alpha_pr > 0.0 && alpha_pr < 1e-6 {
1975 f.push((
1976 "warning",
1977 "tiny_step",
1978 format!(
1979 "Accepted primal step α_pr={alpha_pr:.2e} is tiny — the line search is barely \
1980 moving. Often a poor search direction or an ill-conditioned KKT system."
1981 ),
1982 ));
1983 }
1984 let ls = ctx.ls_count();
1985 if ls >= 10 {
1986 f.push((
1987 "warning",
1988 "heavy_line_search",
1989 format!(
1990 "Line search needed {ls} trial points for the accepted step — search-direction \
1991 quality may be poor (check Hessian accuracy)."
1992 ),
1993 ));
1994 }
1995
1996 if self.in_restoration {
1998 f.push((
1999 "warning",
2000 "in_restoration",
2001 "Currently inside feasibility restoration: the line search could not make \
2002 progress on the original problem at the working point."
2003 .to_string(),
2004 ));
2005 }
2006 if self.mu_stall >= MU_STALL_ITERS {
2007 f.push((
2008 "warning",
2009 "mu_stalled",
2010 format!(
2011 "μ has not decreased for {} consecutive iterations — the barrier is stuck. \
2012 Try mu_strategy=adaptive or a smaller mu_init.",
2013 self.mu_stall
2014 ),
2015 ));
2016 }
2017
2018 if f.is_empty() {
2020 f.push((
2021 "info",
2022 "healthy",
2023 format!(
2024 "No issues detected at iter {}: inf_pr={:.2e}, inf_du={:.2e}, μ={:.2e}.",
2025 ctx.iter(),
2026 inf_pr,
2027 inf_du,
2028 ctx.mu()
2029 ),
2030 ));
2031 }
2032
2033 let rank = |s: &str| match s {
2035 "error" => 0,
2036 "warning" => 1,
2037 _ => 2,
2038 };
2039 f.sort_by_key(|(sev, _, _)| rank(sev));
2040
2041 let lines: Vec<String> = f
2042 .iter()
2043 .map(|(sev, code, msg)| format!("[{sev:>7}] {code}: {msg}"))
2044 .collect();
2045 let data: Vec<_> = f
2046 .iter()
2047 .map(|(sev, code, msg)| serde_json::json!({"severity": sev, "code": code, "message": msg}))
2048 .collect();
2049 let n = data.len();
2050 CmdOut::ok(lines)
2051 .with_data(serde_json::json!({"iter": ctx.iter(), "findings": data, "n_findings": n}))
2052 }
2053
2054 fn cmd_print_kkt(&self, ctx: &dyn DebugState) -> CmdOut {
2057 let Some(k) = ctx.kkt() else {
2058 return CmdOut::err(
2059 "no KKT factorization yet — stop at `after_search_dir` (e.g. `stop-at kkt`)",
2060 );
2061 };
2062 let inertia = if k.provides_inertia {
2063 format!(
2064 "n+={} n-={} (expected n-={}) → {}",
2065 k.n_pos,
2066 k.n_neg,
2067 k.expected_neg,
2068 if k.inertia_correct {
2069 "correct"
2070 } else {
2071 "WRONG (step stabilized)"
2072 }
2073 )
2074 } else {
2075 "n/a (backend reports no inertia)".to_string()
2076 };
2077 let lines = vec![
2078 format!("dim = {}", k.dim),
2079 format!("inertia = {inertia}"),
2080 format!("delta_w = {:.6e} (primal regularization)", k.delta_w),
2081 format!("delta_c = {:.6e} (dual regularization)", k.delta_c),
2082 format!("status = {}", k.status),
2083 ];
2084 CmdOut::ok(lines).with_data(serde_json::json!({
2085 "dim": k.dim,
2086 "n_pos": k.n_pos,
2087 "n_neg": k.n_neg,
2088 "expected_neg": k.expected_neg,
2089 "provides_inertia": k.provides_inertia,
2090 "inertia_correct": k.inertia_correct,
2091 "delta_w": k.delta_w,
2092 "delta_c": k.delta_c,
2093 "status": k.status,
2094 }))
2095 }
2096
2097 fn cmd_print_rank(&self, ctx: &DebugCtx) -> CmdOut {
2106 let Some(rep) = ctx.rank_report() else {
2107 return CmdOut::err(
2108 "no equality-constraint Jacobian to analyze (the problem has no equality \
2109 constraints, or there is no iterate yet)",
2110 );
2111 };
2112 let names = ctx.split_names();
2113 let (lines, data) =
2114 render_rank_report(&rep, &names, self.equation_book.as_ref(), ctx.iter());
2115 CmdOut::ok(lines).with_data(data)
2116 }
2117
2118 fn cmd_run(&mut self, rest: &[&str]) -> CmdOut {
2119 match rest.first().and_then(|s| s.parse::<i32>().ok()) {
2120 Some(n) => {
2121 self.run_to = Some(n);
2122 self.step = false;
2123 CmdOut::ok(vec![format!("running until iteration {n}")]).flow(Flow::Resume)
2124 }
2125 None => CmdOut::err("usage: run <iteration>"),
2126 }
2127 }
2128
2129 fn cmd_break(&mut self, rest: &[&str]) -> CmdOut {
2130 if rest.first().copied() == Some("if") {
2134 let expr: String = rest[1..].concat();
2135 if expr.is_empty() {
2136 return CmdOut::err(
2137 "usage: break if <metric><op><value> (e.g. break if inf_pr<1e-6)",
2138 );
2139 }
2140 return match Condition::parse(&expr) {
2141 Ok(c) => {
2142 let raw = c.raw.clone();
2143 if !self.conds.iter().any(|e| e.raw == raw) {
2144 self.conds.push(c);
2145 }
2146 CmdOut::ok(vec![format!("conditional breakpoint: {raw}")])
2147 .with_data(serde_json::json!({"condition": raw}))
2148 }
2149 Err(e) => CmdOut::err(e),
2150 };
2151 }
2152 if rest.first().copied() == Some("on") {
2154 let Some(&name) = rest.get(1) else {
2155 return CmdOut::err(format!("usage: break on <event> (one of {EVENTS:?})"));
2156 };
2157 let Some(&canon) = EVENTS.iter().find(|&&e| e == name) else {
2158 return CmdOut::err(format!("unknown event `{name}` (one of {EVENTS:?})"));
2159 };
2160 self.break_events.insert(canon);
2161 return CmdOut::ok(vec![format!("break on event `{canon}`")])
2162 .with_data(serde_json::json!({"event": canon}));
2163 }
2164 match rest {
2165 [] => {
2166 let mut bs = self.breaks.clone();
2167 bs.sort_unstable();
2168 let conds: Vec<String> = self.conds.iter().map(|c| c.raw.clone()).collect();
2169 let mut events: Vec<&str> = self.break_events.iter().copied().collect();
2170 events.sort_unstable();
2171 let mut lines = vec![format!("breakpoints: {bs:?}")];
2172 if !conds.is_empty() {
2173 lines.push(format!("conditions: {}", conds.join(", ")));
2174 }
2175 if !events.is_empty() {
2176 lines.push(format!("events: {}", events.join(", ")));
2177 }
2178 CmdOut::ok(lines).with_data(
2179 serde_json::json!({"breakpoints": bs, "conditions": conds, "events": events}),
2180 )
2181 }
2182 ["clear", "cond"] | ["clear", "conditions"] => {
2183 self.conds.clear();
2184 CmdOut::ok(vec!["cleared conditional breakpoints".into()])
2185 }
2186 ["clear", "events"] => {
2187 self.break_events.clear();
2188 CmdOut::ok(vec!["cleared event breakpoints".into()])
2189 }
2190 ["clear"] => {
2191 self.breaks.clear();
2192 self.conds.clear();
2193 self.break_events.clear();
2194 CmdOut::ok(vec!["cleared all breakpoints".into()])
2195 }
2196 ["del", n] | ["delete", n] => match n.parse::<i32>() {
2197 Ok(n) => {
2198 self.breaks.retain(|&b| b != n);
2199 CmdOut::ok(vec![format!("removed breakpoint {n}")])
2200 }
2201 Err(_) => CmdOut::err("usage: break del <iteration>"),
2202 },
2203 [n] => match n.parse::<i32>() {
2204 Ok(n) => {
2205 if !self.breaks.contains(&n) {
2206 self.breaks.push(n);
2207 }
2208 CmdOut::ok(vec![format!("breakpoint at iteration {n}")])
2209 }
2210 Err(_) => CmdOut::err("usage: break <iteration>"),
2211 },
2212 _ => CmdOut::err("usage: break [N | if <m><op><v> | clear | clear cond | del N]"),
2213 }
2214 }
2215
2216 fn cmd_stop_at(&mut self, rest: &[&str]) -> CmdOut {
2220 let canon = |s: &str| -> Option<&'static str> {
2221 match s {
2222 "mu" | "after_mu" => Some("after_mu"),
2223 "kkt" | "search_dir" | "after_search_dir" => Some("after_search_dir"),
2224 "step" | "after_step" => Some("after_step"),
2225 "rejected" | "ls_rejected" | "step_rejected" => Some("step_rejected"),
2226 "resto" | "restoration" | "pre_restoration_entry" => Some("pre_restoration_entry"),
2227 "resto_exit" | "post_restoration_exit" => Some("post_restoration_exit"),
2228 "iter" | "iter_start" => Some("iter_start"),
2229 "terminated" => Some("terminated"),
2230 _ => None,
2231 }
2232 };
2233 match rest {
2234 [] => {
2235 let mut v: Vec<&str> = self.stop_at.iter().copied().collect();
2236 v.sort_unstable();
2237 CmdOut::ok(vec![format!(
2238 "stop-at: {v:?} (available: {CHECKPOINTS:?})"
2239 )])
2240 .with_data(serde_json::json!({"stop_at": v, "available": CHECKPOINTS}))
2241 }
2242 ["clear"] => {
2243 self.stop_at.clear();
2244 CmdOut::ok(vec!["cleared stop-at checkpoints".into()])
2245 }
2246 [name] => match canon(name) {
2247 Some(c) => {
2248 self.stop_at.insert(c);
2249 CmdOut::ok(vec![format!("will stop at checkpoint `{c}`")])
2250 .with_data(serde_json::json!({"stop_at_added": c}))
2251 }
2252 None => CmdOut::err(format!(
2253 "unknown checkpoint `{name}` (one of {CHECKPOINTS:?})"
2254 )),
2255 },
2256 _ => CmdOut::err("usage: stop-at [<checkpoint> | clear]"),
2257 }
2258 }
2259
2260 fn cmd_set(&mut self, rest: &[&str], ctx: &mut dyn DebugState) -> CmdOut {
2261 match rest {
2262 ["mu", v] => match v.parse::<f64>() {
2263 Ok(mu) => match ctx.set_mu(mu) {
2264 Ok(()) => CmdOut::ok(vec![format!("mu := {mu:.6e}")]),
2265 Err(e) => CmdOut::err(e),
2266 },
2267 Err(_) => CmdOut::err("usage: set mu <value>"),
2268 },
2269 ["opt", name, value] => match as_nlp_mut(ctx) {
2270 Some(c) => self.cmd_set_opt(name, value, c),
2271 None => nlp_only("set opt"),
2272 },
2273 [target, value] => self.cmd_set_block(target, value, ctx),
2274 _ => CmdOut::err(
2275 "usage: set mu <v> | set <blk>[<i>] <v> | set <blk> <v0,v1,..> | set opt <name> <v>",
2276 ),
2277 }
2278 }
2279
2280 fn cmd_set_block(&mut self, target: &str, value: &str, ctx: &mut dyn DebugState) -> CmdOut {
2282 if let Some(open) = target.find('[') {
2284 if !target.ends_with(']') {
2285 return CmdOut::err("malformed component target (expected name[idx])");
2286 }
2287 let name = &target[..open];
2288 let idx_str = &target[open + 1..target.len() - 1];
2289 let Ok(idx) = idx_str.parse::<usize>() else {
2290 return CmdOut::err(format!("bad index `{idx_str}`"));
2291 };
2292 let Ok(val) = value.parse::<f64>() else {
2293 return CmdOut::err(format!("bad value `{value}`"));
2294 };
2295 return match ctx.set_component(name, idx, val) {
2296 Ok(()) => CmdOut::ok(vec![format!("{name}[{idx}] := {val:.6e}")]),
2297 Err(e) => CmdOut::err(e),
2298 };
2299 }
2300 let parsed: Result<Vec<f64>, _> =
2302 value.split(',').map(|s| s.trim().parse::<f64>()).collect();
2303 match parsed {
2304 Ok(vals) => match ctx.set_block(target, &vals) {
2305 Ok(()) => CmdOut::ok(vec![format!("{target} := {} value(s)", vals.len())]),
2306 Err(e) => CmdOut::err(e),
2307 },
2308 Err(_) => CmdOut::err("could not parse comma-separated values"),
2309 }
2310 }
2311
2312 fn cmd_set_opt(&mut self, name: &str, value: &str, ctx: &mut DebugCtx) -> CmdOut {
2313 let Some(reg) = self.reg.as_ref() else {
2314 return CmdOut::err("no options registry available");
2315 };
2316 let Some(opt) = reg.get_option(name) else {
2317 return CmdOut::err(format!("unknown option `{name}` (try `opt {name}`)"));
2318 };
2319 let valid = match opt.option_type {
2321 OptionType::OT_Number => value
2322 .parse::<f64>()
2323 .map(|v| opt.is_valid_number(v))
2324 .unwrap_or(false),
2325 OptionType::OT_Integer => value
2326 .parse::<i32>()
2327 .map(|v| opt.is_valid_integer(v))
2328 .unwrap_or(false),
2329 OptionType::OT_String => opt.is_valid_string(value),
2330 OptionType::OT_Unknown => true,
2331 };
2332 if !valid {
2333 return CmdOut::err(format!("`{value}` is not a valid value for `{name}`"));
2334 }
2335 self.staged.retain(|(k, _)| k != name);
2338 self.staged.push((name.to_string(), value.to_string()));
2339 if is_live_tolerance(name) {
2344 if let Ok(v) = value.parse::<f64>() {
2345 ctx.set_live_tolerance(name, v);
2346 return CmdOut::ok(vec![format!(
2347 "{name} = {value} (applied live — the next `step` uses it)"
2348 )])
2349 .with_data(serde_json::json!({
2350 "option": name, "value": value, "live": true
2351 }));
2352 }
2353 }
2354 CmdOut::ok(vec![format!(
2355 "staged {name} = {value} (validated; takes effect on `resolve` — built strategies don't re-read mid-solve)"
2356 )])
2357 .with_data(serde_json::json!({"option": name, "value": value, "staged": true}))
2358 }
2359
2360 fn cmd_get(&self, rest: &[&str]) -> CmdOut {
2367 let name = match rest {
2369 ["opt", n] => *n,
2370 [n] => *n,
2371 _ => return CmdOut::err("usage: get opt <name>"),
2372 };
2373 let Some(reg) = self.reg.as_ref() else {
2374 return CmdOut::err("no options registry available");
2375 };
2376 let Some(o) = reg.get_option(name) else {
2377 return CmdOut::err(format!("unknown option `{name}` (try `opt {name}`)"));
2378 };
2379 let def = default_str(&o.default);
2380 let staged = self
2381 .staged
2382 .iter()
2383 .find(|(k, _)| k == name)
2384 .map(|(_, v)| v.clone());
2385 let (value, source) = match &staged {
2386 Some(v) => (v.clone(), "staged"),
2387 None => (def.clone(), "default"),
2388 };
2389 CmdOut::ok(vec![format!("{name} = {value} ({source}; default={def})")]).with_data(
2390 serde_json::json!({
2391 "option": name, "value": value, "source": source,
2392 "default": def, "staged": staged,
2393 }),
2394 )
2395 }
2396
2397 fn cmd_opt(&self, rest: &[&str]) -> CmdOut {
2398 let Some(reg) = self.reg.as_ref() else {
2399 return CmdOut::err("no options registry available");
2400 };
2401 let filter = rest.first().copied().unwrap_or("");
2402 let mut lines = Vec::new();
2403 let mut data = Vec::new();
2404 for o in reg.registered_options_in_order() {
2405 if !filter.is_empty()
2406 && !o.name.contains(filter)
2407 && !o
2408 .category
2409 .to_ascii_lowercase()
2410 .contains(&filter.to_ascii_lowercase())
2411 {
2412 continue;
2413 }
2414 let ty = type_str(o.option_type);
2415 let def = default_str(&o.default);
2416 lines.push(format!(
2417 " {:<28} {:<7} default={:<12} {}",
2418 o.name, ty, def, o.short_description
2419 ));
2420 data.push(serde_json::json!({
2421 "name": o.name,
2422 "type": ty,
2423 "default": def,
2424 "category": o.category,
2425 "short": o.short_description,
2426 "valid": o.valid_strings.iter().map(|e| e.value.clone()).collect::<Vec<_>>(),
2427 }));
2428 }
2429 if lines.is_empty() {
2430 return CmdOut::ok(vec![format!("no options match `{filter}`")]);
2431 }
2432 if data.len() == 1 {
2434 if let Some(o) = reg.get_option(filter) {
2435 if !o.long_description.is_empty() {
2436 lines.push(String::new());
2437 lines.push(o.long_description.clone());
2438 }
2439 }
2440 }
2441 CmdOut::ok(lines).with_data(serde_json::json!({"options": data}))
2442 }
2443
2444 fn cmd_complete(&self, rest: &[&str]) -> CmdOut {
2449 let (before, word) = match rest.split_last() {
2450 Some((w, pre)) => (pre.join(" "), *w),
2451 None => (String::new(), ""),
2452 };
2453 let mut cands = completion_candidates(self.reg.as_deref(), &before, word);
2454 cands.sort();
2455 cands.dedup();
2456 CmdOut::ok(vec![cands.join(" ")]).with_data(serde_json::json!({"candidates": cands}))
2457 }
2458
2459 fn cmd_save(&self, rest: &[&str], ctx: &dyn DebugState) -> CmdOut {
2463 let iter = ctx.iter();
2464 let path = rest
2465 .first()
2466 .map(PathBuf::from)
2467 .unwrap_or_else(|| std::env::temp_dir().join(format!("pounce-dbg-iter{iter}.json")));
2468 let collect = |delta: bool| -> serde_json::Map<String, serde_json::Value> {
2469 let mut m = serde_json::Map::new();
2470 for b in block_names(ctx) {
2471 let v = if delta {
2472 ctx.delta_block(b)
2473 } else {
2474 ctx.block(b)
2475 };
2476 if let Some(v) = v {
2477 if !v.is_empty() {
2478 let key = if delta {
2479 format!("d{b}")
2480 } else {
2481 b.to_string()
2482 };
2483 m.insert(key, serde_json::json!(v));
2484 }
2485 }
2486 }
2487 m
2488 };
2489 let payload = serde_json::json!({
2490 "iter": iter,
2491 "mu": ctx.mu(),
2492 "objective": ctx.objective(),
2493 "inf_pr": ctx.inf_pr(),
2494 "inf_du": ctx.inf_du(),
2495 "nlp_error": ctx.nlp_error(),
2496 "iterate": collect(false),
2497 "delta": collect(true),
2498 });
2499 match std::fs::write(&path, format!("{payload}\n")) {
2500 Ok(()) => {
2501 let p = path.to_string_lossy().to_string();
2502 CmdOut::ok(vec![format!("saved iterate to {p}")])
2503 .with_data(serde_json::json!({"path": p}))
2504 }
2505 Err(e) => CmdOut::err(format!("save failed: {e}")),
2506 }
2507 }
2508
2509 fn cmd_load(&mut self, rest: &[&str], ctx: &mut DebugCtx) -> CmdOut {
2516 let Some(&path) = rest.first() else {
2517 return CmdOut::err("usage: load <file> [block] (inverse of `save`)");
2518 };
2519 let content = match std::fs::read_to_string(path) {
2520 Ok(c) => c,
2521 Err(e) => return CmdOut::err(format!("cannot read `{path}`: {e}")),
2522 };
2523 if let Ok(v) = serde_json::from_str::<serde_json::Value>(content.trim()) {
2527 let obj = v
2528 .get("iterate")
2529 .and_then(|o| o.as_object())
2530 .or_else(|| v.as_object());
2531 if let Some(obj) = obj {
2532 let mut loaded: Vec<(String, usize)> = Vec::new();
2533 let mut errs: Vec<String> = Vec::new();
2534 for &b in BLOCK_NAMES.iter() {
2535 let Some(arr) = obj.get(b).and_then(|a| a.as_array()) else {
2536 continue;
2537 };
2538 let vals: Option<Vec<f64>> = arr.iter().map(|x| x.as_f64()).collect();
2539 let Some(vals) = vals else {
2540 errs.push(format!("{b}: non-numeric entries"));
2541 continue;
2542 };
2543 match ctx.set_block(b, &vals) {
2544 Ok(()) => loaded.push((b.to_string(), vals.len())),
2545 Err(e) => errs.push(format!("{b}: {e}")),
2546 }
2547 }
2548 if loaded.is_empty() && errs.is_empty() {
2549 return CmdOut::err(
2550 "no recognizable blocks in JSON (expected `x`, `s`, … at top level or under `iterate`)",
2551 );
2552 }
2553 let mut lines: Vec<String> = loaded
2554 .iter()
2555 .map(|(b, n)| format!("loaded {b} ({n} values)"))
2556 .collect();
2557 lines.extend(errs.iter().map(|e| format!("skipped {e}")));
2558 return CmdOut::ok(lines).with_data(serde_json::json!({
2559 "loaded": loaded.iter().map(|(b, n)| serde_json::json!({"block": b, "n": n})).collect::<Vec<_>>(),
2560 "skipped": errs,
2561 }));
2562 }
2563 }
2564 let block = rest.get(1).copied().unwrap_or("x");
2566 let vals = match parse_floats(&content) {
2567 Ok(v) if !v.is_empty() => v,
2568 Ok(_) => return CmdOut::err("file held no numbers"),
2569 Err(e) => return CmdOut::err(e),
2570 };
2571 match ctx.set_block(block, &vals) {
2572 Ok(()) => CmdOut::ok(vec![format!("loaded {block} ({} values)", vals.len())])
2573 .with_data(serde_json::json!({"block": block, "n": vals.len()})),
2574 Err(e) => CmdOut::err(e),
2575 }
2576 }
2577
2578 fn cmd_sweep(&mut self, rest: &[&str], ctx: &mut DebugCtx) -> CmdOut {
2584 if self.restart.is_none() {
2585 return CmdOut::err("sweep needs re-solve, which is not available in this context");
2586 }
2587 let Some(&path) = rest.first() else {
2588 return CmdOut::err("usage: sweep <file> (one start per line, comma-separated)");
2589 };
2590 let content = match std::fs::read_to_string(path) {
2591 Ok(c) => c,
2592 Err(e) => return CmdOut::err(format!("cannot read `{path}`: {e}")),
2593 };
2594 let dim = ctx.block("x").map(|x| x.len()).unwrap_or(0);
2595 let mut seeds: Vec<Vec<f64>> = Vec::new();
2596 for (lineno, raw) in content.lines().enumerate() {
2597 let line = raw.trim();
2598 if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
2599 continue;
2600 }
2601 match parse_floats(line) {
2602 Ok(v) if v.len() == dim => seeds.push(v),
2603 Ok(v) => {
2604 return CmdOut::err(format!(
2605 "line {}: got {} values, expected {dim} (= dim x)",
2606 lineno + 1,
2607 v.len()
2608 ));
2609 }
2610 Err(e) => return CmdOut::err(format!("line {}: {e}", lineno + 1)),
2611 }
2612 }
2613 self.start_sweep(seeds, &format!("sweep `{path}`"))
2614 }
2615
2616 fn cmd_multistart(&mut self, rest: &[&str], ctx: &mut DebugCtx) -> CmdOut {
2624 if self.restart.is_none() {
2625 return CmdOut::err(
2626 "multistart needs re-solve, which is not available in this context",
2627 );
2628 }
2629 let Some(n) = rest.first().and_then(|s| s.parse::<usize>().ok()) else {
2630 return CmdOut::err("usage: multistart <N> [rel] (N sampled restarts)");
2631 };
2632 if n == 0 {
2633 return CmdOut::err("N must be ≥ 1");
2634 }
2635 let rel = rest
2636 .get(1)
2637 .and_then(|s| s.parse::<f64>().ok())
2638 .unwrap_or(0.1);
2639 let Some(base) = ctx.block("x") else {
2640 return CmdOut::err("no current iterate to sample from");
2641 };
2642 let bounds = ctx
2644 .var_bounds()
2645 .filter(|(lo, hi)| lo.len() == base.len() && hi.len() == base.len());
2646 let n_box = bounds
2647 .as_ref()
2648 .map(|(lo, hi)| {
2649 lo.iter()
2650 .zip(hi)
2651 .filter(|(l, u)| l.is_finite() && u.is_finite() && u > l)
2652 .count()
2653 })
2654 .unwrap_or(0);
2655 let seeds: Vec<Vec<f64>> = (0..n)
2656 .map(|k| {
2657 let b = bounds
2658 .as_ref()
2659 .map(|(lo, hi)| (lo.as_slice(), hi.as_slice()));
2660 sample_start(&base, b, rel, k)
2661 })
2662 .collect();
2663 let n_var = base.len();
2664 let label = if n_box == n_var {
2665 format!("multistart {n} (box-sampled, {n_box}/{n_var} vars bounded)")
2666 } else if n_box > 0 {
2667 format!(
2668 "multistart {n} (box {n_box}/{n_var} vars; {} unbounded → jitter rel={rel})",
2669 n_var - n_box
2670 )
2671 } else {
2672 format!("multistart {n} (no finite boxes → jitter rel={rel})")
2673 };
2674 self.start_sweep(seeds, &label)
2675 }
2676
2677 fn start_sweep(&mut self, seeds: Vec<Vec<f64>>, label: &str) -> CmdOut {
2682 if seeds.is_empty() {
2683 return CmdOut::err("no start points");
2684 }
2685 let Some(cell) = self.restart.as_ref() else {
2686 return CmdOut::err("sweep needs re-solve, which is not available in this context");
2687 };
2688 let total = seeds.len();
2689 let mut queue: VecDeque<Vec<f64>> = seeds.into();
2690 let first = queue.pop_front().expect("non-empty");
2691 *cell.borrow_mut() = Some(RestartRequest {
2692 seed_x: first.clone(),
2693 options: self.staged.clone(),
2694 warm: None,
2695 });
2696 let saved_pause_iters = self.pause_iters;
2699 self.pause_iters = false;
2700 self.step = false;
2701 self.sub_step = false;
2702 self.run_to = None;
2703 self.sweep = Some(SweepState {
2704 queue,
2705 current: Some(first),
2706 records: Vec::new(),
2707 total,
2708 saved_pause_iters,
2709 });
2710 CmdOut::ok(vec![format!("{label}: running {total} start(s)…")])
2711 .with_data(serde_json::json!({"sweep": label, "starts": total}))
2712 .flow(Flow::Stop)
2713 }
2714
2715 fn drive_sweep(&mut self, ctx: &DebugCtx) -> Option<DebugAction> {
2722 let mut sweep = self.sweep.take()?;
2723 let rec = SweepRecord {
2724 idx: sweep.records.len(),
2725 seed: sweep.current.clone().unwrap_or_default(),
2726 status: ctx.status().unwrap_or("?").to_string(),
2727 objective: ctx.objective(),
2728 inf_pr: ctx.inf_pr(),
2729 iters: ctx.iter(),
2730 };
2731 self.emit_sweep_progress(&rec, sweep.total);
2732 sweep.records.push(rec);
2733 if let Some(next) = sweep.queue.pop_front() {
2734 sweep.current = Some(next.clone());
2735 if let Some(cell) = self.restart.as_ref() {
2736 *cell.borrow_mut() = Some(RestartRequest {
2737 seed_x: next,
2738 options: self.staged.clone(),
2739 warm: None,
2740 });
2741 }
2742 self.sweep = Some(sweep);
2743 return Some(DebugAction::Resume);
2744 }
2745 self.pause_iters = sweep.saved_pause_iters;
2747 self.emit_sweep_summary(&sweep);
2748 None
2749 }
2750
2751 fn emit_sweep_progress(&self, rec: &SweepRecord, total: usize) {
2754 match self.mode {
2755 DebugMode::Repl => eprintln!(
2756 " sweep {}/{}: {:<22} iters={:<4} obj={:.6e} inf_pr={:.2e}",
2757 rec.idx + 1,
2758 total,
2759 rec.status,
2760 rec.iters,
2761 rec.objective,
2762 rec.inf_pr,
2763 ),
2764 DebugMode::Json => emit_json(&serde_json::json!({
2765 "event": "sweep_result",
2766 "index": rec.idx,
2767 "total": total,
2768 "status": rec.status,
2769 "iters": rec.iters,
2770 "objective": rec.objective,
2771 "inf_pr": rec.inf_pr,
2772 "seed": rec.seed,
2773 })),
2774 }
2775 }
2776
2777 fn emit_sweep_summary(&self, sweep: &SweepState) {
2780 let succeeded: Vec<&SweepRecord> = sweep
2781 .records
2782 .iter()
2783 .filter(|r| is_success_status(&r.status))
2784 .collect();
2785 let mut distinct: Vec<f64> = Vec::new();
2787 for r in &succeeded {
2788 if !distinct
2789 .iter()
2790 .any(|&o| (o - r.objective).abs() <= 1e-6 * o.abs().max(1.0))
2791 {
2792 distinct.push(r.objective);
2793 }
2794 }
2795 let best = succeeded.iter().min_by(|a, b| {
2796 a.objective
2797 .partial_cmp(&b.objective)
2798 .unwrap_or(std::cmp::Ordering::Equal)
2799 });
2800 match self.mode {
2801 DebugMode::Repl => {
2802 eprintln!(
2803 "\n── sweep complete ── {} solves, {} succeeded, {} distinct minima",
2804 sweep.records.len(),
2805 succeeded.len(),
2806 distinct.len()
2807 );
2808 eprintln!(
2809 " {:>3} {:<22} {:>5} {:>14} {:>9}",
2810 "#", "status", "iters", "objective", "inf_pr"
2811 );
2812 for r in &sweep.records {
2813 eprintln!(
2814 " {:>3} {:<22} {:>5} {:>14.6e} {:>9.2e}",
2815 r.idx, r.status, r.iters, r.objective, r.inf_pr
2816 );
2817 }
2818 if let Some(b) = best {
2819 eprintln!(" best: solve #{} obj={:.8e}", b.idx, b.objective);
2820 }
2821 }
2822 DebugMode::Json => emit_json(&serde_json::json!({
2823 "event": "sweep_summary",
2824 "solves": sweep.records.len(),
2825 "succeeded": succeeded.len(),
2826 "distinct_minima": distinct.len(),
2827 "best_index": best.map(|b| b.idx),
2828 "best_objective": best.map(|b| b.objective),
2829 "records": sweep.records.iter().map(|r| serde_json::json!({
2830 "index": r.idx, "status": r.status, "iters": r.iters,
2831 "objective": r.objective, "inf_pr": r.inf_pr,
2832 })).collect::<Vec<_>>(),
2833 })),
2834 }
2835 }
2836
2837 fn cmd_goto(&mut self, rest: &[&str], ctx: &mut dyn DebugState) -> CmdOut {
2839 match rest.first().and_then(|s| s.parse::<i32>().ok()) {
2840 Some(k) => self.restore_to(k, ctx),
2841 None => CmdOut::err("usage: goto <iteration>"),
2842 }
2843 }
2844
2845 fn restore_to(&mut self, k: i32, ctx: &mut dyn DebugState) -> CmdOut {
2849 match self.snapshots.get(&k) {
2850 Some(snap) => {
2851 if !ctx.restore(snap.as_ref()) {
2852 return CmdOut::err(format!(
2853 "this solver does not support rewinding to iter {k}"
2854 ));
2855 }
2856 CmdOut::ok(vec![format!(
2857 "rewound to iter {k} (primal-dual only; strategy history not restored). \
2858 `continue`/`step` to resume."
2859 )])
2860 .with_data(serde_json::json!({"restored_iter": k}))
2861 }
2862 None => {
2863 let have: Vec<i32> = self.snapshots.keys().copied().collect();
2864 CmdOut::err(format!("no snapshot for iter {k} (captured: {have:?})"))
2865 }
2866 }
2867 }
2868
2869 fn cmd_resolve(&mut self, ctx: &DebugCtx) -> CmdOut {
2877 let Some(cell) = self.restart.as_ref() else {
2878 return CmdOut::err("re-solve is not available in this context");
2879 };
2880 let Some(seed_x) = ctx.block("x") else {
2881 return CmdOut::err("no current iterate to seed from");
2882 };
2883 let warm = ctx.snapshot();
2884 let mu = warm.as_ref().map(|s| s.mu());
2885 let options = self.staged.clone();
2886 let n_opt = options.len();
2887 let warm_msg = match mu {
2888 Some(mu) => format!(
2889 "re-solving warm from the current primal-dual iterate (μ={mu:.3e}) \
2890 with {n_opt} staged option override(s)…"
2891 ),
2892 None => format!(
2893 "re-solving from current x (primal-only) with {n_opt} staged option override(s)…"
2894 ),
2895 };
2896 *cell.borrow_mut() = Some(RestartRequest {
2897 seed_x,
2898 options,
2899 warm,
2900 });
2901 CmdOut::ok(vec![warm_msg])
2902 .with_data(serde_json::json!({
2903 "resolve": true,
2904 "options": n_opt,
2905 "warm": mu.is_some(),
2906 "mu": mu,
2907 }))
2908 .flow(Flow::Stop)
2909 }
2910
2911 fn cmd_ask(&self, rest: &[&str], ctx: &dyn DebugState) -> CmdOut {
2917 let question = if rest.is_empty() {
2918 "Explain the current state of this interior-point solve and suggest what to try next."
2919 .to_string()
2920 } else {
2921 rest.join(" ")
2922 };
2923 let prompt = build_ask_prompt(ctx, &question);
2924 match run_llm(&prompt) {
2925 Ok(reply) => {
2926 let lines: Vec<String> = reply.lines().map(|l| l.to_string()).collect();
2927 CmdOut::ok(lines).with_data(serde_json::json!({
2928 "question": question,
2929 "reply": reply,
2930 }))
2931 }
2932 Err(e) => CmdOut::err(e),
2933 }
2934 }
2935
2936 fn cmd_watch(&mut self, rest: &[&str]) -> CmdOut {
2939 match rest {
2940 [] => CmdOut::ok(vec![format!("watches: {:?}", self.watches)])
2941 .with_data(serde_json::json!({"watches": self.watches})),
2942 ["clear"] => {
2943 self.watches.clear();
2944 CmdOut::ok(vec!["cleared watches".into()])
2945 }
2946 ["del", w] | ["delete", w] => {
2947 self.watches.retain(|x| x != w);
2948 CmdOut::ok(vec![format!("unwatched {w}")])
2949 }
2950 [w] => {
2951 let w = w.to_string();
2952 if !self.watches.contains(&w) {
2953 self.watches.push(w.clone());
2954 }
2955 CmdOut::ok(vec![format!("watching {w}")])
2956 }
2957 _ => CmdOut::err("usage: watch [<target> | clear | del <target>]"),
2958 }
2959 }
2960
2961 fn cmd_watchpoint(&mut self, rest: &[&str], ctx: &dyn DebugState) -> CmdOut {
2965 match rest {
2966 [] => {
2967 let v: Vec<&str> = self.watchpoints.iter().map(|w| w.raw.as_str()).collect();
2968 CmdOut::ok(vec![format!("watchpoints: {v:?}")])
2969 .with_data(serde_json::json!({"watchpoints": v}))
2970 }
2971 ["clear"] => {
2972 self.watchpoints.clear();
2973 CmdOut::ok(vec!["cleared watchpoints".into()])
2974 }
2975 ["del", spec] | ["delete", spec] => {
2976 self.watchpoints.retain(|w| w.raw != *spec);
2977 CmdOut::ok(vec![format!("removed watchpoint {spec}")])
2978 }
2979 [spec, rest @ ..] => {
2980 let threshold = rest
2981 .first()
2982 .and_then(|s| s.parse::<f64>().ok())
2983 .unwrap_or(0.0);
2984 let (block, idx) = match spec.find('[') {
2986 Some(open) if spec.ends_with(']') => {
2987 let b = &spec[..open];
2988 match spec[open + 1..spec.len() - 1].parse::<usize>() {
2989 Ok(i) => (b.to_string(), Some(i)),
2990 Err(_) => return CmdOut::err(format!("bad index in `{spec}`")),
2991 }
2992 }
2993 _ => (spec.to_string(), None),
2994 };
2995 if !is_block(ctx, block.as_str()) {
2996 return CmdOut::err(format!("unknown block `{block}`"));
2997 }
2998 let raw = spec.to_string();
2999 if !self.watchpoints.iter().any(|w| w.raw == raw) {
3000 self.watchpoints.push(WatchPoint {
3001 raw: raw.clone(),
3002 block,
3003 idx,
3004 threshold,
3005 last: None,
3006 });
3007 }
3008 CmdOut::ok(vec![format!("watchpoint on {raw} (Δ>{threshold:.3e})")])
3009 }
3010 }
3011 }
3012
3013 fn cmd_commands(&mut self, rest: &[&str]) -> CmdOut {
3018 let Some(iter) = rest.first().and_then(|s| s.parse::<i32>().ok()) else {
3019 if rest.is_empty() {
3020 let mut items: Vec<(i32, Vec<String>)> = self
3021 .bp_commands
3022 .iter()
3023 .map(|(k, v)| (*k, v.clone()))
3024 .collect();
3025 items.sort_by_key(|(k, _)| *k);
3026 let lines = if items.is_empty() {
3027 vec!["no breakpoint command lists".into()]
3028 } else {
3029 items
3030 .iter()
3031 .map(|(k, v)| format!("iter {k}: {}", v.join(" ; ")))
3032 .collect()
3033 };
3034 return CmdOut::ok(lines);
3035 }
3036 return CmdOut::err(
3037 "usage: commands <iter> <cmd> ; <cmd> … (or: commands <iter> clear)",
3038 );
3039 };
3040 let tail = rest[1..].join(" ");
3041 let tail = tail.trim();
3042 if tail.is_empty() || tail == "clear" {
3043 self.bp_commands.remove(&iter);
3044 return CmdOut::ok(vec![format!("cleared commands for iteration {iter}")]);
3045 }
3046 let cmds: Vec<String> = tail
3047 .split(';')
3048 .map(|s| s.trim().to_string())
3049 .filter(|s| !s.is_empty())
3050 .collect();
3051 self.bp_commands.insert(iter, cmds.clone());
3052 CmdOut::ok(vec![format!(
3053 "commands for iter {iter}: {}",
3054 cmds.join(" ; ")
3055 )])
3056 .with_data(serde_json::json!({"iter": iter, "commands": cmds}))
3057 }
3058
3059 fn cmd_diff(&self, ctx: &dyn DebugState) -> CmdOut {
3062 let iter = ctx.iter();
3063 let Some((&piter, prev)) = self.snapshots.range(..iter).next_back() else {
3064 return CmdOut::err("no previous iterate to diff against");
3065 };
3066 let mut lines = vec![format!("Δ since iter {piter}:")];
3067 let dmu = ctx.mu() - prev.mu();
3068 lines.push(format!(" mu = {:.6e} (Δ {:+.3e})", ctx.mu(), dmu));
3069 let mut blocks = serde_json::Map::new();
3070 for b in block_names(ctx) {
3071 let (Some(cur), Some(old)) = (ctx.block(b), prev.block(b)) else {
3072 continue;
3073 };
3074 if cur.is_empty() || cur.len() != old.len() {
3075 continue;
3076 }
3077 let mut amax = 0.0_f64;
3078 let mut imax = 0usize;
3079 for (i, (c, o)) in cur.iter().zip(&old).enumerate() {
3080 let d = (c - o).abs();
3081 if d > amax {
3082 amax = d;
3083 imax = i;
3084 }
3085 }
3086 if amax > 0.0 {
3087 lines.push(format!(
3088 " {b}: max|Δ|={amax:.3e} at [{imax}] ({:.4e} → {:.4e})",
3089 old[imax], cur[imax]
3090 ));
3091 blocks.insert(
3092 b.to_string(),
3093 serde_json::json!({"max_abs_change": amax, "argmax": imax}),
3094 );
3095 }
3096 }
3097 if lines.len() == 2 {
3098 lines.push(" (no change)".into());
3099 }
3100 CmdOut::ok(lines).with_data(
3101 serde_json::json!({"from_iter": piter, "to_iter": iter, "dmu": dmu, "blocks": blocks}),
3102 )
3103 }
3104
3105 fn cmd_source(&mut self, rest: &[&str], ctx: &mut dyn DebugState) -> CmdOut {
3109 let Some(&path) = rest.first() else {
3110 return CmdOut::err("usage: source <file>");
3111 };
3112 let content = match std::fs::read_to_string(path) {
3113 Ok(c) => c,
3114 Err(e) => return CmdOut::err(format!("cannot read `{path}`: {e}")),
3115 };
3116 let mut lines = Vec::new();
3117 let mut flow = Flow::Stay;
3118 for raw in content.lines() {
3119 let cmd = raw.trim();
3120 if cmd.is_empty() || cmd.starts_with('#') || cmd.starts_with("//") {
3121 continue;
3122 }
3123 lines.push(format!("[source] {cmd}"));
3124 let out = self.dispatch(cmd, ctx);
3125 lines.extend(out.lines);
3126 if !matches!(out.flow, Flow::Stay) {
3127 flow = out.flow;
3128 break;
3129 }
3130 }
3131 CmdOut {
3132 ok: true,
3133 lines,
3134 data: None,
3135 flow,
3136 }
3137 }
3138
3139 fn cmd_viz(&self, rest: &[&str], ctx: &mut dyn DebugState) -> CmdOut {
3140 let Some(&target) = rest.first() else {
3141 return CmdOut::err("usage: viz <x|s|y_c|...|dx|kkt|L>");
3142 };
3143 if target == "kkt" {
3146 if as_nlp(ctx).is_none() {
3148 return nlp_only("viz kkt");
3149 }
3150 let Some(k) = ctx.kkt() else {
3151 return CmdOut::err(
3152 "no KKT factorization captured yet — nothing has been factored (iter 0), \
3153 or the debugger is detached. `step` once to capture.",
3154 );
3155 };
3156 let Some((dim, irn, jcn, vals)) = ctx.kkt_matrix() else {
3161 return CmdOut::err(
3162 "KKT matrix not captured here — the debugger is detached \
3163 (running free). `step` once to capture and re-run `viz kkt`.",
3164 );
3165 };
3166 let kiter = k.iter;
3169 let matrix = serde_json::json!({"dim": dim, "irn": irn, "jcn": jcn, "vals": vals,
3170 "format": "triplet_1based_lower"});
3171 let payload = serde_json::json!({
3172 "label": "kkt", "iter": kiter,
3173 "dim": k.dim, "n_pos": k.n_pos, "n_neg": k.n_neg,
3174 "expected_neg": k.expected_neg, "inertia_correct": k.inertia_correct,
3175 "delta_w": k.delta_w, "delta_c": k.delta_c, "status": k.status,
3176 "matrix": matrix,
3177 });
3178 return match write_json_and_open("kkt", kiter, &payload) {
3179 Ok((path, viewer)) => CmdOut::ok(vec![format!(
3180 "wrote {path} (KKT system, iter {kiter}); opened with `{viewer}`"
3181 )])
3182 .with_data(serde_json::json!({"path": path, "viewer": viewer})),
3183 Err(e) => CmdOut::err(e),
3184 };
3185 }
3186 if target == "L" {
3191 if as_nlp(ctx).is_none() {
3192 return nlp_only("viz L");
3193 }
3194 match ctx.kkt_l_factor() {
3195 Some((n, perm, l_irn, l_jcn, l_vals)) => {
3196 let kiter = ctx.kkt_captured_iter().unwrap_or_else(|| ctx.iter());
3198 let payload = serde_json::json!({
3199 "label": "L", "iter": kiter, "n": n, "perm": perm,
3200 "l_irn": l_irn, "l_jcn": l_jcn, "l_vals": l_vals,
3201 "format": "strict_lower_1based_permuted",
3202 });
3203 return match write_json_and_open("L", kiter, &payload) {
3204 Ok((path, viewer)) => CmdOut::ok(vec![format!(
3205 "wrote {path} (L factor, iter {kiter}); opened with `{viewer}`"
3206 )])
3207 .with_data(serde_json::json!({"path": path, "viewer": viewer})),
3208 Err(e) => CmdOut::err(e),
3209 };
3210 }
3211 None => {
3212 return CmdOut::err(
3213 "L factor not captured here — nothing factored yet (iter 0), \
3214 or the debugger is detached. `step` once to capture.",
3215 );
3216 }
3217 }
3218 }
3219 let (label, vals) = if is_block(ctx, target) {
3221 match ctx.block(target) {
3222 Some(v) => (target.to_string(), v),
3223 None => return CmdOut::err(format!("no data for block `{target}`")),
3224 }
3225 } else if let Some(blk) = target.strip_prefix("d").filter(|b| is_block(ctx, b)) {
3226 match ctx.delta_block(blk) {
3227 Some(v) => (format!("d{blk}"), v),
3228 None => return CmdOut::err(format!("no search direction for `d{blk}`")),
3229 }
3230 } else {
3231 return CmdOut::err(format!("don't know how to visualize `{target}`"));
3232 };
3233 match write_and_open(&label, ctx.iter(), &vals) {
3234 Ok((path, viewer)) => CmdOut::ok(vec![format!(
3235 "wrote {} ({} values); opened with `{}`",
3236 path,
3237 vals.len(),
3238 viewer
3239 )])
3240 .with_data(serde_json::json!({"path": path, "viewer": viewer, "n": vals.len()})),
3241 Err(e) => CmdOut::err(e),
3242 }
3243 }
3244
3245 fn emit_pause(&self, ctx: &dyn DebugState, reason: Option<&str>) {
3249 let terminal = matches!(ctx.checkpoint(), Checkpoint::Terminated);
3250 match self.mode {
3251 DebugMode::Repl => {
3252 if terminal {
3253 eprintln!(
3254 "\n── pounce-dbg ── TERMINATED ({}) iter {} obj={:.6e} inf_pr={:.2e} inf_du={:.2e}",
3255 ctx.status().unwrap_or("?"),
3256 ctx.iter(),
3257 ctx.objective(),
3258 ctx.inf_pr(),
3259 ctx.inf_du(),
3260 );
3261 } else {
3262 let resto = if self.in_restoration {
3263 " [restoration]"
3264 } else {
3265 ""
3266 };
3267 eprintln!(
3268 "\n── pounce-dbg ── iter {} @{}{} mu={:.3e} obj={:.6e} inf_pr={:.2e} inf_du={:.2e}",
3269 ctx.iter(),
3270 ctx.checkpoint().as_str(),
3271 resto,
3272 ctx.mu(),
3273 ctx.objective(),
3274 ctx.inf_pr(),
3275 ctx.inf_du(),
3276 );
3277 }
3278 if let Some(r) = reason {
3279 eprintln!(" ↳ {r}");
3280 }
3281 for w in &self.watches {
3282 let out = self.cmd_print(&[w.as_str()], ctx);
3283 if out.ok {
3284 for l in &out.lines {
3285 eprintln!(" watch {l}");
3286 }
3287 } else {
3288 eprintln!(" watch {w}: (n/a)");
3292 }
3293 }
3294 }
3295 DebugMode::Json => {
3296 let watches: Vec<serde_json::Value> = self
3297 .watches
3298 .iter()
3299 .map(|w| {
3300 let out = self.cmd_print(&[w.as_str()], ctx);
3301 serde_json::json!({"expr": w, "ok": out.ok, "output": out.lines, "data": out.data})
3302 })
3303 .collect();
3304 let dims: serde_json::Map<String, serde_json::Value> = ctx
3305 .block_dims()
3306 .into_iter()
3307 .map(|(n, d)| (n.to_string(), serde_json::json!(d)))
3308 .collect();
3309 let conds: Vec<String> = self.conds.iter().map(|c| c.raw.clone()).collect();
3310 let mut ev = serde_json::json!({
3311 "event": "pause",
3312 "checkpoint": ctx.checkpoint().as_str(),
3313 "status": ctx.status(),
3314 "in_restoration": self.in_restoration,
3315 "dims": dims,
3316 "breakpoints": self.breaks,
3317 "conditions": conds,
3318 "reason": reason,
3319 "watches": watches,
3320 });
3321 insert_metric_fields(&mut ev, ctx);
3324 emit_json(&ev);
3325 }
3326 }
3327 }
3328
3329 fn emit_progress_event(&self, ctx: &dyn DebugState) {
3334 let mut ev = serde_json::json!({ "event": "progress" });
3335 insert_metric_fields(&mut ev, ctx);
3337 emit_json(&ev);
3338 }
3339
3340 fn emit_result(&self, command: &str, out: &CmdOut, req_id: Option<&serde_json::Value>) {
3343 match self.mode {
3344 DebugMode::Repl => {
3345 let stderr = std::io::stderr();
3346 let mut h = stderr.lock();
3347 for l in &out.lines {
3348 let _ = writeln!(h, "{l}");
3349 }
3350 if !out.ok {
3351 let _ = writeln!(h, "(error)");
3352 }
3353 }
3354 DebugMode::Json => {
3355 let ev = serde_json::json!({
3356 "event": "result",
3357 "request_id": req_id,
3358 "command": command,
3359 "ok": out.ok,
3360 "output": out.lines,
3361 "data": out.data,
3362 });
3363 emit_json(&ev);
3364 }
3365 }
3366 }
3367
3368 fn emit_hello(&self, ctx: &dyn DebugState) {
3379 let nlp = as_nlp(ctx).is_some();
3380 let viz: &[&str] = if nlp {
3382 &["block", "delta", "kkt", "L"]
3383 } else {
3384 &["block", "delta"]
3385 };
3386 let ev = serde_json::json!({
3387 "event": "hello",
3388 "protocol": "pounce-dbg/1",
3389 "pounce_version": env!("CARGO_PKG_VERSION"),
3390 "capabilities": {
3391 "inspect": true,
3392 "mutate_iterate": true,
3393 "mutate_mu": nlp,
3396 "conditional_breakpoints": "compound",
3397 "request_ids": true,
3398 "viz": viz,
3399 "save": true,
3400 "load": nlp,
3401 "sweep": nlp && self.restart.is_some(),
3402 "kkt_inspect": nlp,
3403 "equations": self.equation_book.is_some(),
3406 "diagnose": nlp,
3408 "structural_diagnose": nlp && self.structure_book.is_some(),
3411 "llm_assist": true,
3412 "rewind": "primal_dual",
3413 "resolve": nlp && self.restart.is_some(),
3414 "terminal_checkpoint": true,
3415 "interruptible": self.interruptible,
3416 "progress_events": self.emit_progress,
3418 "async_pause": "checkpoint",
3419 "pause_command": true,
3422 },
3423 "checkpoints": CHECKPOINTS,
3424 "events": EVENTS,
3425 "commands": COMMANDS,
3426 "blocks": block_names(ctx),
3427 "metrics": METRICS,
3428 });
3429 emit_json(&ev);
3430 }
3431
3432 fn ensure_editor(&mut self) {
3436 if !matches!(self.mode, DebugMode::Repl)
3437 || self.editor.is_some()
3438 || !std::io::stdin().is_terminal()
3439 {
3440 return;
3441 }
3442 let mut ed: Editor<DbgHelper, FileHistory> = match Editor::new() {
3443 Ok(e) => e,
3444 Err(_) => return,
3445 };
3446 ed.set_helper(Some(DbgHelper {
3447 reg: self.reg.clone(),
3448 }));
3449 let path = std::env::var_os("HOME")
3450 .or_else(|| std::env::var_os("USERPROFILE"))
3451 .map(|h| PathBuf::from(h).join(".pounce_dbg_history"));
3452 if let Some(p) = &path {
3453 let _ = ed.load_history(p);
3454 }
3455 self.hist_path = path;
3456 self.editor = Some(ed);
3457 }
3458
3459 fn on_prompt_interrupt(&mut self) -> String {
3464 self.prompt_interrupts += 1;
3465 if self.prompt_interrupts >= 2 {
3466 self.prompt_interrupts = 0;
3467 eprintln!("(quitting — Ctrl-C)");
3468 "quit".to_string()
3469 } else {
3470 eprintln!("(Ctrl-C — press again, or `quit`/Ctrl-D, to stop the solve)");
3471 String::new()
3472 }
3473 }
3474
3475 fn next_command_line(&mut self) -> Option<String> {
3479 if let Some(q) = &self.script_queue {
3483 let cmd = q.borrow_mut().pop_front();
3484 if let Some(c) = &cmd {
3485 let _ = writeln!(std::io::stderr(), "pounce-dbg> {c}");
3486 }
3487 return cmd;
3488 }
3489 if let DebugMode::Repl = self.mode {
3490 if let Some(ed) = self.editor.as_mut() {
3491 return match ed.readline("pounce-dbg> ") {
3492 Ok(l) => {
3493 self.prompt_interrupts = 0;
3494 let _ = ed.add_history_entry(l.as_str());
3495 if let Some(p) = &self.hist_path {
3496 let _ = ed.save_history(p);
3497 }
3498 Some(l)
3499 }
3500 Err(ReadlineError::Interrupted) => Some(self.on_prompt_interrupt()),
3505 Err(ReadlineError::Eof) => None,
3507 Err(_) => None,
3508 };
3509 }
3510 let _ = write!(std::io::stderr(), "pounce-dbg> ");
3511 let _ = std::io::stderr().flush();
3512 return read_stdin_line();
3513 }
3514 self.pump.get_or_insert_with(StdinPump::start).next()
3517 }
3518}
3519
3520fn read_stdin_line() -> Option<String> {
3522 let mut line = String::new();
3523 match std::io::stdin().read_line(&mut line) {
3524 Ok(0) => None,
3525 Ok(_) => Some(line),
3526 Err(_) => None,
3527 }
3528}
3529
3530fn rank_residuals(mut entries: Vec<Residual>, k: usize) -> Vec<Residual> {
3538 entries.sort_by(|a, b| {
3539 b.value
3540 .abs()
3541 .partial_cmp(&a.value.abs())
3542 .unwrap_or(std::cmp::Ordering::Equal)
3543 });
3544 entries.truncate(k);
3545 entries
3546}
3547
3548fn render_rank_report(
3559 rep: &RankReport,
3560 names: &Option<SplitNames>,
3561 equations: Option<&EquationBook>,
3562 iter: i32,
3563) -> (Vec<String>, serde_json::Value) {
3564 let m = rep.n_rows();
3565 let n = rep.n_cols;
3566 let mut lines = vec![
3567 format!("equality Jacobian J_c: {m} row(s) × {n} column(s)"),
3568 format!(
3569 "numerical rank = {} / {} (deficiency {})",
3570 rep.rank,
3571 m,
3572 rep.deficiency()
3573 ),
3574 format!(
3575 "σ_max = {:.3e} σ_min = {:.3e} cond = {} (rank tol τ = {:.3e})",
3576 rep.sigma_max(),
3577 rep.sigma_min(),
3578 fmt_cond(rep.cond),
3579 rep.tol
3580 ),
3581 ];
3582
3583 let shown: Vec<String> = rep
3585 .singular_values
3586 .iter()
3587 .take(MAX_SINGULAR_VALUES_SHOWN)
3588 .map(|s| format!("{s:.3e}"))
3589 .collect();
3590 let tail = if rep.singular_values.len() > MAX_SINGULAR_VALUES_SHOWN {
3591 " …"
3592 } else {
3593 ""
3594 };
3595 lines.push(format!("singular values: [{}{tail}]", shown.join(", ")));
3596
3597 if rep.is_rank_deficient() {
3598 lines.push(format!(
3599 "rank-deficient: {} equation(s) lie in the near-null space \
3600 (linearly dependent / redundant) — the source of δ_c regularization:",
3601 rep.deficiency()
3602 ));
3603 let mut shown_any_eq = false;
3604 for c in rep.culprits.iter().take(MAX_RANK_CULPRITS) {
3605 let row = &rep.rows[c.row];
3606 let label = rank_row_label(row, names);
3607 lines.push(format!(" {label} (participation {:.2})", c.weight));
3608 if let Some(eq) = culprit_equation(row, names, equations) {
3612 lines.push(format!(" {eq}"));
3613 shown_any_eq = true;
3614 }
3615 }
3616 if rep.culprits.len() > MAX_RANK_CULPRITS {
3617 lines.push(format!(
3618 " … and {} more",
3619 rep.culprits.len() - MAX_RANK_CULPRITS
3620 ));
3621 }
3622 if !shown_any_eq {
3625 lines.push("inspect a row with `print equation <name>` to see its terms".to_string());
3626 }
3627 } else {
3628 lines.push("J_c has full row rank at this iterate.".to_string());
3629 }
3630
3631 let culprits_json: Vec<serde_json::Value> = rep
3632 .culprits
3633 .iter()
3634 .map(|c| {
3635 let row = &rep.rows[c.row];
3636 serde_json::json!({
3637 "row": c.row,
3638 "kind": row.kind.tag(),
3639 "index": row.index,
3640 "name": rank_row_name(row, names),
3641 "label": rank_row_label(row, names),
3642 "weight": c.weight,
3643 "equation": culprit_equation(row, names, equations),
3644 })
3645 })
3646 .collect();
3647
3648 let data = serde_json::json!({
3649 "iter": iter,
3650 "n_rows": m,
3651 "n_cols": n,
3652 "rank": rep.rank,
3653 "deficiency": rep.deficiency(),
3654 "rank_deficient": rep.is_rank_deficient(),
3655 "sigma_max": rep.sigma_max(),
3656 "sigma_min": rep.sigma_min(),
3657 "cond": cond_json(rep.cond),
3658 "tol": rep.tol,
3659 "singular_values": rep.singular_values,
3660 "culprits": culprits_json,
3661 });
3662
3663 (lines, data)
3664}
3665
3666fn culprit_equation(
3673 row: &RankRow,
3674 names: &Option<SplitNames>,
3675 equations: Option<&EquationBook>,
3676) -> Option<String> {
3677 let book = equations?;
3678 let name = rank_row_name(row, names)?;
3679 let i = book.resolve(&name)?;
3680 Some(book.equations.get(i)?.clone())
3681}
3682
3683fn rank_row_name(row: &RankRow, names: &Option<SplitNames>) -> Option<String> {
3688 let r = Residual {
3689 kind: row.kind,
3690 index: row.index,
3691 value: 0.0,
3692 };
3693 resid_name(&r, names).map(|s| s.to_string())
3694}
3695
3696fn rank_row_label(row: &RankRow, names: &Option<SplitNames>) -> String {
3699 match rank_row_name(row, names) {
3700 Some(name) => format!("{}[{}]", row.kind.tag(), name),
3701 None => format!("{}[{}]", row.kind.tag(), row.index),
3702 }
3703}
3704
3705fn fmt_cond(cond: f64) -> String {
3708 if cond.is_finite() {
3709 format!("{cond:.3e}")
3710 } else {
3711 "inf (σ_min = 0)".to_string()
3712 }
3713}
3714
3715fn cond_json(cond: f64) -> serde_json::Value {
3718 if cond.is_finite() {
3719 serde_json::json!(cond)
3720 } else {
3721 serde_json::Value::Null
3722 }
3723}
3724
3725fn resid_name<'a>(r: &Residual, names: &'a Option<SplitNames>) -> Option<&'a str> {
3726 let n = names.as_ref()?;
3727 let pool = match r.kind {
3728 ResidKind::Eq => &n.eq,
3729 ResidKind::Ineq | ResidKind::DualS => &n.ineq,
3730 ResidKind::DualX => &n.x_var,
3731 };
3732 pool.get(r.index).and_then(|o| o.as_deref())
3733}
3734
3735fn worst_named(resids: Vec<Residual>, names: &Option<SplitNames>) -> Option<(String, f64)> {
3739 let top = rank_residuals(resids, 1);
3740 let r = top.first()?;
3741 let label = match resid_name(r, names) {
3742 Some(name) => format!("{}[{}]", r.kind.tag(), name),
3743 None => format!("{}[{}]", r.kind.tag(), r.index),
3744 };
3745 Some((label, r.value))
3746}
3747
3748pub fn print_open_banner(mode: DebugMode) {
3752 if !matches!(mode, DebugMode::Repl) {
3753 return;
3754 }
3755 let color = std::io::stderr().is_terminal() && std::env::var_os("NO_COLOR").is_none();
3756 let paint = |r: u8, g: u8, b: u8, bold: bool, s: &str| -> String {
3757 if color {
3758 let w = if bold { "1;" } else { "" };
3759 format!("\x1b[{w}38;2;{r};{g};{b}m{s}\x1b[0m")
3760 } else {
3761 s.to_string()
3762 }
3763 };
3764 let orange = |s: &str| paint(0xE8, 0x7A, 0x1E, true, s);
3766 let gold = |s: &str| paint(0xFF, 0xB0, 0x00, true, s);
3767 let dim = |s: &str| paint(0x7A, 0x7E, 0x88, false, s);
3768 let item = |key: &str, gloss: &str| format!("{} {}", orange(key), dim(gloss));
3770
3771 let err = std::io::stderr();
3772 let mut h = err.lock();
3773 let _ = writeln!(h);
3774 for row in crate::print::logo_rows(color) {
3777 let _ = writeln!(h, " {row}");
3778 }
3779 let _ = writeln!(h);
3780 let _ = writeln!(
3781 h,
3782 " {} {}",
3783 gold("interior-point debugger"),
3784 dim(&format!(
3785 "· pounce {} · pdb for the IPM",
3786 env!("CARGO_PKG_VERSION")
3787 ))
3788 );
3789 let _ = writeln!(h);
3790 let _ = writeln!(
3792 h,
3793 " {} {} {} {} {}",
3794 item("s", "step"),
3795 item("c", "continue"),
3796 item("b", "N break"),
3797 item("r", "N run"),
3798 item("q", "quit"),
3799 );
3800 let _ = writeln!(
3801 h,
3802 " {} {} {} {} {}",
3803 item("p", "x print"),
3804 item("i", "info"),
3805 item("set", "x[i] v"),
3806 item("watch", "x"),
3807 item("viz", "kkt"),
3808 );
3809 let _ = writeln!(
3810 h,
3811 " {} {} {}",
3812 dim("type"),
3813 gold("help"),
3814 dim("for all commands · `ask` to consult Claude · Ctrl-C breaks in"),
3815 );
3816 let _ = writeln!(h);
3817}
3818
3819fn is_pause_command(line: &str) -> bool {
3822 parse_command(line, DebugMode::Json).command.trim() == "pause"
3823}
3824
3825struct StdinPump {
3830 inner: std::sync::Arc<(
3831 std::sync::Mutex<VecDeque<Option<String>>>,
3832 std::sync::Condvar,
3833 )>,
3834}
3835
3836impl StdinPump {
3837 fn start() -> Self {
3838 let inner = std::sync::Arc::new((
3839 std::sync::Mutex::new(VecDeque::new()),
3840 std::sync::Condvar::new(),
3841 ));
3842 let w = std::sync::Arc::clone(&inner);
3843 std::thread::spawn(move || {
3844 use std::io::BufRead;
3845 let stdin = std::io::stdin();
3846 let mut lock = stdin.lock();
3847 let (m, cv) = &*w;
3848 loop {
3849 let mut line = String::new();
3850 let item = match lock.read_line(&mut line) {
3851 Ok(0) | Err(_) => None, Ok(_) => Some(line),
3853 };
3854 let done = item.is_none();
3855 m.lock()
3856 .unwrap_or_else(std::sync::PoisonError::into_inner)
3857 .push_back(item);
3858 cv.notify_one();
3859 if done {
3860 break;
3861 }
3862 }
3863 });
3864 Self { inner }
3865 }
3866
3867 fn next(&self) -> Option<String> {
3869 let (m, cv) = &*self.inner;
3870 let mut q = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
3871 loop {
3872 match q.front() {
3873 None => {
3874 q = cv
3875 .wait(q)
3876 .unwrap_or_else(std::sync::PoisonError::into_inner)
3877 }
3878 Some(None) => return None, Some(Some(_)) => return q.pop_front().flatten(),
3880 }
3881 }
3882 }
3883
3884 fn try_take_pause(&self) -> bool {
3887 let (m, _) = &*self.inner;
3888 let mut q = m.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
3889 if let Some(Some(front)) = q.front() {
3890 if is_pause_command(front) {
3891 q.pop_front();
3892 return true;
3893 }
3894 }
3895 false
3896 }
3897}
3898
3899impl DebugHook for SolverDebugger {
3900 fn wants_kkt_capture(&self) -> bool {
3904 !self.detached
3905 }
3906
3907 fn arm(&mut self) {
3911 self.step = true;
3912 self.detached = false;
3913 self.pause_iters = true;
3914 self.pause_terminal = true;
3915 }
3916
3917 fn at_checkpoint(&mut self, ctx: &mut dyn DebugState) -> DebugAction {
3918 if matches!(self.mode, DebugMode::Json) && !self.hello_sent {
3921 self.emit_hello(&*ctx);
3922 self.hello_sent = true;
3923 }
3924 if let Checkpoint::Terminated = ctx.checkpoint() {
3928 if self.sweep.is_some() {
3932 if let Some(c) = as_nlp(ctx) {
3935 if let Some(action) = self.drive_sweep(c) {
3936 return action;
3937 }
3938 }
3939 }
3940 let failed = ctx.status().map(|s| !is_success_status(s)).unwrap_or(false);
3941 let should =
3942 self.pause_terminal && !self.detached && (!self.terminal_only_on_error || failed);
3943 if !should {
3944 return DebugAction::Resume;
3945 }
3946 self.ensure_editor();
3947 self.emit_pause(ctx, None);
3948 return self.prompt_loop(ctx);
3949 }
3950
3951 let cp = ctx.checkpoint();
3952 match cp {
3954 Checkpoint::PreRestoration => self.in_restoration = true,
3955 Checkpoint::PostRestoration => self.in_restoration = false,
3956 _ => {}
3957 }
3958 let is_iter_start = matches!(cp, Checkpoint::IterStart);
3959
3960 if is_iter_start {
3964 if let Some(snap) = ctx.snapshot() {
3965 self.snapshots.insert(ctx.iter(), snap);
3966 while self.snapshots.len() > SNAPSHOT_CAP {
3967 let Some(&oldest) = self.snapshots.keys().next() else {
3968 break;
3969 };
3970 self.snapshots.remove(&oldest);
3971 }
3972 }
3973 self.update_mu_stall(ctx.mu());
3975 }
3976
3977 let mut reason: Option<String> = None;
3981 let mut pause = self.sub_step || self.stop_at.contains(cp.as_str());
3982
3983 if let Some(ev) = self.matched_event(ctx) {
3987 pause = true;
3988 reason = Some(format!("event: {ev}"));
3989 }
3990
3991 if is_iter_start {
3992 if self.interruptible && interrupt::take() {
3993 pause = true;
3994 reason = Some("interrupt (Ctrl-C)".into());
3995 }
3996 if let Some(p) = self.pump.as_ref() {
3999 if p.try_take_pause() {
4000 pause = true;
4001 reason = Some("pause (requested)".into());
4002 }
4003 }
4004 if self.pause_iters {
4005 if self.should_pause(ctx.iter()) {
4006 pause = true;
4007 }
4008 if let Some(c) = self.matched_condition(ctx) {
4009 pause = true;
4010 reason = Some(c);
4011 }
4012 }
4013 if let Some(w) = self.matched_watchpoint(ctx) {
4016 pause = true;
4017 reason = Some(format!("watchpoint: {w}"));
4018 }
4019 }
4020
4021 if !pause {
4022 if is_iter_start && self.emit_progress && matches!(self.mode, DebugMode::Json) {
4026 self.emit_progress_event(ctx);
4027 }
4028 return DebugAction::Resume;
4029 }
4030 self.step = false;
4032 self.sub_step = false;
4033 self.emit_pause(ctx, reason.as_deref());
4034
4035 if is_iter_start {
4039 if let Some(cmds) = self.bp_commands.get(&ctx.iter()).cloned() {
4040 for c in cmds {
4041 let out = self.dispatch(&c, ctx);
4042 self.emit_result(&c, &out, None);
4043 match out.flow {
4044 Flow::Resume => return DebugAction::Resume,
4045 Flow::Stop => return DebugAction::Stop,
4046 Flow::Stay => {}
4047 }
4048 }
4049 }
4050 }
4051
4052 self.ensure_editor();
4053 self.prompt_loop(ctx)
4054 }
4055}
4056
4057impl SolverDebugger {
4058 fn prompt_loop(&mut self, ctx: &mut dyn DebugState) -> DebugAction {
4060 if let Some(path) = self.pending_script.take() {
4063 let out = self.cmd_source(&[path.as_str()], ctx);
4064 self.emit_result("source", &out, None);
4065 match out.flow {
4066 Flow::Resume => return DebugAction::Resume,
4067 Flow::Stop => return DebugAction::Stop,
4068 Flow::Stay => {}
4069 }
4070 }
4071 loop {
4072 let line = match self.next_command_line() {
4073 Some(l) => l,
4074 None => {
4075 return match self.mode {
4080 DebugMode::Repl => {
4081 self.detached = true;
4082 DebugAction::Resume
4083 }
4084 DebugMode::Json => DebugAction::Stop,
4085 };
4086 }
4087 };
4088 let parsed = parse_command(&line, self.mode);
4089 let cmd = parsed.command.trim().to_string();
4090 if cmd.is_empty() {
4091 continue;
4092 }
4093 let out = self.dispatch(&cmd, ctx);
4094 self.emit_result(&cmd, &out, parsed.id.as_ref());
4095 match out.flow {
4096 Flow::Stay => continue,
4097 Flow::Resume => return DebugAction::Resume,
4098 Flow::Stop => return DebugAction::Stop,
4099 }
4100 }
4101 }
4102}
4103
4104struct ParsedCmd {
4108 command: String,
4109 id: Option<serde_json::Value>,
4110}
4111
4112fn tokenize_quoted(line: &str) -> Vec<String> {
4118 let mut out = Vec::new();
4119 let mut cur = String::new();
4120 let mut in_quote = false;
4121 let mut has_tok = false;
4122 for c in line.chars() {
4123 match c {
4124 '"' => {
4125 in_quote = !in_quote;
4126 has_tok = true; }
4128 c if c.is_whitespace() && !in_quote => {
4129 if has_tok {
4130 out.push(std::mem::take(&mut cur));
4131 has_tok = false;
4132 }
4133 }
4134 c => {
4135 cur.push(c);
4136 has_tok = true;
4137 }
4138 }
4139 }
4140 if has_tok {
4141 out.push(cur);
4142 }
4143 out
4144}
4145
4146fn parse_command(line: &str, mode: DebugMode) -> ParsedCmd {
4150 let trimmed = line.trim();
4151 if let DebugMode::Json = mode {
4152 if trimmed.starts_with('{') {
4153 if let Ok(v) = serde_json::from_str::<serde_json::Value>(trimmed) {
4154 let cmd = v.get("cmd").and_then(|c| c.as_str()).unwrap_or("");
4155 let mut s = cmd.to_string();
4156 if let Some(args) = v.get("args").and_then(|a| a.as_array()) {
4157 for a in args {
4158 s.push(' ');
4159 let tok = a
4160 .as_str()
4161 .map(str::to_string)
4162 .unwrap_or_else(|| a.to_string());
4163 if tok.contains(char::is_whitespace) {
4166 s.push('"');
4167 s.push_str(&tok);
4168 s.push('"');
4169 } else {
4170 s.push_str(&tok);
4171 }
4172 }
4173 }
4174 return ParsedCmd {
4175 command: s,
4176 id: v.get("id").cloned(),
4177 };
4178 }
4179 }
4180 }
4181 ParsedCmd {
4182 command: trimmed.to_string(),
4183 id: None,
4184 }
4185}
4186
4187fn emit_json(v: &serde_json::Value) {
4188 let stdout = std::io::stdout();
4189 let mut h = stdout.lock();
4190 let _ = writeln!(h, "{v}");
4191 let _ = h.flush();
4192}
4193
4194fn as_nlp<'a>(ctx: &'a dyn DebugState) -> Option<&'a DebugCtx> {
4199 ctx.as_any().and_then(|a| a.downcast_ref::<DebugCtx>())
4200}
4201
4202fn as_nlp_mut<'a>(ctx: &'a mut dyn DebugState) -> Option<&'a mut DebugCtx> {
4204 ctx.as_any_mut().and_then(|a| a.downcast_mut::<DebugCtx>())
4205}
4206
4207fn nlp_only(cmd: &str) -> CmdOut {
4209 CmdOut::err(format!(
4210 "`{cmd}` is only available for the NLP solver (not the convex/conic solver)"
4211 ))
4212}
4213
4214fn block_names(ctx: &dyn DebugState) -> Vec<&'static str> {
4219 ctx.block_dims().into_iter().map(|(n, _)| n).collect()
4220}
4221
4222fn is_block(ctx: &dyn DebugState, name: &str) -> bool {
4224 block_names(ctx).iter().any(|n| *n == name)
4225}
4226
4227fn fmt_vec(name: &str, v: &[f64]) -> String {
4228 const MAX: usize = 12;
4229 if v.len() <= MAX {
4230 format!(
4231 "{name} = [{}]",
4232 v.iter()
4233 .map(|x| format!("{x:.6e}"))
4234 .collect::<Vec<_>>()
4235 .join(", ")
4236 )
4237 } else {
4238 let head = v[..MAX]
4239 .iter()
4240 .map(|x| format!("{x:.6e}"))
4241 .collect::<Vec<_>>()
4242 .join(", ");
4243 format!("{name} = [{head}, … ({} total)]", v.len())
4244 }
4245}
4246
4247fn type_str(t: OptionType) -> &'static str {
4248 match t {
4249 OptionType::OT_Number => "Number",
4250 OptionType::OT_Integer => "Integer",
4251 OptionType::OT_String => "String",
4252 OptionType::OT_Unknown => "Unknown",
4253 }
4254}
4255
4256fn default_str(d: &DefaultValue) -> String {
4257 match d {
4258 DefaultValue::None => "-".into(),
4259 DefaultValue::Number(v) => format!("{v}"),
4260 DefaultValue::Integer(v) => format!("{v}"),
4261 DefaultValue::String(s) => s.clone(),
4262 }
4263}
4264
4265fn write_and_open(label: &str, iter: i32, vals: &[f64]) -> Result<(String, String), String> {
4270 let payload = serde_json::json!({"label": label, "iter": iter, "values": vals});
4271 write_json_and_open(label, iter, &payload)
4272}
4273
4274fn build_ask_prompt(ctx: &dyn DebugState, question: &str) -> String {
4277 use std::fmt::Write as _;
4278 let mut p = String::new();
4279 p.push_str(
4280 "You are helping debug a paused run of POUNCE, a pure-Rust interior-point \
4281 optimization solver whose NLP core is ported from Ipopt. The solve is \
4282 stopped at a debugger checkpoint. \
4283 Use the state below to answer concisely and suggest concrete next steps \
4284 (options to try, what to inspect). State:\n\n",
4285 );
4286 let _ = writeln!(p, "checkpoint = {}", ctx.checkpoint().as_str());
4287 if let Some(s) = ctx.status() {
4288 let _ = writeln!(p, "status = {s}");
4289 }
4290 let _ = writeln!(p, "iter = {}", ctx.iter());
4291 let _ = writeln!(p, "mu = {:.6e}", ctx.mu());
4292 let _ = writeln!(p, "objective = {:.8e}", ctx.objective());
4293 let _ = writeln!(p, "inf_pr = {:.6e}", ctx.inf_pr());
4294 let _ = writeln!(p, "inf_du = {:.6e}", ctx.inf_du());
4295 let _ = writeln!(p, "nlp_error = {:.6e}", ctx.nlp_error());
4296 let (ap, ad) = ctx.alpha();
4297 let _ = writeln!(p, "alpha_pr = {ap:.4e}, alpha_du = {ad:.4e}");
4298 let _ = writeln!(p, "ls_trials = {}", ctx.ls_count());
4299 let dims: Vec<String> = ctx
4300 .block_dims()
4301 .into_iter()
4302 .map(|(n, d)| format!("{n}:{d}"))
4303 .collect();
4304 let _ = writeln!(p, "dims = {}", dims.join(" "));
4305 if let Some(k) = ctx.kkt() {
4306 let _ = writeln!(
4307 p,
4308 "kkt = dim {} inertia n+={} n-={} (expected n-={}, {}) delta_w={:.3e} delta_c={:.3e} status={}",
4309 k.dim,
4310 k.n_pos,
4311 k.n_neg,
4312 k.expected_neg,
4313 if k.inertia_correct {
4314 "correct"
4315 } else {
4316 "WRONG"
4317 },
4318 k.delta_w,
4319 k.delta_c,
4320 k.status
4321 );
4322 }
4323 let _ = write!(p, "\nQuestion: {question}\n");
4324 p
4325}
4326
4327const LLM_PROVIDERS: &[&str] = &["claude", "codex", "gemini", "llm"];
4333
4334fn llm_preset(name: &str, prompt: &str) -> Option<(String, Vec<String>, bool)> {
4335 match name {
4336 "claude" => Some(("claude".to_string(), vec!["-p".to_string()], true)),
4338 "codex" => Some((
4340 "codex".to_string(),
4341 vec!["exec".to_string(), prompt.to_string()],
4342 false,
4343 )),
4344 "gemini" => Some((
4346 "gemini".to_string(),
4347 vec!["-p".to_string(), prompt.to_string()],
4348 false,
4349 )),
4350 "llm" => Some(("llm".to_string(), vec![prompt.to_string()], false)),
4352 _ => None,
4353 }
4354}
4355
4356fn llm_command(prompt: &str) -> (String, Vec<String>, bool) {
4362 let raw = std::env::var("POUNCE_DBG_LLM").unwrap_or_default();
4363 let tmpl = raw.trim();
4364 if tmpl.is_empty() {
4365 return llm_preset("claude", prompt).expect("claude is a known provider");
4367 }
4368 if !tmpl.contains(char::is_whitespace) {
4371 if let Some(preset) = llm_preset(tmpl, prompt) {
4372 return preset;
4373 }
4374 }
4375 let mut parts = tmpl
4377 .split_whitespace()
4378 .map(str::to_string)
4379 .collect::<Vec<_>>();
4380 let prog = parts.remove(0);
4381 let mut substituted = false;
4382 for a in parts.iter_mut() {
4383 if a.contains("{}") {
4384 *a = a.replace("{}", prompt);
4385 substituted = true;
4386 }
4387 }
4388 (prog, parts, !substituted)
4389}
4390
4391fn run_llm(prompt: &str) -> Result<String, String> {
4394 use std::io::Write as _;
4395 use std::process::{Command, Stdio};
4396 let (prog, args, on_stdin) = llm_command(prompt);
4397 let mut cmd = Command::new(&prog);
4398 cmd.args(&args)
4399 .stdout(Stdio::piped())
4400 .stderr(Stdio::piped());
4401 cmd.stdin(if on_stdin {
4402 Stdio::piped()
4403 } else {
4404 Stdio::null()
4405 });
4406 let mut child = cmd.spawn().map_err(|e| {
4407 if e.kind() == std::io::ErrorKind::NotFound {
4408 format!(
4412 "LLM CLI `{prog}` is not installed or not on PATH. Install it, \
4413 or set POUNCE_DBG_LLM to another provider \
4414 ({}) or a full command template (e.g. `my-llm --ask {{}}`).",
4415 LLM_PROVIDERS.join(" | ")
4416 )
4417 } else {
4418 format!("could not launch `{prog}`: {e}")
4419 }
4420 })?;
4421 if on_stdin {
4422 if let Some(mut si) = child.stdin.take() {
4424 let _ = si.write_all(prompt.as_bytes());
4425 }
4426 }
4427 let out = child
4428 .wait_with_output()
4429 .map_err(|e| format!("`{prog}` failed: {e}"))?;
4430 if !out.status.success() {
4431 let err = String::from_utf8_lossy(&out.stderr);
4432 return Err(format!(
4433 "`{prog}` exited with {}: {}",
4434 out.status,
4435 err.trim()
4436 ));
4437 }
4438 let reply = String::from_utf8_lossy(&out.stdout).trim().to_string();
4439 if reply.is_empty() {
4440 Err(format!("`{prog}` returned no output"))
4441 } else {
4442 Ok(reply)
4443 }
4444}
4445
4446fn write_json_and_open(
4449 label: &str,
4450 iter: i32,
4451 payload: &serde_json::Value,
4452) -> Result<(String, String), String> {
4453 let dir = std::env::temp_dir();
4454 let path = dir.join(format!("pounce-dbg-{label}-iter{iter}.json"));
4455 std::fs::write(&path, payload.to_string()).map_err(|e| format!("write failed: {e}"))?;
4456 let path_s = path.to_string_lossy().to_string();
4457
4458 let mut candidates: Vec<(String, Vec<String>, String)> = Vec::new();
4468 match std::env::var("POUNCE_DBG_VIEWER") {
4469 Ok(tmpl) if !tmpl.trim().is_empty() => {
4470 let mut parts = tmpl
4471 .split_whitespace()
4472 .map(String::from)
4473 .collect::<Vec<_>>();
4474 let prog = parts.remove(0);
4475 let mut replaced = false;
4476 for a in parts.iter_mut() {
4477 if a.contains("{}") {
4478 *a = a.replace("{}", &path_s);
4479 replaced = true;
4480 }
4481 }
4482 if !replaced {
4483 parts.push(path_s.clone());
4484 }
4485 candidates.push((prog, parts, path_s.clone()));
4486 }
4487 _ => {
4488 candidates.push((
4489 "pounce-dbg-viz".to_string(),
4490 vec![path_s.clone()],
4491 path_s.clone(),
4492 ));
4493 let opener = if cfg!(target_os = "macos") {
4494 "open"
4495 } else {
4496 "xdg-open"
4497 };
4498 let artifact = write_html_viz(label, iter, payload).unwrap_or_else(|_| path_s.clone());
4501 candidates.push((opener.to_string(), vec![artifact.clone()], artifact));
4502 }
4503 }
4504
4505 let mut last_err = String::new();
4506 for (program, args, artifact) in &candidates {
4507 match std::process::Command::new(program).args(args).spawn() {
4508 Ok(_) => return Ok((artifact.clone(), format!("{program} {}", args.join(" ")))),
4509 Err(e) => last_err = format!("`{program}`: {e}"),
4510 }
4511 }
4512 Err(format!(
4513 "wrote {path_s} but could not launch a viewer ({last_err}). \
4514 Install the interactive viewer (`pip install 'pounce-solver[viz]'`) \
4515 or set POUNCE_DBG_VIEWER, e.g. `python my_plot.py {{}}`."
4516 ))
4517}
4518
4519fn write_html_viz(label: &str, iter: i32, payload: &serde_json::Value) -> Result<String, String> {
4526 let dir = std::env::temp_dir();
4527 let path = dir.join(format!("pounce-dbg-{label}-iter{iter}.html"));
4528 let html = VIZ_HTML_TEMPLATE.replace("__PAYLOAD__", &payload.to_string());
4529 std::fs::write(&path, html).map_err(|e| format!("write failed: {e}"))?;
4530 Ok(path.to_string_lossy().to_string())
4531}
4532
4533const VIZ_HTML_TEMPLATE: &str = r##"<!doctype html>
4538<html lang="en"><head><meta charset="utf-8">
4539<title>pounce-dbg viz</title>
4540<style>
4541 html,body{margin:0;background:#0e1116;color:#d6dae0;
4542 font:13px/1.5 -apple-system,BlinkMacSystemFont,"SF Mono",Menlo,monospace}
4543 .wrap{padding:18px 20px;max-width:880px;margin:0 auto}
4544 h1{font-size:15px;margin:0 0 4px;font-weight:600}
4545 .sub{color:#7d8694;margin:0 0 12px}
4546 .stats{color:#9aa4b2;white-space:pre-wrap;margin:0 0 14px;
4547 background:#161b22;border:1px solid #21262d;border-radius:6px;padding:10px 12px}
4548 canvas{background:#161b22;border:1px solid #30363d;border-radius:6px;
4549 max-width:100%;height:auto;image-rendering:pixelated}
4550 .legend{margin-top:10px;color:#9aa4b2}
4551 .pos{color:#4ea1ff}.neg{color:#ff6b6b}.bad{color:#ff6b6b;font-weight:600}
4552 .ok{color:#56d364;font-weight:600}
4553</style></head><body><div class="wrap">
4554<h1 id="title">pounce-dbg</h1>
4555<div class="sub" id="sub"></div>
4556<div class="stats" id="stats"></div>
4557<canvas id="c" width="820" height="820"></canvas>
4558<div class="legend" id="legend"></div>
4559</div>
4560<script>
4561const D = __PAYLOAD__;
4562const cv = document.getElementById('c');
4563const ctx = cv.getContext('2d');
4564const $ = id => document.getElementById(id);
4565const fmt = x => (x===null||x===undefined) ? '—'
4566 : (Math.abs(x) >= 1e4 || (x!==0 && Math.abs(x) < 1e-3) ? x.toExponential(3) : (+x).toPrecision(6));
4567
4568function clearCanvas(){ ctx.fillStyle='#161b22'; ctx.fillRect(0,0,cv.width,cv.height); }
4569
4570function spy(irn, jcn, vals, dim, symmetric, title){
4571 $('sub').textContent = title;
4572 clearCanvas();
4573 const W=cv.width, H=cv.height, pad=42;
4574 const span=Math.max(1, dim);
4575 const cell=(Math.min(W,H)-2*pad)/span;
4576 const px=Math.max(0.7, cell);
4577 // frame + light grid ticks
4578 ctx.strokeStyle='#30363d'; ctx.lineWidth=1;
4579 ctx.strokeRect(pad-0.5, pad-0.5, span*cell+1, span*cell+1);
4580 ctx.fillStyle='#6e7681'; ctx.font='11px monospace';
4581 ctx.fillText('0', pad-12, pad+9);
4582 ctx.fillText(String(dim), pad+span*cell-8, pad-8);
4583 ctx.fillText('row', pad-34, pad+span*cell/2);
4584 ctx.fillText('col', pad+span*cell/2-8, pad-22);
4585 let nnz=0;
4586 for(let k=0;k<irn.length;k++){
4587 const i=irn[k]-1, j=jcn[k]-1, v=vals?vals[k]:1;
4588 ctx.fillStyle = v>=0 ? 'rgba(78,161,255,0.92)' : 'rgba(255,107,107,0.92)';
4589 ctx.fillRect(pad+j*cell, pad+i*cell, px, px); nnz++;
4590 if(symmetric && i!==j){ ctx.fillRect(pad+i*cell, pad+j*cell, px, px); nnz++; }
4591 }
4592 $('legend').innerHTML =
4593 `<span class="pos">■</span> positive <span class="neg">■</span> negative`
4594 + ` · ${dim}×${dim}, ${nnz} plotted nonzeros`
4595 + (symmetric ? ' (lower triangle mirrored)' : '');
4596}
4597
4598function bars(values, title){
4599 $('sub').textContent = title;
4600 clearCanvas();
4601 const W=cv.width, H=cv.height, pad=42;
4602 const n=values.length;
4603 const maxAbs=Math.max(1e-300, ...values.map(v=>Math.abs(v)));
4604 const x0=pad, y0=H-pad, plotW=W-2*pad, plotH=H-2*pad, mid=pad+plotH/2;
4605 const bw=Math.max(0.7, plotW/Math.max(1,n));
4606 // zero axis
4607 ctx.strokeStyle='#30363d'; ctx.beginPath();
4608 ctx.moveTo(pad, mid); ctx.lineTo(W-pad, mid); ctx.stroke();
4609 ctx.fillStyle='#6e7681'; ctx.font='11px monospace';
4610 ctx.fillText('+'+fmt(maxAbs), 4, pad+10);
4611 ctx.fillText('-'+fmt(maxAbs), 4, H-pad-2);
4612 ctx.fillText('0', 4, mid+4);
4613 for(let k=0;k<n;k++){
4614 const v=values[k], h=(Math.abs(v)/maxAbs)*(plotH/2);
4615 ctx.fillStyle = v>=0 ? 'rgba(78,161,255,0.92)' : 'rgba(255,107,107,0.92)';
4616 if(v>=0) ctx.fillRect(pad+k*bw, mid-h, bw, h);
4617 else ctx.fillRect(pad+k*bw, mid, bw, h);
4618 }
4619 $('legend').innerHTML = `${n} components · max |val| = ${fmt(maxAbs)}`;
4620}
4621
4622const lbl = D.label || 'viz';
4623const iter = (D.iter!==undefined) ? D.iter : '?';
4624$('title').textContent = `pounce-dbg · viz ${lbl} · iter ${iter}`;
4625
4626if(D.matrix && D.matrix.irn){
4627 const m=D.matrix;
4628 const inertia = (D.inertia_correct===false)
4629 ? `<span class="bad">WRONG</span>` : `<span class="ok">correct</span>`;
4630 $('stats').innerHTML =
4631 `KKT augmented system dim=${D.dim}\n`+
4632 `inertia n+=${D.n_pos} n-=${D.n_neg} (expected n-=${D.expected_neg}, ${inertia})\n`+
4633 `regularization delta_w=${fmt(D.delta_w)} delta_c=${fmt(D.delta_c)}\n`+
4634 `factorization status: ${D.status}`;
4635 spy(m.irn, m.jcn, m.vals, m.dim, true, 'sparsity pattern (sign-colored)');
4636} else if(D.l_irn){
4637 $('stats').textContent =
4638 `LDLᵀ factor n=${D.n} nnz(L)=${D.l_irn.length} format=${D.format||''}`;
4639 spy(D.l_irn, D.l_jcn, D.l_vals, D.n, false, 'L factor sparsity (permuted, strict lower)');
4640} else if(D.values){
4641 $('stats').textContent = `vector ${lbl} length=${D.values.length}`;
4642 bars(D.values, 'component magnitudes (zero-centered)');
4643} else {
4644 $('stats').textContent = 'unrecognized payload — raw JSON:\n'+JSON.stringify(D,null,2);
4645}
4646</script></body></html>
4647"##;
4648
4649#[cfg(test)]
4650mod tests {
4651 use super::*;
4652
4653 fn dbg(mode: DebugMode) -> SolverDebugger {
4654 SolverDebugger::new(mode, None)
4655 }
4656
4657 #[test]
4658 fn json_command_object_is_flattened() {
4659 assert_eq!(
4660 parse_command("{\"cmd\":\"print x\"}", DebugMode::Json).command,
4661 "print x"
4662 );
4663 let p = parse_command(
4664 "{\"cmd\":\"set\",\"args\":[\"x[0]\",\"1.5\"],\"id\":7}",
4665 DebugMode::Json,
4666 );
4667 assert_eq!(p.command, "set x[0] 1.5");
4668 assert_eq!(p.id, Some(serde_json::json!(7)));
4670 let s = parse_command("step\n", DebugMode::Json);
4672 assert_eq!(s.command, "step");
4673 assert!(s.id.is_none());
4674 assert_eq!(
4675 parse_command(" print x \n", DebugMode::Repl).command,
4676 "print x"
4677 );
4678 }
4679
4680 #[test]
4681 fn pauses_at_first_checkpoint_then_only_when_rearmed() {
4682 let mut d = dbg(DebugMode::Repl);
4683 assert!(d.should_pause(0));
4685 d.step = false;
4687 assert!(!d.should_pause(1));
4688 assert!(!d.should_pause(2));
4689 }
4690
4691 #[test]
4692 fn breakpoints_and_run_to_arm_pauses() {
4693 let mut d = dbg(DebugMode::Repl);
4694 d.step = false;
4695 d.breaks = vec![3, 7];
4696 assert!(!d.should_pause(2));
4697 assert!(d.should_pause(3));
4698 assert!(d.should_pause(7));
4699 d.run_to = Some(5);
4701 assert!(!d.should_pause(4));
4702 assert!(d.should_pause(5));
4703 assert_eq!(d.run_to, None);
4704 assert!(!d.should_pause(6));
4705 }
4706
4707 #[test]
4708 fn atom_parses_metric_op_threshold() {
4709 let a = Atom::parse("mu<1e-4").unwrap();
4710 assert_eq!(a.metric, Metric::Mu);
4711 assert_eq!(a.op, CmpOp::Lt);
4712 assert_eq!(a.rhs, 1e-4);
4713
4714 let a = Atom::parse("inf_pr<=1e-6").unwrap();
4716 assert_eq!(a.metric, Metric::InfPr);
4717 assert_eq!(a.op, CmpOp::Le);
4718
4719 let a = Atom::parse("iter==10").unwrap();
4720 assert_eq!(a.metric, Metric::Iter);
4721 assert_eq!(a.op, CmpOp::Eq);
4722 assert_eq!(a.rhs, 10.0);
4723 }
4724
4725 struct MinimalState;
4731 impl DebugState for MinimalState {
4732 fn checkpoint(&self) -> Checkpoint {
4733 Checkpoint::IterStart
4734 }
4735 fn iter(&self) -> i32 {
4736 7
4737 }
4738 fn mu(&self) -> f64 {
4739 1e-3
4740 }
4741 fn objective(&self) -> f64 {
4742 42.0
4743 }
4744 fn inf_pr(&self) -> f64 {
4745 1e-4
4746 }
4747 fn inf_du(&self) -> f64 {
4748 2e-4
4749 }
4750 fn complementarity(&self) -> f64 {
4751 5e-4
4752 }
4753 fn alpha(&self) -> (f64, f64) {
4754 (1.0, 1.0)
4755 }
4756 fn block_dims(&self) -> Vec<(&'static str, usize)> {
4757 vec![]
4758 }
4759 fn block(&self, _name: &str) -> Option<Vec<f64>> {
4760 None
4761 }
4762 fn delta_block(&self, _name: &str) -> Option<Vec<f64>> {
4763 None
4764 }
4765 }
4766
4767 #[test]
4773 fn metric_fields_match_advertised_vocabulary() {
4774 let fields = metric_fields(&MinimalState);
4775
4776 let names: Vec<&str> = fields.iter().map(|(n, _)| *n).collect();
4778 assert_eq!(names, METRICS);
4779
4780 for &name in METRICS {
4783 assert!(
4784 name == "iter" || Metric::parse(name).is_some(),
4785 "METRICS entry `{name}` has no matching Metric arm"
4786 );
4787 }
4788
4789 let map: std::collections::HashMap<_, _> = fields.into_iter().collect();
4790 assert_eq!(map["iter"], serde_json::json!(7));
4792 assert_eq!(map["objective"], serde_json::json!(42.0));
4793 assert_eq!(map["nlp_error"], serde_json::Value::Null);
4796 }
4797
4798 #[test]
4799 fn atom_parse_rejects_garbage() {
4800 assert!(Atom::parse("inf_pr 1e-6").is_err()); assert!(Atom::parse("bogus<1").is_err()); assert!(Atom::parse("mu<abc").is_err()); }
4804
4805 #[test]
4806 fn compound_condition_parses_and_evaluates_left_to_right() {
4807 let c = Condition::parse("mu<1e-4&&inf_pr>1e-3").unwrap();
4809 assert_eq!(c.rest.len(), 1);
4810 assert_eq!(c.rest[0].0, Join::And);
4811
4812 let c = Condition::parse("iter>10&&(inf_du>1e-2||obj<0)").unwrap();
4814 assert_eq!(c.rest.len(), 2);
4815 assert_eq!(c.rest[0].0, Join::And);
4816 assert_eq!(c.rest[1].0, Join::Or);
4817 assert_eq!(c.raw, "iter>10&&inf_du>1e-2||obj<0");
4818
4819 assert!(Condition::parse("mu<1e-4&&bogus>0").is_err());
4821 }
4822
4823 #[test]
4824 fn completion_is_context_sensitive() {
4825 let c = completion_candidates(None, "", "co");
4827 assert!(c.contains(&"continue".to_string()));
4828 assert!(c.contains(&"complete".to_string()));
4829 assert!(!c.contains(&"step".to_string()));
4830
4831 let c = completion_candidates(None, "set ", "");
4833 assert!(c.contains(&"mu".to_string()));
4834 assert!(c.contains(&"opt".to_string()));
4835 assert!(c.contains(&"x".to_string()));
4836
4837 let c = completion_candidates(None, "break if ", "inf");
4839 assert!(c.contains(&"inf_pr".to_string()));
4840 assert!(c.contains(&"inf_du".to_string()));
4841 assert!(!c.contains(&"mu".to_string()));
4842
4843 let c = completion_candidates(None, "print ", "");
4845 assert!(c.contains(&"x".to_string()));
4846 assert!(c.contains(&"obj".to_string()));
4847 }
4848
4849 #[test]
4850 fn cmp_op_truth_table() {
4851 assert!(CmpOp::Lt.eval(1.0, 2.0));
4852 assert!(!CmpOp::Lt.eval(2.0, 2.0));
4853 assert!(CmpOp::Le.eval(2.0, 2.0));
4854 assert!(CmpOp::Gt.eval(3.0, 2.0));
4855 assert!(CmpOp::Ge.eval(2.0, 2.0));
4856 assert!(CmpOp::Eq.eval(2.0, 2.0));
4857 assert!(!CmpOp::Eq.eval(2.0, 2.5));
4858 }
4859
4860 #[test]
4861 fn interrupt_is_consumed_once() {
4862 interrupt::set_pending_for_test();
4863 assert!(interrupt::take(), "first take sees the pending Ctrl-C");
4864 assert!(!interrupt::take(), "second take is clear (consumed once)");
4865 }
4866
4867 #[test]
4868 fn on_interrupt_constructor_runs_free_but_interruptible() {
4869 let d = SolverDebugger::on_interrupt(DebugMode::Repl, None);
4870 assert!(!d.pause_iters, "on-interrupt does not pause each iter");
4871 assert!(!d.pause_terminal, "on-interrupt does not pause at terminal");
4872 assert!(d.interruptible, "on-interrupt honors Ctrl-C");
4873 assert!(!d.step, "on-interrupt starts un-armed");
4874 }
4875
4876 #[test]
4877 fn coffee_easter_egg_prints_art_but_stays_hidden() {
4878 let d = SolverDebugger::new(DebugMode::Repl, None);
4879 let out = d.cmd_coffee();
4880 assert!(out.ok);
4881 assert!(out.lines.len() > 5, "multi-line art");
4882 assert!(
4883 out.lines.iter().any(|l| l.contains("COFFEE")),
4884 "the mug says COFFEE"
4885 );
4886 assert!(
4888 !COMMANDS.contains(&"coffee"),
4889 "hidden from help/complete/Tab"
4890 );
4891 assert!(
4893 out.lines.iter().all(|l| !l.contains('\x1b')),
4894 "no color when stderr isn't a TTY"
4895 );
4896 }
4897
4898 #[test]
4899 fn double_ctrl_c_at_prompt_quits_single_cancels_line() {
4900 let mut d = SolverDebugger::new(DebugMode::Repl, None);
4901 assert_eq!(d.on_prompt_interrupt(), "");
4903 assert_eq!(d.on_prompt_interrupt(), "quit");
4905 assert_eq!(d.on_prompt_interrupt(), "");
4907 d.prompt_interrupts = 0;
4910 assert_eq!(d.on_prompt_interrupt(), "", "fresh streak after a command");
4911 }
4912
4913 #[test]
4914 fn stop_at_accepts_names_and_aliases() {
4915 let mut d = SolverDebugger::new(DebugMode::Repl, None);
4916 assert!(d.cmd_stop_at(&["after_search_dir"]).ok);
4917 assert!(d.stop_at.contains("after_search_dir"));
4918 assert!(d.cmd_stop_at(&["mu"]).ok);
4920 assert!(d.stop_at.contains("after_mu"));
4921 assert!(d.cmd_stop_at(&["kkt"]).ok);
4922 assert!(d.stop_at.contains("after_search_dir"));
4923 assert!(!d.cmd_stop_at(&["bogus"]).ok);
4925 assert!(d.cmd_stop_at(&["clear"]).ok);
4927 assert!(d.stop_at.is_empty());
4928 }
4929
4930 #[test]
4931 fn llm_command_defaults_and_overrides() {
4932 unsafe { std::env::remove_var("POUNCE_DBG_LLM") };
4935 let (prog, args, on_stdin) = llm_command("hi");
4936 assert_eq!(prog, "claude");
4937 assert_eq!(args, vec!["-p".to_string()]);
4938 assert!(on_stdin);
4939
4940 unsafe { std::env::set_var("POUNCE_DBG_LLM", "mytool --ask {}") };
4943 let (prog, args, on_stdin) = llm_command("why");
4944 assert_eq!(prog, "mytool");
4945 assert_eq!(args, vec!["--ask".to_string(), "why".to_string()]);
4946 assert!(!on_stdin);
4947
4948 unsafe { std::env::set_var("POUNCE_DBG_LLM", "llm -m gpt") };
4951 let (_, _, on_stdin) = llm_command("q");
4952 assert!(on_stdin);
4953
4954 unsafe { std::env::set_var("POUNCE_DBG_LLM", "codex") };
4959 let (prog, args, on_stdin) = llm_command("why is mu stuck");
4960 assert_eq!(prog, "codex");
4961 assert_eq!(
4962 args,
4963 vec!["exec".to_string(), "why is mu stuck".to_string()]
4964 );
4965 assert!(!on_stdin); unsafe { std::env::set_var("POUNCE_DBG_LLM", "gemini") };
4969 let (prog, args, _) = llm_command("q");
4970 assert_eq!(prog, "gemini");
4971 assert_eq!(args, vec!["-p".to_string(), "q".to_string()]);
4972
4973 unsafe { std::env::set_var("POUNCE_DBG_LLM", "llm") };
4975 let (prog, args, _) = llm_command("q");
4976 assert_eq!(prog, "llm");
4977 assert_eq!(args, vec!["q".to_string()]);
4978
4979 unsafe { std::env::set_var("POUNCE_DBG_LLM", "claude") };
4983 let (prog, args, on_stdin) = llm_command("q");
4984 assert_eq!(prog, "claude");
4985 assert_eq!(args, vec!["-p".to_string()]);
4986 assert!(on_stdin);
4987
4988 unsafe { std::env::set_var("POUNCE_DBG_LLM", "mytool") };
4992 let (prog, args, on_stdin) = llm_command("q");
4993 assert_eq!(prog, "mytool");
4994 assert!(args.is_empty());
4995 assert!(on_stdin);
4996
4997 unsafe { std::env::set_var("POUNCE_DBG_LLM", "pounce-no-such-llm-xyz") };
5001 let err = run_llm("hello").unwrap_err();
5002 assert!(err.contains("not installed or not on PATH"), "{err}");
5003 assert!(err.contains("codex"), "{err}");
5004
5005 unsafe { std::env::remove_var("POUNCE_DBG_LLM") };
5007 }
5008
5009 #[test]
5010 fn detach_disables_all_pausing() {
5011 let mut d = dbg(DebugMode::Repl);
5012 d.detached = true;
5013 d.step = true;
5014 d.breaks = vec![1];
5015 assert!(!d.should_pause(0));
5016 assert!(!d.should_pause(1));
5017 }
5018
5019 #[test]
5020 fn kkt_capture_tracks_attached_state() {
5021 let mut d = dbg(DebugMode::Repl);
5024 assert!(d.wants_kkt_capture());
5025 d.detached = true;
5026 assert!(!d.wants_kkt_capture());
5027 }
5028
5029 fn resid(kind: ResidKind, index: usize, value: f64) -> Residual {
5030 Residual { kind, index, value }
5031 }
5032
5033 #[test]
5034 fn rank_residuals_sorts_by_magnitude_and_truncates() {
5035 use ResidKind::*;
5036 let entries = vec![
5037 resid(Eq, 0, -0.5),
5038 resid(Ineq, 1, 3.0),
5039 resid(DualX, 2, -7.0),
5040 resid(DualS, 3, 1.0),
5041 ];
5042 let top = rank_residuals(entries, 2);
5043 assert_eq!(top.len(), 2);
5044 assert_eq!(top[0].value, -7.0);
5046 assert_eq!(top[0].kind, DualX);
5047 assert_eq!(top[1].value, 3.0);
5048 assert_eq!(top[1].kind, Ineq);
5049 }
5050
5051 #[test]
5052 fn rank_residuals_k_zero_and_k_over_len() {
5053 use ResidKind::*;
5054 let entries = vec![resid(Eq, 0, 1.0), resid(Ineq, 1, 2.0)];
5055 assert!(rank_residuals(entries.clone(), 0).is_empty());
5056 let all = rank_residuals(entries, 99);
5058 assert_eq!(all.len(), 2);
5059 assert_eq!(all[0].value, 2.0);
5060 }
5061
5062 #[test]
5063 fn rank_residuals_is_stable_on_magnitude_ties() {
5064 use ResidKind::*;
5065 let entries = vec![
5067 resid(Ineq, 5, -2.0),
5068 resid(Eq, 1, 2.0),
5069 resid(DualX, 9, -2.0),
5070 ];
5071 let top = rank_residuals(entries, 3);
5072 assert_eq!(
5073 top.iter().map(|r| r.kind).collect::<Vec<_>>(),
5074 vec![Ineq, Eq, DualX]
5075 );
5076 }
5077
5078 fn split_names_fixture() -> SplitNames {
5079 SplitNames {
5080 x_var: vec![Some("T_reactor".into()), None],
5081 eq: vec![Some("mass_balance".into()), Some("energy_balance".into())],
5082 ineq: vec![Some("pressure_cap".into())],
5083 }
5084 }
5085
5086 #[test]
5087 fn resid_name_maps_each_kind_to_its_pool() {
5088 use ResidKind::*;
5089 let names = Some(split_names_fixture());
5090 assert_eq!(
5093 resid_name(&resid(Eq, 1, 0.0), &names),
5094 Some("energy_balance")
5095 );
5096 assert_eq!(
5097 resid_name(&resid(Ineq, 0, 0.0), &names),
5098 Some("pressure_cap")
5099 );
5100 assert_eq!(
5101 resid_name(&resid(DualS, 0, 0.0), &names),
5102 Some("pressure_cap")
5103 );
5104 assert_eq!(resid_name(&resid(DualX, 0, 0.0), &names), Some("T_reactor"));
5105 assert_eq!(resid_name(&resid(DualX, 1, 0.0), &names), None);
5107 assert_eq!(resid_name(&resid(Eq, 9, 0.0), &names), None);
5108 assert_eq!(resid_name(&resid(Eq, 0, 0.0), &None), None);
5110 }
5111
5112 #[test]
5113 fn worst_named_picks_largest_and_labels_it() {
5114 use ResidKind::*;
5115 let names = Some(split_names_fixture());
5116 let resids = vec![resid(Eq, 0, 0.5), resid(Eq, 1, -3.2), resid(Ineq, 0, 1.1)];
5118 assert_eq!(
5119 worst_named(resids, &names),
5120 Some(("c[energy_balance]".to_string(), -3.2))
5121 );
5122 let resids = vec![resid(DualX, 7, 9.0)];
5124 assert_eq!(
5125 worst_named(resids, &None),
5126 Some(("grad_x_L[7]".to_string(), 9.0))
5127 );
5128 assert_eq!(worst_named(vec![], &names), None);
5130 }
5131
5132 use pounce_algorithm::debug_rank::RankCulprit;
5133
5134 fn rank_report_fixture() -> RankReport {
5135 RankReport {
5138 rows: vec![
5139 RankRow {
5140 kind: ResidKind::Eq,
5141 index: 0,
5142 },
5143 RankRow {
5144 kind: ResidKind::Eq,
5145 index: 1,
5146 },
5147 ],
5148 n_cols: 3,
5149 singular_values: vec![2.0, 0.0],
5150 tol: 1e-15,
5151 rank: 1,
5152 cond: f64::INFINITY,
5153 culprits: vec![
5154 RankCulprit {
5155 row: 0,
5156 weight: 0.5,
5157 },
5158 RankCulprit {
5159 row: 1,
5160 weight: 0.5,
5161 },
5162 ],
5163 }
5164 }
5165
5166 #[test]
5167 fn render_rank_report_names_culprits_and_builds_json() {
5168 let names = Some(split_names_fixture());
5169 let rep = rank_report_fixture();
5170 let (lines, data) = render_rank_report(&rep, &names, None, 7);
5172
5173 let text = lines.join("\n");
5174 assert!(text.contains("2 row(s) × 3 column(s)"), "{text}");
5175 assert!(text.contains("numerical rank = 1 / 2"), "{text}");
5176 assert!(text.contains("inf (σ_min = 0)"), "{text}");
5178 assert!(text.contains("c[mass_balance]"), "{text}");
5180 assert!(text.contains("c[energy_balance]"), "{text}");
5181 assert!(text.contains("participation 0.50"), "{text}");
5182 assert!(text.contains("print equation"), "{text}");
5184
5185 assert_eq!(data["iter"], 7);
5188 assert_eq!(data["rank"], 1);
5189 assert_eq!(data["deficiency"], 1);
5190 assert_eq!(data["rank_deficient"], true);
5191 assert!(data["cond"].is_null(), "non-finite cond ⇒ null: {data}");
5192 assert_eq!(data["culprits"][0]["name"], "mass_balance");
5193 assert_eq!(data["culprits"][0]["label"], "c[mass_balance]");
5194 assert!(data["culprits"][0]["equation"].is_null());
5195 assert_eq!(data["culprits"][1]["name"], "energy_balance");
5196 }
5197
5198 #[test]
5199 fn render_rank_report_prints_culprit_equations_inline() {
5200 let names = Some(split_names_fixture());
5201 let rep = rank_report_fixture();
5202 let book = EquationBook::new(
5205 vec!["mass_balance".into(), "energy_balance".into()],
5206 vec![
5207 "x[0] + x[1] - 10 = 0".into(),
5208 "T_reactor*flow - Q = 0".into(),
5209 ],
5210 );
5211 let (lines, data) = render_rank_report(&rep, &names, Some(&book), 7);
5212
5213 let text = lines.join("\n");
5214 assert!(text.contains("x[0] + x[1] - 10 = 0"), "{text}");
5217 assert!(text.contains("T_reactor*flow - Q = 0"), "{text}");
5218 assert!(!text.contains("inspect a row with"), "{text}");
5220
5221 assert_eq!(data["culprits"][0]["equation"], "x[0] + x[1] - 10 = 0");
5223 assert_eq!(data["culprits"][1]["equation"], "T_reactor*flow - Q = 0");
5224 }
5225
5226 #[test]
5227 fn render_rank_report_full_rank_reports_positive_signal() {
5228 let rep = RankReport {
5229 rows: vec![
5230 RankRow {
5231 kind: ResidKind::Eq,
5232 index: 0,
5233 },
5234 RankRow {
5235 kind: ResidKind::Eq,
5236 index: 1,
5237 },
5238 ],
5239 n_cols: 3,
5240 singular_values: vec![2.0, 1.0],
5241 tol: 1e-15,
5242 rank: 2,
5243 cond: 2.0,
5244 culprits: vec![],
5245 };
5246 let (lines, data) = render_rank_report(&rep, &None, None, 3);
5247 let text = lines.join("\n");
5248 assert!(text.contains("full row rank"), "{text}");
5249 assert!(!text.contains("rank-deficient"), "{text}");
5250 assert_eq!(data["rank_deficient"], false);
5251 assert_eq!(data["cond"], 2.0);
5252 assert_eq!(data["culprits"].as_array().map(|a| a.len()), Some(0));
5253 }
5254
5255 #[test]
5256 fn print_equation_resolves_by_name_index_and_errors() {
5257 let mut d = dbg(DebugMode::Repl);
5258 let out = d.cmd_print_equation(&[]);
5260 assert!(!out.ok);
5261 assert!(out.lines[0].contains("needs an .nl model"));
5262
5263 d.set_equation_book(EquationBook::new(
5264 vec!["mass_balance".into(), String::new()],
5265 vec!["x[0] + x[1] = 10".into(), "x[0] - x[1] <= 2".into()],
5266 ));
5267
5268 let out = d.cmd_print_equation(&[]);
5270 assert!(out.ok);
5271 assert!(out.lines[0].contains("2 constraint equation"));
5272
5273 let out = d.cmd_print_equation(&["mass_balance"]);
5275 assert!(out.ok);
5276 assert_eq!(out.lines[0], "mass_balance: x[0] + x[1] = 10");
5277
5278 let out = d.cmd_print_equation(&["1"]);
5280 assert!(out.ok);
5281 assert_eq!(out.lines[0], "c[1]: x[0] - x[1] <= 2");
5282
5283 let out = d.cmd_print_equation(&["nope"]);
5285 assert!(!out.ok);
5286 assert!(out.lines[0].contains("no constraint named or indexed"));
5287 }
5288
5289 fn eq_inc(n_vars: usize, eq_row_inner_idx: Vec<usize>, rows: &[&[usize]]) -> EqualityIncidence {
5293 let mut adj_ptr = vec![0usize];
5294 let mut vars = Vec::new();
5295 for r in rows {
5296 let mut v = r.to_vec();
5297 v.sort_unstable();
5298 v.dedup();
5299 vars.extend_from_slice(&v);
5300 adj_ptr.push(vars.len());
5301 }
5302 EqualityIncidence {
5303 n_vars,
5304 eq_row_inner_idx,
5305 adj_ptr,
5306 vars,
5307 }
5308 }
5309
5310 #[test]
5311 fn structural_singularity_names_overdetermined_equations() {
5312 let inc = eq_inc(2, vec![0, 1, 2], &[&[0, 1], &[0, 1], &[0, 1]]);
5318 let book = StructureBook::new(
5319 inc,
5320 vec!["balance_a".into(), "balance_b".into(), "balance_c".into()],
5321 vec!["flow".into(), "temp".into()],
5322 );
5323 let f = book.findings();
5324 assert_eq!(f.len(), 1);
5325 let (sev, code, msg) = &f[0];
5326 assert_eq!(*sev, "warning");
5327 assert_eq!(*code, "structural_singularity");
5328 assert!(msg.contains("balance_a"), "msg: {msg}");
5329 assert!(msg.contains("balance_b"), "msg: {msg}");
5330 assert!(msg.contains("balance_c"), "msg: {msg}");
5331 assert!(msg.contains("flow") && msg.contains("temp"), "msg: {msg}");
5332 assert!(msg.contains("≥1"), "msg: {msg}");
5333 }
5334
5335 #[test]
5336 fn structural_findings_silent_when_well_posed_and_fall_back_to_indices() {
5337 let inc = eq_inc(2, vec![0, 1], &[&[0], &[1]]);
5341 let book = StructureBook::new(inc, vec![], vec![]);
5342 assert!(book.findings().is_empty());
5343
5344 let inc = eq_inc(1, vec![0, 1, 3], &[&[0], &[0], &[0]]);
5348 let book = StructureBook::new(inc, vec![], vec![]);
5349 let f = book.findings();
5350 assert_eq!(f.len(), 1);
5351 let msg = &f[0].2;
5352 assert!(
5353 msg.contains("c[0]") && msg.contains("c[1]") && msg.contains("c[3]"),
5354 "msg: {msg}"
5355 );
5356 }
5357
5358 #[test]
5359 fn structural_singularity_handles_empty_row_with_no_variables() {
5360 let inc = eq_inc(1, vec![0, 1], &[&[0], &[]]);
5363 let book = StructureBook::new(inc, vec!["real".into(), "ghost".into()], vec!["x".into()]);
5364 let f = book.findings();
5365 assert_eq!(f.len(), 1);
5366 let msg = &f[0].2;
5367 assert!(msg.contains("ghost"), "msg: {msg}");
5368 assert!(msg.contains("no variables"), "msg: {msg}");
5369 }
5370
5371 #[test]
5372 fn parse_floats_accepts_commas_whitespace_and_newlines() {
5373 assert_eq!(parse_floats("1, 2 ,3").unwrap(), vec![1.0, 2.0, 3.0]);
5374 assert_eq!(parse_floats("1\n2\n-3.5").unwrap(), vec![1.0, 2.0, -3.5]);
5375 assert_eq!(parse_floats(" 1.0 2e-1 ").unwrap(), vec![1.0, 0.2]);
5376 assert!(parse_floats("1, nope, 3").is_err());
5377 assert_eq!(parse_floats("").unwrap(), Vec::<f64>::new());
5378 }
5379
5380 #[test]
5381 fn jitter_start_zero_is_the_unperturbed_base_and_is_deterministic() {
5382 let base = vec![1.0, -2.0, 0.0];
5383 assert_eq!(jitter(&base, 0.1, 0), base);
5385 let a = jitter(&base, 0.1, 1);
5387 let b = jitter(&base, 0.1, 1);
5388 assert_eq!(a, b);
5389 assert_ne!(a, base);
5390 for (j, (&p, &x)) in a.iter().zip(&base).enumerate() {
5391 let bound = 0.1 * (x.abs() + 1.0);
5392 assert!(
5393 (p - x).abs() <= bound + 1e-12,
5394 "component {j} moved {} > bound {bound}",
5395 (p - x).abs()
5396 );
5397 }
5398 assert_ne!(jitter(&base, 0.1, 1), jitter(&base, 0.1, 2));
5400 }
5401
5402 #[test]
5403 fn sample_start_draws_inside_finite_boxes_and_jitters_unbounded() {
5404 let base = vec![1.0, 1.0, 0.5];
5405 let lo = vec![0.0, 0.0, -1.0];
5407 let hi = vec![2.0, f64::INFINITY, 1.0];
5408 let b = Some((lo.as_slice(), hi.as_slice()));
5409 assert_eq!(sample_start(&base, b, 0.1, 0), base);
5411 for k in 1..50 {
5412 let s = sample_start(&base, b, 0.1, k);
5413 assert!((0.0..=2.0).contains(&s[0]), "var0 {} out of [0,2]", s[0]);
5415 assert!((-1.0..=1.0).contains(&s[2]), "var2 {} out of [-1,1]", s[2]);
5416 let bound = 0.1 * (base[1].abs() + 1.0);
5418 assert!(
5419 (s[1] - base[1]).abs() <= bound + 1e-12,
5420 "var1 jitter exceeded"
5421 );
5422 }
5423 assert_eq!(
5425 sample_start(&base, b, 0.1, 7),
5426 sample_start(&base, b, 0.1, 7)
5427 );
5428 }
5429
5430 #[test]
5431 fn path_completion_lists_matching_files_with_dir_prefix() {
5432 let dir = std::env::temp_dir().join("pounce_dbg_complete_test");
5433 let _ = std::fs::remove_dir_all(&dir);
5434 std::fs::create_dir_all(&dir).unwrap();
5435 std::fs::write(dir.join("starts.txt"), "0,0\n").unwrap();
5436 std::fs::write(dir.join("start2.txt"), "1,1\n").unwrap();
5437 std::fs::write(dir.join("other.json"), "{}").unwrap();
5438 std::fs::create_dir_all(dir.join("subdir")).unwrap();
5439
5440 let p = dir.to_string_lossy().to_string();
5441 let mut got = path_candidates(&format!("{p}/start"));
5443 got.sort();
5444 assert_eq!(
5445 got,
5446 vec![format!("{p}/start2.txt"), format!("{p}/starts.txt")]
5447 );
5448 let got = path_candidates(&format!("{p}/sub"));
5450 assert_eq!(got, vec![format!("{p}/subdir/")]);
5451 assert_eq!(path_candidates(&format!("{p}/")).len(), 4);
5453 assert!(
5455 completion_candidates(None, "load", &format!("{p}/star"))
5456 .iter()
5457 .all(|c| c.contains("start"))
5458 );
5459
5460 let _ = std::fs::remove_dir_all(&dir);
5461 }
5462}