destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
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
//! AI coding agent detection for agent-specific profiles.
//!
//! This module detects which AI coding agent is invoking dcg, enabling per-agent
//! trust levels and configuration overrides.
//!
//! # Detection Methods
//!
//! 1. **Environment variables** (primary): Most agents set identifying env vars
//! 2. **Explicit flag**: `--agent=<name>` CLI flag for manual override
//! 3. **Parent process inspection** (fallback): Check process tree for agent names
//!
//! # Supported Agents
//!
//! - Claude Code: `CLAUDE_CODE=1` or `CLAUDE_SESSION_ID` env var
//! - Augment Code: `AUGMENT_AGENT=1` or `AUGMENT_CONVERSATION_ID` env var
//! - Aider: `AIDER_SESSION=1` env var
//! - Continue: `CONTINUE_SESSION_ID` env var
//! - Codex CLI: `CODEX_CLI=1` env var
//! - Gemini CLI: `GEMINI_CLI=1` env var
//! - Copilot CLI: `COPILOT_CLI=1` or `COPILOT_AGENT_START_TIME_SEC` env var
//!
//! # Usage
//!
//! ```ignore
//! use destructive_command_guard::agent::{Agent, detect_agent};
//!
//! let agent = detect_agent();
//! println!("Detected agent: {}", agent);
//! ```

use std::cell::RefCell;
use std::fmt;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

/// Cache duration before refreshing agent detection.
/// Agent detection is stable within a process, so we use a longer TTL.
const CACHE_TTL: Duration = Duration::from_secs(300);

/// Known AI coding agents that dcg can detect and configure per-agent policies for.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Agent {
    /// Claude Code from Anthropic.
    ClaudeCode,
    /// Augment Code CLI (auggie).
    AugmentCode,
    /// Aider AI coding assistant.
    Aider,
    /// Continue.dev IDE extension.
    Continue,
    /// `OpenAI` Codex CLI.
    CodexCli,
    /// Google Gemini CLI.
    GeminiCli,
    /// GitHub Copilot CLI.
    CopilotCli,
    /// A custom agent specified by name.
    Custom(String),
    /// Unknown or undetected agent.
    Unknown,
}

impl Agent {
    /// Returns the canonical configuration key for this agent.
    ///
    /// This is used to look up agent-specific configuration in config files.
    /// For example, `Agent::ClaudeCode.config_key()` returns `"claude-code"`.
    #[must_use]
    pub fn config_key(&self) -> &str {
        match self {
            Self::ClaudeCode => "claude-code",
            Self::AugmentCode => "augment-code",
            Self::Aider => "aider",
            Self::Continue => "continue",
            Self::CodexCli => "codex-cli",
            Self::GeminiCli => "gemini-cli",
            Self::CopilotCli => "copilot-cli",
            Self::Custom(name) => name,
            Self::Unknown => "unknown",
        }
    }

    /// Returns `true` if this is a known agent (not Unknown or Custom).
    #[must_use]
    pub const fn is_known(&self) -> bool {
        matches!(
            self,
            Self::ClaudeCode
                | Self::AugmentCode
                | Self::Aider
                | Self::Continue
                | Self::CodexCli
                | Self::GeminiCli
                | Self::CopilotCli
        )
    }

    /// Returns `true` if this agent was explicitly specified (not auto-detected).
    #[must_use]
    pub const fn is_explicit(&self) -> bool {
        matches!(self, Self::Custom(_))
    }

    /// Parse an agent name string into an Agent enum.
    ///
    /// Accepts various formats:
    /// - `"claude-code"`, `"claude_code"`, `"claudecode"` -> `ClaudeCode`
    /// - `"augment-code"`, `"augment_code"`, `"augmentcode"`, `"auggie"`, `"augment"` -> `AugmentCode`
    /// - `"aider"` -> `Aider`
    /// - `"continue"` -> `Continue`
    /// - `"codex"`, `"codex-cli"`, `"codex_cli"` -> `CodexCli`
    /// - `"gemini"`, `"gemini-cli"`, `"gemini_cli"` -> `GeminiCli`
    /// - `"unknown"` -> `Unknown`
    /// - Any other value -> `Custom(value)`
    #[must_use]
    pub fn from_name(name: &str) -> Self {
        let normalized = name.to_lowercase().replace(['-', '_'], "");
        match normalized.as_str() {
            "claudecode" => Self::ClaudeCode,
            "augmentcode" | "auggie" | "augment" => Self::AugmentCode,
            "aider" => Self::Aider,
            "continue" => Self::Continue,
            "codexcli" | "codex" => Self::CodexCli,
            "geminicli" | "gemini" => Self::GeminiCli,
            "copilotcli" | "copilot" => Self::CopilotCli,
            "unknown" => Self::Unknown,
            _ => Self::Custom(name.to_string()),
        }
    }
}

impl fmt::Display for Agent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ClaudeCode => write!(f, "Claude Code"),
            Self::AugmentCode => write!(f, "Augment Code"),
            Self::Aider => write!(f, "Aider"),
            Self::Continue => write!(f, "Continue"),
            Self::CodexCli => write!(f, "Codex CLI"),
            Self::GeminiCli => write!(f, "Gemini CLI"),
            Self::CopilotCli => write!(f, "GitHub Copilot CLI"),
            Self::Custom(name) => write!(f, "{name}"),
            Self::Unknown => write!(f, "Unknown"),
        }
    }
}

/// Result of agent detection with metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DetectionResult {
    /// The detected agent.
    pub agent: Agent,
    /// How the agent was detected.
    pub method: DetectionMethod,
    /// The specific environment variable or process name that matched (if any).
    pub matched_value: Option<String>,
}

impl DetectionResult {
    /// Create a new detection result.
    #[must_use]
    pub const fn new(agent: Agent, method: DetectionMethod, matched_value: Option<String>) -> Self {
        Self {
            agent,
            method,
            matched_value,
        }
    }

    /// Create an Unknown detection result.
    #[must_use]
    pub const fn unknown() -> Self {
        Self {
            agent: Agent::Unknown,
            method: DetectionMethod::None,
            matched_value: None,
        }
    }
}

/// How an agent was detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DetectionMethod {
    /// Detected via environment variable.
    Environment,
    /// Explicitly specified via CLI flag.
    Explicit,
    /// Detected via parent process inspection.
    Process,
    /// No detection method succeeded.
    None,
}

impl fmt::Display for DetectionMethod {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Environment => write!(f, "environment variable"),
            Self::Explicit => write!(f, "explicit flag"),
            Self::Process => write!(f, "parent process"),
            Self::None => write!(f, "not detected"),
        }
    }
}

/// Cached agent detection result.
#[derive(Debug)]
struct CachedAgent {
    /// The cached detection result.
    result: DetectionResult,
    /// When this cache entry was created.
    cached_at: Instant,
}

impl CachedAgent {
    /// Returns `true` if this cache entry is still valid.
    fn is_valid(&self) -> bool {
        self.cached_at.elapsed() < CACHE_TTL
    }
}

thread_local! {
    /// Per-thread cache for agent detection.
    static AGENT_CACHE: RefCell<Option<CachedAgent>> = const { RefCell::new(None) };
}

/// Detect the current AI coding agent, using cache if available.
///
/// Returns an [`Agent`] enum indicating which agent is invoking dcg.
/// Results are cached for performance.
///
/// # Detection Order
///
/// 1. Environment variables (checked first as most reliable)
/// 2. Parent process inspection (fallback)
///
/// # Example
///
/// ```ignore
/// use destructive_command_guard::agent::detect_agent;
///
/// let agent = detect_agent();
/// println!("Running under: {}", agent);
/// ```
#[must_use]
pub fn detect_agent() -> Agent {
    detect_agent_with_details().agent
}

/// Detect the current AI coding agent with full details.
///
/// Returns a [`DetectionResult`] containing the agent, detection method,
/// and matched value (if any).
#[must_use]
pub fn detect_agent_with_details() -> DetectionResult {
    // Check cache first
    let cached = AGENT_CACHE.with(|cache| {
        let borrow = cache.borrow();
        if let Some(ref entry) = *borrow {
            if entry.is_valid() {
                return Some(entry.result.clone());
            }
        }
        None
    });

    if let Some(result) = cached {
        return result;
    }

    // Cache miss - perform detection
    let result = perform_detection();

    // Update cache
    AGENT_CACHE.with(|cache| {
        *cache.borrow_mut() = Some(CachedAgent {
            result: result.clone(),
            cached_at: Instant::now(),
        });
    });

    result
}

/// Perform agent detection (not cached).
fn perform_detection() -> DetectionResult {
    // Try environment variable detection first
    if let Some(result) = detect_from_environment() {
        return result;
    }

    // Try parent process detection as fallback
    if let Some(result) = detect_from_parent_process() {
        return result;
    }

    DetectionResult::unknown()
}

/// Detect agent from environment variables.
///
/// Checks for known environment variables set by AI coding agents.
fn detect_from_environment() -> Option<DetectionResult> {
    // Claude Code detection
    if std::env::var("CLAUDE_CODE").is_ok() {
        return Some(DetectionResult::new(
            Agent::ClaudeCode,
            DetectionMethod::Environment,
            Some("CLAUDE_CODE".to_string()),
        ));
    }
    if std::env::var("CLAUDE_SESSION_ID").is_ok() {
        return Some(DetectionResult::new(
            Agent::ClaudeCode,
            DetectionMethod::Environment,
            Some("CLAUDE_SESSION_ID".to_string()),
        ));
    }

    // Augment Code (auggie) detection
    if std::env::var("AUGMENT_AGENT").is_ok() {
        return Some(DetectionResult::new(
            Agent::AugmentCode,
            DetectionMethod::Environment,
            Some("AUGMENT_AGENT".to_string()),
        ));
    }
    if std::env::var("AUGMENT_CONVERSATION_ID").is_ok() {
        return Some(DetectionResult::new(
            Agent::AugmentCode,
            DetectionMethod::Environment,
            Some("AUGMENT_CONVERSATION_ID".to_string()),
        ));
    }

    // Aider detection
    if std::env::var("AIDER_SESSION").is_ok() {
        return Some(DetectionResult::new(
            Agent::Aider,
            DetectionMethod::Environment,
            Some("AIDER_SESSION".to_string()),
        ));
    }

    // Continue detection
    if std::env::var("CONTINUE_SESSION_ID").is_ok() {
        return Some(DetectionResult::new(
            Agent::Continue,
            DetectionMethod::Environment,
            Some("CONTINUE_SESSION_ID".to_string()),
        ));
    }

    // Codex CLI detection
    if std::env::var("CODEX_CLI").is_ok() {
        return Some(DetectionResult::new(
            Agent::CodexCli,
            DetectionMethod::Environment,
            Some("CODEX_CLI".to_string()),
        ));
    }

    // Gemini CLI detection
    if std::env::var("GEMINI_CLI").is_ok() {
        return Some(DetectionResult::new(
            Agent::GeminiCli,
            DetectionMethod::Environment,
            Some("GEMINI_CLI".to_string()),
        ));
    }

    // GitHub Copilot CLI detection
    if std::env::var("COPILOT_CLI").is_ok() {
        return Some(DetectionResult::new(
            Agent::CopilotCli,
            DetectionMethod::Environment,
            Some("COPILOT_CLI".to_string()),
        ));
    }
    if std::env::var("COPILOT_AGENT_START_TIME_SEC").is_ok() {
        return Some(DetectionResult::new(
            Agent::CopilotCli,
            DetectionMethod::Environment,
            Some("COPILOT_AGENT_START_TIME_SEC".to_string()),
        ));
    }

    None
}

/// Detect agent from parent process.
///
/// Reads `/proc/<ppid>/comm` on Linux to check the parent process name.
/// This is a fallback for agents that don't set environment variables.
#[cfg(target_os = "linux")]
fn detect_from_parent_process() -> Option<DetectionResult> {
    use std::fs;
    use std::os::unix::process::parent_id;

    let ppid = parent_id();
    let comm_path = format!("/proc/{ppid}/comm");

    let process_name = fs::read_to_string(&comm_path).ok()?.trim().to_lowercase();

    // Match known agent process names
    if process_name.contains("claude") {
        return Some(DetectionResult::new(
            Agent::ClaudeCode,
            DetectionMethod::Process,
            Some(process_name),
        ));
    }
    if process_name.contains("aider") {
        return Some(DetectionResult::new(
            Agent::Aider,
            DetectionMethod::Process,
            Some(process_name),
        ));
    }
    if process_name.contains("codex") {
        return Some(DetectionResult::new(
            Agent::CodexCli,
            DetectionMethod::Process,
            Some(process_name),
        ));
    }
    if process_name.contains("gemini") {
        return Some(DetectionResult::new(
            Agent::GeminiCli,
            DetectionMethod::Process,
            Some(process_name),
        ));
    }
    if process_name.contains("copilot") {
        return Some(DetectionResult::new(
            Agent::CopilotCli,
            DetectionMethod::Process,
            Some(process_name),
        ));
    }

    None
}

/// Detect agent from parent process (non-Linux fallback - returns None).
#[cfg(not(target_os = "linux"))]
fn detect_from_parent_process() -> Option<DetectionResult> {
    // Parent process detection is currently only implemented for Linux.
    // On other platforms, we rely solely on environment variable detection.
    None
}

/// Create a detection result from an explicit agent name.
///
/// Used when the user specifies `--agent=<name>` on the command line.
#[must_use]
pub fn from_explicit(name: &str) -> DetectionResult {
    DetectionResult::new(
        Agent::from_name(name),
        DetectionMethod::Explicit,
        Some(name.to_string()),
    )
}

/// Clear the agent detection cache.
///
/// Useful for testing or when environment variables change.
pub fn clear_cache() {
    AGENT_CACHE.with(|cache| {
        *cache.borrow_mut() = None;
    });
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_agent_config_keys() {
        assert_eq!(Agent::ClaudeCode.config_key(), "claude-code");
        assert_eq!(Agent::AugmentCode.config_key(), "augment-code");
        assert_eq!(Agent::Aider.config_key(), "aider");
        assert_eq!(Agent::Continue.config_key(), "continue");
        assert_eq!(Agent::CodexCli.config_key(), "codex-cli");
        assert_eq!(Agent::GeminiCli.config_key(), "gemini-cli");
        assert_eq!(Agent::CopilotCli.config_key(), "copilot-cli");
        assert_eq!(Agent::Unknown.config_key(), "unknown");
        assert_eq!(
            Agent::Custom("my-agent".to_string()).config_key(),
            "my-agent"
        );
    }

    #[test]
    fn test_agent_from_name() {
        // Standard names
        assert_eq!(Agent::from_name("claude-code"), Agent::ClaudeCode);
        assert_eq!(Agent::from_name("augment-code"), Agent::AugmentCode);
        assert_eq!(Agent::from_name("aider"), Agent::Aider);
        assert_eq!(Agent::from_name("continue"), Agent::Continue);
        assert_eq!(Agent::from_name("codex-cli"), Agent::CodexCli);
        assert_eq!(Agent::from_name("gemini-cli"), Agent::GeminiCli);
        assert_eq!(Agent::from_name("unknown"), Agent::Unknown);

        // Variations
        assert_eq!(Agent::from_name("Claude-Code"), Agent::ClaudeCode);
        assert_eq!(Agent::from_name("CLAUDE_CODE"), Agent::ClaudeCode);
        assert_eq!(Agent::from_name("claudecode"), Agent::ClaudeCode);
        assert_eq!(Agent::from_name("augmentcode"), Agent::AugmentCode);
        assert_eq!(Agent::from_name("auggie"), Agent::AugmentCode);
        assert_eq!(Agent::from_name("augment"), Agent::AugmentCode);
        assert_eq!(Agent::from_name("codex"), Agent::CodexCli);
        assert_eq!(Agent::from_name("gemini"), Agent::GeminiCli);
        assert_eq!(Agent::from_name("copilot"), Agent::CopilotCli);
        assert_eq!(Agent::from_name("copilotcli"), Agent::CopilotCli);
        assert_eq!(Agent::from_name("copilot-cli"), Agent::CopilotCli);

        // Custom agents
        assert_eq!(
            Agent::from_name("my-custom-agent"),
            Agent::Custom("my-custom-agent".to_string())
        );
    }

    #[test]
    fn test_agent_display() {
        assert_eq!(format!("{}", Agent::ClaudeCode), "Claude Code");
        assert_eq!(format!("{}", Agent::AugmentCode), "Augment Code");
        assert_eq!(format!("{}", Agent::Aider), "Aider");
        assert_eq!(format!("{}", Agent::Continue), "Continue");
        assert_eq!(format!("{}", Agent::CodexCli), "Codex CLI");
        assert_eq!(format!("{}", Agent::GeminiCli), "Gemini CLI");
        assert_eq!(format!("{}", Agent::CopilotCli), "GitHub Copilot CLI");
        assert_eq!(format!("{}", Agent::Unknown), "Unknown");
        assert_eq!(
            format!("{}", Agent::Custom("MyAgent".to_string())),
            "MyAgent"
        );
    }

    #[test]
    fn test_agent_is_known() {
        assert!(Agent::ClaudeCode.is_known());
        assert!(Agent::AugmentCode.is_known());
        assert!(Agent::Aider.is_known());
        assert!(Agent::CopilotCli.is_known());
        assert!(!Agent::Unknown.is_known());
        assert!(!Agent::Custom("x".to_string()).is_known());
    }

    #[test]
    fn test_detection_method_display() {
        assert_eq!(
            format!("{}", DetectionMethod::Environment),
            "environment variable"
        );
        assert_eq!(format!("{}", DetectionMethod::Explicit), "explicit flag");
        assert_eq!(format!("{}", DetectionMethod::Process), "parent process");
        assert_eq!(format!("{}", DetectionMethod::None), "not detected");
    }

    #[test]
    fn test_from_explicit() {
        let result = from_explicit("claude-code");
        assert_eq!(result.agent, Agent::ClaudeCode);
        assert_eq!(result.method, DetectionMethod::Explicit);
        assert_eq!(result.matched_value, Some("claude-code".to_string()));
    }

    #[test]
    fn test_cache_clear() {
        // This test verifies that clear_cache doesn't panic
        clear_cache();
        let _ = detect_agent();
        clear_cache();
    }

    // Note: Environment variable detection tests are in a separate test module
    // that uses temp_env to safely manipulate environment variables.
}

#[cfg(test)]
mod env_tests {
    use super::*;
    use std::sync::Mutex;

    /// Mutex to serialize tests that manipulate environment variables.
    /// This prevents race conditions when tests run in parallel.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    /// All known agent environment variable keys.
    const AGENT_ENV_VARS: &[&str] = &[
        "CLAUDE_CODE",
        "CLAUDE_SESSION_ID",
        "AUGMENT_AGENT",
        "AUGMENT_CONVERSATION_ID",
        "AIDER_SESSION",
        "CONTINUE_SESSION_ID",
        "CODEX_CLI",
        "GEMINI_CLI",
        "COPILOT_CLI",
        "COPILOT_AGENT_START_TIME_SEC",
    ];

    fn with_env_var<F, R>(key: &str, value: &str, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        // Acquire lock to prevent race conditions with parallel tests
        let _lock = ENV_LOCK.lock().unwrap();

        // Clear cache before test
        clear_cache();

        // SAFETY: We hold ENV_LOCK during all tests that modify environment
        // variables, preventing concurrent modifications.

        // Save and clear all agent env vars (to avoid ambient env interference)
        let saved: Vec<_> = AGENT_ENV_VARS
            .iter()
            .map(|&k| (k, std::env::var(k).ok()))
            .collect();

        unsafe {
            for &k in AGENT_ENV_VARS {
                std::env::remove_var(k);
            }
            // Set the test env var
            std::env::set_var(key, value);
        }

        // Run test
        let result = f();

        // SAFETY: See above
        unsafe {
            // Clean up - restore original values
            std::env::remove_var(key);
            for (k, v) in saved {
                if let Some(val) = v {
                    std::env::set_var(k, val);
                }
            }
        }
        clear_cache();

        result
    }

    #[test]
    fn test_detect_claude_code_env() {
        with_env_var("CLAUDE_CODE", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::ClaudeCode);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("CLAUDE_CODE".to_string()));
        });
    }

    #[test]
    fn test_detect_claude_session_id_env() {
        with_env_var("CLAUDE_SESSION_ID", "abc123", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::ClaudeCode);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("CLAUDE_SESSION_ID".to_string()));
        });
    }

    #[test]
    fn test_detect_augment_agent_env() {
        with_env_var("AUGMENT_AGENT", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::AugmentCode);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("AUGMENT_AGENT".to_string()));
        });
    }

    #[test]
    fn test_detect_augment_conversation_id_env() {
        with_env_var("AUGMENT_CONVERSATION_ID", "conv123", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::AugmentCode);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(
                result.matched_value,
                Some("AUGMENT_CONVERSATION_ID".to_string())
            );
        });
    }

    #[test]
    fn test_detect_aider_env() {
        with_env_var("AIDER_SESSION", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::Aider);
            assert_eq!(result.method, DetectionMethod::Environment);
        });
    }

    #[test]
    fn test_detect_continue_env() {
        with_env_var("CONTINUE_SESSION_ID", "session123", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::Continue);
            assert_eq!(result.method, DetectionMethod::Environment);
        });
    }

    #[test]
    fn test_detect_codex_cli_env() {
        with_env_var("CODEX_CLI", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::CodexCli);
            assert_eq!(result.method, DetectionMethod::Environment);
        });
    }

    #[test]
    fn test_detect_gemini_cli_env() {
        with_env_var("GEMINI_CLI", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::GeminiCli);
            assert_eq!(result.method, DetectionMethod::Environment);
        });
    }

    #[test]
    fn test_detect_copilot_cli_env() {
        with_env_var("COPILOT_CLI", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::CopilotCli);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("COPILOT_CLI".to_string()));
        });
    }

    #[test]
    fn test_detect_copilot_agent_start_time_env() {
        with_env_var("COPILOT_AGENT_START_TIME_SEC", "1709573241", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::CopilotCli);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(
                result.matched_value,
                Some("COPILOT_AGENT_START_TIME_SEC".to_string())
            );
        });
    }

    #[test]
    fn test_detect_unknown_no_env() {
        // Acquire lock to prevent race conditions with parallel tests
        let _lock = ENV_LOCK.lock().unwrap();

        // Ensure no agent env vars are set
        clear_cache();
        // SAFETY: We hold ENV_LOCK during this test, preventing concurrent
        // modifications to environment variables.
        unsafe {
            std::env::remove_var("CLAUDE_CODE");
            std::env::remove_var("CLAUDE_SESSION_ID");
            std::env::remove_var("AUGMENT_AGENT");
            std::env::remove_var("AUGMENT_CONVERSATION_ID");
            std::env::remove_var("AIDER_SESSION");
            std::env::remove_var("CONTINUE_SESSION_ID");
            std::env::remove_var("CODEX_CLI");
            std::env::remove_var("GEMINI_CLI");
            std::env::remove_var("COPILOT_CLI");
            std::env::remove_var("COPILOT_AGENT_START_TIME_SEC");
        }

        // Detection should fall back to process detection or Unknown
        let result = detect_agent_with_details();
        // On most test runners, we'll get Unknown since they're not running
        // under an AI agent
        assert!(
            result.method == DetectionMethod::None || result.method == DetectionMethod::Process
        );
    }
}