unfault 1.0.4

Unfault — a cognitive context engine for thoughtful engineers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
//! # Fault Injection Command
//!
//! Generates `fault run` commands (https://fault-project.com) for injecting
//! network-level failure scenarios against HTTP endpoints reachable from a
//! given function.
//!
//! ## Usage
//!
//! ```bash
//! # List all templates for an endpoint reachable from a function
//! unfault fault services/orders.py:validate_order
//!
//! # Generate a specific template
//! unfault fault services/orders.py:validate_order --template latency-normal
//!
//! # Egress mode: inject faults on outbound calls made by the function
//! unfault fault services/orders.py:validate_order --template blackhole --mode egress --url https://payments.example.com
//!
//! # Override local app URL and proxy port
//! unfault fault services/orders.py:validate_order --template mobile-3g --url http://127.0.0.1:8080 --port 9090
//! ```

use anyhow::Result;
use colored::Colorize;

use crate::exit_codes::*;

// ─────────────────────────────────────────────────────────────────────────────
// Egress target
// ─────────────────────────────────────────────────────────────────────────────

/// An outbound dependency discovered by walking the call graph forward from
/// the target function.
#[derive(Debug, Clone)]
pub struct EgressTarget {
    /// Human-readable label, e.g. "requests.get(…)" or "SQLAlchemy query"
    pub label: String,
    /// Best-effort upstream URL for the `fault run --upstream` flag.
    /// None when the URL could not be statically determined.
    pub upstream_url: Option<String>,
    /// Category — used to pick sensible defaults when URL is absent.
    pub kind: EgressKind,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EgressKind {
    Http,
    Database(DatabaseKind),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DatabaseKind {
    Postgres,
    Mysql,
    Other,
}

// ─────────────────────────────────────────────────────────────────────────────
// Template definitions
// ─────────────────────────────────────────────────────────────────────────────

/// All supported fault injection scenario templates, mirroring the VSCode extension.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FaultTemplate {
    LatencyNormal,
    LatencyPareto,
    LatencyWindow,
    JitterLight,
    JitterBidirectional,
    Bandwidth64k,
    Bandwidth48kLatency,
    Mobile3g,
    PacketLoss,
    PacketLossBurst,
    Blackhole,
    BlackholeWindow,
}

impl FaultTemplate {
    pub fn from_str(s: &str) -> Option<Self> {
        match s.to_lowercase().replace('_', "-").as_str() {
            "latency-normal" => Some(Self::LatencyNormal),
            "latency-pareto" => Some(Self::LatencyPareto),
            "latency-window" => Some(Self::LatencyWindow),
            "jitter-light" => Some(Self::JitterLight),
            "jitter-bidirectional" => Some(Self::JitterBidirectional),
            "bandwidth-64k" => Some(Self::Bandwidth64k),
            "bandwidth-48k-latency" => Some(Self::Bandwidth48kLatency),
            "mobile-3g" => Some(Self::Mobile3g),
            "packet-loss" => Some(Self::PacketLoss),
            "packet-loss-burst" => Some(Self::PacketLossBurst),
            "blackhole" => Some(Self::Blackhole),
            "blackhole-window" => Some(Self::BlackholeWindow),
            _ => None,
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::LatencyNormal => "latency-normal",
            Self::LatencyPareto => "latency-pareto",
            Self::LatencyWindow => "latency-window",
            Self::JitterLight => "jitter-light",
            Self::JitterBidirectional => "jitter-bidirectional",
            Self::Bandwidth64k => "bandwidth-64k",
            Self::Bandwidth48kLatency => "bandwidth-48k-latency",
            Self::Mobile3g => "mobile-3g",
            Self::PacketLoss => "packet-loss",
            Self::PacketLossBurst => "packet-loss-burst",
            Self::Blackhole => "blackhole",
            Self::BlackholeWindow => "blackhole-window",
        }
    }

    pub fn description(&self) -> &'static str {
        match self {
            Self::LatencyNormal => "350ms ± 50ms normal distribution latency",
            Self::LatencyPareto => "Pareto-distributed tail latency spikes",
            Self::LatencyWindow => {
                "Latency injection at 25%–75% of run duration (requires --duration)"
            }
            Self::JitterLight => "Light jitter: 30ms amplitude @ 5Hz",
            Self::JitterBidirectional => "Bidirectional jitter: 30ms @ 8Hz (both directions)",
            Self::Bandwidth64k => "Bandwidth throttle: 64 KBps download",
            Self::Bandwidth48kLatency => "48 KBps bandwidth + 200ms added latency",
            Self::Mobile3g => "Mobile 3G simulation: 48 KBps + 200ms + jitter",
            Self::PacketLoss => "Constant packet drop",
            Self::PacketLossBurst => "Packet loss at 25%–75% of run duration (requires --duration)",
            Self::Blackhole => "Blackhole: all traffic dropped (hang / timeout)",
            Self::BlackholeWindow => "Blackhole at 25%–75% of run duration (requires --duration)",
        }
    }

    /// Returns the `fault run` flags (excluding proxy/upstream/duration) for this template.
    pub fn fault_flags(&self, direction: &str) -> Vec<String> {
        match self {
            Self::LatencyNormal => vec![
                "--with-latency".into(),
                format!("--latency-direction {}", direction),
                "--latency-distribution normal".into(),
                "--latency-mean 350".into(),
                "--latency-stddev 50".into(),
            ],
            Self::LatencyPareto => vec![
                "--with-latency".into(),
                format!("--latency-direction {}", direction),
                "--latency-distribution pareto".into(),
                "--latency-shape 1.5".into(),
                "--latency-scale 20".into(),
            ],
            Self::LatencyWindow => vec![
                "--with-latency".into(),
                format!("--latency-direction {}", direction),
                "--latency-distribution normal".into(),
                "--latency-mean 500".into(),
                "--latency-stddev 100".into(),
                r#"--latency-sched "start:25%,duration:50%""#.into(),
            ],
            Self::JitterLight => vec![
                "--with-jitter".into(),
                "--jitter-amplitude 30".into(),
                "--jitter-frequency 5".into(),
            ],
            Self::JitterBidirectional => vec![
                "--with-jitter".into(),
                "--jitter-amplitude 30".into(),
                "--jitter-frequency 8".into(),
                "--jitter-direction both".into(),
            ],
            Self::Bandwidth64k => vec![
                "--with-bandwidth".into(),
                "--bandwidth-rate 64".into(),
                "--bandwidth-unit KBps".into(),
                "--bandwidth-direction ingress".into(),
            ],
            Self::Bandwidth48kLatency => vec![
                "--with-bandwidth".into(),
                "--bandwidth-rate 48".into(),
                "--bandwidth-unit KBps".into(),
                "--with-latency".into(),
                "--latency-direction both".into(),
                "--latency-distribution normal".into(),
                "--latency-mean 200".into(),
                "--latency-stddev 20".into(),
            ],
            Self::Mobile3g => vec![
                "--with-bandwidth".into(),
                "--bandwidth-rate 48".into(),
                "--bandwidth-unit KBps".into(),
                "--with-latency".into(),
                "--latency-direction both".into(),
                "--latency-distribution normal".into(),
                "--latency-mean 200".into(),
                "--latency-stddev 20".into(),
                "--with-jitter".into(),
                "--jitter-amplitude 30".into(),
                "--jitter-frequency 5".into(),
            ],
            Self::PacketLoss => vec![
                "--with-packet-loss".into(),
                format!("--packet-loss-direction {}", direction),
            ],
            Self::PacketLossBurst => vec![
                "--with-packet-loss".into(),
                format!("--packet-loss-direction {}", direction),
                r#"--packet-loss-sched "start:25%,duration:50%""#.into(),
            ],
            Self::Blackhole => vec![
                "--with-blackhole".into(),
                format!("--blackhole-direction {}", direction),
            ],
            Self::BlackholeWindow => vec![
                "--with-blackhole".into(),
                format!("--blackhole-direction {}", direction),
                r#"--blackhole-sched "start:25%,duration:50%""#.into(),
            ],
        }
    }

    pub fn all() -> &'static [FaultTemplate] {
        &[
            Self::LatencyNormal,
            Self::LatencyPareto,
            Self::LatencyWindow,
            Self::JitterLight,
            Self::JitterBidirectional,
            Self::Bandwidth64k,
            Self::Bandwidth48kLatency,
            Self::Mobile3g,
            Self::PacketLoss,
            Self::PacketLossBurst,
            Self::Blackhole,
            Self::BlackholeWindow,
        ]
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Command args
// ─────────────────────────────────────────────────────────────────────────────

#[derive(Debug)]
pub struct FaultArgs {
    /// Function to target in format file:function or just function_name
    pub function: String,
    /// Template name (optional; lists all if absent)
    pub template: Option<String>,
    /// Injection mode: "ingress" (default) or "egress"
    pub mode: String,
    /// Target URL.
    /// Ingress: local app base URL (default: http://127.0.0.1:8000).
    /// Egress: remote dependency base URL (required).
    pub url: Option<String>,
    /// Local proxy port (default: 9090)
    pub port: u16,
    /// Injection duration (default: 2m)
    pub duration: String,
    /// Workspace path (defaults to current directory)
    pub workspace_path: Option<String>,
    /// Verbose output
    pub verbose: bool,
}

// ─────────────────────────────────────────────────────────────────────────────
// Execute
// ─────────────────────────────────────────────────────────────────────────────

pub async fn execute(args: FaultArgs) -> Result<i32> {
    let workspace_path = match &args.workspace_path {
        Some(p) => std::path::PathBuf::from(p),
        None => std::env::current_dir()?,
    };

    // Parse file:function — keep both parts for scoped graph lookup.
    let (file_hint, function_name) = match args.function.split_once(':') {
        Some((file, func)) => (Some(file.to_string()), func.to_string()),
        None => (None, args.function.clone()),
    };

    // ── Build graph (with spinner) ────────────────────────────────────────────
    use indicatif::{ProgressBar, ProgressStyle};
    use std::time::Duration;

    let spinner = if !args.verbose {
        let pb = ProgressBar::new_spinner();
        pb.set_style(
            ProgressStyle::with_template("{spinner:.cyan} {msg}")
                .unwrap()
                .tick_strings(&["", "", "", "", "", "", "", "", "", ""]),
        );
        pb.set_message("Analysing call graph…");
        pb.enable_steady_tick(Duration::from_millis(80));
        Some(pb)
    } else {
        None
    };

    let (graph, semantics) = match crate::local_graph::build_analysis_graph_with_semantics(
        &workspace_path,
        args.verbose,
    ) {
        Ok(r) => r,
        Err(e) => {
            if let Some(pb) = spinner {
                pb.finish_and_clear();
            }
            eprintln!(
                "{} Failed to build code graph: {}",
                "Error:".red().bold(),
                e
            );
            return Ok(EXIT_ERROR);
        }
    };

    if let Some(pb) = &spinner {
        pb.finish_and_clear();
    }

    // ── Resolve HTTP routes via the code graph ────────────────────────────────
    let routes = resolve_routes(&graph, &function_name, file_hint.as_deref());

    // ── Resolve egress targets (outbound HTTP + DB calls) ────────────────────
    let egress_targets =
        resolve_egress_targets(&graph, &semantics, &function_name, file_hint.as_deref());

    // ── Template selection ────────────────────────────────────────────────────
    let templates: Vec<FaultTemplate> = match &args.template {
        Some(name) => match FaultTemplate::from_str(name) {
            Some(t) => vec![t],
            None => {
                eprintln!(
                    "{} Unknown template '{}'. Available templates:",
                    "Error:".red().bold(),
                    name
                );
                print_template_list();
                return Ok(EXIT_ERROR);
            }
        },
        None => FaultTemplate::all().to_vec(),
    };

    let proxy_port = args.port;
    let duration = &args.duration;
    let ingress_url = args
        .url
        .clone()
        .unwrap_or_else(|| "http://127.0.0.1:8000".to_string());

    // ── Print header ──────────────────────────────────────────────────────────
    println!();
    println!(
        "{} Fault injection scenarios for {}",
        "".bright_yellow(),
        function_name.bright_white().bold()
    );

    // ── INGRESS section ───────────────────────────────────────────────────────
    println!();
    println!("{}", "── Ingress".bold());
    println!("  Inject faults on inbound requests to this function.");
    println!();

    if !routes.is_empty() {
        println!("  Reachable routes:");
        for (method, path) in &routes {
            let method_colored = match method.as_str() {
                "GET" => method.bright_green(),
                "POST" => method.bright_yellow(),
                "PUT" | "PATCH" => method.bright_cyan(),
                "DELETE" => method.bright_red(),
                _ => method.normal(),
            };
            println!("    {} {}", method_colored, path);
        }
        println!();
        println!("  Send test requests through the proxy:");
        for (method, path) in &routes {
            println!(
                "    {}",
                format!(
                    "curl -i -X {} http://127.0.0.1:{}/{}",
                    method,
                    proxy_port,
                    path.trim_start_matches('/')
                )
                .bold()
            );
        }
    } else {
        println!(
            "  {} No HTTP routes found — generating commands for {}",
            "".cyan(),
            ingress_url.cyan()
        );
    }

    println!();
    println!("{}", "".repeat(60).dimmed());

    for template in &templates {
        println!();
        println!(
            "  {} {}",
            template.name().bright_white().bold(),
            format!("{}", template.description()).dimmed()
        );
        println!();
        let flags = template.fault_flags("ingress");
        let cmd = build_fault_command(&ingress_url, proxy_port, duration, &flags);
        println!("    {}", cmd.bright_blue());
    }

    // ── EGRESS section ────────────────────────────────────────────────────────
    if !egress_targets.is_empty() {
        println!();
        println!();
        println!("{}", "── Egress".bold());
        println!("  Inject faults on outbound calls made by this function.");

        for (i, target) in egress_targets.iter().enumerate() {
            let egress_port = proxy_port + 1 + i as u16;
            let upstream = target
                .upstream_url
                .clone()
                .unwrap_or_else(|| default_upstream(&target.kind));

            println!();
            println!("  {} {}", "".cyan(), target.label.bright_white());
            println!(
                "    Proxy: localhost:{}{}",
                egress_port.to_string().yellow(),
                upstream.cyan()
            );

            // Usage hint: how to wire the proxy
            let env_hint = match &target.kind {
                EgressKind::Http => format!("export SERVICE_URL=http://127.0.0.1:{}", egress_port),
                EgressKind::Database(_) => {
                    format!("export DATABASE_URL=postgresql://127.0.0.1:{}", egress_port)
                }
            };
            println!(
                "    {}  (restart your app, then trigger the route)",
                env_hint.bold()
            );
            println!();
            println!("{}", "".repeat(60).dimmed());

            for template in &templates {
                println!();
                println!(
                    "  {} {}",
                    template.name().bright_white().bold(),
                    format!("{}", template.description()).dimmed()
                );
                println!();
                let flags = template.fault_flags("egress");
                let cmd = build_fault_command(&upstream, egress_port, duration, &flags);
                println!("    {}", cmd.bright_blue());
            }
        }
    }

    println!();

    // ── Installation hint ─────────────────────────────────────────────────────
    println!(
        "  {}  Install fault: {}",
        "tip".dimmed(),
        "https://fault-project.com".underline().dimmed()
    );
    println!();

    Ok(EXIT_SUCCESS)
}

// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────

/// Build the full `fault run` command string.
fn build_fault_command(target_url: &str, port: u16, duration: &str, flags: &[String]) -> String {
    let mut parts = vec![
        "fault run".to_string(),
        format!("--proxy-address 127.0.0.1:{}", port),
        format!("--upstream {}", target_url),
        format!("--duration {}", duration),
    ];
    // Each entry in `flags` is a single logical flag with its value
    // (e.g. "--latency-mean 350"). Keep them together on one line.
    for flag in flags {
        parts.push(flag.clone());
    }
    parts.join(" \\\n      ")
}

/// Resolve HTTP routes reachable from a function using the pre-built graph.
/// Returns (method, path) pairs.
fn resolve_routes(
    graph: &unfault_analysis::graph::CodeGraph,
    function_name: &str,
    file_hint: Option<&str>,
) -> Vec<(String, String)> {
    let ctx = if let Some(hint) = file_hint {
        unfault_analysis::graph::traversal::get_callers_in_file(graph, function_name, hint, 10)
    } else {
        unfault_analysis::graph::traversal::get_callers(graph, function_name, 10)
    };

    let mut routes: Vec<(String, String)> =
        ctx.routes.into_iter().map(|r| (r.method, r.path)).collect();

    // Also check if the function itself is a handler (direct route).
    use petgraph::Direction;
    use petgraph::visit::EdgeRef;
    use unfault_analysis::graph::GraphEdgeKind;
    use unfault_analysis::graph::GraphNode;

    let lower_target = function_name.to_lowercase();
    let lower_hint = file_hint.map(|h| h.to_lowercase());

    for idx in graph.graph.node_indices() {
        let node = &graph.graph[idx];
        let name = node.display_name().to_lowercase();

        if let Some(ref hint) = lower_hint {
            let node_file = unfault_analysis::graph::traversal::node_file_path_pub(graph, node)
                .unwrap_or_default()
                .to_lowercase();
            if !node_file.ends_with(hint.as_str()) {
                continue;
            }
        }

        if name == lower_target
            || name.ends_with(&format!(".{}", lower_target))
            || name.ends_with(&format!("/{}", lower_target))
        {
            if let GraphNode::Function {
                is_handler: true,
                http_method: Some(method),
                http_path: Some(path),
                ..
            } = node
            {
                let entry = (method.clone(), path.clone());
                if !routes.contains(&entry) {
                    routes.push(entry);
                }
            }

            for edge in graph.graph.edges_directed(idx, Direction::Incoming) {
                if !matches!(edge.weight(), GraphEdgeKind::Contains) {
                    continue;
                }
                if let GraphNode::FastApiRoute {
                    http_method, path, ..
                } = &graph.graph[edge.source()]
                {
                    let entry = (http_method.clone(), path.clone());
                    if !routes.contains(&entry) {
                        routes.push(entry);
                    }
                }
            }
        }
    }

    routes
}

/// Walk forward from `function_name` through `Calls` edges, collecting
/// outbound HTTP calls and database queries from reachable functions.
///
/// Returns a de-duplicated list of `EgressTarget`s, each with the best
/// upstream URL we could determine statically.
fn resolve_egress_targets(
    graph: &unfault_analysis::graph::CodeGraph,
    semantics: &[unfault_core::semantics::SourceSemantics],
    function_name: &str,
    file_hint: Option<&str>,
) -> Vec<EgressTarget> {
    use petgraph::Direction;
    use petgraph::visit::EdgeRef;
    use std::collections::HashSet;
    use unfault_analysis::graph::GraphEdgeKind;
    use unfault_core::semantics::SourceSemantics;

    // Build a map from file_id → semantics for fast lookup.
    let sem_by_file: std::collections::HashMap<
        unfault_core::parse::ast::FileId,
        &unfault_core::semantics::SourceSemantics,
    > = semantics
        .iter()
        .filter_map(|s| {
            let fid = match s {
                SourceSemantics::Python(py) => py.file_id,
                SourceSemantics::Go(go) => go.file_id,
                SourceSemantics::Rust(rs) => rs.file_id,
                SourceSemantics::Typescript(ts) => ts.file_id,
            };
            Some((fid, s))
        })
        .collect();

    // Find the start node(s) for the target function.
    let lower_target = function_name.to_lowercase();
    let lower_hint = file_hint.map(|h| h.to_lowercase());

    let start_nodes: Vec<petgraph::graph::NodeIndex> = graph
        .graph
        .node_indices()
        .filter(|&idx| {
            let node = &graph.graph[idx];
            let name = node.display_name().to_lowercase();
            if !matches!(node, unfault_analysis::graph::GraphNode::Function { .. }) {
                return false;
            }
            let name_matches = name == lower_target
                || name.ends_with(&format!(".{}", lower_target))
                || name.ends_with(&format!("/{}", lower_target));
            if !name_matches {
                return false;
            }
            if let Some(ref hint) = lower_hint {
                let file = unfault_analysis::graph::traversal::node_file_path_pub(graph, node)
                    .unwrap_or_default()
                    .to_lowercase();
                file.ends_with(hint.as_str())
            } else {
                true
            }
        })
        .collect();

    // Forward BFS through Calls edges, collecting file_ids of reachable nodes.
    let mut visited: HashSet<petgraph::graph::NodeIndex> = HashSet::new();
    let mut queue: std::collections::VecDeque<petgraph::graph::NodeIndex> =
        start_nodes.iter().copied().collect();
    visited.extend(start_nodes.iter().copied());

    while let Some(current) = queue.pop_front() {
        for edge in graph.graph.edges_directed(current, Direction::Outgoing) {
            if !matches!(edge.weight(), GraphEdgeKind::Calls) {
                continue;
            }
            let target = edge.target();
            if visited.insert(target) {
                queue.push_back(target);
            }
        }
    }

    // Collect file_ids of all visited function nodes.
    let reachable_file_ids: HashSet<unfault_core::parse::ast::FileId> = visited
        .iter()
        .filter_map(|&idx| graph.graph[idx].file_id())
        .collect();

    // For each reachable file, inspect http_calls and orm_queries.
    let mut targets: Vec<EgressTarget> = Vec::new();
    let mut seen_upstreams: HashSet<String> = HashSet::new();

    for file_id in &reachable_file_ids {
        let sem = match sem_by_file.get(file_id) {
            Some(s) => s,
            None => continue,
        };

        if let SourceSemantics::Python(py) = sem {
            // ── HTTP calls ────────────────────────────────────────────────────
            for call in &py.http_calls {
                let url = extract_url_from_call_text(&call.call_text);
                let upstream = url
                    .as_ref()
                    .and_then(|u| extract_origin(u))
                    .map(|o| o.to_string());

                // De-duplicate by upstream origin (or call_text if no URL).
                let dedup_key = upstream
                    .clone()
                    .unwrap_or_else(|| call.call_text.chars().take(60).collect());
                if !seen_upstreams.insert(dedup_key) {
                    continue;
                }

                let label = if let Some(ref u) = url {
                    format!(
                        "{}.{}(\"{}\")",
                        call.client_kind.as_str(),
                        call.method_name,
                        u
                    )
                } else {
                    format!("{}.{}(…)", call.client_kind.as_str(), call.method_name)
                };

                targets.push(EgressTarget {
                    label,
                    upstream_url: upstream,
                    kind: EgressKind::Http,
                });
            }

            // ── ORM / DB queries ──────────────────────────────────────────────
            for query in &py.orm_queries {
                let kind = orm_kind_from_library(&query.orm_kind);
                let dedup_key = format!("db:{:?}", kind);
                if !seen_upstreams.insert(dedup_key) {
                    continue;
                }
                let label = match &query.model_name {
                    Some(model) => {
                        format!("{} query on {}", orm_library_name(&query.orm_kind), model)
                    }
                    None => format!("{} query", orm_library_name(&query.orm_kind)),
                };
                targets.push(EgressTarget {
                    label,
                    upstream_url: None, // connection string not available statically
                    kind: EgressKind::Database(kind),
                });
            }
        }
    }

    targets
}

/// Try to extract a URL string literal from a raw call expression like
/// `requests.get("https://api.example.com/v1/users", timeout=5)`.
fn extract_url_from_call_text(call_text: &str) -> Option<String> {
    // Match the first quoted string argument.
    let re = regex::Regex::new(r#"["'](?P<url>https?://[^"']+)["']"#).ok()?;
    re.captures(call_text)
        .and_then(|c| c.name("url"))
        .map(|m| m.as_str().to_string())
}

/// Extract just the scheme+host[:port] from a URL, e.g.
/// "https://api.example.com/v1/users" → "https://api.example.com"
fn extract_origin(url: &str) -> Option<&str> {
    // Find the end of the authority: after "scheme://host[:port]"
    let after_scheme = url.find("://")?;
    let host_start = after_scheme + 3;
    let host_end = url[host_start..]
        .find('/')
        .map(|i| host_start + i)
        .unwrap_or(url.len());
    Some(&url[..host_end])
}

/// Default upstream URL when we couldn't extract one statically.
fn default_upstream(kind: &EgressKind) -> String {
    match kind {
        EgressKind::Http => "http://downstream-service".to_string(),
        EgressKind::Database(DatabaseKind::Postgres) => "postgresql://localhost:5432".to_string(),
        EgressKind::Database(DatabaseKind::Mysql) => "mysql://localhost:3306".to_string(),
        EgressKind::Database(DatabaseKind::Other) => "localhost:5432".to_string(),
    }
}

fn orm_kind_from_library(kind: &unfault_core::semantics::python::orm::OrmKind) -> DatabaseKind {
    use unfault_core::semantics::python::orm::OrmKind;
    match kind {
        OrmKind::SqlAlchemy | OrmKind::Django | OrmKind::Tortoise | OrmKind::SqlModel => {
            DatabaseKind::Postgres // sensible default for Python ORMs
        }
        OrmKind::Peewee => DatabaseKind::Mysql,
        _ => DatabaseKind::Other,
    }
}

fn orm_library_name(kind: &unfault_core::semantics::python::orm::OrmKind) -> &'static str {
    kind.as_str()
}

fn print_template_list() {
    for t in FaultTemplate::all() {
        eprintln!("    {:25} {}", t.name().bold(), t.description().dimmed());
    }
}