clash 0.5.1

Command Line Agent Safety Harness — permission policies for coding agents
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
use std::path::PathBuf;

use crate::policy::match_tree::CompiledPolicy;
use crate::policy_loader;
use anyhow::{Context, Result};
use dirs::home_dir;
use serde::{Deserialize, Serialize};
use tracing::{Level, info, instrument, warn};

use crate::audit::AuditConfig;
use crate::notifications::NotificationConfig;

/// The environment variable that disables all clash hooks.
///
/// When set to any non-empty value (except `"0"` or `"false"`), clash becomes a
/// pass-through — all hooks return immediately without evaluating policy.
/// This is naturally session-scoped when set in the shell that launches Claude Code.
pub const CLASH_DISABLE_ENV: &str = "CLASH_DISABLE";

/// The environment variable that enables passthrough mode.
///
/// When set, clash defers all permission decisions to Claude Code's native permission
/// system — hooks return `continue_execution()` ("no opinion") instead of evaluating policy.
/// Tracing still syncs conversation turns, but there are no policy decisions, audit logs,
/// or session stats (since clash doesn't know what Claude decided).
/// If both `CLASH_DISABLE` and `CLASH_PASSTHROUGH` are set, `CLASH_DISABLE` takes priority.
pub const CLASH_PASSTHROUGH_ENV: &str = "CLASH_PASSTHROUGH";

/// Check whether clash is disabled via the [`CLASH_DISABLE`](CLASH_DISABLE_ENV) environment variable.
///
/// Returns `true` when the variable is set to any non-empty value except `"0"` or `"false"`.
pub fn is_disabled() -> bool {
    std::env::var(CLASH_DISABLE_ENV)
        .ok()
        .is_some_and(|v| is_truthy_disable_value(&v))
}

/// Check whether clash is in passthrough mode via the [`CLASH_PASSTHROUGH`](CLASH_PASSTHROUGH_ENV)
/// environment variable.
///
/// Returns `true` when the variable is set to any non-empty value except `"0"` or `"false"`.
pub fn is_passthrough() -> bool {
    std::env::var(CLASH_PASSTHROUGH_ENV)
        .ok()
        .is_some_and(|v| is_truthy_disable_value(&v))
}

/// Returns `true` when `value` should be interpreted as "disabled".
///
/// A non-empty string that is not `"0"` or `"false"` means disabled.
fn is_truthy_disable_value(value: &str) -> bool {
    !value.is_empty() && value != "0" && value != "false"
}

/// Policy level — where a policy file lives in the precedence hierarchy.
///
/// Higher-precedence levels override lower ones: Session > Project > User.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum PolicyLevel {
    /// User-level policy: `~/.clash/policy.json` (or `policy.star`)
    User = 0,
    /// Project-level policy: `<project_root>/.clash/policy.json` (or `policy.star`)
    Project = 1,
    /// Session-level policy: `/tmp/clash-<session_id>/policy.star`
    /// Temporary rules that last only for the current Claude Code session.
    Session = 2,
}

impl PolicyLevel {
    /// All persistent levels in precedence order (highest first).
    /// Session is excluded because it requires a session_id to resolve.
    pub fn all_by_precedence() -> &'static [PolicyLevel] {
        &[PolicyLevel::Project, PolicyLevel::User]
    }

    /// Display name for this level.
    pub fn name(&self) -> &'static str {
        match self {
            PolicyLevel::User => "user",
            PolicyLevel::Project => "project",
            PolicyLevel::Session => "session",
        }
    }
}

impl std::fmt::Display for PolicyLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name())
    }
}

impl std::str::FromStr for PolicyLevel {
    type Err = anyhow::Error;

    fn from_str(s: &str) -> Result<Self> {
        match s {
            "user" => Ok(PolicyLevel::User),
            "project" => Ok(PolicyLevel::Project),
            "session" => Ok(PolicyLevel::Session),
            _ => anyhow::bail!(
                "unknown policy level: {s} (expected 'user', 'project', or 'session')"
            ),
        }
    }
}

/// Default policy source template embedded at compile time.
/// Contains `{preset}` placeholders for the sandbox preset name.
pub const DEFAULT_POLICY_TEMPLATE: &str = include_str!("default_policy.star");

/// Available sandbox presets for `clash init`.
pub const SANDBOX_PRESETS: &[SandboxPreset] = &[
    SandboxPreset {
        name: "dev",
        description: "Build tools, git — read+write project, read home, no network",
    },
    SandboxPreset {
        name: "dev_network",
        description: "Package managers, gh — read+write project, full network",
    },
    SandboxPreset {
        name: "read_only",
        description: "Linters, analyzers — read project + home, no writes outside temp",
    },
    SandboxPreset {
        name: "restricted",
        description: "Untrusted scripts — read-only project, no network",
    },
    SandboxPreset {
        name: "unrestricted",
        description: "Fully trusted — all filesystem + network access",
    },
];

/// A sandbox preset that can be selected during `clash init`.
pub struct SandboxPreset {
    pub name: &'static str,
    pub description: &'static str,
}

impl crate::dialog::SelectItem for SandboxPreset {
    fn label(&self) -> &str {
        self.name
    }
    fn description(&self) -> &str {
        self.description
    }
    fn variants() -> &'static [Self] {
        SANDBOX_PRESETS
    }
}

/// Compile the default policy with the given sandbox preset to JSON.
///
/// Substitutes `{preset}` in the template with the chosen preset name,
/// then evaluates the Starlark source and returns pretty-printed JSON.
pub fn compile_default_policy_to_json_with_preset(preset: &str) -> Result<String> {
    let source = DEFAULT_POLICY_TEMPLATE.replace("{preset}", preset);
    let output =
        clash_starlark::evaluate(&source, "<default_policy>", std::path::Path::new("."))
            .with_context(|| format!("failed to compile default policy with preset '{preset}'"))?;
    let value: serde_json::Value =
        serde_json::from_str(&output.json).context("default policy produced invalid JSON")?;
    serde_json::to_string_pretty(&value).context("failed to pretty-print default policy JSON")
}

/// Compile the default policy with the `dev` preset (used for auto-creation).
pub fn compile_default_policy_to_json() -> Result<String> {
    compile_default_policy_to_json_with_preset("dev")
}

/// Session-level context from Claude Code hook input.
///
/// Carries runtime values that aren't available as standard environment
/// variables but are needed to resolve session-specific policy variables.
#[derive(Debug, Clone, Default)]
pub struct HookContext {
    /// Parent directory of the session transcript file. Agent output files
    /// are stored here and must always be readable.
    pub transcript_dir: Option<String>,
}

impl HookContext {
    /// Build from a transcript_path (as received in hook input).
    pub fn from_transcript_path(transcript_path: &str) -> Self {
        let transcript_dir = if transcript_path.is_empty() {
            None
        } else {
            std::path::Path::new(transcript_path)
                .parent()
                .map(|p| p.to_string_lossy().to_string())
                .filter(|s| !s.is_empty())
        };
        Self { transcript_dir }
    }
}

/// A policy source loaded from a specific level.
#[derive(Debug, Clone)]
pub struct LoadedPolicy {
    /// Which level this policy came from.
    pub level: PolicyLevel,
    /// The file path it was loaded from.
    pub path: PathBuf,
    /// The raw source text.
    pub source: String,
}

#[derive(Debug, Default)]
pub struct ClashSettings {
    /// Pre-compiled policy tree for fast evaluation.
    compiled: Option<CompiledPolicy>,

    /// Policy sources loaded from each level (ordered by precedence, highest first).
    loaded_policies: Vec<LoadedPolicy>,

    /// Notification and external service configuration, loaded from policy.yaml.
    pub notifications: NotificationConfig,

    /// Warning message if parsing the notifications config failed or was incomplete.
    pub notification_warning: Option<String>,

    /// Audit logging configuration, loaded from policy.yaml.
    pub audit: AuditConfig,

    /// Error message if policy failed to parse or compile.
    policy_error: Option<String>,
}

impl ClashSettings {
    /// Returns the clash settings directory (`~/.clash/`).
    ///
    /// Respects `CLASH_HOME` env var for override, otherwise defaults to `$HOME/.clash`.
    pub fn settings_dir() -> Result<PathBuf> {
        if let Ok(p) = std::env::var("CLASH_HOME") {
            return Ok(PathBuf::from(p));
        }
        home_dir()
            .map(|h| h.join(".clash"))
            .ok_or_else(|| anyhow::anyhow!("$HOME is not set; cannot determine settings directory"))
    }

    /// Returns the user-level policy file path.
    ///
    /// Respects `CLASH_POLICY_FILE` env var for override.
    /// Prefers `policy.json` over `policy.star` when both exist.
    pub fn policy_file() -> Result<PathBuf> {
        if let Ok(p) = std::env::var("CLASH_POLICY_FILE") {
            return Ok(PathBuf::from(p));
        }
        let dir = Self::settings_dir()?;
        Ok(prefer_json_over_star(&dir))
    }

    /// Returns the policy file path for a specific level.
    ///
    /// Prefers `policy.json` over `policy.star` when both exist.
    /// For `Session`, reads the active session ID from `~/.clash/active_session`.
    pub fn policy_file_for_level(level: PolicyLevel) -> Result<PathBuf> {
        match level {
            PolicyLevel::User => Self::policy_file(),
            PolicyLevel::Project => {
                let root = Self::project_root()?;
                let dir = root.join(".clash");
                Ok(prefer_json_over_star(&dir))
            }
            PolicyLevel::Session => {
                let session_id = Self::active_session_id()?;
                Ok(Self::session_policy_path(&session_id))
            }
        }
    }

    // Returns the policy file path for a session, given its ID.
    pub fn session_policy_path(session_id: &str) -> PathBuf {
        crate::audit::session_dir(session_id).join("policy.star")
    }

    /// Path to the active-session marker file.
    fn active_session_file() -> Result<PathBuf> {
        Self::settings_dir().map(|d| d.join("active_session"))
    }

    /// Read the active session ID from `~/.clash/active_session`.
    pub fn active_session_id() -> Result<String> {
        let path = Self::active_session_file()?;
        let id = std::fs::read_to_string(&path)
            .map_err(|e| {
                if e.kind() == std::io::ErrorKind::NotFound {
                    anyhow::anyhow!("no active session — start a session with `clash launch` first")
                } else {
                    anyhow::anyhow!("failed to read active session: {e}")
                }
            })?
            .trim()
            .to_string();
        if id.is_empty() {
            anyhow::bail!("active session file is empty");
        }
        Ok(id)
    }

    /// Write the active session ID to `~/.clash/active_session`.
    pub fn set_active_session(session_id: &str) -> Result<()> {
        let path = Self::active_session_file()?;
        std::fs::create_dir_all(path.parent().unwrap())?;
        std::fs::write(&path, session_id)?;
        Ok(())
    }

    /// Find the project root by walking up from cwd looking for `.clash/` or `.git/`.
    ///
    /// Stops searching at `$HOME` — `~/.clash/` is the user config dir, not a project.
    /// Returns an error if no project root is found (e.g. in a temp directory).
    pub fn project_root() -> Result<PathBuf> {
        let cwd = std::env::current_dir()
            .map_err(|e| anyhow::anyhow!("cannot determine current directory: {e}"))?;
        let stop_at = home_dir();

        // First, look for .clash directory
        if let Some(root) = find_ancestor_with(&cwd, ".clash", stop_at.as_deref()) {
            return Ok(root);
        }

        // Fallback to .git
        if let Some(root) = find_ancestor_with(&cwd, ".git", stop_at.as_deref()) {
            return Ok(root);
        }

        anyhow::bail!(
            "no project root found (looked for .clash/ or .git/ in ancestors of {})",
            cwd.display()
        )
    }

    /// Returns all policy levels that have an existing policy file.
    ///
    /// Levels are returned in precedence order (highest first: project, then user).
    pub fn available_policy_levels() -> Vec<(PolicyLevel, PathBuf)> {
        let mut levels = Vec::new();
        for &level in PolicyLevel::all_by_precedence() {
            if let Ok(path) = Self::policy_file_for_level(level)
                && path.exists()
                && path.is_file()
            {
                levels.push((level, path));
            }
        }
        levels
    }

    /// Diagnostic: reports what paths were checked for each policy level and why
    /// they were not found. Returns a list of `(level_name, path_or_error, reason)`.
    pub fn diagnose_missing_policies() -> Vec<(String, String, String)> {
        let mut results = Vec::new();
        for &level in PolicyLevel::all_by_precedence() {
            match Self::policy_file_for_level(level) {
                Ok(path) => {
                    let path_str = path.display().to_string();
                    match std::fs::metadata(&path) {
                        Ok(m) if m.is_file() => {
                            results.push((level.name().to_string(), path_str, "ok".to_string()));
                        }
                        Ok(_) => {
                            results.push((
                                level.name().to_string(),
                                path_str,
                                "path exists but is not a file".to_string(),
                            ));
                        }
                        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                            results.push((
                                level.name().to_string(),
                                path_str,
                                "file does not exist".to_string(),
                            ));
                        }
                        Err(e) => {
                            results.push((level.name().to_string(), path_str, format!("{e}")));
                        }
                    }
                }
                Err(e) => {
                    results.push((level.name().to_string(), "".to_string(), format!("{e}")));
                }
            }
        }
        results
    }

    /// Determine the default scope for modification commands.
    ///
    /// If a project-level policy exists, returns `Project`; else `User`.
    /// Session scope is never the default — it must be explicitly requested.
    pub fn default_scope() -> PolicyLevel {
        if let Ok(path) = Self::policy_file_for_level(PolicyLevel::Project)
            && path.exists()
            && path.is_file()
        {
            return PolicyLevel::Project;
        }
        PolicyLevel::User
    }

    /// Ensure a user-level policy file exists, creating one with safe defaults if not.
    ///
    /// Returns `Ok(Some(path))` if a new file was created, `Ok(None)` if one already existed.
    /// The created file uses the embedded `DEFAULT_POLICY` (deny-all with read access to CWD).
    pub fn ensure_user_policy_exists() -> Result<Option<PathBuf>> {
        let path = Self::policy_file().context("failed to determine user policy file path")?;
        Self::ensure_policy_at(path)
    }

    /// Write the compiled default policy JSON to `path` if no policy exists.
    ///
    /// The path passed in may point to `policy.star` (from `prefer_json_over_star`
    /// when no file exists yet). We always write `policy.json` instead, compiling
    /// the embedded Starlark source to JSON at runtime.
    fn ensure_policy_at(path: PathBuf) -> Result<Option<PathBuf>> {
        if path.exists() {
            return Ok(None);
        }

        // Always write the compiled JSON variant, even if `path` ends in `.star`.
        let json_path = path.with_extension("json");

        if let Some(parent) = json_path.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("failed to create directory {}", parent.display()))?;

            // Restrict directory permissions on unix (owner-only).
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let _ = std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o700));
            }
        }

        let json =
            compile_default_policy_to_json().context("failed to compile default policy to JSON")?;
        std::fs::write(&json_path, &json).with_context(|| {
            format!("failed to write default policy to {}", json_path.display())
        })?;

        // Restrict file permissions on unix (owner-only read/write).
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(&json_path, std::fs::Permissions::from_mode(0o600));
        }

        info!(path = %json_path.display(), "Created default user policy");
        Ok(Some(json_path))
    }

    /// Return the policy parse/compile error, if any.
    pub fn policy_error(&self) -> Option<&str> {
        self.policy_error.as_deref()
    }

    /// Set the policy source directly (compile from policy source text).
    pub fn set_policy_source(&mut self, source: &str) {
        match policy_loader::compile_source(source) {
            Ok(tree) => {
                self.compiled = Some(tree);
                self.policy_error = None;
            }
            Err(e) => {
                let msg = format!("Failed to compile policy: {}", e);
                warn!(error = %e, "Failed to compile policy");
                self.policy_error = Some(msg);
                self.compiled = None;
            }
        }
    }

    /// Maximum policy file size (1 MiB) — canonical value in [`policy_loader`].
    #[cfg(test)]
    const MAX_POLICY_SIZE: u64 = policy_loader::MAX_POLICY_SIZE;

    /// Return the pre-compiled policy tree, if one was successfully compiled.
    pub fn policy_tree(&self) -> Option<&CompiledPolicy> {
        self.compiled.as_ref()
    }

    /// Backward-compat alias for `policy_tree()`.
    #[doc(hidden)]
    pub fn decision_tree(&self) -> Option<&CompiledPolicy> {
        self.compiled.as_ref()
    }

    /// Load and validate a .star policy file from an explicit path, then compile it.
    ///
    /// Returns true if a policy was successfully loaded and compiled.
    #[cfg(test)]
    fn load_policy_from_path(&mut self, path: &std::path::Path) -> bool {
        match policy_loader::load_and_compile_single(path, &mut self.policy_error) {
            Some(tree) => {
                self.load_notification_audit_config();
                self.compiled = Some(tree);
                true
            }
            None => false,
        }
    }

    /// Load notification and audit config from a companion policy.yaml if it exists.
    fn load_notification_audit_config(&mut self) {
        let yaml_path = match Self::settings_dir() {
            Ok(d) => d.join("policy.yaml"),
            Err(_) => return,
        };
        if let Ok(contents) = std::fs::read_to_string(&yaml_path) {
            let (notif_config, notif_warning) = parse_notification_config(&contents);
            self.notifications = notif_config;
            self.notification_warning = notif_warning;
            self.audit = parse_audit_config(&contents);
        }
    }

    /// Load settings without session context (for CLI commands).
    ///
    /// Loads user and project policies only. Session-level policies are excluded
    /// because CLI commands run outside of an active Claude Code session — the
    /// `~/.clash/active_session` marker may be stale from a previous session.
    ///
    /// Use `load_or_create_with_session()` with an explicit session ID (from hook
    /// input) to include session-level policies.
    pub fn load_or_create() -> Result<Self> {
        Self::load_or_create_with_session(None, None)
    }

    /// Return the loaded policy sources (ordered by precedence, highest first).
    pub fn loaded_policies(&self) -> &[LoadedPolicy] {
        &self.loaded_policies
    }

    /// Load settings by resolving policies from disk and compiling them.
    ///
    /// Loads from all available levels (user, project, session) and merges them
    /// with session > project > user precedence.
    ///
    /// Pass `session_id` when processing a hook event (it's in the hook input JSON).
    /// For CLI commands, pass `None` — session policy won't be loaded.
    ///
    /// Pass `hook_ctx` to inject session-specific internal policies (e.g., the
    /// transcript directory). Pass `None` for CLI commands.
    #[instrument(level = Level::TRACE, skip(session_id, _hook_ctx))]
    pub fn load_or_create_with_session(
        session_id: Option<&str>,
        _hook_ctx: Option<&HookContext>,
    ) -> Result<Self> {
        let mut this = Self::default();

        // Collect policy sources from all available levels.
        // Each entry: (level, json_source, display_path).
        let mut level_sources: Vec<(PolicyLevel, String, String)> = Vec::new();

        // Load persistent levels (user, project) in reverse precedence order.
        for &level in PolicyLevel::all_by_precedence().iter().rev() {
            if let Ok(path) = Self::policy_file_for_level(level)
                && let Some(validated) =
                    policy_loader::try_load_policy(level, &path, &mut this.policy_error)
            {
                if level == PolicyLevel::User {
                    this.load_notification_audit_config();
                }
                let display_path = tilde_path(&path);
                level_sources.push((level, validated.json_source, display_path));
                this.loaded_policies.push(validated.loaded);
            }
        }

        // Load session-level policy if session_id is provided.
        if let Some(sid) = session_id {
            let session_path = Self::session_policy_path(sid);
            if let Some(validated) = policy_loader::try_load_policy(
                PolicyLevel::Session,
                &session_path,
                &mut this.policy_error,
            ) {
                let display_path = tilde_path(&session_path);
                level_sources.push((PolicyLevel::Session, validated.json_source, display_path));
                this.loaded_policies.push(validated.loaded);
            }
        }

        // Re-sort loaded_policies by precedence (highest first).
        this.loaded_policies.sort_by(|a, b| b.level.cmp(&a.level));

        if level_sources.is_empty() {
            // No policy files found — keep default (no compiled tree).
            return Ok(this);
        }

        // Compile all discovered policies into a single tree.
        match policy_loader::compile_policies(&level_sources) {
            Ok(tree) => {
                this.compiled = Some(tree);
                this.policy_error = None;
            }
            Err(e) => {
                let msg = format!("Failed to compile policy: {}", e);
                warn!(error = %e, "Failed to compile policy");
                this.policy_error = Some(msg);
            }
        }

        Ok(this)
    }
}

/// Return `policy.json` if it exists in `dir`, otherwise `policy.star`.
fn prefer_json_over_star(dir: &std::path::Path) -> PathBuf {
    let json_path = dir.join("policy.json");
    if json_path.exists() {
        json_path
    } else {
        dir.join("policy.star")
    }
}

/// Shorten a path by replacing the home directory prefix with `~`.
fn tilde_path(path: &std::path::Path) -> String {
    if let Some(home) = home_dir()
        && let Ok(rest) = path.strip_prefix(&home)
    {
        return format!("~/{}", rest.display());
    }
    path.display().to_string()
}

/// Extract the `notifications:` section from a YAML string.
///
/// Returns the parsed config (falling back to defaults on error) and an
/// optional warning message if parsing failed.
pub fn parse_notification_config(yaml_str: &str) -> (NotificationConfig, Option<String>) {
    #[derive(Deserialize)]
    struct RawYaml {
        #[serde(default)]
        notifications: Option<NotificationConfig>,
    }

    match serde_yaml::from_str::<RawYaml>(yaml_str) {
        Ok(raw) => (raw.notifications.unwrap_or_default(), None),
        Err(e) => {
            let warning = format!("notifications config parse error: {}", e);
            warn!(error = %e, "Failed to parse notifications config");
            (NotificationConfig::default(), Some(warning))
        }
    }
}

/// Extract the `audit:` section from a YAML string.
///
/// Returns the parsed config, falling back to defaults on error.
fn parse_audit_config(yaml_str: &str) -> AuditConfig {
    #[derive(Deserialize)]
    struct RawYaml {
        #[serde(default)]
        audit: Option<AuditConfig>,
    }

    match serde_yaml::from_str::<RawYaml>(yaml_str) {
        Ok(raw) => raw.audit.unwrap_or_default(),
        Err(_) => AuditConfig::default(),
    }
}

/// Evaluate a `.star` policy file and return the compiled JSON source.
///
/// Delegates to [`policy_loader::evaluate_star_policy`]. This wrapper is kept
/// for backward compatibility with callers that import from `settings`.
pub fn evaluate_star_policy(path: &std::path::Path) -> Result<String> {
    policy_loader::evaluate_star_policy(path)
}

/// Evaluate a policy file (`.json` or `.star`) and return the compiled JSON source.
///
/// Dispatches based on file extension: `.json` → [`policy_loader::load_json_policy`],
/// `.star` (or anything else) → [`policy_loader::evaluate_star_policy`].
pub fn evaluate_policy_file(path: &std::path::Path) -> Result<String> {
    if path.extension().is_some_and(|ext| ext == "json") {
        policy_loader::load_json_policy(path)
    } else {
        policy_loader::evaluate_star_policy(path)
    }
}

/// Find the nearest ancestor directory containing the given name.
///
/// If `stop_at` is provided, stops searching before checking that directory.
/// This prevents `~/.clash/` from being mistaken for a project root.
fn find_ancestor_with(
    start: &std::path::Path,
    name: &str,
    stop_at: Option<&std::path::Path>,
) -> Option<PathBuf> {
    let mut current = start.to_path_buf();
    loop {
        if let Some(boundary) = stop_at
            && current == boundary
        {
            return None;
        }
        if current.join(name).exists() {
            return Some(current);
        }
        if !current.pop() {
            return None;
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Write;

    #[allow(dead_code)]
    struct TestEnv;
    impl crate::policy::compile::EnvResolver for TestEnv {
        fn resolve(&self, name: &str) -> anyhow::Result<String> {
            match name {
                "PWD" => Ok("/tmp".into()),
                "HOME" => Ok("/tmp/home".into()),
                "TMPDIR" => Ok("/tmp".into()),
                other => anyhow::bail!("unknown env var in test: {other}"),
            }
        }
    }

    #[test]
    fn default_policy_compiles() -> anyhow::Result<()> {
        let source = DEFAULT_POLICY_TEMPLATE.replace("{preset}", "dev");
        let output =
            clash_starlark::evaluate(&source, "default_policy.star", std::path::Path::new("."))?;
        let tree = crate::policy::compile::compile_to_tree(&output.json)?;
        let _ = tree;
        Ok(())
    }

    #[test]
    fn default_policy_compiles_all_presets() -> anyhow::Result<()> {
        for preset in SANDBOX_PRESETS {
            compile_default_policy_to_json_with_preset(preset.name)?;
        }
        Ok(())
    }

    #[test]
    fn default_policy_cwd_sandbox_uses_subpath() -> anyhow::Result<()> {
        let json_str = compile_default_policy_to_json_with_preset("dev")?;
        let policy: serde_json::Value = serde_json::from_str(&json_str)?;
        let cwd_sandbox = &policy["sandboxes"]["cwd"];
        let rules = cwd_sandbox["rules"].as_array().unwrap();
        // The $PWD rule should be subpath (from .recurse()), not literal.
        let pwd_rule = rules
            .iter()
            .find(|r| r["path"].as_str() == Some("$PWD"))
            .expect("should have a $PWD rule");
        assert_eq!(
            pwd_rule["path_match"].as_str(),
            Some("subpath"),
            "cwd() with .recurse() should produce subpath match, got: {pwd_rule}"
        );
        Ok(())
    }

    #[test]
    fn load_missing_file_returns_false() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nonexistent-policy.star");
        let mut settings = ClashSettings::default();
        let result = settings.load_policy_from_path(&path);
        assert!(!result);
        assert!(
            settings.policy_error.is_none(),
            "missing file should not set error"
        );
    }

    #[test]
    fn load_directory_sets_error() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("policy.star");
        std::fs::create_dir(&policy_path).unwrap();

        let mut settings = ClashSettings::default();
        let result = settings.load_policy_from_path(&policy_path);
        assert!(!result);
        assert!(
            settings.policy_error().unwrap().contains("is a directory"),
            "expected directory error, got: {:?}",
            settings.policy_error()
        );
    }

    #[test]
    fn load_empty_file_sets_error() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("policy.star");
        std::fs::write(&policy_path, "").unwrap();

        let mut settings = ClashSettings::default();
        let result = settings.load_policy_from_path(&policy_path);
        assert!(!result);
        assert!(
            settings.policy_error().is_some(),
            "expected error for empty file, got: {:?}",
            settings.policy_error()
        );
    }

    #[test]
    fn load_oversized_file_sets_error() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("policy.star");
        let mut f = std::fs::File::create(&policy_path).unwrap();
        let chunk = vec![b'#'; 8192];
        for _ in 0..(ClashSettings::MAX_POLICY_SIZE / 8192 + 1) {
            f.write_all(&chunk).unwrap();
        }
        drop(f);

        let mut settings = ClashSettings::default();
        let result = settings.load_policy_from_path(&policy_path);
        assert!(!result);
        assert!(
            settings.policy_error().unwrap().contains("too large"),
            "expected size error, got: {:?}",
            settings.policy_error()
        );
    }

    #[test]
    fn load_valid_policy_succeeds() {
        let star_policy = "load(\"@clash//std.star\", \"policy\")\ndef main():\n    return policy(default = allow, rules = [])\n";
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("policy.star");
        std::fs::write(&policy_path, star_policy).unwrap();

        let mut settings = ClashSettings::default();
        let result = settings.load_policy_from_path(&policy_path);
        assert!(result, "valid policy should compile successfully");
        assert!(settings.policy_error.is_none());
        assert!(settings.decision_tree().is_some());
    }

    #[test]
    fn load_malformed_policy_sets_error() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("policy.star");
        std::fs::write(&policy_path, "this is not valid starlark {{{").unwrap();

        let mut settings = ClashSettings::default();
        let result = settings.load_policy_from_path(&policy_path);
        assert!(!result);
        assert!(
            settings.policy_error().is_some(),
            "expected error for malformed policy, got: {:?}",
            settings.policy_error()
        );
    }

    #[test]
    fn set_policy_source_works() {
        let simple_policy = r#"{"schema_version":5,"default_effect":"deny","sandboxes":{},"tree":[
            {"condition":{"observe":"fs_op","pattern":{"literal":{"literal":"read"}},"children":[
                {"condition":{"observe":"fs_path","pattern":{"prefix":{"literal":"/tmp"}},"children":[
                    {"decision":{"allow":null}}
                ]}}
            ]}}
        ]}"#;
        let mut settings = ClashSettings::default();
        settings.set_policy_source(simple_policy);
        assert!(settings.decision_tree().is_some());
        assert!(settings.policy_error.is_none());
    }

    #[test]
    fn ensure_policy_creates_json_file_when_missing() {
        let dir = tempfile::tempdir().unwrap();
        // Pass a .star path — ensure_policy_at should write .json instead.
        let star_path = dir.path().join(".clash").join("policy.star");
        let json_path = dir.path().join(".clash").join("policy.json");

        let result = ClashSettings::ensure_policy_at(star_path).unwrap();
        assert!(result.is_some(), "should have created the file");
        assert_eq!(result.unwrap(), json_path);
        assert!(json_path.exists(), "policy.json should exist on disk");

        let contents = std::fs::read_to_string(&json_path).unwrap();
        let parsed: serde_json::Value =
            serde_json::from_str(&contents).expect("written file should be valid JSON");
        assert!(
            parsed.get("tree").is_some(),
            "JSON should contain a tree field"
        );
    }

    #[test]
    fn ensure_policy_noop_when_exists() {
        let dir = tempfile::tempdir().unwrap();
        let policy_path = dir.path().join("policy.star");
        std::fs::write(
            &policy_path,
            "def main():\n    return policy(default = deny, rules = [])\n",
        )
        .unwrap();

        let result = ClashSettings::ensure_policy_at(policy_path.clone()).unwrap();
        assert!(result.is_none(), "should not recreate existing file");

        // Verify original content is preserved.
        let contents = std::fs::read_to_string(&policy_path).unwrap();
        assert!(contents.contains("def main"), "original content preserved");
    }

    #[test]
    #[cfg(unix)]
    fn ensure_policy_sets_permissions() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let star_path = dir.path().join(".clash").join("policy.star");
        let json_path = dir.path().join(".clash").join("policy.json");

        ClashSettings::ensure_policy_at(star_path).unwrap();
        let mode = std::fs::metadata(&json_path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "policy file should be owner-only read/write");
    }

    // --- HookContext / SessionEnvResolver tests ---

    /// Environment resolver that provides session-level variables from [`HookContext`]
    /// in addition to standard environment variables.
    struct SessionEnvResolver<'a> {
        hook_ctx: Option<&'a HookContext>,
    }

    impl crate::policy::compile::EnvResolver for SessionEnvResolver<'_> {
        fn resolve(&self, name: &str) -> anyhow::Result<String> {
            if name == "TRANSCRIPT_DIR"
                && let Some(dir) = self.hook_ctx.and_then(|ctx| ctx.transcript_dir.clone())
            {
                return Ok(dir);
            }
            crate::policy::compile::StdEnvResolver.resolve(name)
        }
    }

    #[test]
    fn hook_context_from_transcript_path() {
        let ctx = HookContext::from_transcript_path("/tmp/session-123/transcript.jsonl");
        assert_eq!(ctx.transcript_dir.as_deref(), Some("/tmp/session-123"));
    }

    #[test]
    fn hook_context_from_empty_path() {
        let ctx = HookContext::from_transcript_path("");
        assert!(ctx.transcript_dir.is_none());
    }

    #[test]
    fn hook_context_from_root_file() {
        let ctx = HookContext::from_transcript_path("/transcript.jsonl");
        assert_eq!(ctx.transcript_dir.as_deref(), Some("/"));
    }

    #[test]
    fn session_resolver_provides_transcript_dir() {
        use crate::policy::compile::EnvResolver;
        let ctx = HookContext::from_transcript_path("/tmp/session-123/transcript.jsonl");
        let resolver = SessionEnvResolver {
            hook_ctx: Some(&ctx),
        };
        assert_eq!(
            resolver.resolve("TRANSCRIPT_DIR").unwrap(),
            "/tmp/session-123"
        );
    }

    #[test]
    fn session_resolver_returns_sentinel_without_context() {
        use crate::policy::compile::{EnvResolver, UNAVAILABLE_SESSION_PATH};
        let resolver = SessionEnvResolver { hook_ctx: None };
        let result = resolver.resolve("TRANSCRIPT_DIR").unwrap();
        assert_eq!(result, UNAVAILABLE_SESSION_PATH);
    }

    #[test]
    fn session_resolver_falls_through_to_std_env() {
        use crate::policy::compile::EnvResolver;
        let resolver = SessionEnvResolver { hook_ctx: None };
        // HOME should always be set in test environments
        let result = resolver.resolve("HOME");
        assert!(result.is_ok(), "HOME should resolve via StdEnvResolver");
    }

    //
    // These test `is_truthy_disable_value` directly to avoid env var races.
    // `env::set_var` is process-wide and Rust runs tests on parallel threads,
    // so multiple tests mutating the same env var is inherently racy.

    #[test]
    fn is_truthy_disable_value_not_set() {
        // Empty string = not disabled (matches env var missing or empty).
        assert!(!is_truthy_disable_value(""));
    }

    #[test]
    fn is_truthy_disable_value_falsy() {
        assert!(!is_truthy_disable_value("0"));
        assert!(!is_truthy_disable_value("false"));
    }

    #[test]
    fn is_truthy_disable_value_truthy() {
        assert!(is_truthy_disable_value("1"));
        assert!(is_truthy_disable_value("true"));
        assert!(is_truthy_disable_value("yes"));
        assert!(is_truthy_disable_value("anything"));
    }
}