vtcode_core/cli/
args.rs

1//! CLI argument parsing and configuration
2
3use crate::config::models::ModelId;
4use clap::{ColorChoice, Parser, Subcommand, ValueEnum, 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-5 - 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    /// Start Agent Client Protocol bridge for IDE integrations
208    #[command(name = "acp")]
209    AgentClientProtocol {
210        /// Client to connect over ACP
211        #[arg(value_enum, default_value_t = AgentClientProtocolTarget::Zed)]
212        target: AgentClientProtocolTarget,
213    },
214
215    /// **Interactive AI coding assistant** with advanced capabilities
216    ///
217    /// Features:
218    ///   • Real-time code generation and editing
219    ///   • Tree-sitter powered analysis
220    ///   • Research-preview context management
221    ///
222    /// Usage: vtcode chat
223    Chat,
224
225    /// **Single prompt mode** - prints model reply without tools
226    ///
227    /// Perfect for:
228    ///   • Quick questions
229    ///   • Code explanations
230    ///   • Simple queries
231    ///
232    /// Example: vtcode ask "Explain Rust ownership"
233    Ask { prompt: String },
234
235    /// **Verbose interactive chat** with enhanced transparency
236    ///
237    /// Shows:
238    ///   • Tool execution details
239    ///   • API request/response
240    ///   • Performance metrics
241    ///
242    /// Usage: vtcode chat-verbose
243    ChatVerbose,
244
245    /// **Analyze workspace** with tree-sitter integration
246    ///
247    /// Provides:
248    ///   • Project structure analysis
249    ///   • Language detection
250    ///   • Code complexity metrics
251    ///   • Dependency insights
252    ///   • Symbol extraction
253    ///
254    /// Usage: vtcode analyze
255    Analyze,
256
257    /// **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
258    Performance,
259
260    /// Pretty-print trajectory logs and show basic analytics
261    ///
262    /// Sources:
263    ///   • .vtcode/logs/trajectory.jsonl (default)
264    /// Options:
265    ///   • --file to specify an alternate path
266    ///   • --top to limit report rows (default: 10)
267    ///
268    /// Shows:
269    ///   • Class distribution with percentages
270    ///   • Model usage statistics
271    ///   • Tool success rates with status indicators
272    ///   • Time range of logged activity
273    #[command(name = "trajectory")]
274    Trajectory {
275        /// Optional path to trajectory JSONL file
276        #[arg(long)]
277        file: Option<std::path::PathBuf>,
278        /// Number of top entries to show for each section
279        #[arg(long, default_value_t = 10)]
280        top: usize,
281    },
282
283    /// **Benchmark against SWE-bench evaluation framework**
284    ///
285    /// Features:
286    ///   • Automated performance testing
287    ///   • Comparative analysis across models
288    ///   • Benchmark scoring and metrics
289    ///   • Optimization insights
290    ///
291    /// Usage: vtcode benchmark
292    Benchmark,
293
294    /// **Create complete Rust project with advanced features**
295    ///
296    /// Features:
297    ///   • Web frameworks (Axum, Rocket, Warp)
298    ///   • Database integration
299    ///   • Authentication systems
300    ///   • Testing setup
301    ///   • Tree-sitter integration
302    ///
303    /// Example: vtcode create-project myapp web,auth,db
304    CreateProject { name: String, features: Vec<String> },
305
306    /// **Compress conversation context** for long-running sessions
307    ///
308    /// Benefits:
309    ///   • Reduced token usage
310    ///   • Faster responses
311    ///   • Memory optimization
312    ///   • Context preservation
313    ///
314    /// Usage: vtcode compress-context
315    CompressContext,
316
317    /// **Revert agent to a previous snapshot
318    ///
319    /// Features:
320    ///   • Revert to any previous turn
321    ///   • Partial reverts (memory, context, full)
322    ///   • Safe rollback with validation
323    ///
324    /// Examples:
325    ///   vtcode revert --turn 5
326    ///   vtcode revert --turn 3 --partial memory
327    Revert {
328        /// Turn number to revert to
329        ///
330        /// Required: Yes
331        /// Example: 5
332        #[arg(short, long)]
333        turn: usize,
334
335        /// Scope of revert operation
336        ///
337        /// Options: memory, context, full
338        /// Default: full
339        /// Examples:
340        ///   --partial memory (revert conversation only)
341        ///   --partial context (revert decisions/errors only)
342        #[arg(short, long)]
343        partial: Option<String>,
344    },
345
346    /// **List all available snapshots**
347    ///
348    /// Shows:
349    ///   • Snapshot ID and turn number
350    ///   • Creation timestamp
351    ///   • Description
352    ///   • File size and compression status
353    ///
354    /// Usage: vtcode snapshots
355    Snapshots,
356
357    /// **Clean up old snapshots**
358    ///
359    /// Features:
360    ///   • Remove snapshots beyond limit
361    ///   • Configurable retention policy
362    ///   • Safe deletion with confirmation
363    ///
364    /// Examples:
365    ///   vtcode cleanup-snapshots
366    ///   vtcode cleanup-snapshots --max 20
367    #[command(name = "cleanup-snapshots")]
368    CleanupSnapshots {
369        /// Maximum number of snapshots to keep
370        ///
371        /// Default: 50
372        /// Example: --max 20
373        #[arg(short, long, default_value_t = 50)]
374        max: usize,
375    },
376
377    /// **Initialize project** with enhanced dot-folder structure
378    ///
379    /// Features:
380    ///   • Creates project directory structure
381    ///   • Sets up config, cache, embeddings directories
382    ///   • Creates .project metadata file
383    ///   • Tree-sitter parser setup
384    ///
385    /// Usage: vtcode init
386    Init,
387
388    /// **Initialize project with dot-folder structure** - sets up ~/.vtcode/projects/<project-name> structure
389    ///
390    /// Features:
391    ///   • Creates project directory structure in ~/.vtcode/projects/
392    ///   • Sets up config, cache, embeddings, and retrieval directories
393    ///   • Creates .project metadata file
394    ///   • Migrates existing config/cache files with user confirmation
395    ///
396    /// Examples:
397    ///   vtcode init-project
398    ///   vtcode init-project --name my-project
399    ///   vtcode init-project --force
400    #[command(name = "init-project")]
401    InitProject {
402        /// Project name - defaults to current directory name
403        #[arg(long)]
404        name: Option<String>,
405
406        /// Force initialization - overwrite existing project structure
407        #[arg(long)]
408        force: bool,
409
410        /// Migrate existing files - move existing config/cache files to new structure
411        #[arg(long)]
412        migrate: bool,
413    },
414
415    /// **Generate configuration file - creates a vtcode.toml configuration file
416    ///
417    /// Features:
418    ///   • Generate default configuration
419    ///   • Support for global (home directory) and local configuration
420    ///   • TOML format with comprehensive settings
421    ///   • Tree-sitter and performance monitoring settings
422    ///
423    /// Examples:
424    ///   vtcode config
425    ///   vtcode config --output ./custom-config.toml
426    ///   vtcode config --global
427    Config {
428        /// Output file path - where to save the configuration file
429        #[arg(long)]
430        output: Option<std::path::PathBuf>,
431
432        /// Create in user home directory - creates ~/.vtcode/vtcode.toml
433        #[arg(long)]
434        global: bool,
435    },
436
437    /// **Manage tool execution policies** - control which tools the agent can use
438    ///
439    /// Features:
440    ///   • Granular tool permissions
441    ///   • Security level presets
442    ///   • Audit logging
443    ///   • Safe tool execution
444    ///
445    /// Examples:
446    ///   vtcode tool-policy status
447    ///   vtcode tool-policy allow file-write
448    ///   vtcode tool-policy deny shell-exec
449    #[command(name = "tool-policy")]
450    ToolPolicy {
451        #[command(subcommand)]
452        command: crate::cli::tool_policy_commands::ToolPolicyCommands,
453    },
454
455    /// **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
456    Models {
457        #[command(subcommand)]
458        command: ModelCommands,
459    },
460
461    /// **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
462    Security,
463
464    /// **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
465    #[command(name = "tree-sitter")]
466    TreeSitter,
467
468    /// **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
469    Man {
470        /// **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**
471        command: Option<String>,
472
473        /// **Output file path** to save man page\n\n**Format:** Standard Unix man page format (.1, .8, etc.)\n**Default:** Display to stdout
474        #[arg(short, long)]
475        output: Option<std::path::PathBuf>,
476    },
477}
478
479/// Supported Agent Client Protocol clients
480#[derive(Clone, Copy, Debug, ValueEnum)]
481pub enum AgentClientProtocolTarget {
482    /// Zed IDE integration
483    Zed,
484}
485
486/// Model management commands with concise, actionable help
487#[derive(Subcommand, Debug)]
488pub enum ModelCommands {
489    /// List all providers and models with status indicators
490    List,
491
492    /// Set default provider (gemini, openai, anthropic, deepseek)
493    #[command(name = "set-provider")]
494    SetProvider {
495        /// Provider name to set as default
496        provider: String,
497    },
498
499    /// Set default model (e.g., deepseek-reasoner, gpt-5, claude-sonnet-4-5)
500    #[command(name = "set-model")]
501    SetModel {
502        /// Model name to set as default
503        model: String,
504    },
505
506    /// Configure provider settings (API keys, base URLs, models)
507    Config {
508        /// Provider name to configure
509        provider: String,
510
511        /// API key for the provider
512        #[arg(long)]
513        api_key: Option<String>,
514
515        /// Base URL for local providers
516        #[arg(long)]
517        base_url: Option<String>,
518
519        /// Default model for this provider
520        #[arg(long)]
521        model: Option<String>,
522    },
523
524    /// Test provider connectivity and validate configuration
525    Test {
526        /// Provider name to test
527        provider: String,
528    },
529
530    /// Compare model performance across providers (coming soon)
531    Compare,
532
533    /// Show detailed model information and specifications
534    Info {
535        /// Model name to get information about
536        model: String,
537    },
538}
539
540/// Configuration file structure with latest features
541#[derive(Debug)]
542pub struct ConfigFile {
543    pub model: Option<String>,
544    pub provider: Option<String>,
545    pub api_key_env: Option<String>,
546    pub verbose: Option<bool>,
547    pub log_level: Option<String>,
548    pub workspace: Option<PathBuf>,
549    pub tools: Option<ToolConfig>,
550    pub context: Option<ContextConfig>,
551    pub logging: Option<LoggingConfig>,
552    pub tree_sitter: Option<TreeSitterConfig>,
553    pub performance: Option<PerformanceConfig>,
554    pub security: Option<SecurityConfig>,
555}
556
557/// Tool configuration from config file
558#[derive(Debug, serde::Deserialize)]
559pub struct ToolConfig {
560    pub enable_validation: Option<bool>,
561    pub max_execution_time_seconds: Option<u64>,
562    pub allow_file_creation: Option<bool>,
563    pub allow_file_deletion: Option<bool>,
564}
565
566/// Context management configuration
567#[derive(Debug, serde::Deserialize)]
568pub struct ContextConfig {
569    pub max_context_length: Option<usize>,
570    pub compression_threshold: Option<usize>,
571    pub summarization_interval: Option<usize>,
572}
573
574/// Logging configuration
575#[derive(Debug, serde::Deserialize)]
576pub struct LoggingConfig {
577    pub file_logging: Option<bool>,
578    pub log_directory: Option<String>,
579    pub max_log_files: Option<usize>,
580    pub max_log_size_mb: Option<usize>,
581}
582
583/// Tree-sitter configuration
584#[derive(Debug, serde::Deserialize)]
585pub struct TreeSitterConfig {
586    pub enabled: Option<bool>,
587    pub supported_languages: Option<Vec<String>>,
588    pub max_file_size_kb: Option<usize>,
589    pub enable_symbol_extraction: Option<bool>,
590    pub enable_complexity_analysis: Option<bool>,
591}
592
593/// Performance monitoring configuration
594#[derive(Debug, serde::Deserialize)]
595pub struct PerformanceConfig {
596    pub enabled: Option<bool>,
597    pub track_token_usage: Option<bool>,
598    pub track_api_costs: Option<bool>,
599    pub track_response_times: Option<bool>,
600    pub enable_benchmarking: Option<bool>,
601    pub metrics_retention_days: Option<usize>,
602}
603
604/// Security configuration
605#[derive(Debug, serde::Deserialize)]
606pub struct SecurityConfig {
607    pub level: Option<String>,
608    pub enable_audit_logging: Option<bool>,
609    pub enable_vulnerability_scanning: Option<bool>,
610    pub allow_external_urls: Option<bool>,
611    pub max_file_access_depth: Option<usize>,
612}
613
614impl Default for Cli {
615    fn default() -> Self {
616        Self {
617            color: ColorSelection {
618                color: ColorChoice::Auto,
619            },
620            workspace_path: None,
621            model: Some(ModelId::default().as_str().to_string()),
622            provider: Some("gemini".to_string()),
623            api_key_env: "GEMINI_API_KEY".to_string(),
624            workspace: None,
625            enable_tree_sitter: false,
626            performance_monitoring: false,
627            research_preview: false,
628            security_level: "moderate".to_string(),
629            show_file_diffs: false,
630            max_concurrent_ops: 5,
631            api_rate_limit: 30,
632            max_tool_calls: 10,
633            verbose: false,
634            config: None,
635            log_level: "info".to_string(),
636            no_color: false,
637            theme: None,
638            skip_confirmations: false,
639            full_auto: false,
640            debug: false,
641            command: Some(Commands::Chat),
642        }
643    }
644}
645
646impl Cli {
647    /// Get the model to use, with fallback to default
648    pub fn get_model(&self) -> String {
649        self.model
650            .clone()
651            .unwrap_or_else(|| ModelId::default().as_str().to_string())
652    }
653
654    /// Load configuration from a simple TOML-like file without external deps
655    ///
656    /// Supported keys (top-level): model, api_key_env, verbose, log_level, workspace
657    /// Example:
658    ///   model = "gemini-2.5-flash-preview-05-20"
659    ///   api_key_env = "GEMINI_API_KEY"
660    ///   verbose = true
661    ///   log_level = "info"
662    ///   workspace = "/path/to/workspace"
663    pub fn load_config(&self) -> Result<ConfigFile, Box<dyn std::error::Error>> {
664        use std::fs;
665        use std::path::Path;
666
667        // Resolve candidate path
668        let path = if let Some(p) = &self.config {
669            p.clone()
670        } else {
671            let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
672            let primary = cwd.join("vtcode.toml");
673            let secondary = cwd.join(".vtcode.toml");
674            if primary.exists() {
675                primary
676            } else if secondary.exists() {
677                secondary
678            } else {
679                // No config file; return empty config
680                return Ok(ConfigFile {
681                    model: None,
682                    provider: None,
683                    api_key_env: None,
684                    verbose: None,
685                    log_level: None,
686                    workspace: None,
687                    tools: None,
688                    context: None,
689                    logging: None,
690                    tree_sitter: None,
691                    performance: None,
692                    security: None,
693                });
694            }
695        };
696
697        let text = fs::read_to_string(&path)?;
698
699        // Very small parser: key = value, supports quoted strings, booleans, and plain paths
700        let mut cfg = ConfigFile {
701            model: None,
702            provider: None,
703            api_key_env: None,
704            verbose: None,
705            log_level: None,
706            workspace: None,
707            tools: None,
708            context: None,
709            logging: None,
710            tree_sitter: None,
711            performance: None,
712            security: None,
713        };
714
715        for raw_line in text.lines() {
716            let line = raw_line.trim();
717            if line.is_empty() || line.starts_with('#') || line.starts_with("//") {
718                continue;
719            }
720            // Strip inline comments after '#'
721            let line = match line.find('#') {
722                Some(idx) => &line[..idx],
723                None => line,
724            }
725            .trim();
726
727            // Expect key = value
728            let mut parts = line.splitn(2, '=');
729            let key = parts.next().map(|s| s.trim()).unwrap_or("");
730            let val = parts.next().map(|s| s.trim()).unwrap_or("");
731            if key.is_empty() || val.is_empty() {
732                continue;
733            }
734
735            // Remove surrounding quotes if present
736            let unquote = |s: &str| -> String {
737                let s = s.trim();
738                if (s.starts_with('"') && s.ends_with('"'))
739                    || (s.starts_with('\'') && s.ends_with('\''))
740                {
741                    s[1..s.len() - 1].to_string()
742                } else {
743                    s.to_string()
744                }
745            };
746
747            match key {
748                "model" => cfg.model = Some(unquote(val)),
749                "api_key_env" => cfg.api_key_env = Some(unquote(val)),
750                "verbose" => {
751                    let v = unquote(val).to_lowercase();
752                    cfg.verbose = Some(matches!(v.as_str(), "true" | "1" | "yes"));
753                }
754                "log_level" => cfg.log_level = Some(unquote(val)),
755                "workspace" => {
756                    let v = unquote(val);
757                    let p = if Path::new(&v).is_absolute() {
758                        PathBuf::from(v)
759                    } else {
760                        // Resolve relative to config file directory
761                        let base = path.parent().unwrap_or(Path::new("."));
762                        base.join(v)
763                    };
764                    cfg.workspace = Some(p);
765                }
766                _ => {
767                    // Ignore unknown keys in this minimal parser
768                }
769            }
770        }
771
772        Ok(cfg)
773    }
774
775    /// Get the effective workspace path
776    pub fn get_workspace(&self) -> std::path::PathBuf {
777        self.workspace
778            .clone()
779            .unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")))
780    }
781
782    /// Get the effective API key environment variable
783    ///
784    /// Automatically infers the API key environment variable based on the provider
785    /// when the current value matches the default or is not explicitly set.
786    pub fn get_api_key_env(&self) -> String {
787        // If api_key_env is the default or empty, infer from provider
788        if self.api_key_env == crate::config::constants::defaults::DEFAULT_API_KEY_ENV
789            || self.api_key_env.is_empty()
790        {
791            if let Some(provider) = &self.provider {
792                match provider.to_lowercase().as_str() {
793                    "openai" => "OPENAI_API_KEY".to_string(),
794                    "anthropic" => "ANTHROPIC_API_KEY".to_string(),
795                    "gemini" => "GEMINI_API_KEY".to_string(),
796                    "deepseek" => "DEEPSEEK_API_KEY".to_string(),
797                    "openrouter" => "OPENROUTER_API_KEY".to_string(),
798                    "xai" => "XAI_API_KEY".to_string(),
799                    _ => "GEMINI_API_KEY".to_string(),
800                }
801            } else {
802                "GEMINI_API_KEY".to_string()
803            }
804        } else {
805            self.api_key_env.clone()
806        }
807    }
808
809    /// Check if verbose mode is enabled
810    pub fn is_verbose(&self) -> bool {
811        self.verbose
812    }
813
814    /// Check if tree-sitter analysis is enabled
815    pub fn is_tree_sitter_enabled(&self) -> bool {
816        self.enable_tree_sitter
817    }
818
819    /// Check if performance monitoring is enabled
820    pub fn is_performance_monitoring_enabled(&self) -> bool {
821        self.performance_monitoring
822    }
823
824    /// Check if research-preview features are enabled
825    pub fn is_research_preview_enabled(&self) -> bool {
826        self.research_preview
827    }
828
829    /// Get the security level
830    pub fn get_security_level(&self) -> &str {
831        &self.security_level
832    }
833
834    /// Check if debug mode is enabled (includes verbose)
835    pub fn is_debug_mode(&self) -> bool {
836        self.debug || self.verbose
837    }
838}