vtcode_core/cli/
args.rs

1//! CLI argument parsing and configuration
2
3use crate::config::models::ModelId;
4use clap::{ColorChoice, Parser, Subcommand, ValueHint};
5use colorchoice_clap::Color as ColorSelection;
6use std::path::PathBuf;
7
8/// Main CLI structure for vtcode with advanced features
9#[derive(Parser, Debug)]
10#[command(
11    name = "vtcode",
12    version,
13    about = "Advanced coding agent with Decision Ledger\n\nFeatures:\n• Single-agent architecture with Decision Ledger for reliable task execution\n• Tree-sitter powered code analysis (Rust, Python, JavaScript, TypeScript, Go, Java)\n• Multi-provider LLM support (Gemini, OpenAI, Anthropic, DeepSeek)\n• Real-time performance monitoring and benchmarking\n• Enhanced security with tool policies and sandboxing\n• Research-preview context management and conversation compression\n\nQuick Start:\n  export GEMINI_API_KEY=\"your_key\"\n  vtcode chat",
14    color = ColorChoice::Auto
15)]
16pub struct Cli {
17    /// Color output selection (auto, always, never)
18    #[command(flatten)]
19    pub color: ColorSelection,
20
21    /// Optional positional path to run vtcode against a different workspace
22    #[arg(
23        value_name = "WORKSPACE",
24        value_hint = ValueHint::DirPath,
25        global = true
26    )]
27    pub workspace_path: Option<PathBuf>,
28
29    /// LLM Model ID with latest model support
30    ///
31    /// Available providers & models:
32    ///   • gemini-2.5-flash-preview-05-20 - Latest fast Gemini model (default)
33    ///   • gemini-2.5-flash - Fast, cost-effective
34    ///   • gemini-2.5-pro - Latest, most capable
35    ///   • gpt-5 - OpenAI's latest
36    ///   • claude-sonnet-4-20250514 - Anthropic's latest
37    ///   • qwen/qwen3-4b-2507 - Qwen3 local model
38    ///   • deepseek-reasoner - DeepSeek reasoning model
39    ///   • x-ai/grok-code-fast-1 - OpenRouter Grok fast coding model
40    ///   • qwen/qwen3-coder - OpenRouter Qwen3 Coder optimized for IDE usage
41    ///   • grok-2-latest - xAI Grok flagship model
42    #[arg(long, global = true)]
43    pub model: Option<String>,
44
45    /// **LLM Provider** with expanded support
46    ///
47    /// Available providers:
48    ///   • gemini - Google Gemini (default)
49    ///   • openai - OpenAI GPT models
50    ///   • anthropic - Anthropic Claude models
51    ///   • deepseek - DeepSeek models
52    ///   • openrouter - OpenRouter marketplace models
53    ///   • xai - xAI Grok models
54    ///
55    /// Example: --provider deepseek
56    #[arg(long, global = true)]
57    pub provider: Option<String>,
58
59    /// **API key environment variable**\n\n**Auto-detects based on provider:**\n• Gemini: `GEMINI_API_KEY`\n• OpenAI: `OPENAI_API_KEY`\n• Anthropic: `ANTHROPIC_API_KEY`\n• DeepSeek: `DEEPSEEK_API_KEY`\n• OpenRouter: `OPENROUTER_API_KEY`\n• xAI: `XAI_API_KEY`\n\n**Override:** --api-key-env CUSTOM_KEY
60    #[arg(long, global = true, default_value = crate::config::constants::defaults::DEFAULT_API_KEY_ENV)]
61    pub api_key_env: String,
62
63    /// **Workspace root directory for file operations**
64    ///
65    /// Security: All file operations restricted to this path
66    /// Default: Current directory
67    #[arg(
68        long,
69        global = true,
70        alias = "workspace-dir",
71        value_name = "PATH",
72        value_hint = ValueHint::DirPath
73    )]
74    pub workspace: Option<PathBuf>,
75
76    /// **Enable tree-sitter code analysis**
77    ///
78    /// Features:
79    ///   • AST-based code parsing
80    ///   • Symbol extraction and navigation
81    ///   • Intelligent refactoring suggestions
82    ///   • Multi-language support (Rust, Python, JS, TS, Go, Java)
83    #[arg(long, global = true)]
84    pub enable_tree_sitter: bool,
85
86    /// **Enable performance monitoring**
87    ///
88    /// Tracks:
89    ///   • Token usage and API costs
90    ///   • Response times and latency
91    ///   • Tool execution metrics
92    ///   • Memory usage patterns
93    #[arg(long, global = true)]
94    pub performance_monitoring: bool,
95
96    /// **Enable research-preview features**
97    ///
98    /// Includes:
99    ///   • Advanced context compression
100    ///   • Conversation summarization
101    ///   • Enhanced error recovery
102    ///   • Decision transparency tracking
103    #[arg(long, global = true)]
104    pub research_preview: bool,
105
106    /// **Security level** for tool execution
107    ///
108    /// Options:
109    ///   • strict - Maximum security, prompt for all tools
110    ///   • moderate - Balance security and usability
111    ///   • permissive - Minimal restrictions (not recommended)
112    #[arg(long, global = true, default_value = "moderate")]
113    pub security_level: String,
114
115    /// **Show diffs for file changes in chat interface**
116    ///
117    /// Features:
118    ///   • Real-time diff rendering
119    ///   • Syntax highlighting
120    ///   • Line-by-line changes
121    ///   • Before/after comparison
122    #[arg(long, global = true)]
123    pub show_file_diffs: bool,
124
125    /// **Maximum concurrent async operations**
126    ///
127    /// Default: 5
128    /// Higher values: Better performance but more resource usage
129    #[arg(long, global = true, default_value_t = 5)]
130    pub max_concurrent_ops: usize,
131
132    /// **Maximum API requests per minute**
133    ///
134    /// Default: 30
135    /// Purpose: Prevents rate limiting
136    #[arg(long, global = true, default_value_t = 30)]
137    pub api_rate_limit: usize,
138
139    /// **Maximum tool calls per session**
140    ///
141    /// Default: 10
142    /// Purpose: Prevents runaway execution
143    #[arg(long, global = true, default_value_t = 10)]
144    pub max_tool_calls: usize,
145
146    /// **Enable debug output for troubleshooting**
147    ///
148    /// Shows:
149    ///   • Tool call details
150    ///   • API request/response
151    ///   • Internal agent state
152    ///   • Performance metrics
153    #[arg(long, global = true)]
154    pub debug: bool,
155
156    /// **Enable verbose logging**
157    ///
158    /// Includes:
159    ///   • Detailed operation logs
160    ///   • Context management info
161    ///   • Agent coordination details
162    #[arg(long, global = true)]
163    pub verbose: bool,
164
165    /// **Configuration file path**
166    ///
167    /// Supported formats: TOML
168    /// Default locations: ./vtcode.toml, ~/.vtcode/vtcode.toml
169    #[arg(long, global = true)]
170    pub config: Option<PathBuf>,
171
172    /// Log level (error, warn, info, debug, trace)
173    ///
174    /// Default: info
175    #[arg(long, global = true, default_value = "info")]
176    pub log_level: String,
177
178    /// Disable color output
179    ///
180    /// Useful for: Log files, CI/CD pipelines
181    #[arg(long, global = true)]
182    pub no_color: bool,
183
184    /// Select UI theme for ANSI styling (e.g., ciapre-dark, ciapre-blue)
185    #[arg(long, global = true, value_name = "THEME")]
186    pub theme: Option<String>,
187
188    /// **Skip safety confirmations**
189    ///
190    /// Warning: Reduces security, use with caution
191    #[arg(long, global = true)]
192    pub skip_confirmations: bool,
193
194    /// **Enable full-auto mode (no interaction)**
195    ///
196    /// Runs the agent without pausing for approvals. Requires enabling in configuration.
197    #[arg(long, global = true)]
198    pub full_auto: bool,
199
200    #[command(subcommand)]
201    pub command: Option<Commands>,
202}
203
204/// Available commands with comprehensive features
205#[derive(Subcommand, Debug)]
206pub enum Commands {
207    /// **Interactive AI coding assistant** with advanced capabilities
208    ///
209    /// Features:
210    ///   • Real-time code generation and editing
211    ///   • Tree-sitter powered analysis
212    ///   • Research-preview context management
213    ///
214    /// Usage: vtcode chat
215    Chat,
216
217    /// **Single prompt mode** - prints model reply without tools
218    ///
219    /// Perfect for:
220    ///   • Quick questions
221    ///   • Code explanations
222    ///   • Simple queries
223    ///
224    /// Example: vtcode ask "Explain Rust ownership"
225    Ask { prompt: String },
226
227    /// **Verbose interactive chat** with enhanced transparency
228    ///
229    /// Shows:
230    ///   • Tool execution details
231    ///   • API request/response
232    ///   • Performance metrics
233    ///
234    /// Usage: vtcode chat-verbose
235    ChatVerbose,
236
237    /// **Analyze workspace** with tree-sitter integration
238    ///
239    /// Provides:
240    ///   • Project structure analysis
241    ///   • Language detection
242    ///   • Code complexity metrics
243    ///   • Dependency insights
244    ///   • Symbol extraction
245    ///
246    /// Usage: vtcode analyze
247    Analyze,
248
249    /// **Display performance metrics** and system status\n\n**Shows:**\n• Token usage and API costs\n• Response times and latency\n• Tool execution statistics\n• Memory usage patterns\n\n**Usage:** vtcode performance
250    Performance,
251
252    /// Pretty-print trajectory logs and show basic analytics
253    ///
254    /// Sources:
255    ///   • .vtcode/logs/trajectory.jsonl (default)
256    /// Options:
257    ///   • --file to specify an alternate path
258    ///   • --top to limit report rows (default: 10)
259    ///
260    /// Shows:
261    ///   • Class distribution with percentages
262    ///   • Model usage statistics
263    ///   • Tool success rates with status indicators
264    ///   • Time range of logged activity
265    #[command(name = "trajectory")]
266    Trajectory {
267        /// Optional path to trajectory JSONL file
268        #[arg(long)]
269        file: Option<std::path::PathBuf>,
270        /// Number of top entries to show for each section
271        #[arg(long, default_value_t = 10)]
272        top: usize,
273    },
274
275    /// **Benchmark against SWE-bench evaluation framework**
276    ///
277    /// Features:
278    ///   • Automated performance testing
279    ///   • Comparative analysis across models
280    ///   • Benchmark scoring and metrics
281    ///   • Optimization insights
282    ///
283    /// Usage: vtcode benchmark
284    Benchmark,
285
286    /// **Create complete Rust project with advanced features**
287    ///
288    /// Features:
289    ///   • Web frameworks (Axum, Rocket, Warp)
290    ///   • Database integration
291    ///   • Authentication systems
292    ///   • Testing setup
293    ///   • Tree-sitter integration
294    ///
295    /// Example: vtcode create-project myapp web,auth,db
296    CreateProject { name: String, features: Vec<String> },
297
298    /// **Compress conversation context** for long-running sessions
299    ///
300    /// Benefits:
301    ///   • Reduced token usage
302    ///   • Faster responses
303    ///   • Memory optimization
304    ///   • Context preservation
305    ///
306    /// Usage: vtcode compress-context
307    CompressContext,
308
309    /// **Revert agent to a previous snapshot
310    ///
311    /// Features:
312    ///   • Revert to any previous turn
313    ///   • Partial reverts (memory, context, full)
314    ///   • Safe rollback with validation
315    ///
316    /// Examples:
317    ///   vtcode revert --turn 5
318    ///   vtcode revert --turn 3 --partial memory
319    Revert {
320        /// Turn number to revert to
321        ///
322        /// Required: Yes
323        /// Example: 5
324        #[arg(short, long)]
325        turn: usize,
326
327        /// Scope of revert operation
328        ///
329        /// Options: memory, context, full
330        /// Default: full
331        /// Examples:
332        ///   --partial memory (revert conversation only)
333        ///   --partial context (revert decisions/errors only)
334        #[arg(short, long)]
335        partial: Option<String>,
336    },
337
338    /// **List all available snapshots**
339    ///
340    /// Shows:
341    ///   • Snapshot ID and turn number
342    ///   • Creation timestamp
343    ///   • Description
344    ///   • File size and compression status
345    ///
346    /// Usage: vtcode snapshots
347    Snapshots,
348
349    /// **Clean up old snapshots**
350    ///
351    /// Features:
352    ///   • Remove snapshots beyond limit
353    ///   • Configurable retention policy
354    ///   • Safe deletion with confirmation
355    ///
356    /// Examples:
357    ///   vtcode cleanup-snapshots
358    ///   vtcode cleanup-snapshots --max 20
359    #[command(name = "cleanup-snapshots")]
360    CleanupSnapshots {
361        /// Maximum number of snapshots to keep
362        ///
363        /// Default: 50
364        /// Example: --max 20
365        #[arg(short, long, default_value_t = 50)]
366        max: usize,
367    },
368
369    /// **Initialize project** with enhanced dot-folder structure
370    ///
371    /// Features:
372    ///   • Creates project directory structure
373    ///   • Sets up config, cache, embeddings directories
374    ///   • Creates .project metadata file
375    ///   • Tree-sitter parser setup
376    ///
377    /// Usage: vtcode init
378    Init,
379
380    /// **Initialize project with dot-folder structure** - sets up ~/.vtcode/projects/<project-name> structure
381    ///
382    /// Features:
383    ///   • Creates project directory structure in ~/.vtcode/projects/
384    ///   • Sets up config, cache, embeddings, and retrieval directories
385    ///   • Creates .project metadata file
386    ///   • Migrates existing config/cache files with user confirmation
387    ///
388    /// Examples:
389    ///   vtcode init-project
390    ///   vtcode init-project --name my-project
391    ///   vtcode init-project --force
392    #[command(name = "init-project")]
393    InitProject {
394        /// Project name - defaults to current directory name
395        #[arg(long)]
396        name: Option<String>,
397
398        /// Force initialization - overwrite existing project structure
399        #[arg(long)]
400        force: bool,
401
402        /// Migrate existing files - move existing config/cache files to new structure
403        #[arg(long)]
404        migrate: bool,
405    },
406
407    /// **Generate configuration file - creates a vtcode.toml configuration file
408    ///
409    /// Features:
410    ///   • Generate default configuration
411    ///   • Support for global (home directory) and local configuration
412    ///   • TOML format with comprehensive settings
413    ///   • Tree-sitter and performance monitoring settings
414    ///
415    /// Examples:
416    ///   vtcode config
417    ///   vtcode config --output ./custom-config.toml
418    ///   vtcode config --global
419    Config {
420        /// Output file path - where to save the configuration file
421        #[arg(long)]
422        output: Option<std::path::PathBuf>,
423
424        /// Create in user home directory - creates ~/.vtcode/vtcode.toml
425        #[arg(long)]
426        global: bool,
427    },
428
429    /// **Manage tool execution policies** - control which tools the agent can use
430    ///
431    /// Features:
432    ///   • Granular tool permissions
433    ///   • Security level presets
434    ///   • Audit logging
435    ///   • Safe tool execution
436    ///
437    /// Examples:
438    ///   vtcode tool-policy status
439    ///   vtcode tool-policy allow file-write
440    ///   vtcode tool-policy deny shell-exec
441    #[command(name = "tool-policy")]
442    ToolPolicy {
443        #[command(subcommand)]
444        command: crate::cli::tool_policy_commands::ToolPolicyCommands,
445    },
446
447    /// **Manage models and providers** - configure and switch between LLM providers\n\n**Features:**\n• Support for latest models (DeepSeek, etc.)\n• Provider configuration and testing\n• Model performance comparison\n• API key management\n\n**Examples:**\n  vtcode models list\n  vtcode models set-provider deepseek\n  vtcode models set-model deepseek-reasoner
448    Models {
449        #[command(subcommand)]
450        command: ModelCommands,
451    },
452
453    /// **Security and safety management**\n\n**Features:**\n• Security scanning and vulnerability detection\n• Audit logging and monitoring\n• Access control management\n• Privacy protection settings\n\n**Usage:** vtcode security
454    Security,
455
456    /// **Tree-sitter code analysis tools**\n\n**Features:**\n• AST-based code parsing\n• Symbol extraction and navigation\n• Code complexity analysis\n• Multi-language refactoring\n\n**Usage:** vtcode tree-sitter
457    #[command(name = "tree-sitter")]
458    TreeSitter,
459
460    /// **Generate or display man pages** for VTCode commands\n\n**Features:**\n• Generate Unix man pages for all commands\n• Display detailed command documentation\n• Save man pages to files\n• Comprehensive help for all VTCode features\n\n**Examples:**\n  vtcode man\n  vtcode man chat\n  vtcode man chat --output chat.1
461    Man {
462        /// **Command name** to generate man page for (optional)\n\n**Available commands:**\n• chat, ask, analyze, performance, benchmark\n• create-project, init, man\n\n**If not specified, shows main VTCode man page**
463        command: Option<String>,
464
465        /// **Output file path** to save man page\n\n**Format:** Standard Unix man page format (.1, .8, etc.)\n**Default:** Display to stdout
466        #[arg(short, long)]
467        output: Option<std::path::PathBuf>,
468    },
469}
470
471/// Model management commands with concise, actionable help
472#[derive(Subcommand, Debug)]
473pub enum ModelCommands {
474    /// List all providers and models with status indicators
475    List,
476
477    /// Set default provider (gemini, openai, anthropic, deepseek)
478    #[command(name = "set-provider")]
479    SetProvider {
480        /// Provider name to set as default
481        provider: String,
482    },
483
484    /// Set default model (e.g., deepseek-reasoner, gpt-5, claude-sonnet-4-20250514)
485    #[command(name = "set-model")]
486    SetModel {
487        /// Model name to set as default
488        model: String,
489    },
490
491    /// Configure provider settings (API keys, base URLs, models)
492    Config {
493        /// Provider name to configure
494        provider: String,
495
496        /// API key for the provider
497        #[arg(long)]
498        api_key: Option<String>,
499
500        /// Base URL for local providers
501        #[arg(long)]
502        base_url: Option<String>,
503
504        /// Default model for this provider
505        #[arg(long)]
506        model: Option<String>,
507    },
508
509    /// Test provider connectivity and validate configuration
510    Test {
511        /// Provider name to test
512        provider: String,
513    },
514
515    /// Compare model performance across providers (coming soon)
516    Compare,
517
518    /// Show detailed model information and specifications
519    Info {
520        /// Model name to get information about
521        model: String,
522    },
523}
524
525/// Configuration file structure with latest features
526#[derive(Debug)]
527pub struct ConfigFile {
528    pub model: Option<String>,
529    pub provider: Option<String>,
530    pub api_key_env: Option<String>,
531    pub verbose: Option<bool>,
532    pub log_level: Option<String>,
533    pub workspace: Option<PathBuf>,
534    pub tools: Option<ToolConfig>,
535    pub context: Option<ContextConfig>,
536    pub logging: Option<LoggingConfig>,
537    pub tree_sitter: Option<TreeSitterConfig>,
538    pub performance: Option<PerformanceConfig>,
539    pub security: Option<SecurityConfig>,
540}
541
542/// Tool configuration from config file
543#[derive(Debug, serde::Deserialize)]
544pub struct ToolConfig {
545    pub enable_validation: Option<bool>,
546    pub max_execution_time_seconds: Option<u64>,
547    pub allow_file_creation: Option<bool>,
548    pub allow_file_deletion: Option<bool>,
549}
550
551/// Context management configuration
552#[derive(Debug, serde::Deserialize)]
553pub struct ContextConfig {
554    pub max_context_length: Option<usize>,
555    pub compression_threshold: Option<usize>,
556    pub summarization_interval: Option<usize>,
557}
558
559/// Logging configuration
560#[derive(Debug, serde::Deserialize)]
561pub struct LoggingConfig {
562    pub file_logging: Option<bool>,
563    pub log_directory: Option<String>,
564    pub max_log_files: Option<usize>,
565    pub max_log_size_mb: Option<usize>,
566}
567
568/// Tree-sitter configuration
569#[derive(Debug, serde::Deserialize)]
570pub struct TreeSitterConfig {
571    pub enabled: Option<bool>,
572    pub supported_languages: Option<Vec<String>>,
573    pub max_file_size_kb: Option<usize>,
574    pub enable_symbol_extraction: Option<bool>,
575    pub enable_complexity_analysis: Option<bool>,
576}
577
578/// Performance monitoring configuration
579#[derive(Debug, serde::Deserialize)]
580pub struct PerformanceConfig {
581    pub enabled: Option<bool>,
582    pub track_token_usage: Option<bool>,
583    pub track_api_costs: Option<bool>,
584    pub track_response_times: Option<bool>,
585    pub enable_benchmarking: Option<bool>,
586    pub metrics_retention_days: Option<usize>,
587}
588
589/// Security configuration
590#[derive(Debug, serde::Deserialize)]
591pub struct SecurityConfig {
592    pub level: Option<String>,
593    pub enable_audit_logging: Option<bool>,
594    pub enable_vulnerability_scanning: Option<bool>,
595    pub allow_external_urls: Option<bool>,
596    pub max_file_access_depth: Option<usize>,
597}
598
599impl Default for Cli {
600    fn default() -> Self {
601        Self {
602            color: ColorSelection {
603                color: ColorChoice::Auto,
604            },
605            workspace_path: None,
606            model: Some(ModelId::default().as_str().to_string()),
607            provider: Some("gemini".to_string()),
608            api_key_env: "GEMINI_API_KEY".to_string(),
609            workspace: None,
610            enable_tree_sitter: false,
611            performance_monitoring: false,
612            research_preview: false,
613            security_level: "moderate".to_string(),
614            show_file_diffs: false,
615            max_concurrent_ops: 5,
616            api_rate_limit: 30,
617            max_tool_calls: 10,
618            verbose: false,
619            config: None,
620            log_level: "info".to_string(),
621            no_color: false,
622            theme: None,
623            skip_confirmations: false,
624            full_auto: false,
625            debug: false,
626            command: Some(Commands::Chat),
627        }
628    }
629}
630
631impl Cli {
632    /// Get the model to use, with fallback to default
633    pub fn get_model(&self) -> String {
634        self.model
635            .clone()
636            .unwrap_or_else(|| ModelId::default().as_str().to_string())
637    }
638
639    /// Load configuration from a simple TOML-like file without external deps
640    ///
641    /// Supported keys (top-level): model, api_key_env, verbose, log_level, workspace
642    /// Example:
643    ///   model = "gemini-2.5-flash-preview-05-20"
644    ///   api_key_env = "GEMINI_API_KEY"
645    ///   verbose = true
646    ///   log_level = "info"
647    ///   workspace = "/path/to/workspace"
648    pub fn load_config(&self) -> Result<ConfigFile, Box<dyn std::error::Error>> {
649        use std::fs;
650        use std::path::Path;
651
652        // Resolve candidate path
653        let path = if let Some(p) = &self.config {
654            p.clone()
655        } else {
656            let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
657            let primary = cwd.join("vtcode.toml");
658            let secondary = cwd.join(".vtcode.toml");
659            if primary.exists() {
660                primary
661            } else if secondary.exists() {
662                secondary
663            } else {
664                // No config file; return empty config
665                return Ok(ConfigFile {
666                    model: None,
667                    provider: None,
668                    api_key_env: None,
669                    verbose: None,
670                    log_level: None,
671                    workspace: None,
672                    tools: None,
673                    context: None,
674                    logging: None,
675                    tree_sitter: None,
676                    performance: None,
677                    security: None,
678                });
679            }
680        };
681
682        let text = fs::read_to_string(&path)?;
683
684        // Very small parser: key = value, supports quoted strings, booleans, and plain paths
685        let mut cfg = ConfigFile {
686            model: None,
687            provider: None,
688            api_key_env: None,
689            verbose: None,
690            log_level: None,
691            workspace: None,
692            tools: None,
693            context: None,
694            logging: None,
695            tree_sitter: None,
696            performance: None,
697            security: None,
698        };
699
700        for raw_line in text.lines() {
701            let line = raw_line.trim();
702            if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
703                continue;
704            }
705            // Strip inline comments after '#'
706            let line = match line.find('#') {
707                Some(idx) => &line[..idx],
708                None => line,
709            }
710            .trim();
711
712            // Expect key = value
713            let mut parts = line.splitn(2, '=');
714            let key = parts.next().map(|s| s.trim()).unwrap_or("");
715            let val = parts.next().map(|s| s.trim()).unwrap_or("");
716            if key.is_empty() || val.is_empty() {
717                continue;
718            }
719
720            // Remove surrounding quotes if present
721            let unquote = |s: &str| -> String {
722                let s = s.trim();
723                if (s.starts_with('"') && s.ends_with('"'))
724                    || (s.starts_with('\'') && s.ends_with('\''))
725                {
726                    s[1..s.len() - 1].to_string()
727                } else {
728                    s.to_string()
729                }
730            };
731
732            match key {
733                "model" => cfg.model = Some(unquote(val)),
734                "api_key_env" => cfg.api_key_env = Some(unquote(val)),
735                "verbose" => {
736                    let v = unquote(val).to_lowercase();
737                    cfg.verbose = Some(matches!(v.as_str(), "true" | "1" | "yes"));
738                }
739                "log_level" => cfg.log_level = Some(unquote(val)),
740                "workspace" => {
741                    let v = unquote(val);
742                    let p = if Path::new(&v).is_absolute() {
743                        PathBuf::from(v)
744                    } else {
745                        // Resolve relative to config file directory
746                        let base = path.parent().unwrap_or(Path::new("."));
747                        base.join(v)
748                    };
749                    cfg.workspace = Some(p);
750                }
751                _ => {
752                    // Ignore unknown keys in this minimal parser
753                }
754            }
755        }
756
757        Ok(cfg)
758    }
759
760    /// Get the effective workspace path
761    pub fn get_workspace(&self) -> std::path::PathBuf {
762        self.workspace
763            .clone()
764            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
765    }
766
767    /// Get the effective API key environment variable
768    ///
769    /// Automatically infers the API key environment variable based on the provider
770    /// when the current value matches the default or is not explicitly set.
771    pub fn get_api_key_env(&self) -> String {
772        // If api_key_env is the default or empty, infer from provider
773        if self.api_key_env == crate::config::constants::defaults::DEFAULT_API_KEY_ENV
774            || self.api_key_env.is_empty()
775        {
776            if let Some(provider) = &self.provider {
777                match provider.to_lowercase().as_str() {
778                    "openai" => "OPENAI_API_KEY".to_string(),
779                    "anthropic" => "ANTHROPIC_API_KEY".to_string(),
780                    "gemini" => "GEMINI_API_KEY".to_string(),
781                    "deepseek" => "DEEPSEEK_API_KEY".to_string(),
782                    "openrouter" => "OPENROUTER_API_KEY".to_string(),
783                    _ => "GEMINI_API_KEY".to_string(),
784                }
785            } else {
786                "GEMINI_API_KEY".to_string()
787            }
788        } else {
789            self.api_key_env.clone()
790        }
791    }
792
793    /// Check if verbose mode is enabled
794    pub fn is_verbose(&self) -> bool {
795        self.verbose
796    }
797
798    /// Check if tree-sitter analysis is enabled
799    pub fn is_tree_sitter_enabled(&self) -> bool {
800        self.enable_tree_sitter
801    }
802
803    /// Check if performance monitoring is enabled
804    pub fn is_performance_monitoring_enabled(&self) -> bool {
805        self.performance_monitoring
806    }
807
808    /// Check if research-preview features are enabled
809    pub fn is_research_preview_enabled(&self) -> bool {
810        self.research_preview
811    }
812
813    /// Get the security level
814    pub fn get_security_level(&self) -> &str {
815        &self.security_level
816    }
817
818    /// Check if debug mode is enabled (includes verbose)
819    pub fn is_debug_mode(&self) -> bool {
820        self.debug || self.verbose
821    }
822}