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
use anyhow::Result;
use tracing::{Level, instrument, warn};

use crate::sandbox;
use crate::settings::ClashSettings;
use crate::style;
use crate::ui;

/// Outcome of a single diagnostic check.
enum CheckResult {
    /// Check passed — everything looks good.
    Pass(String),
    /// Check passed with a caveat.
    Warn(String),
    /// Check failed — action required.
    Fail(String),
}

/// Identifies a fixable issue for the onboard flow.
enum OnboardFix {
    /// The clash plugin is not installed in Claude Code.
    InstallPlugin,
    /// No policy files exist.
    CreatePolicy,
    /// Status line is not installed (optional enhancement).
    InstallStatusLine,
}

impl CheckResult {
    fn print(&self, label: &str) {
        match self {
            CheckResult::Pass(msg) => {
                println!(
                    "  {} {}: {}",
                    style::green_bold("PASS"),
                    style::bold(label),
                    msg
                );
            }
            CheckResult::Warn(msg) => {
                println!(
                    "  {} {}: {}",
                    style::yellow_bold("WARN"),
                    style::bold(label),
                    msg
                );
            }
            CheckResult::Fail(msg) => {
                println!(
                    "  {} {}: {}",
                    style::red_bold("FAIL"),
                    style::bold(label),
                    msg
                );
            }
        }
    }

    fn is_fail(&self) -> bool {
        matches!(self, CheckResult::Fail(_))
    }

    fn is_warn(&self) -> bool {
        matches!(self, CheckResult::Warn(_))
    }
}

/// Run all diagnostic checks and report results.
///
/// When `onboard` is true, failing or warning checks prompt the user
/// to fix the issue interactively before moving on.
#[instrument(level = Level::TRACE, skip(onboard))]
pub fn run(onboard: bool) -> Result<()> {
    if onboard {
        run_onboard()
    } else {
        run_diagnose()
    }
}

/// Standard diagnostic mode — report all checks without offering fixes.
fn run_diagnose() -> Result<()> {
    ui::banner_section("Doctor");

    let checks = vec![
        ("Disabled", check_disabled()),
        ("Passthrough", check_passthrough()),
        ("Policy files", check_policy_files()),
        ("Policy parsing", check_policy_parsing()),
        ("Plugin installed", check_plugin_installed()),
        ("Binary on PATH", check_binary_on_path()),
        ("File permissions", check_file_permissions()),
        ("Sandbox support", check_sandbox_support()),
    ];

    let mut fail_count = 0;
    let mut warn_count = 0;

    for (label, result) in &checks {
        result.print(label);
        if result.is_fail() {
            fail_count += 1;
        }
        if result.is_warn() {
            warn_count += 1;
        }
    }

    println!();

    if fail_count == 0 && warn_count == 0 {
        println!(
            "  {} All checks passed. clash is ready to use.",
            style::green_bold("OK"),
        );
    } else if fail_count == 0 {
        println!(
            "  {} {} warning(s), but no failures.",
            style::yellow_bold("OK"),
            warn_count,
        );
    } else {
        println!(
            "  {} {} check(s) failed, {} warning(s). See above for fix instructions.",
            style::red_bold("!!"),
            fail_count,
            warn_count,
        );
    }

    Ok(())
}

/// Interactive onboarding mode — diagnose and offer to fix each issue.
fn run_onboard() -> Result<()> {
    ui::banner_section("Doctor (onboard)");
    println!("  Checking your setup...\n");

    let mut fixed = 0u32;
    let mut already_ok = 0u32;

    // --- Check 1: Binary on PATH ---
    let binary_check = check_binary_on_path();
    binary_check.print("Binary on PATH");
    match &binary_check {
        CheckResult::Pass(_) => already_ok += 1,
        _ => {
            // Nothing we can auto-fix for PATH issues; just inform.
            println!(
                "    {} This must be fixed manually — ensure clash is on your $PATH.",
                style::dim("->"),
            );
        }
    }

    // --- Check 2: Plugin installed ---
    let plugin_ok = check_plugin_status();

    if plugin_ok {
        println!(
            "  {} {}: installed",
            style::green_bold("PASS"),
            style::bold("Claude Code plugin"),
        );
        already_ok += 1;
    } else {
        println!(
            "  {} {}: not installed",
            style::red_bold("FAIL"),
            style::bold("Claude Code plugin"),
        );
        if offer_fix(OnboardFix::InstallPlugin)? {
            ui::progress("Installing plugin...");
            match super::init::install_plugin() {
                Ok(()) => fixed += 1,
                Err(e) => {
                    warn!(error = %e, "Plugin install failed during onboard");
                    ui::fail(&format!("Could not install plugin: {e}"));
                }
            }
        }
    }

    // --- Check 3: Policy files ---
    let policy_check = check_policy_files();
    policy_check.print("Policy files");
    match &policy_check {
        CheckResult::Fail(_) => {
            if offer_fix(OnboardFix::CreatePolicy)? {
                ui::progress("Launching policy editor...");
                match crate::cmd::init::write_starter_policy() {
                    Ok(path) => match crate::tui::run_with_options(&path, false, true) {
                        Ok(()) => fixed += 1,
                        Err(e) => {
                            warn!(error = %e, "Policy editor failed during onboard");
                            ui::fail(&format!("Policy creation failed: {e}"));
                        }
                    },
                    Err(e) => {
                        warn!(error = %e, "Could not write starter policy");
                        ui::fail(&format!("Policy creation failed: {e}"));
                    }
                }
            }
        }
        _ => already_ok += 1,
    }

    // --- Check 4: Status line (optional) ---
    let statusline_installed = check_statusline_installed();
    if statusline_installed {
        println!(
            "  {} {}: installed",
            style::green_bold("PASS"),
            style::bold("Status line"),
        );
        already_ok += 1;
    } else {
        println!(
            "  {} {}: not installed (optional)",
            style::green_bold("PASS"),
            style::bold("Status line"),
        );
        if offer_fix(OnboardFix::InstallStatusLine)? {
            ui::progress("Installing status line...");
            match super::statusline::install() {
                Ok(()) => fixed += 1,
                Err(e) => {
                    warn!(error = %e, "Status line install failed during onboard");
                    ui::fail(&format!("Could not install status line: {e}"));
                }
            }
        }
    }

    // --- Additional informational checks ---
    check_disabled().print("Disabled");
    check_passthrough().print("Passthrough");
    check_sandbox_support().print("Sandbox support");

    // --- Summary ---
    println!();
    if fixed > 0 {
        println!(
            "  {} Fixed {} issue(s). {} already OK.",
            style::green_bold("OK"),
            fixed,
            already_ok,
        );
    } else {
        println!("  {} All checks passed.", style::green_bold("OK"),);
    }

    println!(
        "\n  Run {} to see your active policy.",
        style::bold("`clash status`"),
    );

    // Enable the plugin marker in Claude Code settings (same as init).
    let claude = claude_settings::ClaudeSettings::new();
    if let Err(e) = claude.set_plugin_enabled(claude_settings::SettingsLevel::User, "clash", true) {
        warn!(error = %e, "Could not set enabledPlugins during onboard");
    }

    Ok(())
}

/// Prompt the user to fix an issue. The default answer varies by fix type:
/// optional enhancements default to No, required fixes default to Yes.
fn offer_fix(fix: OnboardFix) -> Result<bool> {
    let (prompt, default_yes) = match fix {
        OnboardFix::InstallPlugin => ("Install now?", true),
        OnboardFix::CreatePolicy => ("Create a starter policy?", true),
        OnboardFix::InstallStatusLine => ("Install status line?", false),
    };

    // dialoguer::Confirm with explicit default
    let result = dialoguer::Confirm::new()
        .with_prompt(format!("    {} {}", style::dim("->"), prompt))
        .default(default_yes)
        .interact();

    match result {
        Ok(answer) => Ok(answer),
        Err(_) => {
            // Non-interactive terminal — skip the fix silently
            ui::skip("Skipping (non-interactive)");
            Ok(false)
        }
    }
}

/// Check whether the clash plugin is installed in Claude Code settings.
fn check_plugin_status() -> bool {
    let claude = claude_settings::ClaudeSettings::new();
    let settings = match claude.read(claude_settings::SettingsLevel::User) {
        Ok(Some(s)) => s,
        _ => return false,
    };

    settings.hooks.as_ref().is_some_and(hooks_reference_clash)
        || settings
            .enabled_plugins
            .as_ref()
            .and_then(|p| p.get("clash").copied())
            == Some(true)
}

/// Check whether the clash status line is installed in Claude Code settings.
fn check_statusline_installed() -> bool {
    let cs = claude_settings::ClaudeSettings::new();
    let current = match cs.read_or_default(claude_settings::SettingsLevel::User) {
        Ok(s) => s,
        Err(_) => return false,
    };

    current
        .extra
        .get("statusLine")
        .and_then(|v| v.get("command"))
        .and_then(|v| v.as_str())
        .is_some_and(|c| c.contains("clash statusline"))
}

// -----------------------------------------------------------------------
// Individual diagnostic checks (unchanged from standard doctor mode)
// -----------------------------------------------------------------------

/// Check 0: Is clash disabled via environment variable?
fn check_disabled() -> CheckResult {
    if crate::settings::is_disabled() {
        CheckResult::Warn(format!(
            "{} is set — all hooks are pass-through. Unset to re-enable.",
            crate::settings::CLASH_DISABLE_ENV,
        ))
    } else {
        CheckResult::Pass("Clash is enabled.".into())
    }
}

/// Check: Is CLASH_PASSTHROUGH set?
fn check_passthrough() -> CheckResult {
    if crate::settings::is_passthrough() {
        CheckResult::Warn(format!(
            "{} is set — permission decisions are deferred to Claude Code's native system. \
             Unset to re-enable policy enforcement.",
            crate::settings::CLASH_PASSTHROUGH_ENV,
        ))
    } else {
        CheckResult::Pass("Policy enforcement is active.".into())
    }
}

/// Check 1: Do policy files exist?
fn check_policy_files() -> CheckResult {
    let levels = ClashSettings::available_policy_levels();

    if levels.is_empty() {
        return CheckResult::Fail("No policy files found. Run `clash init` to create one.".into());
    }

    let names: Vec<String> = levels
        .iter()
        .map(|(level, path)| format!("{} ({})", level, path.display()))
        .collect();

    CheckResult::Pass(format!("Found: {}", names.join(", ")))
}

/// Check 2: Do the policy files parse and compile successfully?
fn check_policy_parsing() -> CheckResult {
    let levels = ClashSettings::available_policy_levels();

    if levels.is_empty() {
        return CheckResult::Warn("No policy files to parse (none found).".into());
    }

    let mut errors = Vec::new();

    for (level, path) in &levels {
        match crate::settings::evaluate_policy_file(path) {
            Ok(json) => {
                if let Err(e) = crate::policy::compile::compile_to_tree(&json) {
                    errors.push(format!("{}: {}", level, e));
                }
            }
            Err(e) => {
                errors.push(format!("{}: {}", level, e));
            }
        }
    }

    if errors.is_empty() {
        CheckResult::Pass("All policy files parse and compile successfully.".into())
    } else {
        CheckResult::Fail(format!(
            "Policy errors:\n{}",
            errors
                .iter()
                .map(|e| format!("      {}", e))
                .collect::<Vec<_>>()
                .join("\n")
        ))
    }
}

/// Check 3: Is clash registered as a Claude Code plugin?
///
/// Looks for hook commands referencing "clash" in the Claude Code user settings
/// (specifically the hooks configuration).
fn check_plugin_installed() -> CheckResult {
    let claude = claude_settings::ClaudeSettings::new();

    // Check user-level settings for hooks referencing clash.
    let settings = match claude.read(claude_settings::SettingsLevel::User) {
        Ok(Some(s)) => s,
        Ok(None) => {
            return CheckResult::Warn(
                "No Claude Code user settings found. \
                 Run `clash init` to install the plugin."
                    .into(),
            );
        }
        Err(e) => {
            return CheckResult::Warn(format!(
                "Could not read Claude Code settings: {}. \
                 Run `clash init` to install the plugin.",
                e
            ));
        }
    };

    // Check if hooks reference clash commands
    if let Some(ref hooks) = settings.hooks
        && hooks_reference_clash(hooks)
    {
        return CheckResult::Pass("clash hooks are registered.".into());
    }

    // Hooks not found — check if maybe the plugin is installed via the
    // marketplace/plugin system (look for enabled_plugins).
    if let Some(ref plugins) = settings.enabled_plugins
        && plugins.get("clash").copied() == Some(true)
    {
        return CheckResult::Pass("clash plugin is enabled.".into());
    }

    CheckResult::Fail(
        "clash is not registered as a Claude Code plugin. \
         Fix: run `clash init` to install and configure."
            .into(),
    )
}

/// Returns true if any hook command in the Hooks config references "clash".
fn hooks_reference_clash(hooks: &claude_settings::Hooks) -> bool {
    let configs = [
        hooks.pre_tool_use.as_ref(),
        hooks.post_tool_use.as_ref(),
        hooks.notification.as_ref(),
    ];

    for config in configs.into_iter().flatten() {
        match config {
            claude_settings::HookConfig::Simple(map) => {
                for cmd in map.values() {
                    if cmd.contains("clash") {
                        return true;
                    }
                }
            }
            claude_settings::HookConfig::Matchers(matchers) => {
                for matcher in matchers {
                    for hook in &matcher.hooks {
                        if let Some(ref cmd) = hook.command
                            && cmd.contains("clash")
                        {
                            return true;
                        }
                    }
                }
            }
        }
    }

    false
}

/// Check 4: Is the `clash` binary findable on PATH?
fn check_binary_on_path() -> CheckResult {
    match which_clash() {
        Some(path) => CheckResult::Pass(format!("Found at {}", path)),
        None => CheckResult::Fail(
            "clash not found on PATH. \
             Ensure the clash binary is installed and in your $PATH."
                .into(),
        ),
    }
}

/// Locate the clash binary on PATH.
fn which_clash() -> Option<String> {
    std::process::Command::new("which")
        .arg("clash")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

/// Check 5: Are policy files readable with appropriate permissions?
fn check_file_permissions() -> CheckResult {
    let levels = ClashSettings::available_policy_levels();

    if levels.is_empty() {
        return CheckResult::Warn("No policy files to check permissions on.".into());
    }

    let mut issues = Vec::new();

    for (level, path) in &levels {
        match std::fs::metadata(path) {
            Ok(metadata) => {
                // Check readability (we already read it, so it's readable if we got metadata).
                if metadata.is_dir() {
                    issues.push(format!(
                        "{}: {} is a directory, not a file. \
                         Remove it and run `clash init`.",
                        level,
                        path.display()
                    ));
                    continue;
                }

                // Check for overly permissive permissions on Unix
                #[cfg(unix)]
                {
                    use std::os::unix::fs::PermissionsExt;
                    let mode = metadata.permissions().mode() & 0o777;
                    if mode & 0o077 != 0 {
                        issues.push(format!(
                            "{}: {} has mode {:o} (world/group accessible). \
                             Fix: chmod 600 {}",
                            level,
                            path.display(),
                            mode,
                            path.display()
                        ));
                    }
                }
            }
            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
                issues.push(format!(
                    "{}: {} is not readable. Fix: chmod 600 {}",
                    level,
                    path.display(),
                    path.display()
                ));
            }
            Err(e) => {
                issues.push(format!("{}: cannot stat {}{}", level, path.display(), e));
            }
        }
    }

    if issues.is_empty() {
        CheckResult::Pass("All policy files have appropriate permissions.".into())
    } else {
        // Permission issues are warnings since the files still work, just insecure
        CheckResult::Warn(format!(
            "Permission issues:\n{}",
            issues
                .iter()
                .map(|i| format!("      {}", i))
                .collect::<Vec<_>>()
                .join("\n")
        ))
    }
}

/// Check 6: Does the platform support sandboxing?
fn check_sandbox_support() -> CheckResult {
    match sandbox::check_support() {
        sandbox::SupportLevel::Full => {
            let backend = if cfg!(target_os = "macos") {
                "seatbelt"
            } else if cfg!(target_os = "linux") {
                "landlock"
            } else {
                "unknown"
            };
            CheckResult::Pass(format!("Fully supported ({backend})."))
        }
        sandbox::SupportLevel::Partial { missing } => CheckResult::Warn(format!(
            "Partially supported. Missing: {}",
            missing.join(", ")
        )),
        sandbox::SupportLevel::Unsupported { reason } => CheckResult::Warn(format!(
            "Not supported on this platform: {}. \
             Sandbox enforcement will be skipped.",
            reason
        )),
    }
}

/// Check that the user-level settings dir (~/.clash/) exists.
///
/// Not used as a top-level check but available as a helper.
#[allow(dead_code)]
fn check_settings_dir() -> CheckResult {
    match ClashSettings::settings_dir() {
        Ok(dir) if dir.exists() => CheckResult::Pass(format!("Found at {}", dir.display())),
        Ok(dir) => CheckResult::Fail(format!(
            "{} does not exist. Run `clash init` to create it.",
            dir.display()
        )),
        Err(e) => CheckResult::Fail(format!("Cannot determine settings directory: {}", e)),
    }
}

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

    #[test]
    fn check_result_pass_is_not_fail() {
        let r = CheckResult::Pass("ok".into());
        assert!(!r.is_fail());
        assert!(!r.is_warn());
    }

    #[test]
    fn check_result_warn_is_warn() {
        let r = CheckResult::Warn("warning".into());
        assert!(!r.is_fail());
        assert!(r.is_warn());
    }

    #[test]
    fn check_result_fail_is_fail() {
        let r = CheckResult::Fail("error".into());
        assert!(r.is_fail());
        assert!(!r.is_warn());
    }

    #[test]
    fn which_clash_returns_some_when_on_path() {
        // clash should be available in the dev environment
        // This test may not pass in CI if clash is not installed;
        // it's a sanity check for the logic.
        let result = which_clash();
        // We don't assert Some because the test may run in an env without clash
        // Just verify it doesn't panic
        let _ = result;
    }

    #[test]
    fn hooks_reference_clash_detects_matcher_hooks() {
        use claude_settings::{Hook, HookConfig, HookMatcher, Hooks};

        let hooks = Hooks {
            pre_tool_use: Some(HookConfig::Matchers(vec![HookMatcher {
                matcher: "*".into(),
                hooks: vec![Hook {
                    hook_type: "command".into(),
                    command: Some("clash hook pre-tool-use".into()),
                    timeout: None,
                }],
            }])),
            post_tool_use: None,
            stop: None,
            notification: None,
        };

        assert!(hooks_reference_clash(&hooks));
    }

    #[test]
    fn hooks_reference_clash_returns_false_for_unrelated_hooks() {
        use claude_settings::{Hook, HookConfig, HookMatcher, Hooks};

        let hooks = Hooks {
            pre_tool_use: Some(HookConfig::Matchers(vec![HookMatcher {
                matcher: "*".into(),
                hooks: vec![Hook {
                    hook_type: "command".into(),
                    command: Some("other-tool hook".into()),
                    timeout: None,
                }],
            }])),
            post_tool_use: None,
            stop: None,
            notification: None,
        };

        assert!(!hooks_reference_clash(&hooks));
    }

    #[test]
    fn hooks_reference_clash_handles_empty_hooks() {
        let hooks = claude_settings::Hooks {
            pre_tool_use: None,
            post_tool_use: None,
            stop: None,
            notification: None,
        };

        assert!(!hooks_reference_clash(&hooks));
    }

    #[test]
    fn check_sandbox_does_not_panic() {
        // Just verify the check runs without panicking
        let result = check_sandbox_support();
        // On macOS and Linux, should be Pass or Warn (not Fail)
        assert!(!result.is_fail());
    }

    #[test]
    fn check_binary_on_path_does_not_panic() {
        let _ = check_binary_on_path();
    }

    #[test]
    fn check_plugin_status_does_not_panic() {
        let plugin = check_plugin_status();
        // Just verify it returns without panicking; values depend on environment
        let _ = plugin;
    }

    #[test]
    fn check_statusline_installed_does_not_panic() {
        let _ = check_statusline_installed();
    }
}