omamori 0.10.2

AI Agent's Omamori — protect your system from dangerous commands executed via AI CLI tools
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
use std::env;
use std::fs;
use std::path::{Component, Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::rules::{ActionKind, CommandInvocation, RuleConfig};

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
pub struct ContextEvaluation {
    pub action_override: Option<ActionKind>,
    pub reason: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextConfig {
    #[serde(default = "default_regenerable_paths")]
    pub regenerable_paths: Vec<String>,
    #[serde(default = "default_protected_paths")]
    pub protected_paths: Vec<String>,
    #[serde(default)]
    pub git: GitContextConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitContextConfig {
    #[serde(default)]
    pub enabled: bool,
    #[serde(default = "default_timeout_ms")]
    pub timeout_ms: u64,
}

impl Default for GitContextConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            timeout_ms: default_timeout_ms(),
        }
    }
}

fn default_timeout_ms() -> u64 {
    100
}

// ---------------------------------------------------------------------------
// Built-in defaults
// ---------------------------------------------------------------------------

pub fn default_regenerable_paths() -> Vec<String> {
    vec![
        "target/".to_string(),
        "node_modules/".to_string(),
        ".next/".to_string(),
        "dist/".to_string(),
        "build/".to_string(),
        "__pycache__/".to_string(),
        ".cache/".to_string(),
    ]
}

pub fn default_protected_paths() -> Vec<String> {
    vec![
        "src/".to_string(),
        "lib/".to_string(),
        ".git/".to_string(),
        ".env".to_string(),
        ".ssh/".to_string(),
    ]
}

/// Paths that can never be classified as regenerable, regardless of config.
/// If a user adds one of these to regenerable_paths, it is silently ignored
/// and a config warning is emitted.
pub const NEVER_REGENERABLE: &[&str] = &["src", "lib", "app", ".git", ".env", ".ssh"];

// ---------------------------------------------------------------------------
// Path normalization
// ---------------------------------------------------------------------------

/// Lexical path normalization with an explicit base directory for relative-path
/// resolution: expand `~`, resolve relative paths against `base`, remove `.` and
/// `..`. Does NOT access the filesystem (no symlink resolution).
///
/// Internal callers that need to pin a specific base (to avoid races with
/// concurrent `env::set_current_dir` elsewhere in the process) use this
/// directly. Public callers that want process CWD semantics use
/// [`normalize_path`].
pub(crate) fn normalize_path_with_base(path: &str, base: &Path) -> PathBuf {
    // Step 1: ~ expansion
    let path = if let Some(rest) = path.strip_prefix("~/") {
        if let Some(home) = env::var_os("HOME") {
            PathBuf::from(home).join(rest)
        } else {
            PathBuf::from(path)
        }
    } else {
        PathBuf::from(path)
    };

    // Step 2: relative → absolute (based on explicit base, not process CWD)
    let path = if path.is_relative() {
        base.join(&path)
    } else {
        path
    };

    // Step 3: lexical resolution of .. / . / //
    let mut components: Vec<Component> = Vec::new();
    for component in path.components() {
        match component {
            Component::ParentDir => {
                if let Some(last) = components.last()
                    && !matches!(last, Component::RootDir)
                {
                    components.pop();
                }
            }
            Component::CurDir => {}
            other => components.push(other),
        }
    }
    components.iter().collect()
}

/// Lexical path normalization relative to the process CWD.
///
/// Thin wrapper over [`normalize_path_with_base`] that captures the current
/// working directory once at entry. Public API preserved for backwards
/// compatibility (semver).
pub fn normalize_path(path: &str) -> PathBuf {
    let base = env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
    normalize_path_with_base(path, &base)
}

/// Try to resolve the real path (symlinks included) via `fs::canonicalize`
/// after lexically absolutizing against `base`.
///
/// Because the value passed to `fs::canonicalize` is already absolute, the
/// result is independent of the process CWD — this closes the v0.9.5
/// `multi_target_*` quarantine root cause (#164).
///
/// Returns `(canonical, true)` on success, `(lexical, false)` if the path
/// does not exist.
pub(crate) fn resolve_path_with_base(raw: &str, base: &Path) -> (PathBuf, bool) {
    let lexical = normalize_path_with_base(raw, base);
    // canonicalize on the absolute lexical path, not on `raw`, so the result
    // does not depend on the current process CWD.
    match fs::canonicalize(&lexical) {
        Ok(canonical) => (canonical, true),
        Err(_) => (lexical, false),
    }
}

/// Try to resolve the real path (symlinks included) via canonicalize().
/// Returns Ok(canonical) if the path exists, Err(lexical) if it doesn't.
///
/// Thin wrapper over [`resolve_path_with_base`] that captures process CWD.
pub fn resolve_path(raw: &str) -> (PathBuf, bool) {
    let base = env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
    resolve_path_with_base(raw, &base)
}

// ---------------------------------------------------------------------------
// Component boundary matching
// ---------------------------------------------------------------------------

/// Check if `normalized` path contains `pattern` as a contiguous subsequence
/// of path components. This ensures "target" matches "/foo/target/bar" but
/// NOT "/foo/target_dir/bar".
pub fn path_matches_pattern(normalized: &Path, pattern: &str) -> bool {
    let pattern_path = Path::new(pattern);
    let pattern_components: Vec<Component> = pattern_path.components().collect();
    let path_components: Vec<Component> = normalized.components().collect();

    if pattern_components.is_empty() {
        return false;
    }

    path_components
        .windows(pattern_components.len())
        .any(|window| window == pattern_components.as_slice())
}

/// Check if a path matches any pattern in a list.
fn matches_any_pattern(path: &Path, patterns: &[String]) -> Option<String> {
    for pattern in patterns {
        if path_matches_pattern(path, pattern) {
            return Some(pattern.clone());
        }
    }
    None
}

// ---------------------------------------------------------------------------
// NEVER_REGENERABLE validation
// ---------------------------------------------------------------------------

/// Check if a path pattern conflicts with NEVER_REGENERABLE.
pub fn is_never_regenerable(pattern: &str) -> bool {
    let clean = pattern.trim_end_matches('/');
    NEVER_REGENERABLE.contains(&clean)
}

/// Validate regenerable_paths against NEVER_REGENERABLE.
/// Returns warnings for conflicting patterns.
pub fn validate_regenerable_paths(paths: &[String]) -> Vec<String> {
    let mut warnings = Vec::new();
    for path in paths {
        if is_never_regenerable(path) {
            warnings.push(format!(
                "regenerable_paths pattern \"{}\" conflicts with protected system path; pattern ignored for security",
                path
            ));
        }
    }
    warnings
}

/// Filter out NEVER_REGENERABLE patterns from a list.
fn effective_regenerable_paths(paths: &[String]) -> Vec<String> {
    paths
        .iter()
        .filter(|p| !is_never_regenerable(p))
        .cloned()
        .collect()
}

// ---------------------------------------------------------------------------
// Context evaluation (Tier 1: path-based)
// ---------------------------------------------------------------------------

/// Evaluate context for a matched rule with an explicit base directory.
///
/// Evaluation priority (highest first):
/// 1. protected_paths match → escalate to Block
/// 2. NEVER_REGENERABLE match → ignore regenerable config, keep original
/// 3. regenerable_paths match AND canonicalize succeeded → downgrade to LogOnly
/// 4. regenerable_paths match AND canonicalize failed → no downgrade (fail-close)
/// 5. No match → keep original
///
/// Relative target paths in `invocation` are resolved against `base` via
/// [`resolve_path_with_base`], so the verdict does not depend on the process
/// CWD. Internal callers that need deterministic resolution (tests with
/// concurrent `env::set_current_dir` neighbors) use this directly.
pub(crate) fn evaluate_context_with_base(
    invocation: &CommandInvocation,
    _rule: &RuleConfig,
    config: &ContextConfig,
    base: &Path,
) -> ContextEvaluation {
    let targets = invocation.target_args();
    if targets.is_empty() {
        return ContextEvaluation {
            action_override: None,
            reason: "no target paths to evaluate".to_string(),
        };
    }

    let effective_regenerable = effective_regenerable_paths(&config.regenerable_paths);

    // Evaluate ALL targets and collect the most severe result.
    // This prevents early-return on a regenerable path from skipping
    // a later protected path (e.g., `rm -rf target/ src/`).
    let mut result = ContextEvaluation {
        action_override: None,
        reason: "no context pattern matched".to_string(),
    };

    for target in &targets {
        let (resolved, canonicalized) = resolve_path_with_base(target, base);

        // Priority 1: protected_paths → escalate to Block (most severe, short-circuit)
        if let Some(pattern) = matches_any_pattern(&resolved, &config.protected_paths) {
            return ContextEvaluation {
                action_override: Some(ActionKind::Block),
                reason: format!("protected path (matched: {})", pattern),
            };
        }

        // Priority 3+4: regenerable_paths check (only adopt if no override yet)
        if result.action_override.is_none()
            && let Some(pattern) = matches_any_pattern(&resolved, &effective_regenerable)
        {
            if canonicalized {
                result = ContextEvaluation {
                    action_override: Some(ActionKind::LogOnly),
                    reason: format!("regenerable path (matched: {})", pattern),
                };
            } else {
                result = ContextEvaluation {
                    action_override: None,
                    reason: format!(
                        "regenerable pattern matched ({}) but path could not be resolved; keeping original action",
                        pattern
                    ),
                };
            }
        }
    }

    result
}

/// Evaluate context for a matched rule.
///
/// Thin wrapper over [`evaluate_context_with_base`] that captures the process
/// CWD at entry. Public API preserved for backwards compatibility (semver).
pub fn evaluate_context(
    invocation: &CommandInvocation,
    rule: &RuleConfig,
    config: &ContextConfig,
) -> ContextEvaluation {
    let base = env::current_dir().unwrap_or_else(|_| PathBuf::from("/"));
    evaluate_context_with_base(invocation, rule, config, &base)
}

// ---------------------------------------------------------------------------
// Git-aware evaluation (Tier 2)
// ---------------------------------------------------------------------------

/// Git env vars that must be removed from subprocess to prevent spoofing (T4).
const GIT_SPOOFABLE_ENV_VARS: &[&str] = &[
    "GIT_DIR",
    "GIT_WORK_TREE",
    "GIT_INDEX_FILE",
    "GIT_COMMON_DIR",
];

/// Query `git status --porcelain` with timeout and env var sanitization.
/// Returns Ok(output) on success, Err(reason) on failure/timeout.
fn git_status_porcelain(detector_env_keys: &[String], timeout_ms: u64) -> Result<String, String> {
    use std::process::{Command, Stdio};
    use std::sync::mpsc;
    use std::time::Duration;

    let mut cmd = Command::new("git");
    cmd.args(["status", "--porcelain"])
        .stdout(Stdio::piped())
        .stderr(Stdio::null());

    // Remove AI detector env vars (self-interference prevention)
    for key in detector_env_keys {
        cmd.env_remove(key);
    }
    // Remove git spoofable env vars (T4 defense)
    for key in GIT_SPOOFABLE_ENV_VARS {
        cmd.env_remove(key);
    }

    let mut child = cmd
        .spawn()
        .map_err(|e| format!("failed to spawn git: {e}"))?;

    let (tx, rx) = mpsc::channel();
    let child_stdout = child.stdout.take();

    std::thread::spawn(move || {
        use std::io::Read;
        let mut output = String::new();
        if let Some(mut stdout) = child_stdout {
            let _ = stdout.read_to_string(&mut output);
        }
        let _ = tx.send(output);
    });

    match rx.recv_timeout(Duration::from_millis(timeout_ms)) {
        Ok(output) => {
            let _ = child.wait(); // reap
            Ok(output)
        }
        Err(_) => {
            let _ = child.kill();
            let _ = child.wait(); // reap zombie
            Err(format!("git status timed out after {}ms", timeout_ms))
        }
    }
}

/// Check if we're inside a git repository.
fn is_inside_git_repo(detector_env_keys: &[String]) -> bool {
    use std::process::{Command, Stdio};

    let mut cmd = Command::new("git");
    cmd.args(["rev-parse", "--is-inside-work-tree"])
        .stdout(Stdio::null())
        .stderr(Stdio::null());

    for key in detector_env_keys {
        cmd.env_remove(key);
    }
    for key in GIT_SPOOFABLE_ENV_VARS {
        cmd.env_remove(key);
    }

    cmd.status().map(|s| s.success()).unwrap_or(false)
}

/// Evaluate git context for a matched rule.
/// Only applies to git commands (reset --hard, clean).
/// Returns None if git-aware is disabled or not applicable.
pub fn evaluate_git_context(
    invocation: &CommandInvocation,
    config: &GitContextConfig,
    detector_env_keys: &[String],
) -> Option<ContextEvaluation> {
    if !config.enabled {
        return None;
    }

    // Only evaluate git commands
    if invocation.program != "git" {
        return None;
    }

    // Not inside a git repo → skip (avoid false positives)
    if !is_inside_git_repo(detector_env_keys) {
        return Some(ContextEvaluation {
            action_override: None,
            reason: "not inside a git repository; skipping git-aware evaluation".to_string(),
        });
    }

    let args: Vec<&str> = invocation.args.iter().map(String::as_str).collect();

    // git reset --hard: check for uncommitted changes
    if args.contains(&"reset") && args.contains(&"--hard") {
        return match git_status_porcelain(detector_env_keys, config.timeout_ms) {
            Ok(output) if output.trim().is_empty() => Some(ContextEvaluation {
                action_override: Some(ActionKind::LogOnly),
                reason: "no uncommitted changes detected".to_string(),
            }),
            Ok(_) => Some(ContextEvaluation {
                action_override: None,
                reason: "uncommitted changes present; keeping original action".to_string(),
            }),
            Err(reason) => Some(ContextEvaluation {
                action_override: None,
                reason: format!("git status failed ({}); keeping original action", reason),
            }),
        };
    }

    // git clean with force flag: check for untracked files
    let expanded_args = crate::rules::expand_short_flags(&invocation.args);
    let has_force = expanded_args.iter().any(|a| a == "-f" || a == "--force");
    if args.contains(&"clean") && has_force {
        return match git_status_porcelain(detector_env_keys, config.timeout_ms) {
            Ok(output) => {
                let has_untracked = output.lines().any(|line| line.starts_with("??"));
                if has_untracked {
                    Some(ContextEvaluation {
                        action_override: None,
                        reason: "untracked files present; keeping original action".to_string(),
                    })
                } else {
                    Some(ContextEvaluation {
                        action_override: Some(ActionKind::LogOnly),
                        reason: "no untracked files detected".to_string(),
                    })
                }
            }
            Err(reason) => Some(ContextEvaluation {
                action_override: None,
                reason: format!("git status failed ({}); keeping original action", reason),
            }),
        };
    }

    None // Not a git command we evaluate
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // NOTE (v0.9.6 structural fix for #164):
    // The v0.9.5 `multi_target_*` quarantine has been resolved by introducing
    // `evaluate_context_with_base` / `resolve_path_with_base` /
    // `normalize_path_with_base`. Tests that previously relied on the process
    // CWD to resolve relative paths now pass an explicit base (via
    // `test_base()`), so `fs::canonicalize` receives an absolute path and its
    // result no longer depends on concurrent `env::set_current_dir` calls in
    // the `git_context_*` family.
    //
    // As a result:
    //   - `multi_target_*` tests no longer need `#[serial_test::serial]`.
    //   - `git_context_*` tests still mutate CWD themselves and therefore
    //     remain `#[serial_test::serial]`; that serialization is structural
    //     to their intent (exercising git-aware evaluation that shells out
    //     to `git`).
    //
    // v0.10.0 #175 tracks the full public-API promotion of
    // `normalize_path`/`resolve_path`/`evaluate_context` to require an
    // explicit `base: &Path`, at which point the process CWD can be banned
    // outside the shim/hook entry points via `.clippy.toml` disallowed_methods.

    // --- normalize_path ---

    #[test]
    fn normalize_resolves_dot_dot() {
        let result = normalize_path("target/../src/main.rs");
        assert!(
            result.ends_with("src/main.rs"),
            "expected ends_with src/main.rs, got: {}",
            result.display()
        );
        // Must NOT contain "target" after normalization
        let s = result.to_string_lossy();
        assert!(
            !s.contains("/target/"),
            "should not contain /target/ after normalization: {}",
            s
        );
    }

    #[test]
    fn normalize_resolves_dot() {
        let result = normalize_path("./target/");
        assert!(result.ends_with("target"));
    }

    #[test]
    fn normalize_expands_tilde() {
        let result = normalize_path("~/Documents");
        if let Some(home) = env::var_os("HOME") {
            assert!(result.starts_with(PathBuf::from(home)));
        }
    }

    #[test]
    fn normalize_makes_absolute() {
        let result = normalize_path("target");
        assert!(result.is_absolute());
    }

    // --- path_matches_pattern ---

    #[test]
    fn pattern_matches_exact_component() {
        let cwd = env::current_dir().unwrap();
        assert!(path_matches_pattern(&cwd.join("target"), "target"));
        assert!(path_matches_pattern(&cwd.join("target/debug"), "target"));
    }

    #[test]
    fn pattern_does_not_match_partial_name() {
        let cwd = env::current_dir().unwrap();
        assert!(!path_matches_pattern(&cwd.join("target_dir"), "target"));
        assert!(!path_matches_pattern(&cwd.join("my-target"), "target"));
        assert!(!path_matches_pattern(&cwd.join("src_backup"), "src"));
    }

    #[test]
    fn pattern_matches_intermediate_component() {
        let cwd = env::current_dir().unwrap();
        assert!(path_matches_pattern(&cwd.join("lib/src/foo"), "src"));
    }

    #[test]
    fn trailing_slash_does_not_affect_match() {
        let cwd = env::current_dir().unwrap();
        let path = cwd.join("target");
        assert!(path_matches_pattern(&path, "target"));
        assert!(path_matches_pattern(&path, "target/"));

        let path_slash = cwd.join("target/");
        assert!(path_matches_pattern(&path_slash, "target"));
    }

    // --- NEVER_REGENERABLE ---

    #[test]
    fn never_regenerable_catches_src() {
        assert!(is_never_regenerable("src"));
        assert!(is_never_regenerable("src/"));
        assert!(is_never_regenerable(".git"));
        assert!(is_never_regenerable(".git/"));
        assert!(is_never_regenerable(".env"));
    }

    #[test]
    fn never_regenerable_allows_target() {
        assert!(!is_never_regenerable("target"));
        assert!(!is_never_regenerable("target/"));
        assert!(!is_never_regenerable("node_modules"));
        assert!(!is_never_regenerable("dist"));
    }

    #[test]
    fn validate_regenerable_warns_on_conflict() {
        let paths = vec!["target/".to_string(), "src/".to_string()];
        let warnings = validate_regenerable_paths(&paths);
        assert_eq!(warnings.len(), 1);
        assert!(warnings[0].contains("src/"));
    }

    // --- evaluate_context ---

    fn test_config() -> ContextConfig {
        ContextConfig {
            regenerable_paths: vec!["target/".to_string(), "node_modules/".to_string()],
            protected_paths: vec!["src/".to_string(), ".git/".to_string()],
            git: GitContextConfig::default(),
        }
    }

    fn test_rule() -> RuleConfig {
        RuleConfig::new(
            "rm-recursive-to-trash",
            "rm",
            ActionKind::Trash,
            Vec::new(),
            vec!["-rf".to_string()],
            Some("test".to_string()),
        )
    }

    /// Unique absolute base for context tests that need deterministic path
    /// resolution regardless of concurrent `env::set_current_dir` elsewhere
    /// in the process. Tied to the current PID so parallel test binaries
    /// cannot collide either.
    ///
    /// Also idempotently creates fixture children (`target/`, `node_modules/`)
    /// so that `fs::canonicalize` through `resolve_path_with_base` succeeds
    /// and regenerable-path canonicalization tests can reach the `LogOnly`
    /// branch. Cleanup is deliberately skipped: parallel tests in the same
    /// PID would race on a cleanup, and the tree is tiny under `/tmp`.
    ///
    /// Example: `/tmp/omamori-ctx-test-12345/target/` is what a relative
    /// `target/` arg resolves to when evaluating via
    /// `evaluate_context_with_base(&inv, &rule, &config, &test_base())`.
    fn test_base() -> PathBuf {
        let base = PathBuf::from(format!("/tmp/omamori-ctx-test-{}", std::process::id()));
        std::fs::create_dir_all(base.join("target")).unwrap();
        std::fs::create_dir_all(base.join("node_modules")).unwrap();
        base
    }

    #[test]
    fn context_protected_path_escalates_to_block() {
        let config = test_config();
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "src/".to_string()],
        );
        let result = evaluate_context(&inv, &test_rule(), &config);
        assert_eq!(result.action_override, Some(ActionKind::Block));
        assert!(result.reason.contains("protected path"));
    }

    #[test]
    fn context_no_targets_returns_none() {
        let config = test_config();
        let inv = CommandInvocation::new("rm".to_string(), vec!["-rf".to_string()]);
        let result = evaluate_context(&inv, &test_rule(), &config);
        assert!(result.action_override.is_none());
    }

    #[test]
    fn context_unmatched_path_returns_none() {
        let config = test_config();
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "data/".to_string()],
        );
        let result = evaluate_context(&inv, &test_rule(), &config);
        assert!(result.action_override.is_none());
    }

    #[test]
    fn context_never_regenerable_overrides_config() {
        // Even if user adds "src/" to regenerable_paths, it should be ignored
        let config = ContextConfig {
            regenerable_paths: vec!["src/".to_string()],
            protected_paths: vec![],
            git: GitContextConfig::default(),
        };
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "src/".to_string()],
        );
        let result = evaluate_context(&inv, &test_rule(), &config);
        // src/ is in NEVER_REGENERABLE, so it should NOT be downgraded
        assert!(
            result.action_override.is_none(),
            "src/ should not be downgraded even if in regenerable_paths"
        );
    }

    #[test]
    fn context_both_match_escalation_wins() {
        // A path that matches both regenerable and protected should be blocked
        let config = ContextConfig {
            regenerable_paths: vec!["shared/".to_string()],
            protected_paths: vec!["shared/".to_string()],
            git: GitContextConfig::default(),
        };
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "shared/".to_string()],
        );
        let result = evaluate_context(&inv, &test_rule(), &config);
        assert_eq!(result.action_override, Some(ActionKind::Block));
    }

    #[test]
    fn traversal_attack_is_caught() {
        let config = test_config();
        // target/../src/ should normalize to CWD/src/ and match protected_paths
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target/../src/".to_string()],
        );
        let result = evaluate_context(&inv, &test_rule(), &config);
        assert_eq!(
            result.action_override,
            Some(ActionKind::Block),
            "target/../src/ should be caught as protected path after normalization"
        );
    }

    #[test]
    fn component_boundary_prevents_false_match() {
        let config = test_config();
        // target_dir should NOT match "target" pattern
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target_dir/".to_string()],
        );
        let result = evaluate_context(&inv, &test_rule(), &config);
        assert!(
            result.action_override.is_none(),
            "target_dir should not match target pattern"
        );
    }

    #[test]
    fn multi_target_protected_wins_over_regenerable() {
        // P1-1: rm -rf target/ src/ — src/ must be caught even though target/ matches first.
        //
        // Uses `evaluate_context_with_base` + `test_base()` so concurrent
        // `env::set_current_dir` in `git_context_*` tests cannot flip the
        // verdict. This closes the v0.9.5 #164 quarantine (structural fix,
        // v0.9.6 scope 10).
        let base = test_base();
        let config = test_config();
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target/".to_string(), "src/".to_string()],
        );
        let result = evaluate_context_with_base(&inv, &test_rule(), &config, &base);
        assert_eq!(
            result.action_override,
            Some(ActionKind::Block),
            "protected src/ must win even when regenerable target/ appears first"
        );
    }

    #[test]
    fn multi_target_all_regenerable_downgrades() {
        // #164 structural fix: explicit base via `evaluate_context_with_base`
        // instead of relying on process CWD. See module note.
        let base = test_base();
        let config = test_config();
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec![
                "-rf".to_string(),
                "target/".to_string(),
                "node_modules/".to_string(),
            ],
        );
        let result = evaluate_context_with_base(&inv, &test_rule(), &config, &base);
        assert_eq!(result.action_override, Some(ActionKind::LogOnly));
    }

    // --- CI consistency check: NEVER_REGENERABLE ⊃ default_protected_paths ---

    // --- evaluate_git_context (G-01) ---

    /// Helper: create a real git repo in a temp directory.
    /// Returns the temp dir path (caller must clean up).
    fn create_git_repo() -> PathBuf {
        let dir = std::env::temp_dir().join(format!("omamori-git-ctx-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        dir
    }

    fn git_config() -> GitContextConfig {
        GitContextConfig {
            enabled: true,
            timeout_ms: 5000,
        }
    }

    #[test]
    #[serial_test::serial]
    fn git_context_clean_repo_downgrades_to_log_only() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        // Create initial commit so repo is clean
        std::fs::write(dir.join("dummy.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();

        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(result.is_some());
        let eval = result.unwrap();
        assert_eq!(eval.action_override, Some(ActionKind::LogOnly));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[serial_test::serial]
    fn git_context_dirty_repo_keeps_original() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        // Create initial commit
        std::fs::write(dir.join("dummy.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();

        // Make dirty
        std::fs::write(dir.join("dirty.txt"), "uncommitted").unwrap();

        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(result.is_some());
        let eval = result.unwrap();
        assert!(eval.action_override.is_none());
        assert!(eval.reason.contains("uncommitted"));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[serial_test::serial]
    fn git_context_timeout_keeps_original() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        let config = GitContextConfig {
            enabled: true,
            timeout_ms: 0, // 0ms = guaranteed timeout
        };
        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        // With 0ms timeout, git status may or may not time out depending on system.
        // Either way, the result should not downgrade to LogOnly for a dirty/timeout case.
        let result = evaluate_git_context(&inv, &config, &[]);
        // We just check it returns Some (git command is evaluated)
        assert!(result.is_some());

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[serial_test::serial]
    fn git_context_sanitizes_git_dir_env() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        // Create initial commit so repo is clean
        std::fs::write(dir.join("dummy.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();

        // GIT_DIR spoof: point to a non-existent dir.
        // evaluate_git_context should remove GIT_DIR before calling git.
        // SAFETY: test is #[serial], no other threads access env vars concurrently.
        unsafe { env::set_var("GIT_DIR", "/nonexistent/.git") };
        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        // SAFETY: test is #[serial], no other threads access env vars concurrently.
        unsafe { env::remove_var("GIT_DIR") };

        // Should still work correctly (env var sanitized)
        assert!(result.is_some());
        let eval = result.unwrap();
        // Clean repo → LogOnly (proves GIT_DIR was sanitized, not followed)
        assert_eq!(eval.action_override, Some(ActionKind::LogOnly));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[serial_test::serial]
    fn git_context_sanitizes_git_work_tree_env() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        // Create initial commit so repo is clean
        std::fs::write(dir.join("dummy.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();

        // GIT_WORK_TREE spoof: point to a non-existent dir.
        // evaluate_git_context should remove GIT_WORK_TREE before calling git.
        // SAFETY: test is #[serial], no other threads access env vars concurrently.
        unsafe { env::set_var("GIT_WORK_TREE", "/nonexistent/fake") };
        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        // SAFETY: test is #[serial], no other threads access env vars concurrently.
        unsafe { env::remove_var("GIT_WORK_TREE") };

        // Should still work correctly (env var sanitized)
        assert!(result.is_some());
        let eval = result.unwrap();
        // Clean repo → LogOnly (proves GIT_WORK_TREE was sanitized, not followed)
        assert_eq!(eval.action_override, Some(ActionKind::LogOnly));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn git_context_non_git_command_returns_none() {
        let inv = CommandInvocation::new(
            "rm".to_string(),
            vec!["-rf".to_string(), "target/".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(result.is_none());
    }

    #[test]
    fn git_context_disabled_returns_none() {
        let config = GitContextConfig {
            enabled: false,
            timeout_ms: 100,
        };
        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let result = evaluate_git_context(&inv, &config, &[]);
        assert!(result.is_none());
    }

    #[test]
    #[serial_test::serial]
    fn git_context_non_git_directory_returns_some_none_override() {
        let dir = std::env::temp_dir().join(format!("omamori-nongit-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        let inv = CommandInvocation::new(
            "git".to_string(),
            vec!["reset".to_string(), "--hard".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(result.is_some());
        let eval = result.unwrap();
        assert!(eval.action_override.is_none());
        assert!(eval.reason.contains("not inside a git repository"));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    // --- evaluate_git_context: git clean path (G-01 cont.) ---

    #[test]
    #[serial_test::serial]
    fn git_context_clean_no_untracked_downgrades_to_log_only() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        // Create initial commit so repo is clean with no untracked files
        std::fs::write(dir.join("committed.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();

        let inv = super::CommandInvocation::new(
            "git".to_string(),
            vec!["clean".to_string(), "-fdx".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(result.is_some());
        let eval = result.unwrap();
        assert_eq!(eval.action_override, Some(ActionKind::LogOnly));
        assert!(eval.reason.contains("no untracked"));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    #[serial_test::serial]
    fn git_context_clean_with_untracked_keeps_original() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        // Create initial commit, then add an untracked file
        std::fs::write(dir.join("committed.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();
        std::fs::write(dir.join("untracked.txt"), "not tracked").unwrap();

        let inv = super::CommandInvocation::new(
            "git".to_string(),
            vec!["clean".to_string(), "-fd".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(result.is_some());
        let eval = result.unwrap();
        assert!(eval.action_override.is_none());
        assert!(eval.reason.contains("untracked files present"));

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    // --- #78: git clean with split flags must also trigger context evaluation ---

    #[test]
    #[serial_test::serial]
    fn git_context_clean_split_flags_triggers_evaluation() {
        let dir = create_git_repo();
        let saved = env::current_dir().unwrap();
        env::set_current_dir(&dir).unwrap();

        std::fs::write(dir.join("committed.txt"), "init").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .status()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(&dir)
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .unwrap();

        // git clean -f -d (split flags) should still trigger evaluation
        let inv = super::CommandInvocation::new(
            "git".to_string(),
            vec!["clean".to_string(), "-f".to_string(), "-d".to_string()],
        );
        let result = evaluate_git_context(&inv, &git_config(), &[]);
        assert!(
            result.is_some(),
            "split -f -d must trigger context evaluation"
        );
        let eval = result.unwrap();
        assert_eq!(eval.action_override, Some(ActionKind::LogOnly));

        // git clean --force -d should also trigger
        let inv2 = super::CommandInvocation::new(
            "git".to_string(),
            vec!["clean".to_string(), "--force".to_string(), "-d".to_string()],
        );
        let result2 = evaluate_git_context(&inv2, &git_config(), &[]);
        assert!(result2.is_some(), "--force must trigger context evaluation");

        env::set_current_dir(&saved).unwrap();
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn never_regenerable_covers_all_default_protected_paths() {
        let protected = default_protected_paths();
        let never: std::collections::HashSet<&str> = NEVER_REGENERABLE.iter().copied().collect();
        let missing: Vec<&str> = protected
            .iter()
            .map(|p| p.trim_end_matches('/'))
            .filter(|p| !never.contains(p))
            .collect();
        assert!(
            missing.is_empty(),
            "default_protected_paths() contains entries not in NEVER_REGENERABLE: {:?}\n\
             Either add them to NEVER_REGENERABLE or remove from default_protected_paths()",
            missing,
        );
    }
}