unfault 0.9.1

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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
//! # Unfault CLI
//!
//! Unfault — a calm reviewer for thoughtful engineers
//!
//! Unfault analyzes your code for clarity, boundaries, and behavior,
//! highlighting places where decisions matter — before reality does.
//!
//! You write the code. Unfault helps you build it right.
//!
//! ## Usage
//!
//! ```bash
//! # Authenticate
//! unfault login
//!
//! # Analyze code
//! unfault review
//!
//! ```

use clap::{Parser, Subcommand, ValueEnum};
use unfault::commands;

/// Initialize logger based on verbose flag
fn init_logger(verbose: bool) {
    let mut log_builder = env_logger::Builder::from_default_env();
    if verbose {
        log_builder.filter_level(log::LevelFilter::Debug);
    } else {
        log_builder.filter_level(log::LevelFilter::Info);
    }
    log_builder.init();
}

/// Output format options for commands
#[derive(Clone, Debug, ValueEnum)]
pub enum OutputFormat {
    /// Basic output showing only header and summary line (default)
    Basic,
    /// Concise output with just summary statistics
    Concise,
    /// Full output with detailed analysis and findings
    Full,
    /// JSON output format
    Json,
    /// SARIF output format for GitHub Code Scanning / IDE integration
    Sarif,
}

/// Main CLI structure
#[derive(Parser)]
#[command(name = "unfault")]
#[command(about = "Unfault — a calm reviewer for thoughtful engineers", long_about = None)]
#[command(version)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}
/// Available CLI commands
#[derive(Subcommand)]
enum Commands {
    /// Manage CLI configuration
    Config {
        #[command(subcommand)]
        command: ConfigCommands,
    },
    /// Query the code graph for impact analysis, dependencies, and critical files
    Graph {
        #[command(subcommand)]
        command: GraphCommands,
    },
    /// Generate fault injection scenario commands for endpoints reachable from a function
    Fault {
        /// Function to target in format file:function or just function_name
        #[arg(value_name = "FUNCTION")]
        function: String,
        /// Fault scenario template (omit to list all 12 templates)
        #[arg(long, short = 't', value_name = "TEMPLATE")]
        template: Option<String>,
        /// Injection mode: ingress (inbound to your app) or egress (outbound to dependencies)
        #[arg(long, short = 'm', value_name = "MODE", default_value = "ingress")]
        mode: String,
        /// Target URL.
        /// Ingress: local app base URL (default: http://127.0.0.1:8000).
        /// Egress: remote dependency base URL (required).
        #[arg(long, short = 'u', value_name = "URL")]
        url: Option<String>,
        /// Local proxy port for the fault proxy (default: 9090)
        #[arg(long, short = 'p', value_name = "PORT", default_value = "9090")]
        port: u16,
        /// Injection duration (default: 2m)
        #[arg(long, short = 'd', value_name = "DURATION", default_value = "2m")]
        duration: String,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Start the LSP server for IDE integration
    Lsp {
        /// Enable verbose logging to stderr
        #[arg(long, short = 'v')]
        verbose: bool,
        /// Use stdio transport (default, added for compatibility with language clients)
        #[arg(long, hide = true)]
        stdio: bool,
    },
    /// Analyze code and get recommendations
    Review {
        /// Output format (basic: header + summary, concise: brief findings, full: detailed analysis)
        #[arg(long, value_name = "OUTPUT", default_value = "basic")]
        output: OutputFormat,
        /// Enable verbose output (dumps raw API responses)
        #[arg(long, short = 'v')]
        verbose: bool,
        /// Override the detected profile (e.g., python_fastapi_backend)
        #[arg(long, value_name = "PROFILE")]
        profile: Option<String>,
        /// Dimensions to analyze (can be specified multiple times)
        /// Available: stability, correctness, performance, scalability
        /// Default: all dimensions from the profile
        #[arg(long, short = 'd', value_name = "DIMENSION")]
        dimension: Vec<String>,
        /// Auto-apply all suggested fixes
        #[arg(long)]
        fix: bool,
        /// Show what fixes would be applied without actually applying them
        #[arg(long)]
        dry_run: bool,
        /// Show all findings in full (same as unfault lint)
        #[arg(long)]
        all: bool,
        /// Discard the enrichment cache and re-fetch SLOs and traces from providers
        #[arg(long)]
        refresh_cache: bool,
        /// Skip SLO and trace fetching entirely — useful in CI or pre-commit hooks
        #[arg(long)]
        offline: bool,
        /// Analyze only files changed in a specific git commit (SHA, branch, tag, or HEAD~N).
        /// Useful for incremental cache warming: only changed files are parsed, the rest
        /// are served from cache. Can be combined with --files.
        #[arg(long, value_name = "REF")]
        commit: Option<String>,
        /// Analyze only these specific files (can be repeated or space-separated).
        /// Can be combined with --commit; duplicates are deduplicated automatically.
        #[arg(long, value_name = "FILE", num_args = 1..)]
        files: Vec<std::path::PathBuf>,
    },
    /// Show all findings grouped by severity and rule — the detailed linter view
    Lint {
        /// Output format (text or json)
        #[arg(long, value_name = "OUTPUT", default_value = "basic")]
        output: OutputFormat,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
        /// Override the detected profile
        #[arg(long, value_name = "PROFILE")]
        profile: Option<String>,
        /// Dimensions to analyze
        #[arg(long, short = 'd', value_name = "DIMENSION")]
        dimension: Vec<String>,
        /// Auto-apply all suggested fixes
        #[arg(long)]
        fix: bool,
        /// Show what fixes would be applied without actually applying them
        #[arg(long)]
        dry_run: bool,
        /// Analyze only files changed in a specific git commit (SHA, branch, tag, or HEAD~N).
        /// Useful for incremental cache warming: only changed files are parsed, the rest
        /// are served from cache. Can be combined with --files.
        #[arg(long, value_name = "REF")]
        commit: Option<String>,
        /// Analyze only these specific files (can be repeated or space-separated).
        /// Can be combined with --commit; duplicates are deduplicated automatically.
        #[arg(long, value_name = "FILE", num_args = 1..)]
        files: Vec<std::path::PathBuf>,
    },
    /// Show SRE glossary entry for a failure mode (e.g. SLO-001)
    Info {
        /// Glossary ID to look up (e.g. SLO-001, SLO-002)
        #[arg(value_name = "ID")]
        id: String,
    },
}

/// Graph subcommands
#[derive(Subcommand)]
enum GraphCommands {
    /// Analyze impact: "What breaks if I change this file?"
    Impact {
        /// File path to analyze
        #[arg(value_name = "FILE")]
        file_path: String,
        /// Analysis session ID (advanced: overrides workspace auto-detection)
        #[arg(long, short = 's', value_name = "SESSION_ID")]
        session: Option<String>,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Maximum depth for transitive analysis (1-10)
        #[arg(long, value_name = "DEPTH", default_value = "5")]
        max_depth: i32,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Analyze function impact: "What breaks if I change this function?"
    FunctionImpact {
        /// Function in format file:function
        #[arg(value_name = "FUNCTION")]
        function: String,
        /// Analysis session ID (advanced: overrides workspace auto-detection)
        #[arg(long, short = 's', value_name = "SESSION_ID")]
        session: Option<String>,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Maximum depth for transitive analysis (1-10)
        #[arg(long, value_name = "DEPTH", default_value = "5")]
        max_depth: i32,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Find files that use a specific library
    Library {
        /// Library name to search for (e.g., "requests", "fastapi")
        #[arg(value_name = "LIBRARY")]
        library_name: String,
        /// Analysis session ID (advanced: overrides workspace auto-detection)
        #[arg(long, short = 's', value_name = "SESSION_ID")]
        session: Option<String>,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Find external dependencies of a file
    Deps {
        /// File path to analyze
        #[arg(value_name = "FILE")]
        file_path: String,
        /// Analysis session ID (advanced: overrides workspace auto-detection)
        #[arg(long, short = 's', value_name = "SESSION_ID")]
        session: Option<String>,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Find the most critical/hub files in the codebase
    Critical {
        /// Analysis session ID (advanced: overrides workspace auto-detection)
        #[arg(long, short = 's', value_name = "SESSION_ID")]
        session: Option<String>,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Maximum number of files to return (1-50)
        #[arg(long, short = 'n', value_name = "COUNT", default_value = "10")]
        limit: i32,
        /// Metric to sort by
        #[arg(long, value_name = "METRIC", default_value = "in_degree")]
        sort_by: SortMetric,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Get code graph statistics
    Stats {
        /// Analysis session ID (advanced: overrides workspace auto-detection)
        #[arg(long, short = 's', value_name = "SESSION_ID")]
        session: Option<String>,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Build and dump the local code graph (for debugging)
    Dump {
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Output only call edges (useful for debugging call graph issues)
        #[arg(long)]
        calls_only: bool,
        /// Output only specific file's information
        #[arg(long, value_name = "FILE")]
        file: Option<String>,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
    /// Show who calls a function and which HTTP routes reach it ("you are here")
    ///
    /// Traces the inbound call chain from a function back to its HTTP entry points.
    /// Use file:function to disambiguate when the same name appears in multiple files.
    ///
    /// Examples:
    ///   unfault graph callers validate_order
    ///   unfault graph callers services/orders.py:validate_order
    ///   unfault graph callers validate_order --max-depth 3
    ///   unfault graph callers validate_order --json
    Callers {
        /// Function to trace. Use "function_name" or "file.py:function_name" to disambiguate.
        ///
        /// Examples: validate_order  |  services/orders.py:validate_order
        #[arg(value_name = "FUNCTION")]
        function: String,
        /// Workspace path to analyze (defaults to current directory)
        #[arg(long, short = 'w', value_name = "PATH")]
        workspace: Option<String>,
        /// Maximum number of call-chain hops to follow upward (default: 5)
        #[arg(long, value_name = "DEPTH", default_value = "5")]
        max_depth: i32,
        /// Output raw JSON (callers list + routes) instead of the rendered tree
        #[arg(long)]
        json: bool,
        /// Enable verbose output
        #[arg(long, short = 'v')]
        verbose: bool,
    },
}

/// Centrality sort metric options
#[derive(Clone, Debug, ValueEnum)]
pub enum SortMetric {
    /// Sort by number of files that import this file (most critical dependencies)
    InDegree,
    /// Sort by number of files this file imports
    OutDegree,
    /// Sort by total connectivity (in + out)
    TotalDegree,
    /// Sort by number of external libraries used
    LibraryUsage,
    /// Sort by weighted importance score
    ImportanceScore,
}

impl SortMetric {
    fn as_str(&self) -> &'static str {
        match self {
            SortMetric::InDegree => "in_degree",
            SortMetric::OutDegree => "out_degree",
            SortMetric::TotalDegree => "total_degree",
            SortMetric::LibraryUsage => "library_usage",
            SortMetric::ImportanceScore => "importance_score",
        }
    }
}

/// Config subcommands
#[derive(Subcommand)]
enum ConfigCommands {
    /// Show current configuration
    Show {
        /// Show full secrets instead of masked values
        #[arg(long)]
        show_secrets: bool,
    },
    /// Manage LLM configuration for AI-powered insights
    Llm {
        #[command(subcommand)]
        command: LlmCommands,
    },
    /// Inspect and verify observability integrations (SLOs, traces)
    Integrations {
        #[command(subcommand)]
        command: IntegrationsCommands,
    },
    /// Generate agent skill files for Claude Code or OpenCode
    Agent {
        /// Agent tool to configure skills for
        #[command(subcommand)]
        tool: AgentTool,
    },
}

/// Integrations subcommands
#[derive(Subcommand)]
enum IntegrationsCommands {
    /// Show detected integrations and their credential status (no network calls)
    Show,
    /// Verify integrations by making live API calls to confirm auth works
    Verify,
}

/// Agent tool targets for skill generation
#[derive(Subcommand, Clone, Debug)]
pub enum AgentTool {
    /// Generate skills for Claude Code (.claude/skills/)
    Claude {
        /// Write to ~/.claude/skills/ instead of .claude/skills/ in the project
        #[arg(long)]
        global: bool,
        /// Print what would be created without writing files
        #[arg(long)]
        dry_run: bool,
    },
    /// Generate skills for OpenCode (.opencode/skills/)
    Opencode {
        /// Write to ~/.config/opencode/skills/ instead of .opencode/skills/ in the project
        #[arg(long)]
        global: bool,
        /// Print what would be created without writing files
        #[arg(long)]
        dry_run: bool,
    },
}

/// LLM subcommands
#[derive(Subcommand)]
enum LlmCommands {
    /// Configure OpenAI as LLM provider
    Openai {
        /// Model name (e.g., gpt-4, gpt-4o, gpt-3.5-turbo)
        #[arg(long, short = 'm', default_value = "gpt-4")]
        model: String,
        /// API key (optional, prefers OPENAI_API_KEY env var)
        #[arg(long, short = 'k')]
        api_key: Option<String>,
    },
    /// Configure Anthropic as LLM provider
    Anthropic {
        /// Model name (e.g., claude-3-5-sonnet-latest, claude-3-opus)
        #[arg(long, short = 'm', default_value = "claude-3-5-sonnet-latest")]
        model: String,
        /// API key (optional, prefers ANTHROPIC_API_KEY env var)
        #[arg(long, short = 'k')]
        api_key: Option<String>,
    },
    /// Configure local Ollama as LLM provider
    Ollama {
        /// Ollama API endpoint
        #[arg(long, short = 'e', default_value = "http://localhost:11434")]
        endpoint: String,
        /// Model name (e.g., llama3.2, mistral, codellama)
        #[arg(long, short = 'm', default_value = "llama3.2")]
        model: String,
    },
    /// Configure custom OpenAI-compatible endpoint
    Custom {
        /// API endpoint URL
        #[arg(long, short = 'e')]
        endpoint: String,
        /// Model name
        #[arg(long, short = 'm')]
        model: String,
        /// API key (optional)
        #[arg(long, short = 'k')]
        api_key: Option<String>,
    },
    /// Show current LLM configuration
    Show {
        /// Show full secrets instead of masked values
        #[arg(long)]
        show_secrets: bool,
    },
    /// Remove LLM configuration
    Remove,
}

#[tokio::main]
async fn main() {
    let cli = Cli::parse();
    let exit_code = run_command(cli.command).await;
    std::process::exit(exit_code);
}

async fn run_command(command: Commands) -> i32 {
    use unfault::exit_codes::*;

    match command {
        Commands::Config { command } => run_config_command(command).await,
        Commands::Graph { command } => run_graph_command(command).await,
        Commands::Fault {
            function,
            template,
            mode,
            url,
            port,
            duration,
            workspace,
            verbose,
        } => {
            let args = commands::fault::FaultArgs {
                function,
                template,
                mode,
                url,
                port,
                duration,
                workspace_path: workspace,
                verbose,
            };
            match commands::fault::execute(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Fault error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        Commands::Info { id } => commands::info::execute(&id),
        Commands::Lint {
            output,
            verbose,
            profile,
            dimension,
            fix,
            dry_run,
            commit,
            files,
        } => {
            init_logger(verbose);
            let output_format = match output {
                OutputFormat::Json => "json".to_string(),
                _ => "text".to_string(),
            };
            let args = commands::lint::LintArgs {
                output_format,
                verbose,
                profile,
                dimensions: if dimension.is_empty() {
                    None
                } else {
                    Some(dimension)
                },
                fix,
                dry_run,
                commit,
                files,
            };
            match commands::lint::execute(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Lint error: {}", e);
                    EXIT_CONFIG_ERROR
                }
            }
        }
        Commands::Lsp { verbose, stdio: _ } => {
            init_logger(verbose);
            // stdio flag is just for compatibility with language clients, we always use stdio
            let args = commands::lsp::LspArgs { verbose };
            match commands::lsp::execute(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("LSP error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        Commands::Review {
            output,
            verbose,
            profile,
            dimension,
            fix,
            dry_run,
            all,
            refresh_cache,
            offline,
            commit,
            files,
        } => {
            init_logger(verbose);
            // Convert OutputFormat to string for backward compatibility
            let output_format = match output {
                OutputFormat::Json => "json".to_string(),
                OutputFormat::Sarif => "sarif".to_string(),
                OutputFormat::Basic => "text".to_string(),
                OutputFormat::Concise => "text".to_string(),
                OutputFormat::Full => "text".to_string(),
            };

            // Determine output mode
            let output_mode = match output {
                OutputFormat::Basic => "basic".to_string(),
                OutputFormat::Concise => "concise".to_string(),
                OutputFormat::Full => "full".to_string(),
                OutputFormat::Json => "full".to_string(), // JSON is always full
                OutputFormat::Sarif => "full".to_string(), // SARIF is always full
            };

            let args = commands::review::ReviewArgs {
                output_format,
                output_mode,
                verbose,
                profile,
                dimensions: if dimension.is_empty() {
                    None
                } else {
                    Some(dimension)
                },
                fix,
                dry_run,
                all,
                refresh_cache,
                offline,
                commit,
                files,
            };
            match commands::review::execute(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Review error: {}", e);
                    EXIT_CONFIG_ERROR
                }
            }
        }
    }
}

async fn run_config_command(command: ConfigCommands) -> i32 {
    use unfault::exit_codes::*;

    match command {
        ConfigCommands::Show { show_secrets } => {
            let args = commands::config::ConfigShowArgs { show_secrets };
            match commands::config::execute_show(args) {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Config error: {}", e);
                    EXIT_CONFIG_ERROR
                }
            }
        }
        ConfigCommands::Llm { command } => run_llm_command(command),
        ConfigCommands::Integrations { command } => run_integrations_command(command).await,
        ConfigCommands::Agent { tool } => {
            let (agent_tool, global, dry_run) = match tool {
                AgentTool::Claude { global, dry_run } => {
                    (commands::agent_skills::AgentTool::Claude, global, dry_run)
                }
                AgentTool::Opencode { global, dry_run } => {
                    (commands::agent_skills::AgentTool::Opencode, global, dry_run)
                }
            };
            let args = commands::agent_skills::AgentSkillsArgs {
                tool: agent_tool,
                global,
                dry_run,
            };
            match commands::agent_skills::execute(args) {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Agent skills error: {}", e);
                    EXIT_ERROR
                }
            }
        }
    }
}

fn run_llm_command(command: LlmCommands) -> i32 {
    use commands::config::{ConfigLlmArgs, LlmProvider};
    use unfault::exit_codes::*;

    let args = match command {
        LlmCommands::Openai { model, api_key } => {
            ConfigLlmArgs::Set(LlmProvider::OpenAI { model, api_key })
        }
        LlmCommands::Anthropic { model, api_key } => {
            ConfigLlmArgs::Set(LlmProvider::Anthropic { model, api_key })
        }
        LlmCommands::Ollama { endpoint, model } => {
            ConfigLlmArgs::Set(LlmProvider::Ollama { endpoint, model })
        }
        LlmCommands::Custom {
            endpoint,
            model,
            api_key,
        } => ConfigLlmArgs::Set(LlmProvider::Custom {
            endpoint,
            model,
            api_key,
        }),
        LlmCommands::Show { show_secrets } => ConfigLlmArgs::Show { show_secrets },
        LlmCommands::Remove => ConfigLlmArgs::Remove,
    };

    match commands::config::execute_llm(args) {
        Ok(exit_code) => exit_code,
        Err(e) => {
            eprintln!("Config LLM error: {}", e);
            EXIT_CONFIG_ERROR
        }
    }
}

async fn run_integrations_command(command: IntegrationsCommands) -> i32 {
    use unfault::exit_codes::*;

    match command {
        IntegrationsCommands::Show => match commands::integrations::execute_show() {
            Ok(exit_code) => exit_code,
            Err(e) => {
                eprintln!("Integrations error: {}", e);
                EXIT_ERROR
            }
        },
        IntegrationsCommands::Verify => match commands::integrations::execute_verify().await {
            Ok(exit_code) => exit_code,
            Err(e) => {
                eprintln!("Integrations verify error: {}", e);
                EXIT_ERROR
            }
        },
    }
}

async fn run_graph_command(command: GraphCommands) -> i32 {
    use unfault::exit_codes::*;

    match command {
        GraphCommands::Impact {
            file_path,
            session,
            workspace,
            max_depth,
            json,
            verbose,
        } => {
            let args = commands::graph::ImpactArgs {
                session_id: session,
                workspace_path: workspace,
                file_path,
                max_depth,
                json,
                verbose,
            };
            match commands::graph::execute_impact(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph impact error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::FunctionImpact {
            function,
            session,
            workspace,
            max_depth,
            json,
            verbose,
        } => {
            let args = commands::graph::FunctionImpactArgs {
                session_id: session,
                workspace_path: workspace,
                function,
                max_depth,
                json,
                verbose,
            };
            match commands::graph::execute_function_impact(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph function impact error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::Library {
            library_name,
            session,
            workspace,
            json,
            verbose,
        } => {
            let args = commands::graph::LibraryArgs {
                session_id: session,
                workspace_path: workspace,
                library_name,
                json,
                verbose,
            };
            match commands::graph::execute_library(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph library error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::Deps {
            file_path,
            session,
            workspace,
            json,
            verbose,
        } => {
            let args = commands::graph::DepsArgs {
                session_id: session,
                workspace_path: workspace,
                file_path,
                json,
                verbose,
            };
            match commands::graph::execute_deps(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph deps error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::Critical {
            session,
            workspace,
            limit,
            sort_by,
            json,
            verbose,
        } => {
            let args = commands::graph::CriticalArgs {
                session_id: session,
                workspace_path: workspace,
                limit,
                sort_by: sort_by.as_str().to_string(),
                json,
                verbose,
            };
            match commands::graph::execute_critical(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph critical error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::Stats {
            session,
            workspace,
            json,
            verbose,
        } => {
            let args = commands::graph::StatsArgs {
                session_id: session,
                workspace_path: workspace,
                json,
                verbose,
            };
            match commands::graph::execute_stats(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph stats error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::Dump {
            workspace,
            calls_only,
            file,
            verbose,
        } => {
            let args = commands::graph::DumpArgs {
                workspace_path: workspace,
                calls_only,
                file,
                verbose,
            };
            match commands::graph::execute_dump(args) {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph dump error: {}", e);
                    EXIT_ERROR
                }
            }
        }
        GraphCommands::Callers {
            function,
            workspace,
            max_depth,
            json,
            verbose,
        } => {
            let args = commands::graph::CallersArgs {
                workspace_path: workspace,
                function,
                max_depth,
                json,
                verbose,
            };
            match commands::graph::execute_callers(args).await {
                Ok(exit_code) => exit_code,
                Err(e) => {
                    eprintln!("Graph callers error: {}", e);
                    EXIT_ERROR
                }
            }
        }
    }
}