clash 0.5.5

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
//! Detect filesystem errors in sandboxed Bash output and provide actionable hints.
//!
//! When a Bash command runs inside a clash sandbox, filesystem access outside
//! the sandbox's allowed paths is blocked at the OS level. The command sees
//! "operation not permitted" or "permission denied" errors. This module detects
//! those errors in PostToolUse responses, identifies which paths were blocked,
//! and returns advisory context explaining the cause and suggesting policy fixes.
//!
//! This is the filesystem counterpart to [`crate::network_hints`], which handles
//! network sandbox violations.
//!
//! # Submodules
//!
//! - [`audit_source`] — Reads sandbox violations from the session audit log.
//! - [`stderr_source`] — Parses stderr for filesystem error patterns.
//! - [`formatter`] — Builds the advisory hint message for Claude.

mod audit_source;
pub(crate) mod formatter;
mod stderr_source;

use std::collections::BTreeSet;
use std::path::Path;

use tracing::{Level, info, instrument};

use crate::hooks::ToolUseHookInput;
use crate::network_hints::extract_response_text;
use crate::policy::sandbox_types::{Cap, SandboxPolicy};
use crate::settings::ClashSettings;

use audit_source::{paths_from_audit, read_audit_violations};
use formatter::build_fs_hint;
use stderr_source::{contains_fs_error, extract_blocked_paths, extract_paths_from_errors};

/// Filesystem error patterns that indicate a process had access blocked.
///
/// These are substrings matched case-insensitively against the tool response text.
const FS_ERROR_PATTERNS: &[&str] = &[
    // macOS Seatbelt produces EPERM
    "operation not permitted",
    // Linux Landlock produces EACCES, also common for general fs errors
    "permission denied",
];

/// Maximum number of blocked paths to report in a single hint.
const MAX_REPORTED_PATHS: usize = 5;

/// Paths that are commonly denied by macOS Seatbelt but are not user-visible
/// errors. These are background denials from process startup (DTrace, etc.)
/// that should be filtered out to avoid confusing noise in hints.
const NOISE_PATH_PREFIXES: &[&str] = &["/dev/dtrace", "/dev/dtracehelper", "/dev/oslog"];

/// Check if a PostToolUse Bash response contains filesystem errors likely caused
/// by sandbox restrictions. Returns advisory context if so.
///
/// Uses two data sources:
/// 1. **Audit log** (primary): reads sandbox violations written by `clash sandbox
///    exec` after the sandboxed process exited. These are kernel-verified denials
///    captured from the macOS unified log.
/// 2. **Stderr heuristic** (fallback): parses error messages from the command
///    output to extract paths. Used when no audit entries are found (Linux, or
///    if `log show` didn't capture anything).
#[instrument(level = Level::TRACE, skip(input, settings))]
pub fn check_for_sandbox_fs_hint(
    input: &ToolUseHookInput,
    settings: &ClashSettings,
) -> Option<String> {
    // Only check Bash tool responses
    if input.tool_name != "Bash" {
        return None;
    }

    // Get the sandbox policy. Try re-evaluation first (works if tool_input
    // is the original command). Fall back to extracting the policy from the
    // rewritten command string (PostToolUse may receive the rewritten command
    // like "clash sandbox exec --sandbox '{...}' ...").
    let sandbox = match resolve_sandbox_policy(input, settings) {
        Some(s) => s,
        None => {
            info!("check_for_sandbox_fs_hint: no sandbox policy resolved, skipping");
            return None;
        }
    };

    // Source 1: Read violations from the audit log (written by clash sandbox exec).
    // This is the primary, high-confidence source — kernel-verified denials.
    let audit_violations = read_audit_violations(input);
    let has_audit = !audit_violations.is_empty();

    // Source 2: Parse stderr for filesystem error patterns (fallback).
    // Note: don't use `?` on tool_response — we still want to proceed if we
    // have audit violations even when the response is missing.
    let response_text = input.tool_response.as_ref().and_then(extract_response_text);
    let stderr_has_errors = response_text.as_ref().is_some_and(|t| contains_fs_error(t));

    info!(
        has_audit = has_audit,
        audit_count = audit_violations.len(),
        has_response = response_text.is_some(),
        stderr_has_errors = stderr_has_errors,
        "check_for_sandbox_fs_hint: source analysis"
    );

    // If neither source found anything, bail early.
    if !has_audit && !stderr_has_errors {
        return None;
    }

    // Merge paths from both sources.
    let mut blocked_paths = Vec::new();

    // Audit-derived paths are high-confidence (kernel-verified denials).
    if has_audit {
        blocked_paths.extend(paths_from_audit(&audit_violations, &sandbox, &input.cwd));
    }

    // Stderr heuristic paths fill in gaps (e.g., paths the audit missed,
    // or Linux where no audit entries exist).
    if let Some(ref text) = response_text {
        let extracted_paths = extract_paths_from_errors(text);
        info!(
            extracted_count = extracted_paths.len(),
            paths = ?extracted_paths,
            "check_for_sandbox_fs_hint: paths extracted from stderr"
        );
        let stderr_blocked = extract_blocked_paths(text, &sandbox, &input.cwd);
        info!(
            stderr_blocked_count = stderr_blocked.len(),
            "check_for_sandbox_fs_hint: stderr paths confirmed as sandbox violations"
        );
        // Deduplicate: only add stderr paths whose suggested_dir isn't already covered.
        let existing_dirs: BTreeSet<String> = blocked_paths
            .iter()
            .map(|bp| bp.suggested_dir.clone())
            .collect();
        for bp in stderr_blocked {
            if !existing_dirs.contains(&bp.suggested_dir) {
                blocked_paths.push(bp);
            }
        }
    }

    if blocked_paths.is_empty() {
        info!("check_for_sandbox_fs_hint: no blocked paths after filtering, returning None");
        return None;
    }

    info!(
        tool = "Bash",
        blocked_count = blocked_paths.len(),
        from_audit = has_audit,
        "Detected filesystem sandbox violations in command output"
    );

    Some(build_fs_hint(&blocked_paths))
}

// ── Shared helpers ───────────────────────────────────────────────────────

/// Try to recover the sandbox policy for this tool invocation.
///
/// 1. Re-evaluate the policy (works when PostToolUse gets the original command).
/// 2. Fall back to extracting the `--sandbox` JSON from the rewritten command
///    string (works when PostToolUse gets the `clash sandbox exec ...` wrapper).
fn resolve_sandbox_policy(
    input: &ToolUseHookInput,
    settings: &ClashSettings,
) -> Option<SandboxPolicy> {
    // Path 1: re-evaluate against the decision tree.
    if let Some(tree) = settings.policy_tree() {
        let decision = tree.evaluate(&input.tool_name, &input.tool_input);
        if let Some(sandbox) = decision.sandbox {
            info!("resolve_sandbox_policy: found sandbox via decision tree re-evaluation");
            return Some(sandbox);
        }
        info!("resolve_sandbox_policy: decision tree returned no sandbox");
    } else {
        info!("resolve_sandbox_policy: no decision tree available");
    }

    // Path 2: extract --sandbox JSON from the rewritten command string.
    let command = input.tool_input.get("command")?.as_str()?;
    if !command.contains("sandbox exec") || !command.contains("--sandbox") {
        info!(
            command_prefix = &command[..command.len().min(80)],
            "resolve_sandbox_policy: command does not contain sandbox exec + --sandbox"
        );
        return None;
    }

    let result = extract_policy_json(command);
    info!(
        found = result.is_some(),
        "resolve_sandbox_policy: extracted policy JSON from rewritten command"
    );
    result
}

/// Extract the sandbox policy JSON from a rewritten `clash sandbox exec` command.
fn extract_policy_json(command: &str) -> Option<SandboxPolicy> {
    let policy_idx = command.find("--sandbox ")?;
    let after_flag = &command[policy_idx + "--sandbox ".len()..];

    // The policy JSON is shell-escaped in single quotes: '--sandbox '{...}''
    // We need to find the JSON object boundaries.
    let json_start = after_flag.find('{')?;
    let json_str = &after_flag[json_start..];

    // Find the matching closing brace (handling nesting).
    let mut depth = 0;
    let mut end = 0;
    for (i, ch) in json_str.char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    end = i + 1;
                    break;
                }
            }
            _ => {}
        }
    }

    if end == 0 {
        return None;
    }

    serde_json::from_str(&json_str[..end]).ok()
}

/// Filter out sandbox noise paths that aren't user-visible errors.
fn is_noise_path(path: &str) -> bool {
    NOISE_PATH_PREFIXES
        .iter()
        .any(|prefix| path.starts_with(prefix))
}

/// Map a Seatbelt operation to the sandbox `Cap` flags it requires.
///
/// If the sandbox policy already grants these caps for a path, then a deny
/// event for that operation can't be from *our* sandbox — it's noise from
/// another sandboxed process on the system. Returns `None` for unknown
/// operations so they are kept conservatively.
fn operation_to_required_caps(operation: &str) -> Option<Cap> {
    match operation {
        op if op.starts_with("file-read-") => Some(Cap::READ),
        "file-write-create" => Some(Cap::WRITE | Cap::CREATE),
        "file-write-unlink" => Some(Cap::WRITE | Cap::DELETE),
        op if op.starts_with("file-write-") => Some(Cap::WRITE),
        _ => None,
    }
}

/// Find a useful parent directory to suggest for a blocked path.
///
/// For paths under `$HOME`, suggests the top-level dot-directory (e.g., `~/.fly`).
/// For other paths, suggests the immediate parent directory.
fn suggest_parent_directory(path: &str) -> String {
    let p = Path::new(path);

    if let Some(home) = dirs::home_dir()
        && let Ok(rel) = p.strip_prefix(&home)
    {
        // Look for the first component — if it starts with "." it's a config dir
        if let Some(first) = rel.components().next() {
            let first_str = first.as_os_str().to_string_lossy();
            if first_str.starts_with('.') {
                return home.join(first_str.as_ref()).to_string_lossy().into_owned();
            }
        }
    }

    // Fallback: immediate parent directory
    p.parent()
        .map(|parent| parent.to_string_lossy().into_owned())
        .unwrap_or_else(|| path.to_string())
}

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

    use crate::policy::sandbox_types::{NetworkPolicy, PathMatch, RuleEffect, SandboxRule};

    use formatter::BlockedPath;
    use stderr_source::{
        contains_fs_error, extract_paths_from_errors, is_likely_sandbox_violation,
    };

    // --- contains_fs_error ---

    #[test]
    fn test_contains_fs_error_operation_not_permitted() {
        assert!(contains_fs_error(
            "open /Users/user/.fly/perms.123: operation not permitted"
        ));
    }

    #[test]
    fn test_contains_fs_error_permission_denied() {
        assert!(contains_fs_error("Permission denied: '/tmp/secret'"));
    }

    #[test]
    fn test_contains_fs_error_case_insensitive() {
        assert!(contains_fs_error("OPERATION NOT PERMITTED"));
    }

    #[test]
    fn test_contains_fs_error_no_match() {
        assert!(!contains_fs_error("file not found: /tmp/test.txt"));
    }

    // --- extract_paths_from_errors ---

    #[test]
    fn test_extract_path_go_style() {
        let text = "open /Users/user/.fly/perms.123: operation not permitted";
        let paths = extract_paths_from_errors(text);
        assert_eq!(paths, vec!["/Users/user/.fly/perms.123"]);
    }

    #[test]
    fn test_extract_path_python_style() {
        let text = "PermissionError: [Errno 1] Operation not permitted: '/home/user/.cache/thing'";
        let paths = extract_paths_from_errors(text);
        assert!(paths.contains(&"/home/user/.cache/thing".to_string()));
    }

    #[test]
    fn test_extract_path_node_style() {
        let text = "Error: EACCES: permission denied, open '/tmp/app/config.json'";
        let paths = extract_paths_from_errors(text);
        assert!(paths.contains(&"/tmp/app/config.json".to_string()));
    }

    #[test]
    fn test_extract_path_shell_style() {
        let text = "/etc/shadow: Permission denied";
        let paths = extract_paths_from_errors(text);
        assert!(paths.contains(&"/etc/shadow".to_string()));
    }

    #[test]
    fn test_extract_path_issue_example() {
        // The exact error from GitHub issue #101
        let text = "Error: failed ensuring config directory perms: open /Users/emschwartz/.fly/perms.3199984107: operation not permitted";
        let paths = extract_paths_from_errors(text);
        assert!(paths.contains(&"/Users/emschwartz/.fly/perms.3199984107".to_string()));
    }

    #[test]
    fn test_extract_path_multiple_errors() {
        let text = "open /Users/user/.fly/config: operation not permitted\nstat /Users/user/.cache/sccache/db: operation not permitted";
        let paths = extract_paths_from_errors(text);
        assert!(paths.len() >= 2);
        assert!(paths.contains(&"/Users/user/.fly/config".to_string()));
        assert!(paths.contains(&"/Users/user/.cache/sccache/db".to_string()));
    }

    #[test]
    fn test_extract_path_no_match() {
        let text = "curl: (6) Could not resolve host: example.com";
        let paths = extract_paths_from_errors(text);
        assert!(paths.is_empty());
    }

    #[test]
    fn test_extract_path_deduplicates() {
        let text = "open /tmp/foo: operation not permitted\nopen /tmp/foo: operation not permitted";
        let paths = extract_paths_from_errors(text);
        assert_eq!(paths.len(), 1);
    }

    // --- suggest_parent_directory ---

    #[test]
    fn test_suggest_parent_home_dotdir() {
        let home = dirs::home_dir().unwrap();
        let path = format!("{}/.fly/perms.123", home.display());
        let suggested = suggest_parent_directory(&path);
        assert_eq!(suggested, format!("{}/.fly", home.display()));
    }

    #[test]
    fn test_suggest_parent_home_deep_dotdir() {
        let home = dirs::home_dir().unwrap();
        let path = format!("{}/.cache/sccache/some/deep/file.db", home.display());
        let suggested = suggest_parent_directory(&path);
        assert_eq!(suggested, format!("{}/.cache", home.display()));
    }

    #[test]
    fn test_suggest_parent_non_home_path() {
        let suggested = suggest_parent_directory("/opt/homebrew/lib/libfoo.so");
        assert_eq!(suggested, "/opt/homebrew/lib");
    }

    // --- is_likely_sandbox_violation ---

    #[test]
    fn test_violation_outside_allowed_paths() {
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![SandboxRule {
                effect: RuleEffect::Allow,
                caps: Cap::all(),
                path: "/project".into(),
                path_match: PathMatch::Subpath,
                follow_worktrees: false,
                doc: None,
            }],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        // Path outside /project -> likely violation
        assert!(is_likely_sandbox_violation(
            "/Users/user/.fly/config",
            &sandbox,
            "/project"
        ));
    }

    #[test]
    fn test_no_violation_inside_allowed_paths() {
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![SandboxRule {
                effect: RuleEffect::Allow,
                caps: Cap::all(),
                path: "/project".into(),
                path_match: PathMatch::Subpath,
                follow_worktrees: false,
                doc: None,
            }],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        // Path inside /project with full caps -> not a violation
        assert!(!is_likely_sandbox_violation(
            "/project/src/main.rs",
            &sandbox,
            "/project"
        ));
    }

    #[test]
    fn test_no_violation_when_write_granted() {
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::WRITE | Cap::CREATE | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        // Default grants write+create -> not a violation even for foreign paths
        assert!(!is_likely_sandbox_violation(
            "/Users/user/.fly/config",
            &sandbox,
            "/project"
        ));
    }

    // --- build_fs_hint ---

    #[test]
    fn test_build_hint_contains_key_info() {
        let blocked = vec![BlockedPath {
            path: "/Users/user/.fly/perms.123".into(),
            suggested_dir: "/Users/user/.fly".into(),
            current_caps: Cap::READ | Cap::EXECUTE,
        }];
        let hint = build_fs_hint(&blocked);
        assert!(hint.contains("SANDBOX_FS_HINT"));
        assert!(hint.contains("/Users/user/.fly"));
        assert!(hint.contains("clash sandbox add-rule"));
        assert!(hint.contains("Do NOT retry"));
    }

    #[test]
    fn test_build_hint_empty_caps() {
        let blocked = vec![BlockedPath {
            path: "/secret/file".into(),
            suggested_dir: "/secret".into(),
            current_caps: Cap::empty(),
        }];
        let hint = build_fs_hint(&blocked);
        assert!(hint.contains("SANDBOX_FS_HINT"));
        assert!(hint.contains("/secret"));
        assert!(hint.contains("clash sandbox add-rule"));
    }

    // --- paths_from_audit ---

    #[test]
    fn test_is_noise_path() {
        assert!(is_noise_path("/dev/dtracehelper"));
        assert!(is_noise_path("/dev/dtrace"));
        assert!(is_noise_path("/dev/oslog/foo"));
        assert!(!is_noise_path("/Users/user/.fly/config"));
        assert!(!is_noise_path("/var/tmp/test"));
        assert!(!is_noise_path("/dev/null")); // not in the noise list
    }

    #[test]
    fn test_paths_from_audit_filters_noise() {
        use audit_source::paths_from_audit;
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        let violations = vec![
            crate::audit::SandboxViolation {
                operation: "file-read-data".into(),
                path: "/dev/dtracehelper".into(),
            },
            crate::audit::SandboxViolation {
                operation: "file-write-create".into(),
                path: "/Users/user/.fly/config".into(),
            },
        ];
        let blocked = paths_from_audit(&violations, &sandbox, "/project");
        assert_eq!(blocked.len(), 1);
        assert!(blocked[0].path.contains(".fly"));
    }

    #[test]
    fn test_paths_from_audit_deduplicates_by_dir() {
        use audit_source::paths_from_audit;
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        let violations = vec![
            crate::audit::SandboxViolation {
                operation: "file-write-create".into(),
                path: "/Users/user/.fly/perms.123".into(),
            },
            crate::audit::SandboxViolation {
                operation: "file-write-data".into(),
                path: "/Users/user/.fly/config.json".into(),
            },
        ];
        let blocked = paths_from_audit(&violations, &sandbox, "/project");
        // Both paths are under ~/.fly — should be deduplicated to one entry
        assert_eq!(blocked.len(), 1);
        assert!(blocked[0].suggested_dir.ends_with(".fly"));
    }

    // --- operation_to_required_caps ---

    #[test]
    fn test_operation_to_required_caps() {
        // file-read-* -> READ
        assert_eq!(
            operation_to_required_caps("file-read-data"),
            Some(Cap::READ)
        );
        assert_eq!(
            operation_to_required_caps("file-read-metadata"),
            Some(Cap::READ)
        );

        // file-write-create -> WRITE | CREATE
        assert_eq!(
            operation_to_required_caps("file-write-create"),
            Some(Cap::WRITE | Cap::CREATE)
        );

        // file-write-unlink -> WRITE | DELETE
        assert_eq!(
            operation_to_required_caps("file-write-unlink"),
            Some(Cap::WRITE | Cap::DELETE)
        );

        // file-write-* (other) -> WRITE
        assert_eq!(
            operation_to_required_caps("file-write-data"),
            Some(Cap::WRITE)
        );
        assert_eq!(
            operation_to_required_caps("file-write-flags"),
            Some(Cap::WRITE)
        );

        // Unknown -> None (keep conservatively)
        assert_eq!(operation_to_required_caps("network-outbound"), None);
        assert_eq!(operation_to_required_caps("process-exec"), None);
    }

    // --- paths_from_audit policy-aware filtering ---

    #[test]
    fn test_paths_from_audit_filters_granted_read() {
        use audit_source::paths_from_audit;
        // Sandbox grants READ (via default caps) — a file-read-data violation
        // on that path must be from another process, so it should be filtered.
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        let violations = vec![crate::audit::SandboxViolation {
            operation: "file-read-data".into(),
            path: "/Applications/LM Studio.app/Contents/Info.plist".into(),
        }];
        let blocked = paths_from_audit(&violations, &sandbox, "/project");
        assert!(
            blocked.is_empty(),
            "read violation on path where sandbox grants READ should be filtered"
        );
    }

    #[test]
    fn test_paths_from_audit_keeps_denied_write() {
        use audit_source::paths_from_audit;
        // Sandbox only grants READ+EXECUTE by default — a file-write-create
        // violation is a real sandbox denial and should be kept.
        let sandbox = SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Deny,
            doc: None,
        };
        let violations = vec![crate::audit::SandboxViolation {
            operation: "file-write-create".into(),
            path: "/Users/user/Desktop/testfile".into(),
        }];
        let blocked = paths_from_audit(&violations, &sandbox, "/project");
        assert_eq!(
            blocked.len(),
            1,
            "write violation where sandbox denies WRITE should be kept"
        );
        assert!(blocked[0].path.contains("Desktop"));
    }

    // --- check_for_sandbox_fs_hint (integration) ---

    #[test]
    fn test_check_returns_none_for_non_bash() {
        let input = ToolUseHookInput {
            tool_name: "Read".into(),
            tool_response: Some(json!("operation not permitted")),
            ..Default::default()
        };
        let settings = ClashSettings::default();
        assert!(check_for_sandbox_fs_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_none_without_response() {
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_response: None,
            ..Default::default()
        };
        let settings = ClashSettings::default();
        assert!(check_for_sandbox_fs_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_none_for_non_fs_error() {
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_response: Some(json!("file not found")),
            ..Default::default()
        };
        let settings = ClashSettings::default();
        assert!(check_for_sandbox_fs_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_none_without_policy() {
        let settings = ClashSettings::default();
        assert!(settings.decision_tree().is_none());
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "fly logs"}),
            tool_response: Some(json!(
                "open /Users/user/.fly/perms.123: operation not permitted"
            )),
            ..Default::default()
        };
        assert!(check_for_sandbox_fs_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_hint_with_sandbox() {
        // V5: allow Bash with a sandbox that denies network and has limited fs
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"restricted":{"default":["read","execute"],"rules":[{"effect":"allow","caps":["read"],"path":"/tmp"}],"network":"deny"}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"decision":{"allow":"restricted"}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "fly logs --app scour-rs"}),
            tool_response: Some(json!(
                "Error: failed ensuring config directory perms: open /Users/emschwartz/.fly/perms.3199984107: operation not permitted"
            )),
            cwd: "/tmp".into(),
            ..Default::default()
        };
        let result = check_for_sandbox_fs_hint(&input, &settings);
        assert!(
            result.is_some(),
            "should return hint for sandboxed filesystem error"
        );
        let hint = result.unwrap();
        assert!(hint.contains("SANDBOX_FS_HINT"));
        assert!(hint.contains(".fly"));
    }

    #[test]
    fn test_check_returns_none_when_path_is_allowed() {
        // Sandbox allows read+write+create under the .fly path -> not a sandbox violation
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"permissive":{"default":["read","execute"],"rules":[{"effect":"allow","caps":["read","write","create"],"path":"/Users/emschwartz/.fly"}],"network":"deny"}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"decision":{"allow":"permissive"}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "fly logs"}),
            tool_response: Some(json!(
                "open /Users/emschwartz/.fly/perms.123: operation not permitted"
            )),
            cwd: "/tmp".into(),
            ..Default::default()
        };
        let result = check_for_sandbox_fs_hint(&input, &settings);
        assert!(
            result.is_none(),
            "should not hint when the path is explicitly allowed"
        );
    }

    #[test]
    fn test_check_returns_hint_with_explicit_sandbox() {
        // Explicit sandbox only allows read under /project -> .fly access denied
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"restricted":{"default":["read","execute"],"rules":[{"effect":"allow","caps":["read"],"path":"/project"}],"network":"deny"}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"condition":{"observe":{"positional_arg":0},"pattern":{"literal":{"literal":"fly"}},"children":[
        {"decision":{"allow":"restricted"}}
      ]}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "fly logs --app scour-rs"}),
            tool_response: Some(json!(
                "open /Users/user/.fly/perms.123: operation not permitted"
            )),
            cwd: "/project".into(),
            ..Default::default()
        };
        let result = check_for_sandbox_fs_hint(&input, &settings);
        assert!(
            result.is_some(),
            "should return hint for explicit sandbox violation"
        );
    }
}