clash 0.6.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
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use tracing::{Level, info, instrument};

use crate::cli::PolicyCmd;
use crate::policy::manifest_edit;
use crate::policy::match_tree::{Decision, PolicyManifest};
use crate::settings::{ClashSettings, PolicyLevel};
use crate::style;

/// Handle `clash policy` subcommands.
#[instrument(level = Level::TRACE)]
pub fn run(cmd: PolicyCmd) -> Result<()> {
    match cmd {
        PolicyCmd::Schema { json } => super::schema::run(json),
        PolicyCmd::Explain {
            json,
            trace,
            tool,
            args,
        } => super::explain::run(json, trace, tool.unwrap_or_default(), args.join(" ")),
        PolicyCmd::Check { json } => handle_check_portable(json),
        PolicyCmd::List { json } => handle_list(json),
        PolicyCmd::Validate { file, json } => handle_validate(file, json),
        PolicyCmd::Show { json } => handle_show(json),
        PolicyCmd::Edit { scope, raw, test } => handle_edit(scope, raw, test),
        PolicyCmd::Allow {
            command,
            tool,
            bin,
            sandbox,
            scope,
        } => handle_allow(command, tool, bin, sandbox, scope),
        PolicyCmd::Deny {
            command,
            tool,
            bin,
            scope,
        } => handle_deny(command, tool, bin, scope),
        PolicyCmd::Remove {
            command,
            tool,
            bin,
            scope,
        } => handle_remove(command, tool, bin, scope),
    }
}

// ---------------------------------------------------------------------------
// Subcommand handlers
// ---------------------------------------------------------------------------

/// Handle `clash policy check` — scan for portability issues.
fn handle_check_portable(json: bool) -> Result<()> {
    use crate::policy::match_tree::{Node, Observable, Pattern, Value};
    use crate::style;
    use crate::ui;

    let settings = ClashSettings::load_or_create()?;
    let policy = match settings.policy_tree() {
        Some(t) => t,
        None => {
            if let Some(err) = settings.policy_error() {
                anyhow::bail!("{}", err);
            }
            anyhow::bail!("no policy configured — run `clash init`");
        }
    };

    /// Collect portability warnings by walking the tree.
    struct Warning {
        tool_name: String,
        canonical: Option<&'static str>,
        source: Option<String>,
    }

    fn walk_tree(nodes: &[Node], warnings: &mut Vec<Warning>) {
        for node in nodes {
            match node {
                Node::Condition {
                    observe: Observable::ToolName,
                    pattern,
                    children,
                    source,
                    ..
                } => {
                    check_pattern(pattern, source, warnings);
                    walk_tree(children, warnings);
                }
                Node::Condition { children, .. } => walk_tree(children, warnings),
                Node::Decision(_) => {}
            }
        }
    }

    fn check_pattern(pattern: &Pattern, source: &Option<String>, warnings: &mut Vec<Warning>) {
        match pattern {
            Pattern::Literal(Value::Literal(name)) => {
                // Check if this is an internal (Claude-specific) name that has a canonical alias
                if let Some(canonical) = crate::agents::internal_to_canonical(name) {
                    warnings.push(Warning {
                        tool_name: name.clone(),
                        canonical: Some(canonical),
                        source: source.clone(),
                    });
                }
                // Check if this is an agent-native name that's not canonical
                else if crate::agents::resolve_any_to_internal(name).is_some()
                    && crate::agents::canonical_to_internal(name).is_none()
                    && crate::agents::internal_to_canonical(name).is_none()
                {
                    // It's an agent-native name like "run_shell_command"
                    let internal = crate::agents::resolve_any_to_internal(name).unwrap();
                    let canonical = crate::agents::internal_to_canonical(internal);
                    warnings.push(Warning {
                        tool_name: name.clone(),
                        canonical,
                        source: source.clone(),
                    });
                }
            }
            Pattern::AnyOf(pats) => {
                for p in pats {
                    check_pattern(p, source, warnings);
                }
            }
            _ => {}
        }
    }

    let mut warnings = Vec::new();
    walk_tree(&policy.tree, &mut warnings);

    if json {
        let entries: Vec<serde_json::Value> = warnings
            .iter()
            .map(|w| {
                serde_json::json!({
                    "tool_name": w.tool_name,
                    "suggestion": w.canonical,
                    "source": w.source,
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&entries)?);
        return Ok(());
    }

    if warnings.is_empty() {
        ui::success("Policy is portable — no agent-specific tool names found.");
        println!(
            "  All tool name rules use canonical names or capabilities that work across agents."
        );
    } else {
        println!(
            "  {} portability warning(s) found:\n",
            style::yellow_bold(&warnings.len().to_string())
        );
        for w in &warnings {
            let location = w.source.as_deref().unwrap_or("unknown");
            print!(
                "  {} tool(\"{}\") is agent-specific",
                style::yellow_bold("!"),
                w.tool_name
            );
            if let Some(canonical) = w.canonical {
                print!(
                    " — use tool(\"{}\") for portability",
                    style::green_bold(canonical)
                );
            }
            println!();
            println!("    {}", style::dim(location));
        }
        println!();
        println!(
            "  {} Canonical names (shell, read, write, edit, glob, grep, web_fetch, web_search)",
            style::dim("Tip:")
        );
        println!(
            "  {} match across all supported agents automatically.",
            style::dim("    ")
        );
    }

    Ok(())
}

/// Handle `clash policy list`.
fn handle_list(json: bool) -> Result<()> {
    let settings = ClashSettings::load_or_create()?;
    let policy = match settings.policy_tree() {
        Some(t) => t,
        None => {
            if let Some(err) = settings.policy_error() {
                anyhow::bail!("{}", err);
            }
            anyhow::bail!("no policy configured — run `clash init`");
        }
    };

    if json {
        let rules = policy.format_rules();
        let entries: Vec<serde_json::Value> = rules
            .iter()
            .enumerate()
            .map(|(i, r)| {
                serde_json::json!({
                    "index": i,
                    "rule": r,
                })
            })
            .collect();
        println!("{}", serde_json::to_string_pretty(&entries)?);
    } else {
        let lines = policy.format_tree();
        if lines.is_empty() {
            println!(
                "No rules in policy. {}",
                style::dim(&format!("(default: {})", policy.default_effect))
            );
            return Ok(());
        }
        println!(
            "Policy {}\n",
            style::dim(&format!(
                "(default: {})",
                style::effect(&policy.default_effect.to_string()),
            ))
        );
        for line in &lines {
            println!("  {}", line);
        }
    }
    Ok(())
}

/// Handle `clash policy show`.
fn handle_show(json: bool) -> Result<()> {
    let settings = ClashSettings::load_or_create()?;
    let policy = match settings.policy_tree() {
        Some(t) => t,
        None => {
            if let Some(err) = settings.policy_error() {
                anyhow::bail!("{}", err);
            }
            anyhow::bail!("no policy configured — run `clash init`");
        }
    };

    let loaded = settings.loaded_policies();

    if json {
        let output = serde_json::json!({
            "default": format!("{}", policy.default_effect),
            "rule_count": policy.rule_count(),
            "levels": loaded
                .iter()
                .map(|lp| {
                    serde_json::json!({
                        "level": lp.level.to_string(),
                        "path": lp.path.display().to_string(),
                        "source": &lp.source,
                    })
                })
                .collect::<Vec<serde_json::Value>>(),
        });
        println!("{}", serde_json::to_string_pretty(&output)?);
    } else {
        for lp in loaded {
            println!(
                "{} {}",
                style::cyan(&format!("[{}]", lp.level)),
                lp.path.display()
            );
            println!("{}", style::dim(&"".repeat(40)));
            print!("{}", lp.source);
            if !lp.source.ends_with('\n') {
                println!();
            }
            println!();
        }
        if loaded.is_empty() {
            for rule in policy.format_rules() {
                println!("  {}", rule);
            }
        }
    }
    Ok(())
}

/// Handle `clash policy validate`.
fn handle_validate(file: Option<std::path::PathBuf>, json: bool) -> Result<()> {
    if let Some(path) = file {
        return validate_single_file(&path, json);
    }

    let levels = ClashSettings::available_policy_levels();
    if levels.is_empty() {
        let diag = ClashSettings::diagnose_missing_policies();
        if json {
            let details: Vec<serde_json::Value> = diag
                .iter()
                .map(|(level, path, reason)| {
                    serde_json::json!({"level": level, "path": path, "reason": reason})
                })
                .collect();
            println!(
                "{}",
                serde_json::json!({"valid": false, "error": "no policy files found", "hint": "run `clash init` to create a policy", "checked": details})
            );
        } else {
            eprintln!("{}: no policy files found", style::err_red_bold("error"));
            eprintln!();
            eprintln!("  Checked the following locations:");
            for (level, path, reason) in &diag {
                eprintln!(
                    "    {} ({}): {}{}",
                    level,
                    path,
                    style::err_red_bold(""),
                    reason
                );
            }
            eprintln!();
            eprintln!(
                "  {}: run {} to create a policy",
                style::err_cyan_bold("hint"),
                style::bold("clash init")
            );
        }
        std::process::exit(1);
    }

    let mut all_valid = true;
    let mut results: Vec<serde_json::Value> = Vec::new();

    for (level, path) in &levels {
        let source = match crate::settings::evaluate_policy_file(path) {
            Ok(s) => s,
            Err(e) => {
                all_valid = false;
                if json {
                    results.push(serde_json::json!({
                        "level": level.to_string(),
                        "path": path.display().to_string(),
                        "valid": false,
                        "error": format!("{}", e),
                    }));
                } else {
                    eprintln!(
                        "{} {} {}",
                        style::err_red_bold(""),
                        style::cyan(&format!("[{}]", level)),
                        path.display()
                    );
                    eprintln!("  {}", style::dim(&format!("{}", e)));
                }
                continue;
            }
        };

        match crate::policy::compile::compile_to_tree(&source) {
            Ok(policy) => {
                let warnings = policy.platform_warnings();
                if json {
                    let mut entry = serde_json::json!({
                        "level": level.to_string(),
                        "path": path.display().to_string(),
                        "valid": true,
                        "default": format!("{}", policy.default_effect),
                        "rule_count": policy.rule_count(),
                    });
                    if !warnings.is_empty() {
                        entry["warnings"] = serde_json::json!(warnings);
                    }
                    results.push(entry);
                } else {
                    println!(
                        "{} {} {}",
                        style::green_bold(""),
                        style::cyan(&format!("[{}]", level)),
                        path.display()
                    );
                    println!(
                        "  default {}, {} rules",
                        style::effect(&policy.default_effect.to_string()),
                        policy.rule_count()
                    );
                    for w in &warnings {
                        eprintln!("  {} {}", style::err_yellow("warning:"), w,);
                    }
                }
            }
            Err(e) => {
                all_valid = false;
                let hint = extract_policy_hint(&e);
                if json {
                    let mut entry = serde_json::json!({
                        "level": level.to_string(),
                        "path": path.display().to_string(),
                        "valid": false,
                        "error": format!("{}", e),
                    });
                    if let Some(h) = &hint {
                        entry["hint"] = serde_json::json!(h);
                    }
                    results.push(entry);
                } else {
                    eprintln!(
                        "{} {} {}",
                        style::err_red_bold(""),
                        style::cyan(&format!("[{}]", level)),
                        path.display()
                    );
                    eprintln!("  {}", e);
                    if let Some(h) = hint {
                        eprintln!("  {}: {}", style::err_cyan_bold("hint"), h);
                    }
                }
            }
        }
    }

    if json {
        println!(
            "{}",
            serde_json::to_string_pretty(&serde_json::json!({
                "valid": all_valid,
                "levels": results,
            }))?
        );
    } else if all_valid {
        println!("\n{}", style::green_bold("All policy files are valid."));
    } else {
        eprintln!("\n{}", style::err_red_bold("Policy validation failed."));
        std::process::exit(1);
    }

    Ok(())
}

fn validate_single_file(path: &std::path::Path, json: bool) -> Result<()> {
    let source = crate::settings::evaluate_policy_file(path)
        .with_context(|| format!("failed to evaluate: {}", path.display()))?;

    match crate::policy::compile::compile_to_tree(&source) {
        Ok(policy) => {
            let warnings = policy.platform_warnings();
            if json {
                let mut output = serde_json::json!({
                    "valid": true,
                    "path": path.display().to_string(),
                    "default": format!("{}", policy.default_effect),
                    "rule_count": policy.rule_count(),
                });
                if !warnings.is_empty() {
                    output["warnings"] = serde_json::json!(warnings);
                }
                println!("{}", serde_json::to_string_pretty(&output)?);
            } else {
                println!("{} {}", style::green_bold(""), path.display());
                println!(
                    "  default {}, {} rules",
                    style::effect(&policy.default_effect.to_string()),
                    policy.rule_count()
                );
                for w in &warnings {
                    eprintln!("  {} {}", style::err_yellow("warning:"), w,);
                }
            }
            Ok(())
        }
        Err(e) => {
            let hint = extract_policy_hint(&e);
            if json {
                let mut entry = serde_json::json!({
                    "valid": false,
                    "path": path.display().to_string(),
                    "error": format!("{}", e),
                });
                if let Some(h) = &hint {
                    entry["hint"] = serde_json::json!(h);
                }
                println!("{}", serde_json::to_string_pretty(&entry)?);
            } else {
                eprintln!("{} {}", style::err_red_bold(""), path.display());
                eprintln!("  {}", e);
                if let Some(h) = hint {
                    eprintln!("  {}: {}", style::err_cyan_bold("hint"), h);
                }
            }
            std::process::exit(1);
        }
    }
}

/// Open a policy file in `$EDITOR` (falls back to `vi`).
pub fn open_in_editor(path: &Path) -> Result<()> {
    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".into());
    let status = std::process::Command::new(&editor)
        .arg(path)
        .status()
        .with_context(|| format!("failed to launch editor: {editor}"))?;
    if !status.success() {
        anyhow::bail!("editor exited with {status}");
    }
    Ok(())
}

/// Handle `clash policy edit`.
fn handle_edit(scope: Option<String>, raw: bool, test: bool) -> Result<()> {
    if raw {
        // --raw: open in $EDITOR
        let level = match scope.as_deref() {
            Some("user") => PolicyLevel::User,
            Some("project") => PolicyLevel::Project,
            Some(other) => {
                anyhow::bail!("unknown scope: \"{other}\" (expected \"user\" or \"project\")")
            }
            None => ClashSettings::default_scope(),
        };
        let path = ClashSettings::policy_file_for_level(level)?;
        if !path.exists() {
            anyhow::bail!(
                "no policy file at {} — run `clash init {}` first",
                path.display(),
                level,
            );
        }
        return open_in_editor(&path);
    }

    // Interactive TUI editor
    let path = resolve_manifest_path(scope)?;
    crate::tui::run_with_options(&path, test, false)
}

// ---------------------------------------------------------------------------
// Allow / Deny / Remove handlers
// ---------------------------------------------------------------------------

/// The mutation to apply to a policy rule.
enum PolicyMutation {
    Allow { sandbox: Option<String> },
    Deny,
    Remove,
}

/// Shared pipeline for allow / deny / remove: resolve path, build node, mutate, write, report.
fn apply_mutation(
    command: Vec<String>,
    tool: Option<String>,
    bin: Option<String>,
    scope: Option<String>,
    mutation: PolicyMutation,
) -> Result<()> {
    let path = resolve_manifest_path(scope)?;
    let mut manifest = crate::policy_loader::read_manifest(&path)?;

    // For Remove we only need the observable chain — Decision::Deny is a dummy.
    let dummy_decision = Decision::Deny;
    let decision = match &mutation {
        PolicyMutation::Allow { sandbox } => Decision::Allow(
            sandbox
                .as_deref()
                .map(|s| crate::policy::match_tree::SandboxRef(s.to_string())),
        ),
        PolicyMutation::Deny | PolicyMutation::Remove => dummy_decision,
    };

    let node = build_rule_node(&command, tool, bin, decision)?;

    let result_str = match mutation {
        PolicyMutation::Remove => {
            if manifest_edit::remove_rule(&mut manifest, &node) {
                crate::policy_loader::write_manifest(&path, &manifest)?;
                println!("{} Rule removed", style::green_bold(""));
                println!("  {}", style::dim(&path.display().to_string()));
            } else {
                println!("No matching rule found");
            }
            return Ok(());
        }
        _ => {
            let result = manifest_edit::upsert_rule(&mut manifest, node);
            crate::policy_loader::write_manifest(&path, &manifest)?;
            match result {
                manifest_edit::UpsertResult::Inserted => "Rule added",
                manifest_edit::UpsertResult::Replaced => "Rule updated (replaced existing)",
            }
        }
    };

    println!("{} {}", style::green_bold(""), result_str);
    println!("  {}", style::dim(&path.display().to_string()));
    Ok(())
}

/// Resolve the policy.json path for the given scope, creating it if needed.
pub(crate) fn resolve_manifest_path(scope: Option<String>) -> Result<PathBuf> {
    let level = match scope.as_deref() {
        Some("user") => PolicyLevel::User,
        Some("project") => PolicyLevel::Project,
        Some(other) => {
            anyhow::bail!("unknown scope: \"{other}\" (expected \"user\" or \"project\")")
        }
        None => ClashSettings::default_scope(),
    };

    let dir = match level {
        PolicyLevel::User => ClashSettings::settings_dir()?,
        PolicyLevel::Project => ClashSettings::project_root()?.join(".clash"),
        PolicyLevel::Session => anyhow::bail!("session scope not supported for policy mutation"),
    };

    let json_path = dir.join("policy.json");
    if json_path.exists() {
        return Ok(json_path);
    }

    // If policy.star exists but no policy.json, create a manifest that includes it.
    let star_path = dir.join("policy.star");
    let manifest = if star_path.exists() {
        PolicyManifest {
            includes: vec![crate::policy::match_tree::IncludeEntry {
                path: "policy.star".into(),
            }],
            policy: crate::policy::match_tree::CompiledPolicy {
                sandboxes: std::collections::HashMap::new(),
                tree: vec![],
                default_effect: crate::policy::Effect::Deny,
                default_sandbox: None,
            },
        }
    } else {
        // No policy at all — create a bare manifest.
        std::fs::create_dir_all(&dir)
            .with_context(|| format!("failed to create {}", dir.display()))?;
        PolicyManifest {
            includes: vec![],
            policy: crate::policy::match_tree::CompiledPolicy {
                sandboxes: std::collections::HashMap::new(),
                tree: vec![],
                default_effect: crate::policy::Effect::Deny,
                default_sandbox: None,
            },
        }
    };

    crate::policy_loader::write_manifest(&json_path, &manifest)?;
    info!(path = %json_path.display(), "Created policy.json");
    Ok(json_path)
}

/// Parse a positional command string into (bin, args).
///
/// Splits on whitespace: `"gh pr create"` → `("gh", ["pr", "create"])`.
/// If the command vec has multiple words (from trailing_var_arg), joins them first.
fn parse_command(command: &[String]) -> Option<(String, Vec<String>)> {
    // Join all positional args, then split on whitespace to handle both
    // `clash policy allow "gh pr create"` and `clash policy allow gh pr create`.
    let joined = command.join(" ");
    let parts: Vec<&str> = joined.split_whitespace().collect();
    if parts.is_empty() {
        return None;
    }
    let bin = parts[0].to_string();
    let args: Vec<String> = parts[1..].iter().map(|s| s.to_string()).collect();
    Some((bin, args))
}

/// Build a rule node from CLI arguments.
///
/// Priority: positional `command` > `--bin` > `--tool`.
/// If no flags or command are provided, returns an error.
fn build_rule_node(
    command: &[String],
    tool: Option<String>,
    bin: Option<String>,
    decision: Decision,
) -> Result<crate::policy::match_tree::Node> {
    // Positional command takes priority.
    if let Some((bin_name, args)) = parse_command(command) {
        let arg_refs: Vec<&str> = args.iter().map(|s| s.as_str()).collect();
        return Ok(manifest_edit::build_exec_rule(
            &bin_name, &arg_refs, decision,
        ));
    }
    match (tool.as_deref(), bin.as_deref()) {
        (_, Some(bin_name)) => Ok(manifest_edit::build_exec_rule(bin_name, &[], decision)),
        (Some(tool_name), None) => {
            // Resolve canonical/case-insensitive names: "shell" → "Bash", "bash" → "Bash", etc.
            let resolved = crate::agents::resolve_any_to_internal(tool_name).unwrap_or(tool_name);
            Ok(manifest_edit::build_tool_rule(resolved, decision))
        }
        (None, None) => anyhow::bail!("provide a command, --tool, or --bin"),
    }
}

fn handle_allow(
    command: Vec<String>,
    tool: Option<String>,
    bin: Option<String>,
    sandbox: Option<String>,
    scope: Option<String>,
) -> Result<()> {
    apply_mutation(command, tool, bin, scope, PolicyMutation::Allow { sandbox })
}

fn handle_deny(
    command: Vec<String>,
    tool: Option<String>,
    bin: Option<String>,
    scope: Option<String>,
) -> Result<()> {
    apply_mutation(command, tool, bin, scope, PolicyMutation::Deny)
}

fn handle_remove(
    command: Vec<String>,
    tool: Option<String>,
    bin: Option<String>,
    scope: Option<String>,
) -> Result<()> {
    apply_mutation(command, tool, bin, scope, PolicyMutation::Remove)
}

/// Extract a help hint from an anyhow error chain.
fn extract_policy_hint(err: &anyhow::Error) -> Option<String> {
    err.chain().find_map(|cause| {
        if let Some(e) = cause.downcast_ref::<crate::policy::error::PolicyParseError>() {
            return e.help();
        }
        if let Some(e) = cause.downcast_ref::<crate::policy::error::CompileError>() {
            return e.help();
        }
        None
    })
}