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
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
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::AppError;
use crate::audit::AuditConfig;
use crate::context::ContextConfig;
use crate::detector::DetectorConfig;
use crate::rules::{ActionKind, RuleConfig};

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

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    #[serde(default = "default_detectors")]
    pub detectors: Vec<DetectorConfig>,
    #[serde(default = "default_rules")]
    pub rules: Vec<RuleConfig>,
    #[serde(default)]
    pub audit: AuditConfig,
    /// Context-aware evaluation config. None = context evaluation disabled (v0.3 compat).
    /// Present (even empty) = built-in defaults active.
    #[serde(default)]
    pub context: Option<ContextConfig>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            detectors: default_detectors(),
            rules: default_rules(),
            audit: AuditConfig::default(),
            context: None,
        }
    }
}

#[derive(Debug, Clone)]
pub struct ConfigLoadResult {
    pub config: Config,
    pub warnings: Vec<String>,
}

// ---------------------------------------------------------------------------
// User config (deserialized from TOML — all rule fields optional for merge)
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Deserialize)]
struct UserConfig {
    detectors: Option<Vec<DetectorConfig>>,
    #[serde(default)]
    rules: Vec<UserRule>,
    #[serde(default)]
    audit: AuditConfig,
    #[serde(default)]
    context: Option<ContextConfig>,
    /// `[overrides]` section: `rule_name = false` allows disabling core rules.
    #[serde(default)]
    overrides: HashMap<String, bool>,
}

#[derive(Debug, Clone, Deserialize)]
struct UserRule {
    name: String,
    command: Option<String>,
    action: Option<ActionKind>,
    enabled: Option<bool>,
    destination: Option<String>,
    match_all: Option<Vec<String>>,
    match_any: Option<Vec<String>>,
    message: Option<String>,
}

// ---------------------------------------------------------------------------
// Blocked system directories for move-to destination
// ---------------------------------------------------------------------------

pub const BLOCKED_DESTINATION_PREFIXES: &[&str] = &[
    "/usr", "/etc", "/System", "/Library", "/bin", "/sbin", "/var", "/private",
];

// ---------------------------------------------------------------------------
// Config loading
// ---------------------------------------------------------------------------

pub fn load_config(path: Option<&Path>) -> Result<ConfigLoadResult, AppError> {
    let path = path.map(Path::to_path_buf).or_else(default_config_path);
    let mut warnings = Vec::new();

    let config = match path {
        Some(path) => {
            if !path.exists() {
                warnings.push(format!(
                    "config not found at {}\n  \
                     Built-in default rules are active (safe to use as-is).\n  \
                     To create a config for customization, run: omamori init",
                    path.display()
                ));
                Config::default()
            } else if !permissions_are_safe(&path)? {
                warnings.push(format!(
                    "config permissions are too open at {}\n  \
                     Built-in default rules are active for security.\n  \
                     To fix, run: chmod 600 {}",
                    path.display(),
                    path.display()
                ));
                Config::default()
            } else {
                let content = fs::read_to_string(&path)?;
                match toml::from_str::<UserConfig>(&content) {
                    Ok(user_config) => build_merged_config(user_config, &mut warnings),
                    Err(error) => {
                        warnings.push(format!(
                            "failed to parse config at {} ({error})\n  \
                             Built-in default rules are active for safety.\n  \
                             Fix the syntax error or run: omamori init --force",
                            path.display()
                        ));
                        Config::default()
                    }
                }
            }
        }
        None => Config::default(),
    };

    Ok(ConfigLoadResult { config, warnings })
}

// ---------------------------------------------------------------------------
// Merge logic
// ---------------------------------------------------------------------------

fn build_merged_config(user: UserConfig, warnings: &mut Vec<String>) -> Config {
    let detectors = user.detectors.unwrap_or_else(default_detectors);
    let mut rules = merge_rules(default_rules(), &user.rules, &user.overrides, warnings);
    validate_rules(&mut rules, warnings);

    // Validate context config if present
    if let Some(ref ctx) = user.context {
        let ctx_warnings = crate::context::validate_regenerable_paths(&ctx.regenerable_paths);
        warnings.extend(ctx_warnings);
    }

    let (validated_audit, audit_warnings) = user.audit.validate();
    warnings.extend(audit_warnings);

    Config {
        detectors,
        rules,
        audit: validated_audit,
        context: user.context,
    }
}

fn merge_rules(
    defaults: Vec<RuleConfig>,
    user_rules: &[UserRule],
    overrides: &HashMap<String, bool>,
    warnings: &mut Vec<String>,
) -> Vec<RuleConfig> {
    // Check for duplicate names in user config
    let mut seen_names = HashSet::new();
    for ur in user_rules {
        if !seen_names.insert(&ur.name) {
            warnings.push(format!(
                "duplicate rule name `{}` in config; only the first occurrence is used",
                ur.name
            ));
        }
    }

    let mut merged = defaults;
    let mut applied_names = HashSet::new();

    for ur in user_rules {
        if applied_names.contains(&ur.name) {
            continue; // skip duplicates
        }
        applied_names.insert(ur.name.clone());

        if let Some(existing) = merged.iter_mut().find(|r| r.name == ur.name) {
            // Override existing rule fields
            apply_user_overrides(existing, ur, overrides, warnings);
        } else {
            // New rule — must have command + action
            match (&ur.command, &ur.action) {
                (Some(command), Some(action)) => {
                    let mut rule = RuleConfig::new(
                        &ur.name,
                        command,
                        action.clone(),
                        ur.match_all.clone().unwrap_or_default(),
                        ur.match_any.clone().unwrap_or_default(),
                        ur.message.clone(),
                    );
                    if let Some(enabled) = ur.enabled {
                        rule.enabled = enabled;
                    }
                    if let Some(dest) = &ur.destination {
                        rule.destination = Some(dest.clone());
                    }
                    merged.push(rule);
                }
                _ => {
                    warnings.push(format!(
                        "rule `{}` is not a built-in rule and is missing `command` or `action`; skipped",
                        ur.name
                    ));
                }
            }
        }
    }

    // Apply [overrides] section: disable core rules that have explicit override
    for (rule_name, &enabled) in overrides {
        if !enabled
            && let Some(rule) = merged.iter_mut().find(|r| r.name == *rule_name)
            && rule.is_builtin
        {
            rule.enabled = false;
        }
    }

    merged
}

fn apply_user_overrides(
    rule: &mut RuleConfig,
    ur: &UserRule,
    overrides: &HashMap<String, bool>,
    warnings: &mut Vec<String>,
) {
    if rule.is_builtin {
        // Core rule immutability: only `message` can be customized.
        // `enabled` immutability can be bypassed via [overrides] section.
        let has_non_message = ur.command.is_some()
            || ur.action.is_some()
            || ur.match_all.is_some()
            || ur.match_any.is_some()
            || ur.destination.is_some();

        let has_enabled_override = ur.enabled.is_some();

        // Check if [overrides] section has an explicit entry for this rule
        let has_overrides_entry = overrides.contains_key(&rule.name);

        if has_non_message {
            // Check action specifically for upgrade vs downgrade
            if let Some(action) = &ur.action {
                if action.defense_level() < rule.action.defense_level() {
                    warnings.push(format!(
                        "rule `{}` is a core safety rule — action downgrade from `{}` to `{}` \
                         is not allowed. Override ignored.",
                        rule.name,
                        rule.action.as_str(),
                        action.as_str()
                    ));
                } else if action.defense_level() >= rule.action.defense_level()
                    && action != &rule.action
                {
                    // Same or higher defense level — allow action upgrade
                    rule.action = action.clone();
                }
                // Same action — no warning needed
            }

            // Warn about other non-message field overrides
            if ur.command.is_some()
                || ur.match_all.is_some()
                || ur.match_any.is_some()
                || ur.destination.is_some()
            {
                warnings.push(format!(
                    "rule `{}` is a core safety rule. Only `message` can be customized. \
                     Other overrides (`command`, `match_all`, `match_any`, `destination`) are ignored.",
                    rule.name
                ));
            }
        }

        if has_enabled_override && !has_overrides_entry && ur.enabled == Some(false) {
            warnings.push(format!(
                "rule `{}` is a core safety rule and cannot be disabled via config. \
                 Ignored. To override: omamori override disable {}",
                rule.name, rule.name
            ));
        }

        // Only apply message override
        if let Some(message) = &ur.message {
            rule.message = Some(message.clone());
        }

        return;
    }

    // Non-core rules: apply all overrides as before
    if let Some(command) = &ur.command {
        rule.command = command.clone();
    }
    if let Some(action) = &ur.action {
        rule.action = action.clone();
    }
    if let Some(enabled) = ur.enabled {
        rule.enabled = enabled;
    }
    if let Some(dest) = &ur.destination {
        rule.destination = Some(dest.clone());
    }
    if let Some(match_all) = &ur.match_all {
        rule.match_all = match_all.clone();
    }
    if let Some(match_any) = &ur.match_any {
        rule.match_any = match_any.clone();
    }
    if let Some(message) = &ur.message {
        rule.message = Some(message.clone());
    }
}

// ---------------------------------------------------------------------------
// Validation
// ---------------------------------------------------------------------------

fn validate_rules(rules: &mut [RuleConfig], warnings: &mut Vec<String>) {
    for rule in rules.iter_mut() {
        // MoveTo requires destination
        if rule.action == ActionKind::MoveTo && rule.destination.is_none() {
            warnings.push(format!(
                "rule `{}` uses action `move-to` but has no `destination`; rule disabled",
                rule.name
            ));
            rule.enabled = false;
        }

        // destination without MoveTo
        if rule.destination.is_some() && rule.action != ActionKind::MoveTo {
            warnings.push(format!(
                "rule `{}` has a `destination` but action is `{}`; destination is ignored",
                rule.name,
                rule.action.as_str()
            ));
        }

        // Validate destination path — violations disable the rule (enforcement)
        if let Some(dest) = &rule.destination.clone()
            && !validate_destination(dest, &rule.name, warnings)
        {
            rule.enabled = false;
        }
    }
}

/// Returns `true` if the destination is valid, `false` if it should be blocked.
fn validate_destination(dest: &str, rule_name: &str, warnings: &mut Vec<String>) -> bool {
    let path = Path::new(dest);

    // Must be absolute
    if !path.is_absolute() {
        warnings.push(format!(
            "rule `{rule_name}`: destination `{dest}` is not an absolute path; rule disabled"
        ));
        return false;
    }

    // Check symlink on original path before canonicalize resolves it (#105)
    if let Ok(meta) = fs::symlink_metadata(path)
        && meta.file_type().is_symlink()
    {
        warnings.push(format!(
            "rule `{rule_name}`: destination `{dest}` is a symlink; rule disabled for security"
        ));
        return false;
    }

    // Resolve canonical path (catches .. traversal)
    if let Ok(canonical) = path.canonicalize() {
        let canonical_str = canonical.to_string_lossy();
        for prefix in BLOCKED_DESTINATION_PREFIXES {
            if canonical_str.starts_with(prefix) {
                warnings.push(format!(
                    "rule `{rule_name}`: destination `{dest}` resolves to system directory \
                     `{canonical_str}`; rule disabled for security"
                ));
                return false;
            }
        }
    }
    // If canonicalize fails (path doesn't exist yet), we'll catch it at runtime
    true
}

// ---------------------------------------------------------------------------
// Defaults
// ---------------------------------------------------------------------------

/// Returns the default config file path, respecting `XDG_CONFIG_HOME`.
/// Priority: `$XDG_CONFIG_HOME/omamori/config.toml` → `$HOME/.config/omamori/config.toml`.
pub fn default_config_path() -> Option<PathBuf> {
    // XDG_CONFIG_HOME must be absolute if set
    if let Some(xdg) = std::env::var_os("XDG_CONFIG_HOME") {
        let xdg_path = PathBuf::from(&xdg);
        if xdg_path.is_absolute() {
            return Some(xdg_path.join("omamori").join("config.toml"));
        }
        // Relative XDG_CONFIG_HOME is ignored (XDG spec requires absolute)
    }
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .map(|home| home.join(".config").join("omamori").join("config.toml"))
}

pub fn default_detectors() -> Vec<DetectorConfig> {
    vec![
        DetectorConfig::env_var("claude-code", "CLAUDECODE", "1"),
        DetectorConfig::env_var("codex-cli", "CODEX_CI", "1"),
        // Verified: Cursor sets CURSOR_AGENT=1. Confirmed via E2E testing (2026-03-17).
        DetectorConfig::env_var("cursor", "CURSOR_AGENT", "1"),
        // Provisional: based on agents.md #136 reports. Verify with actual tool releases.
        DetectorConfig::env_var("gemini-cli", "GEMINI_CLI", "1"),
        DetectorConfig::env_var("cline", "CLINE_ACTIVE", "true"),
        DetectorConfig::env_var("ai-guard-fallback", "AI_GUARD", "1"),
    ]
}

pub fn default_rules() -> Vec<RuleConfig> {
    vec![
        RuleConfig::new(
            "rm-recursive-to-trash",
            "rm",
            ActionKind::Trash,
            Vec::new(),
            vec![
                "-r".to_string(),
                "-rf".to_string(),
                "-fr".to_string(),
                "--recursive".to_string(),
            ],
            Some(
                "omamori moved the recursive rm targets to Trash instead of deleting them"
                    .to_string(),
            ),
        )
        .with_builtin(true),
        RuleConfig::new(
            "git-reset-hard-stash",
            "git",
            ActionKind::StashThenExec,
            vec!["reset".to_string(), "--hard".to_string()],
            Vec::new(),
            Some("omamori stashed changes before running git reset --hard".to_string()),
        )
        .with_builtin(true),
        RuleConfig::new(
            "git-push-force-block",
            "git",
            ActionKind::Block,
            vec!["push".to_string()],
            vec!["--force".to_string(), "-f".to_string()],
            Some("omamori blocked a force push".to_string()),
        )
        .with_builtin(true),
        RuleConfig::new(
            "git-clean-force-block",
            "git",
            ActionKind::Block,
            vec!["clean".to_string()],
            vec!["-f".to_string(), "--force".to_string()],
            Some("omamori blocked git clean because it would remove untracked files".to_string()),
        )
        .with_builtin(true),
        RuleConfig::new(
            "chmod-777-block",
            "chmod",
            ActionKind::Block,
            Vec::new(),
            vec!["777".to_string()],
            Some("omamori blocked chmod 777".to_string()),
        )
        .with_builtin(true),
        RuleConfig::new(
            "find-delete-block",
            "find",
            ActionKind::Block,
            Vec::new(),
            vec!["-delete".to_string(), "--delete".to_string()],
            Some("omamori blocked find with -delete flag".to_string()),
        )
        .with_builtin(true),
        RuleConfig::new(
            "rsync-delete-block",
            "rsync",
            ActionKind::Block,
            Vec::new(),
            vec![
                "--delete".to_string(),
                "--del".to_string(),
                "--delete-before".to_string(),
                "--delete-during".to_string(),
                "--delete-after".to_string(),
                "--delete-excluded".to_string(),
                "--delete-delay".to_string(),
                "--remove-source-files".to_string(),
            ],
            Some("omamori blocked rsync with destructive flags".to_string()),
        )
        .with_builtin(true),
    ]
}

/// Names of the 7 core (built-in) safety rules.
pub fn core_rule_names() -> Vec<&'static str> {
    vec![
        "rm-recursive-to-trash",
        "git-reset-hard-stash",
        "git-push-force-block",
        "git-clean-force-block",
        "chmod-777-block",
        "find-delete-block",
        "rsync-delete-block",
    ]
}

// ---------------------------------------------------------------------------
// Config file writing
// ---------------------------------------------------------------------------

#[derive(Debug)]
pub struct WriteConfigResult {
    pub path: PathBuf,
    pub created: bool,
}

/// Generate the default config template as a string (all rules commented out).
pub fn config_template() -> String {
    let defaults = default_rules();
    let mut out = String::new();
    out.push_str(
        "# omamori config — only write the rules you want to change.\n\
         # Built-in rules are inherited automatically.\n\
         # To disable a rule: set enabled = false\n\
         # To change an action: override the action field\n\
         #\n\
         # Docs: https://github.com/yottayoshida/omamori\n\
         #\n",
    );
    for rule in &defaults {
        out.push_str("\n# [[rules]]\n");
        out.push_str(&format!("# name = \"{}\"\n", rule.name));
        out.push_str(&format!("# command = \"{}\"\n", rule.command));
        out.push_str(&format!("# action = \"{}\"\n", rule.action.as_str()));
        if !rule.match_all.is_empty() {
            out.push_str(&format!("# match_all = {:?}\n", rule.match_all));
        }
        if !rule.match_any.is_empty() {
            out.push_str(&format!("# match_any = {:?}\n", rule.match_any));
        }
        out.push_str("# # enabled = false  # uncomment to disable this rule\n");
    }
    out.push_str(
        "\n# --- Custom rule example ---\n\
         # [[rules]]\n\
         # name = \"rm-to-backup\"\n\
         # command = \"rm\"\n\
         # action = \"move-to\"\n\
         # destination = \"/tmp/omamori-quarantine/\"\n\
         # match_any = [\"-r\", \"-rf\", \"-fr\", \"--recursive\"]\n\
         # message = \"omamori moved targets to backup instead of deleting\"\n",
    );
    out
}

/// Write the default config template to the given path.
///
/// Safety features:
/// - Refuses to write to symlinks (`O_NOFOLLOW` + `symlink_metadata` check)
/// - `force=false`: uses `create_new(true)` to prevent TOCTOU races
/// - `force=true`: atomic write via temp file + rename + fsync
/// - Sets directory permissions to 700, file permissions to 600
pub fn write_default_config(path: &Path, force: bool) -> Result<WriteConfigResult, AppError> {
    let dir = path
        .parent()
        .ok_or_else(|| AppError::Config(format!("invalid config path: {}", path.display())))?;

    // Create directory with mode 700
    if !dir.exists() {
        fs::create_dir_all(dir)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(dir, fs::Permissions::from_mode(0o700))?;
        }
    } else {
        // P2 fix: reject symlinked parent directory
        reject_symlink(dir, "config directory")?;
    }

    // Check for symlink at target path
    if path.exists() || path.symlink_metadata().is_ok() {
        reject_symlink(path, "config path")?;

        if !force {
            return Err(AppError::Config(format!(
                "config already exists at {}\n  Use `omamori init --force` to overwrite.",
                path.display()
            )));
        }
    }

    let content = config_template();

    if force && path.exists() {
        // Atomic write: temp file → fsync → rename
        let temp_path = path.with_extension("toml.tmp");
        // P1 fix: reject symlink at temp path too
        if temp_path.symlink_metadata().is_ok() {
            reject_symlink(&temp_path, "temp config path")?;
            // Remove stale temp file (non-symlink) if it exists
            let _ = fs::remove_file(&temp_path);
        }
        write_new_config(&temp_path, &content)?;
        // fsync the file
        let file = fs::File::open(&temp_path)?;
        file.sync_all()?;
        drop(file);
        // Atomic rename
        fs::rename(&temp_path, path)?;
        // fsync the parent directory
        if let Ok(dir_file) = fs::File::open(dir) {
            let _ = dir_file.sync_all();
        }
    } else {
        // New file: use O_NOFOLLOW + create_new for TOCTOU safety
        write_new_config(path, &content)?;
    }

    Ok(WriteConfigResult {
        path: path.to_path_buf(),
        created: true,
    })
}

/// Public wrapper for symlink rejection (used by config enable/disable).
pub fn reject_symlink_public(path: &Path, label: &str) -> Result<(), AppError> {
    reject_symlink(path, label)
}

fn reject_symlink(path: &Path, label: &str) -> Result<(), AppError> {
    if let Ok(meta) = fs::symlink_metadata(path)
        && meta.file_type().is_symlink()
    {
        return Err(AppError::Config(format!(
            "{label} `{}` is a symlink; refusing to write for security",
            path.display()
        )));
    }
    Ok(())
}

#[cfg(unix)]
fn write_new_config(path: &Path, content: &str) -> Result<(), AppError> {
    use std::os::unix::fs::OpenOptionsExt;

    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .custom_flags(libc::O_NOFOLLOW)
        .open(path)?;
    file.write_all(content.as_bytes())?;
    file.sync_all()?;
    Ok(())
}

#[cfg(not(unix))]
fn write_new_config(path: &Path, content: &str) -> Result<(), AppError> {
    fs::write(path, content)?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Permissions check
// ---------------------------------------------------------------------------

#[cfg(unix)]
fn permissions_are_safe(path: &Path) -> Result<bool, AppError> {
    use std::os::unix::fs::MetadataExt;

    let metadata = fs::metadata(path)?;
    Ok(metadata.mode() & 0o777 == 0o600)
}

#[cfg(not(unix))]
fn permissions_are_safe(_path: &Path) -> Result<bool, AppError> {
    Ok(true)
}

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

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

    fn no_overrides() -> HashMap<String, bool> {
        HashMap::new()
    }

    #[test]
    fn merge_core_rule_ignores_disable_without_override() {
        // Core rule `enabled = false` in config is ignored (immutability)
        let user_rules = vec![UserRule {
            name: "git-push-force-block".to_string(),
            command: None,
            action: None,
            enabled: Some(false),
            destination: None,
            match_all: None,
            match_any: None,
            message: None,
        }];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        let rule = merged
            .iter()
            .find(|r| r.name == "git-push-force-block")
            .unwrap();
        assert!(rule.enabled); // core rule stays enabled
        assert_eq!(rule.action, ActionKind::Block);
        assert!(
            warnings.iter().any(
                |w: &String| w.contains("core safety rule") && w.contains("cannot be disabled")
            ),
            "expected immutability warning, got: {warnings:?}"
        );
    }

    #[test]
    fn merge_core_rule_disabled_via_overrides_section() {
        // [overrides] section allows disabling core rules
        let user_rules = vec![UserRule {
            name: "git-push-force-block".to_string(),
            command: None,
            action: None,
            enabled: Some(false),
            destination: None,
            match_all: None,
            match_any: None,
            message: None,
        }];
        let mut overrides = HashMap::new();
        overrides.insert("git-push-force-block".to_string(), false);
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &overrides, &mut warnings);

        let rule = merged
            .iter()
            .find(|r| r.name == "git-push-force-block")
            .unwrap();
        assert!(!rule.enabled); // overrides section allows disable
    }

    #[test]
    fn merge_adds_new_rule() {
        let user_rules = vec![UserRule {
            name: "custom-rm".to_string(),
            command: Some("rm".to_string()),
            action: Some(ActionKind::MoveTo),
            enabled: None,
            destination: Some("/tmp/backup".to_string()),
            match_all: None,
            match_any: Some(vec!["-rf".to_string()]),
            message: Some("custom".to_string()),
        }];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        let rule = merged.iter().find(|r| r.name == "custom-rm").unwrap();
        assert_eq!(rule.action, ActionKind::MoveTo);
        assert_eq!(rule.destination.as_deref(), Some("/tmp/backup"));
        assert!(rule.enabled);
    }

    #[test]
    fn merge_new_rule_without_command_warns() {
        let user_rules = vec![UserRule {
            name: "bad-rule".to_string(),
            command: None,
            action: None,
            enabled: Some(false),
            destination: None,
            match_all: None,
            match_any: None,
            message: None,
        }];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        assert!(merged.iter().all(|r| r.name != "bad-rule"));
        assert!(
            warnings
                .iter()
                .any(|w: &String| w.contains("missing `command` or `action`"))
        );
    }

    #[test]
    fn merge_duplicate_name_warns() {
        let user_rules = vec![
            UserRule {
                name: "git-push-force-block".to_string(),
                command: None,
                action: None,
                enabled: Some(false),
                destination: None,
                match_all: None,
                match_any: None,
                message: None,
            },
            UserRule {
                name: "git-push-force-block".to_string(),
                command: None,
                action: None,
                enabled: Some(true),
                destination: None,
                match_all: None,
                match_any: None,
                message: None,
            },
        ];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        let rule = merged
            .iter()
            .find(|r| r.name == "git-push-force-block")
            .unwrap();
        // Core rule: enabled = false is ignored, so it stays enabled
        assert!(rule.enabled);
        assert!(
            warnings
                .iter()
                .any(|w: &String| w.contains("duplicate rule name"))
        );
    }

    #[test]
    fn merge_preserves_all_defaults_when_no_user_rules() {
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &[], &no_overrides(), &mut warnings);
        assert_eq!(merged.len(), default_rules().len());
        assert!(warnings.is_empty());
    }

    #[test]
    fn merge_core_rule_action_downgrade_rejected() {
        // Trying to downgrade rm-recursive-to-trash from trash to log-only
        let user_rules = vec![UserRule {
            name: "rm-recursive-to-trash".to_string(),
            command: None,
            action: Some(ActionKind::LogOnly),
            enabled: None,
            destination: None,
            match_all: None,
            match_any: None,
            message: None,
        }];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        let rule = merged
            .iter()
            .find(|r| r.name == "rm-recursive-to-trash")
            .unwrap();
        assert_eq!(rule.action, ActionKind::Trash); // stays at original
        assert!(
            warnings
                .iter()
                .any(|w: &String| w.contains("action downgrade")),
            "expected downgrade warning, got: {warnings:?}"
        );
    }

    #[test]
    fn merge_core_rule_action_upgrade_allowed() {
        // Upgrading rm-recursive-to-trash from trash to block is allowed
        let user_rules = vec![UserRule {
            name: "rm-recursive-to-trash".to_string(),
            command: None,
            action: Some(ActionKind::Block),
            enabled: None,
            destination: None,
            match_all: None,
            match_any: None,
            message: None,
        }];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        let rule = merged
            .iter()
            .find(|r| r.name == "rm-recursive-to-trash")
            .unwrap();
        assert_eq!(rule.action, ActionKind::Block); // upgraded
    }

    #[test]
    fn merge_core_rule_message_override_allowed() {
        let user_rules = vec![UserRule {
            name: "git-push-force-block".to_string(),
            command: None,
            action: None,
            enabled: None,
            destination: None,
            match_all: None,
            match_any: None,
            message: Some("my custom message".to_string()),
        }];
        let mut warnings = Vec::new();
        let merged = merge_rules(default_rules(), &user_rules, &no_overrides(), &mut warnings);

        let rule = merged
            .iter()
            .find(|r| r.name == "git-push-force-block")
            .unwrap();
        assert_eq!(rule.message.as_deref(), Some("my custom message"));
        // No warnings for message-only override
        assert!(
            warnings.is_empty(),
            "no warnings for message override: {warnings:?}"
        );
    }

    #[test]
    fn validate_move_to_without_destination_disables_rule() {
        let mut rules = vec![RuleConfig::new(
            "bad",
            "rm",
            ActionKind::MoveTo,
            Vec::new(),
            Vec::new(),
            None,
        )];
        let mut warnings = Vec::new();
        validate_rules(&mut rules, &mut warnings);
        assert!(warnings.iter().any(|w| w.contains("no `destination`")));
        assert!(!rules[0].enabled); // rule gets disabled
    }

    #[test]
    fn validate_destination_on_non_move_to_warns() {
        let mut rules = vec![
            RuleConfig::new(
                "weird",
                "rm",
                ActionKind::Trash,
                Vec::new(),
                Vec::new(),
                None,
            )
            .with_destination("/tmp/x".to_string()),
        ];
        let mut warnings = Vec::new();
        validate_rules(&mut rules, &mut warnings);
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("destination is ignored"))
        );
        assert!(rules[0].enabled); // rule stays enabled (just a warning)
    }

    #[test]
    fn validate_relative_destination_disables_rule() {
        let mut rules = vec![
            RuleConfig::new(
                "rel",
                "rm",
                ActionKind::MoveTo,
                Vec::new(),
                Vec::new(),
                None,
            )
            .with_destination("relative/path".to_string()),
        ];
        let mut warnings = Vec::new();
        validate_rules(&mut rules, &mut warnings);
        assert!(warnings.iter().any(|w| w.contains("not an absolute path")));
        assert!(!rules[0].enabled); // rule gets disabled
    }

    #[test]
    fn validate_symlink_destination_disables_rule() {
        use std::os::unix::fs::symlink;
        let dir = std::env::temp_dir().join(format!("omamori-symdest-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let real_dir = dir.join("real");
        std::fs::create_dir_all(&real_dir).unwrap();
        let link = dir.join("link");
        symlink(&real_dir, &link).unwrap();

        let mut rules = vec![
            RuleConfig::new(
                "sym",
                "rm",
                ActionKind::MoveTo,
                Vec::new(),
                Vec::new(),
                None,
            )
            .with_destination(link.display().to_string()),
        ];
        let mut warnings = Vec::new();
        validate_rules(&mut rules, &mut warnings);
        assert!(
            warnings.iter().any(|w| w.contains("is a symlink")),
            "expected symlink warning, got: {warnings:?}"
        );
        assert!(!rules[0].enabled);

        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn default_rules_all_enabled() {
        for rule in default_rules() {
            assert!(
                rule.enabled,
                "rule {} should be enabled by default",
                rule.name
            );
        }
    }

    #[test]
    fn user_config_without_detectors_uses_defaults() {
        let toml_str = r#"
[[rules]]
name = "git-push-force-block"
enabled = false
"#;
        let user: UserConfig = toml::from_str(toml_str).unwrap();
        assert!(user.detectors.is_none());
        let mut warnings = Vec::new();
        let config = build_merged_config(user, &mut warnings);
        assert_eq!(config.detectors.len(), 6); // defaults (claude-code, codex-cli, cursor, gemini-cli, cline, ai-guard-fallback)
    }

    #[test]
    fn user_config_with_custom_detectors_replaces() {
        let toml_str = r#"
[[detectors]]
name = "my-tool"
type = "env_var"
env_key = "MY_TOOL"
env_value = "1"
"#;
        let user: UserConfig = toml::from_str(toml_str).unwrap();
        assert!(user.detectors.is_some());
        let mut warnings = Vec::new();
        let config = build_merged_config(user, &mut warnings);
        assert_eq!(config.detectors.len(), 1);
        assert_eq!(config.detectors[0].name, "my-tool");
    }

    #[test]
    fn enabled_field_defaults_to_true_in_toml() {
        let toml_str = r#"
[[rules]]
name = "test-rule"
command = "rm"
action = "block"
"#;
        // Parse as full RuleConfig (simulating direct deserialization)
        #[derive(Deserialize)]
        struct Wrapper {
            rules: Vec<RuleConfig>,
        }
        let parsed: Wrapper = toml::from_str(toml_str).unwrap();
        assert!(parsed.rules[0].enabled);
    }

    // --- CI consistency checks (PR 2: config.default.toml ↔ code sync) ---

    #[test]
    fn config_default_toml_rules_match_default_rules() {
        let toml_str = include_str!("../config.default.toml");
        let parsed: Config = toml::from_str(toml_str).unwrap();
        let toml_names: HashSet<&str> = parsed.rules.iter().map(|r| r.name.as_str()).collect();
        let code_rules = default_rules();
        let code_names: HashSet<&str> = code_rules.iter().map(|r| r.name.as_str()).collect();
        assert_eq!(
            toml_names,
            code_names,
            "config.default.toml rules and default_rules() are out of sync.\n\
             In TOML only: {:?}\n\
             In code only: {:?}",
            toml_names.difference(&code_names).collect::<Vec<_>>(),
            code_names.difference(&toml_names).collect::<Vec<_>>(),
        );
    }

    #[test]
    fn config_default_toml_detectors_match_default_detectors() {
        let toml_str = include_str!("../config.default.toml");
        let parsed: Config = toml::from_str(toml_str).unwrap();
        let toml_names: HashSet<&str> = parsed.detectors.iter().map(|d| d.name.as_str()).collect();
        let code_detectors = default_detectors();
        let code_names: HashSet<&str> = code_detectors.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(
            toml_names,
            code_names,
            "config.default.toml detectors and default_detectors() are out of sync.\n\
             In TOML only: {:?}\n\
             In code only: {:?}",
            toml_names.difference(&code_names).collect::<Vec<_>>(),
            code_names.difference(&toml_names).collect::<Vec<_>>(),
        );
    }

    // --- G-05: write_default_config ---

    #[test]
    fn write_default_config_creates_with_correct_permissions() {
        let dir = std::env::temp_dir().join(format!("omamori-cfg-g05-1-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);

        let path = dir.join("config.toml");
        let result = write_default_config(&path, false);
        assert!(result.is_ok());

        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            let meta = fs::metadata(&path).unwrap();
            assert_eq!(meta.mode() & 0o777, 0o600, "file should be mode 600");
            let dir_meta = fs::metadata(&dir).unwrap();
            assert_eq!(dir_meta.mode() & 0o777, 0o700, "dir should be mode 700");
        }

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_default_config_rejects_symlink_target() {
        let dir = std::env::temp_dir().join(format!("omamori-cfg-g05-2-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        #[cfg(unix)]
        {
            let real_file = dir.join("real.toml");
            fs::write(&real_file, "real").unwrap();
            let link_path = dir.join("config.toml");
            std::os::unix::fs::symlink(&real_file, &link_path).unwrap();

            let result = write_default_config(&link_path, false);
            assert!(result.is_err());
            let err = format!("{}", result.unwrap_err());
            assert!(err.contains("symlink"));
        }

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_default_config_force_atomic_write() {
        let dir = std::env::temp_dir().join(format!("omamori-cfg-g05-3-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);

        let path = dir.join("config.toml");
        // First create
        write_default_config(&path, false).unwrap();
        let content1 = fs::read_to_string(&path).unwrap();

        // Force overwrite
        let result = write_default_config(&path, true);
        assert!(result.is_ok());
        let content2 = fs::read_to_string(&path).unwrap();
        assert_eq!(content1, content2, "content should be the same template");

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_default_config_no_force_errors_on_existing() {
        let dir = std::env::temp_dir().join(format!("omamori-cfg-g05-4-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);

        let path = dir.join("config.toml");
        write_default_config(&path, false).unwrap();

        // Second create without force should fail
        let result = write_default_config(&path, false);
        assert!(result.is_err());

        let _ = fs::remove_dir_all(&dir);
    }

    // --- G-06: load_config permissions ---

    #[test]
    fn load_config_rejects_insecure_permissions() {
        let dir = std::env::temp_dir().join(format!("omamori-cfg-g06-1-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let path = dir.join("config.toml");
        fs::write(&path, "# test config\n").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            // Set insecure permissions (world-readable)
            fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap();

            let result = load_config(Some(&path)).unwrap();
            // Should warn about permissions and use default config
            assert!(
                result.warnings.iter().any(|w| w.contains("permissions")),
                "should warn about insecure permissions"
            );
        }

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn load_config_accepts_secure_permissions() {
        let dir = std::env::temp_dir().join(format!("omamori-cfg-g06-2-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();

        let path = dir.join("config.toml");
        // Write a minimal valid config
        fs::write(&path, "# valid config\n").unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();

            let result = load_config(Some(&path)).unwrap();
            // No permission warnings
            assert!(
                !result.warnings.iter().any(|w| w.contains("permissions")),
                "should not warn about secure permissions"
            );
        }

        let _ = fs::remove_dir_all(&dir);
    }
}