destructive_command_guard 0.5.6

An AI coding agent 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
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
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
//! 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. **Explicit flag**: `--agent=<name>` CLI flag for manual override
//! 2. **Environment variables**: Most agents set identifying env vars
//! 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
//! - Cursor IDE: `CURSOR_IDE=1` env var (set by dcg's Cursor hook script)
//! - Hermes Agent: `HERMES_AGENT=1` or `HERMES_SESSION_ID` env var
//! - Grok (xAI): `GROK_SESSION_ID`, `GROK_HOOK_EVENT`, or `GROK_WORKSPACE_ROOT`
//!   env var (set when Grok invokes hooks defined in `~/.grok/hooks/*.json`,
//!   `.grok/hooks/*.json`, or `~/.claude/settings.json` via the Claude-Code
//!   compatibility layer)
//!
//! # 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);

const WINDOWS_EXECUTABLE_SUFFIXES: &[&str] = &[".exe", ".cmd", ".bat", ".ps1"];

/// 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,
    /// Cursor IDE (via beforeShellExecution hook).
    CursorIde,
    /// `NousResearch` Hermes Agent (via shell `pre_tool_call` hook).
    Hermes,
    /// xAI Grok CLI / Grok Build TUI (via `~/.grok/hooks/*.json` and the
    /// `~/.claude/settings.json` compatibility layer; emits `pre_tool_use`
    /// events with `run_terminal_cmd` as the shell tool).
    Grok,
    /// 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::CursorIde => "cursor-ide",
            Self::Hermes => "hermes",
            Self::Grok => "grok",
            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
                | Self::CursorIde
                | Self::Hermes
                | Self::Grok
        )
    }

    /// Returns `true` if this is a custom, non-built-in agent name.
    ///
    /// Whether a built-in agent was explicitly specified is stored on
    /// [`DetectionResult::method`], not on the [`Agent`] enum.
    #[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`
    /// - `"cursor"`, `"cursor-ide"`, `"cursor_ide"` -> `CursorIde`
    /// - `"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,
            "cursoride" | "cursor" => Self::CursorIde,
            "hermes" | "hermesagent" | "hermescli" => Self::Hermes,
            "grok" | "grokcli" | "grokbuild" | "xai" | "xaigrok" => Self::Grok,
            "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::CursorIde => write!(f, "Cursor IDE"),
            Self::Hermes => write!(f, "Hermes Agent"),
            Self::Grok => write!(f, "Grok (xAI)"),
            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. Explicit `--agent` CLI flag
/// 2. Environment variables
/// 3. 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 {
    // Honor explicit CLI override before ambient environment detection.
    if let Some(agent_name) = explicit_agent_from_args(std::env::args()) {
        return from_explicit(&agent_name);
    }

    // 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()
}

fn explicit_agent_from_args<I, S>(args: I) -> Option<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    let mut args = args.into_iter().skip(1);
    while let Some(arg) = args.next() {
        let arg = arg.as_ref();
        if arg == "--" {
            break;
        }
        if let Some(value) = arg.strip_prefix("--agent=") {
            return non_empty_agent_name(value);
        }
        if arg == "--agent" {
            return args
                .next()
                .and_then(|value| non_empty_agent_name(value.as_ref()));
        }
    }

    None
}

fn non_empty_agent_name(value: &str) -> Option<String> {
    let value = value.trim();
    if value.is_empty() {
        None
    } else {
        Some(value.to_string())
    }
}

/// 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()),
        ));
    }

    // Cursor IDE detection (set by dcg's Cursor hook script before invoking dcg)
    if std::env::var("CURSOR_IDE").is_ok() {
        return Some(DetectionResult::new(
            Agent::CursorIde,
            DetectionMethod::Environment,
            Some("CURSOR_IDE".to_string()),
        ));
    }

    // Hermes Agent detection. Hermes documents `HERMES_ACCEPT_HOOKS` for
    // bypassing consent prompts; we treat `HERMES_AGENT` / `HERMES_SESSION_ID`
    // as the canonical session markers (mirroring CLAUDE_CODE / CLAUDE_SESSION_ID).
    if std::env::var("HERMES_AGENT").is_ok() {
        return Some(DetectionResult::new(
            Agent::Hermes,
            DetectionMethod::Environment,
            Some("HERMES_AGENT".to_string()),
        ));
    }
    if std::env::var("HERMES_SESSION_ID").is_ok() {
        return Some(DetectionResult::new(
            Agent::Hermes,
            DetectionMethod::Environment,
            Some("HERMES_SESSION_ID".to_string()),
        ));
    }

    // Grok (xAI) detection. Grok sets three variables when invoking hooks
    // (per ~/.grok/docs/user-guide/10-hooks.md):
    //   - GROK_HOOK_EVENT       (e.g. "pre_tool_use")
    //   - GROK_SESSION_ID       (the current session id)
    //   - GROK_WORKSPACE_ROOT   (workspace root path)
    // Any one of these is sufficient to identify the invoking agent.
    if std::env::var("GROK_SESSION_ID").is_ok() {
        return Some(DetectionResult::new(
            Agent::Grok,
            DetectionMethod::Environment,
            Some("GROK_SESSION_ID".to_string()),
        ));
    }
    if std::env::var("GROK_HOOK_EVENT").is_ok() {
        return Some(DetectionResult::new(
            Agent::Grok,
            DetectionMethod::Environment,
            Some("GROK_HOOK_EVENT".to_string()),
        ));
    }
    if std::env::var("GROK_WORKSPACE_ROOT").is_ok() {
        return Some(DetectionResult::new(
            Agent::Grok,
            DetectionMethod::Environment,
            Some("GROK_WORKSPACE_ROOT".to_string()),
        ));
    }

    None
}

/// Detect agent from parent process.
///
/// 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");

    if let Ok(process_name) = fs::read_to_string(&comm_path) {
        if let Some(result) = detection_from_process_name(&process_name) {
            return Some(result);
        }
    }

    let cmdline_path = format!("/proc/{ppid}/cmdline");
    let process_args = fs::read(&cmdline_path)
        .ok()
        .and_then(|bytes| nul_separated_args_to_string(&bytes))?;
    detection_from_process_name(&process_args)
}

/// Detect agent from parent process on Unix platforms without `/proc`.
#[cfg(all(unix, not(target_os = "linux")))]
fn detect_from_parent_process() -> Option<DetectionResult> {
    use std::os::unix::process::parent_id;

    let ppid = parent_id();
    parent_process_name_from_ps(ppid).and_then(|name| detection_from_process_name(&name))
}

#[cfg(all(unix, not(target_os = "linux")))]
fn parent_process_name_from_ps(pid: u32) -> Option<String> {
    let pid = pid.to_string();
    let output = std::process::Command::new("ps")
        .args(["-p", &pid, "-o", "comm="])
        .output()
        .ok()?;

    if output.status.success() {
        if let Some(name) = first_non_empty_line(&String::from_utf8_lossy(&output.stdout)) {
            if detection_from_process_name(name).is_some() {
                return Some(name.to_string());
            }
        }
    }

    parent_process_args_from_ps(&pid)
}

#[cfg(all(unix, not(target_os = "linux")))]
fn parent_process_args_from_ps(pid: &str) -> Option<String> {
    let output = std::process::Command::new("ps")
        .args(["-p", pid, "-o", "args="])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    first_non_empty_line(&String::from_utf8_lossy(&output.stdout)).map(str::to_string)
}

/// Detect agent from parent process on Windows.
#[cfg(windows)]
fn detect_from_parent_process() -> Option<DetectionResult> {
    parent_process_name_from_windows(std::process::id())
        .and_then(|name| detection_from_process_name(&name))
}

#[cfg(windows)]
fn parent_process_name_from_windows(current_pid: u32) -> Option<String> {
    let script = format!(
        "$p = Get-CimInstance Win32_Process -Filter 'ProcessId = {current_pid}'; \
         if ($null -eq $p) {{ exit 1 }}; \
         $parent = Get-CimInstance Win32_Process -Filter \"ProcessId = $($p.ParentProcessId)\"; \
         if ($null -eq $parent) {{ exit 1 }}; \
         Write-Output $parent.Name"
    );

    ["powershell.exe", "powershell", "pwsh"]
        .iter()
        .find_map(|program| windows_parent_name_with(program, &script))
}

#[cfg(windows)]
fn windows_parent_name_with(program: &str, script: &str) -> Option<String> {
    let output = std::process::Command::new(program)
        .args(["-NoProfile", "-NonInteractive", "-Command", script])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    first_non_empty_line(&String::from_utf8_lossy(&output.stdout)).map(str::to_string)
}

/// Detect agent from parent process on platforms without a safe implementation.
#[cfg(not(any(target_os = "linux", unix, windows)))]
fn detect_from_parent_process() -> Option<DetectionResult> {
    None
}

fn detection_from_process_name(raw_process_name: &str) -> Option<DetectionResult> {
    let process_name = normalize_process_name(raw_process_name)?;
    let agent = agent_from_process_name(&process_name)?;
    Some(DetectionResult::new(
        agent,
        DetectionMethod::Process,
        Some(process_name),
    ))
}

fn normalize_process_name(raw_process_name: &str) -> Option<String> {
    first_non_empty_line(raw_process_name).map(str::to_lowercase)
}

fn first_non_empty_line(value: &str) -> Option<&str> {
    value.lines().map(str::trim).find(|line| !line.is_empty())
}

fn nul_separated_args_to_string(bytes: &[u8]) -> Option<String> {
    let mut args = Vec::new();

    for arg in bytes.split(|byte| *byte == b'\0') {
        if arg.is_empty() {
            continue;
        }
        args.push(String::from_utf8_lossy(arg));
    }

    if args.is_empty() {
        None
    } else {
        Some(args.join(" "))
    }
}

/// Map a parent-process name to a known agent.
///
/// Tokenizes the input on whitespace and matches each token's basename (after
/// `\` → `/` normalization, last path segment, `.exe` strip, lower-case)
/// against an explicit name/alias table. This rejects false positives like
/// `claude-explorer`, `myproject-continue`, or `cursor-ext` whose basename
/// merely *contains* an agent name without *being* one.
///
/// The whitespace tokenization handles wrapper-style invocations like
/// `node /usr/local/bin/codex`: the first argv token is treated as the process
/// executable, while later tokens are only considered when they look like
/// path-like executable/script arguments. This avoids misclassifying ordinary
/// arguments such as `cargo test codex` or URL paths ending in `/codex`.
fn agent_from_process_name(process_name: &str) -> Option<Agent> {
    for (index, token) in process_name.split_whitespace().enumerate() {
        if index > 0 && !is_path_like_process_token(token) {
            continue;
        }

        if let Some(agent) = agent_for_basename(executable_basename(token).as_str()) {
            return Some(agent);
        }
    }
    None
}

fn is_path_like_process_token(token: &str) -> bool {
    let token = token.trim_matches(['"', '\'']);
    !token.starts_with('-')
        && !token.contains("://")
        && (token.contains('/') || token.contains('\\'))
}

fn executable_basename(token: &str) -> String {
    let normalized = token
        .trim_matches(['"', '\''])
        .to_lowercase()
        .replace('\\', "/");
    let last = normalized.rsplit('/').next().unwrap_or(&normalized);
    for suffix in WINDOWS_EXECUTABLE_SUFFIXES {
        if let Some(stem) = last.strip_suffix(suffix) {
            return stem.to_string();
        }
    }
    last.to_string()
}

fn agent_for_basename(basename: &str) -> Option<Agent> {
    // Exact-match table. New aliases for the same agent go in the same arm.
    // Substring matching is intentionally NOT used: a tool whose name merely
    // contains "claude" / "aider" / "continue" / "cursor" would otherwise be
    // misclassified.
    match basename {
        "claude" | "claude-code" | "claude_code" => Some(Agent::ClaudeCode),
        "augment" | "augment-code" | "auggie" => Some(Agent::AugmentCode),
        "aider" => Some(Agent::Aider),
        "continue" | "continue-cli" => Some(Agent::Continue),
        "codex" | "codex-cli" => Some(Agent::CodexCli),
        "gemini" | "gemini-cli" => Some(Agent::GeminiCli),
        "copilot" | "copilot-cli" | "gh-copilot" => Some(Agent::CopilotCli),
        "cursor" | "cursor-ide" => Some(Agent::CursorIde),
        "hermes" | "hermes-agent" | "hermes-cli" => Some(Agent::Hermes),
        "grok" | "grok-cli" | "grok-build" => Some(Agent::Grok),
        _ => 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::CursorIde.config_key(), "cursor-ide");
        assert_eq!(Agent::Hermes.config_key(), "hermes");
        assert_eq!(Agent::Grok.config_key(), "grok");
        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);
        assert_eq!(Agent::from_name("cursor"), Agent::CursorIde);
        assert_eq!(Agent::from_name("cursor-ide"), Agent::CursorIde);
        assert_eq!(Agent::from_name("cursor_ide"), Agent::CursorIde);
        assert_eq!(Agent::from_name("hermes"), Agent::Hermes);
        assert_eq!(Agent::from_name("Hermes"), Agent::Hermes);
        assert_eq!(Agent::from_name("hermes-agent"), Agent::Hermes);
        assert_eq!(Agent::from_name("hermes_cli"), Agent::Hermes);
        assert_eq!(Agent::from_name("grok"), Agent::Grok);
        assert_eq!(Agent::from_name("Grok"), Agent::Grok);
        assert_eq!(Agent::from_name("grok-cli"), Agent::Grok);
        assert_eq!(Agent::from_name("grok_build"), Agent::Grok);
        assert_eq!(Agent::from_name("xai"), Agent::Grok);
        assert_eq!(Agent::from_name("xai-grok"), Agent::Grok);

        // 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::CursorIde), "Cursor IDE");
        assert_eq!(format!("{}", Agent::Hermes), "Hermes Agent");
        assert_eq!(format!("{}", Agent::Grok), "Grok (xAI)");
        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::CursorIde.is_known());
        assert!(Agent::Hermes.is_known());
        assert!(Agent::Grok.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_agent_from_process_name_recognizes_known_agents() {
        assert_eq!(agent_from_process_name("claude"), Some(Agent::ClaudeCode));
        assert_eq!(
            agent_from_process_name("/Applications/Claude.app/Contents/MacOS/Claude"),
            Some(Agent::ClaudeCode)
        );
        assert_eq!(agent_from_process_name("auggie"), Some(Agent::AugmentCode));
        assert_eq!(
            agent_from_process_name("augment-code"),
            Some(Agent::AugmentCode)
        );
        assert_eq!(agent_from_process_name("aider"), Some(Agent::Aider));
        assert_eq!(agent_from_process_name("continue"), Some(Agent::Continue));
        assert_eq!(agent_from_process_name("codex"), Some(Agent::CodexCli));
        assert_eq!(
            agent_from_process_name("node /usr/local/bin/codex"),
            Some(Agent::CodexCli)
        );
        assert_eq!(agent_from_process_name("gemini"), Some(Agent::GeminiCli));
        assert_eq!(
            agent_from_process_name("copilot.exe"),
            Some(Agent::CopilotCli)
        );
        assert_eq!(
            agent_from_process_name(r"C:\Users\dev\AppData\Local\Programs\Cursor\Cursor.exe"),
            Some(Agent::CursorIde)
        );
        assert_eq!(
            agent_from_process_name(r"C:\Users\dev\AppData\Roaming\npm\codex.cmd"),
            Some(Agent::CodexCli)
        );
        assert_eq!(
            agent_from_process_name("gemini.ps1"),
            Some(Agent::GeminiCli)
        );
        assert_eq!(agent_from_process_name("hermes"), Some(Agent::Hermes));
        assert_eq!(agent_from_process_name("hermes-agent"), Some(Agent::Hermes));
        assert_eq!(
            agent_from_process_name("/usr/local/bin/hermes"),
            Some(Agent::Hermes)
        );
        assert_eq!(agent_from_process_name("grok"), Some(Agent::Grok));
        assert_eq!(agent_from_process_name("grok-cli"), Some(Agent::Grok));
        assert_eq!(agent_from_process_name("grok-build"), Some(Agent::Grok));
        assert_eq!(
            agent_from_process_name("/home/user/.local/bin/grok"),
            Some(Agent::Grok)
        );
    }

    #[test]
    fn test_agent_from_process_name_ignores_unknown_processes() {
        assert_eq!(agent_from_process_name("zsh"), None);
        assert_eq!(agent_from_process_name("cargo test agent"), None);
        assert_eq!(agent_from_process_name("cargo test codex"), None);
        assert_eq!(agent_from_process_name("node"), None);
        assert_eq!(agent_from_process_name("curl https://codex.com"), None);
        assert_eq!(
            agent_from_process_name("curl https://example.com/codex"),
            None
        );
        assert_eq!(agent_from_process_name("git commit -m codex"), None);
    }

    #[test]
    fn test_agent_from_process_name_rejects_substring_false_positives() {
        // Previously these all returned a (wrong) Agent because the
        // implementation matched on substring. They must now return None.
        assert_eq!(agent_from_process_name("claude-explorer"), None);
        assert_eq!(agent_from_process_name("myclaude"), None);
        assert_eq!(agent_from_process_name("anti-claude"), None);
        assert_eq!(agent_from_process_name("aider-helper"), None);
        assert_eq!(agent_from_process_name("myproject-continue"), None);
        assert_eq!(agent_from_process_name("continue-on-error"), None);
        assert_eq!(agent_from_process_name("cursor-ext"), None);
        assert_eq!(agent_from_process_name("xcursor"), None);
        assert_eq!(agent_from_process_name("codex-runner"), None);
        assert_eq!(agent_from_process_name("gemini-tools"), None);
        assert_eq!(agent_from_process_name("copilot-stub"), None);
        assert_eq!(agent_from_process_name("augment-helpers"), None);
        // Greek mythology should not be auto-classified as Hermes Agent.
        assert_eq!(agent_from_process_name("hermes-helper"), None);
        assert_eq!(agent_from_process_name("xhermes"), None);
        assert_eq!(agent_from_process_name("anti-hermes"), None);
        // The word "grok" appears in unrelated tool names; require exact match.
        assert_eq!(agent_from_process_name("grok-helper"), None);
        assert_eq!(agent_from_process_name("xgrok"), None);
        assert_eq!(agent_from_process_name("anti-grok"), None);
        assert_eq!(agent_from_process_name("grokking"), None);
    }

    #[test]
    fn test_agent_from_process_name_accepts_known_aliases() {
        // Hyphenated and underscored aliases for the same agent.
        assert_eq!(
            agent_from_process_name("claude_code"),
            Some(Agent::ClaudeCode)
        );
        assert_eq!(
            agent_from_process_name("claude-code"),
            Some(Agent::ClaudeCode)
        );
        assert_eq!(agent_from_process_name("codex-cli"), Some(Agent::CodexCli));
        assert_eq!(
            agent_from_process_name("gemini-cli"),
            Some(Agent::GeminiCli)
        );
        assert_eq!(
            agent_from_process_name("gh-copilot"),
            Some(Agent::CopilotCli)
        );
        assert_eq!(
            agent_from_process_name("cursor-ide"),
            Some(Agent::CursorIde)
        );
        assert_eq!(
            agent_from_process_name("continue-cli"),
            Some(Agent::Continue)
        );
    }

    #[test]
    fn test_agent_from_process_name_each_argv_token_checked() {
        // Wrapper invocations: tokenize argv, basename each token, exact match.
        assert_eq!(
            agent_from_process_name("node /usr/local/bin/codex --foo"),
            Some(Agent::CodexCli)
        );
        assert_eq!(
            agent_from_process_name("node ./bin/gemini --foo"),
            Some(Agent::GeminiCli)
        );
        assert_eq!(
            agent_from_process_name(r#"node "C:\Users\dev\AppData\Roaming\npm\codex.cmd""#),
            Some(Agent::CodexCli)
        );
        // First-token wins on ties.
        assert_eq!(
            agent_from_process_name("/opt/codex /opt/cursor"),
            Some(Agent::CodexCli)
        );
    }

    #[test]
    fn test_detection_from_process_name_normalizes_matches() {
        let result = detection_from_process_name("\n  Codex.exe  \n").unwrap();

        assert_eq!(result.agent, Agent::CodexCli);
        assert_eq!(result.method, DetectionMethod::Process);
        assert_eq!(result.matched_value, Some("codex.exe".to_string()));
    }

    #[test]
    fn test_detection_from_process_name_rejects_empty_output() {
        assert_eq!(detection_from_process_name("\n\n  "), None);
    }

    #[test]
    fn test_nul_separated_args_to_string_preserves_wrapped_agent_argv() {
        let args = nul_separated_args_to_string(b"node\0/usr/local/bin/codex\0--foo\0")
            .expect("argv bytes should decode");

        assert_eq!(args, "node /usr/local/bin/codex --foo");
        assert_eq!(agent_from_process_name(&args), Some(Agent::CodexCli));
    }

    #[test]
    fn test_nul_separated_args_to_string_rejects_empty_argv() {
        assert_eq!(nul_separated_args_to_string(b"\0\0"), None);
    }

    #[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_explicit_agent_from_args_accepts_separate_value() {
        let agent = explicit_agent_from_args(["dcg", "--agent", "custom-agent", "--version"]);

        assert_eq!(agent, Some("custom-agent".to_string()));
    }

    #[test]
    fn test_explicit_agent_from_args_accepts_equals_value() {
        let agent = explicit_agent_from_args(["dcg", "--agent=codex-cli", "test"]);

        assert_eq!(agent, Some("codex-cli".to_string()));
    }

    #[test]
    fn test_explicit_agent_from_args_ignores_blank_value() {
        let agent = explicit_agent_from_args(["dcg", "--agent", "  "]);

        assert_eq!(agent, None);
    }

    #[test]
    fn test_explicit_agent_from_args_stops_at_double_dash() {
        let agent = explicit_agent_from_args(["dcg", "test", "--", "--agent=payload-agent"]);

        assert_eq!(agent, None);
    }

    #[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",
        "CURSOR_IDE",
        "HERMES_AGENT",
        "HERMES_SESSION_ID",
        "GROK_SESSION_ID",
        "GROK_HOOK_EVENT",
        "GROK_WORKSPACE_ROOT",
    ];

    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_cursor_ide_env() {
        with_env_var("CURSOR_IDE", "1", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::CursorIde);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("CURSOR_IDE".to_string()));
        });
    }

    #[test]
    fn test_detect_grok_session_id_env() {
        with_env_var("GROK_SESSION_ID", "sess-abc-123", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::Grok);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("GROK_SESSION_ID".to_string()));
        });
    }

    #[test]
    fn test_detect_grok_hook_event_env() {
        with_env_var("GROK_HOOK_EVENT", "pre_tool_use", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::Grok);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(result.matched_value, Some("GROK_HOOK_EVENT".to_string()));
        });
    }

    #[test]
    fn test_detect_grok_workspace_root_env() {
        with_env_var("GROK_WORKSPACE_ROOT", "/work/repo", || {
            let result = detect_agent_with_details();
            assert_eq!(result.agent, Agent::Grok);
            assert_eq!(result.method, DetectionMethod::Environment);
            assert_eq!(
                result.matched_value,
                Some("GROK_WORKSPACE_ROOT".to_string())
            );
        });
    }

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

        let saved: Vec<_> = AGENT_ENV_VARS
            .iter()
            .map(|&k| (k, std::env::var(k).ok()))
            .collect();

        // Ensure no agent env vars are set
        clear_cache();
        // SAFETY: We hold ENV_LOCK during this test, preventing concurrent
        // modifications to environment variables.
        unsafe {
            for &k in AGENT_ENV_VARS {
                std::env::remove_var(k);
            }
        }

        // Detection should fall back to process detection or Unknown
        let result = detect_agent_with_details();
        unsafe {
            for (k, v) in saved {
                if let Some(val) = v {
                    std::env::set_var(k, val);
                }
            }
        }
        clear_cache();

        // 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
        );
    }
}