clash 0.7.1

Command Line Agent Safety Harness — permission policies for coding agents
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
use clap::{Parser, Subcommand};

use crate::cmd::debug::DebugCmd;
use crate::cmd::session::SessionCmd;
use crate::cmd::statusline::StatuslineCmd;
use crate::cmd::trace::TraceCmd;
use crate::sandbox_cmd::SandboxCmd;

#[derive(Parser, Debug)]
#[command(name = "clash")]
#[command(version = crate::version::version_long())]
#[command(about = "Command line agent safety harness")]
pub struct Cli {
    #[arg(short, long, global = true)]
    pub verbose: bool,

    #[command(subcommand)]
    pub command: Commands,
}

/// Top-level hook command with shared `--agent` flag.
#[derive(Parser, Debug)]
pub struct HookCmd {
    /// Which coding agent is invoking the hook (default: claude)
    #[arg(long, default_value = "claude")]
    pub agent: crate::agents::AgentKind,

    #[command(subcommand)]
    pub subcommand: HookSubcommand,
}

#[derive(Subcommand, Debug)]
pub enum HookSubcommand {
    /// Handle PreToolUse hook - called before a tool is executed
    #[command(name = "pre-tool-use")]
    PreToolUse,

    /// Handle PostToolUse hook - called after a tool is executed
    #[command(name = "post-tool-use")]
    PostToolUse,

    /// Handle PermissionRequest hook - respond to permission prompts on behalf of user
    #[command(name = "permission-request")]
    PermissionRequest,

    /// Handle SessionStart hook - called when a coding agent session begins
    #[command(name = "session-start")]
    SessionStart,

    /// Handle Stop hook - called when a conversation turn ends without a tool call
    #[command(name = "stop")]
    Stop,
}

#[derive(Subcommand, Debug)]
pub enum PolicyCmd {
    /// List rules in the active policy
    List {
        #[arg(long)]
        json: bool,
    },
    /// Validate policy files and report errors
    Validate {
        /// Path to a specific policy file to validate (default: all active levels)
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Open the interactive policy editor (or $EDITOR with --raw)
    Edit {
        /// Policy scope to edit: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
    },
    /// Add an allow rule for a tool or binary
    ///
    /// Examples:
    ///   clash policy allow "gh pr create"
    ///   clash policy allow --tool Read
    ///   clash policy allow --bin grep --sandbox cwd
    Allow {
        /// Command to allow (e.g. "gh pr create" → bin=gh, args=[pr, create])
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
        /// Tool name (e.g. "Bash", "Read", "Write")
        #[arg(long)]
        tool: Option<String>,
        /// Binary name (implies --tool Bash)
        #[arg(long)]
        bin: Option<String>,
        /// Named sandbox to apply (must be defined in the policy)
        #[arg(long)]
        sandbox: Option<String>,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
        /// Widen the match by dropping trailing arguments and using a glob pattern.
        #[arg(long)]
        broad: bool,
        /// Skip confirmation dialog.
        #[arg(long, short = 'y')]
        yes: bool,
    },
    /// Add a deny rule for a tool or binary
    ///
    /// Examples:
    ///   clash policy deny "rm -rf"
    ///   clash policy deny --tool WebSearch
    Deny {
        /// Command to deny (e.g. "git push" → bin=git, args=[push])
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
        /// Tool name (e.g. "Bash", "Read", "Write")
        #[arg(long)]
        tool: Option<String>,
        /// Binary name (implies --tool Bash)
        #[arg(long)]
        bin: Option<String>,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
        /// Widen the match by dropping trailing arguments and using a glob pattern.
        #[arg(long)]
        broad: bool,
        /// Skip confirmation dialog.
        #[arg(long, short = 'y')]
        yes: bool,
    },
    /// Remove a rule matching a tool or binary
    ///
    /// Examples:
    ///   clash policy remove "gh pr create"
    ///   clash policy remove --tool Read
    Remove {
        /// Command to match (e.g. "gh pr create")
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
        /// Tool name (e.g. "Bash", "Read", "Write")
        #[arg(long)]
        tool: Option<String>,
        /// Binary name (implies --tool Bash)
        #[arg(long)]
        bin: Option<String>,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
    },
    /// Check policy for multi-agent portability issues
    ///
    /// Scans policy rules and warns about agent-specific tool names
    /// that won't match across all agents. Suggests canonical alternatives.
    Check {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    // --- Hidden/power-user subcommands ---
    /// Show policy summary: active policy, default effect, rule count
    #[command(hide = true)]
    Show {
        #[arg(long)]
        json: bool,
    },
    /// Show the full schema of policy settings
    #[command(hide = true)]
    Schema {
        #[arg(long)]
        json: bool,
    },
    /// Convert policy.json to policy.star (Starlark format)
    ///
    /// Reads the JSON policy, converts it to idiomatic Starlark, and writes
    /// a .star file alongside it. The original .json is preserved unless
    /// --replace is passed.
    Convert {
        /// Path to the policy.json file (default: auto-detect active policy)
        #[arg(long)]
        file: Option<std::path::PathBuf>,
        /// Delete the .json file after successful conversion
        #[arg(long)]
        replace: bool,
    },
    /// Migrate policy from when()/rules= syntax to dict syntax
    ///
    /// Converts deprecated when() calls and rules= lists to dict syntax.
    /// Adds from_claude_settings() if not already present.
    Migrate {
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
        /// Skip confirmation dialog
        #[arg(long, short = 'y')]
        yes: bool,
    },
    /// Explain which policy rule would match a given tool invocation
    #[command(hide = true)]
    Explain {
        /// Output as JSON instead of human-readable text
        #[arg(long)]
        json: bool,
        /// Show detailed decision trace with per-condition match details
        #[arg(long)]
        trace: bool,
        /// Tool type: bash, read, write, edit, tool (or full tool name like Bash, Read, etc.)
        tool: Option<String>,
        /// The command, file path, or noun to check (remaining args joined)
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },
}

#[derive(Subcommand, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum Commands {
    /// Initialize a new clash policy with a safe default configuration
    ///
    /// By default, imports permissions from your coding agent's existing
    /// configuration and generates a matching Clash policy. Use --no-import
    /// to skip policy generation and just install hooks.
    Init {
        /// Generate policy from an observed session trace file.
        /// Pass a path to trace.jsonl or audit.jsonl, or "latest" to auto-detect.
        #[arg(long = "from-trace", value_name = "PATH", conflicts_with = "no_import")]
        from_trace: Option<std::path::PathBuf>,
        /// Skip policy import — just install hooks and print setup instructions
        #[arg(long = "no-import", conflicts_with = "from_trace")]
        no_import: bool,
        /// Which coding agent to set up (prompts if omitted)
        #[arg(long)]
        agent: Option<crate::agents::AgentKind>,
    },

    /// Install the clash plugin/hooks for a coding agent (skip policy setup)
    Install {
        /// Which coding agent to install for (prompts if omitted)
        #[arg(long)]
        agent: Option<crate::agents::AgentKind>,
    },

    /// Remove clash: undo bypass permissions, uninstall plugin, remove config and binary
    Uninstall {
        /// Skip confirmation prompts
        #[arg(long, short = 'y')]
        yes: bool,
    },

    /// Show policy status: layers, rules with shadowing, and potential issues
    Status {
        /// Output as JSON instead of human-readable text
        #[arg(long)]
        json: bool,
    },

    /// View and manage policy rules
    #[command(subcommand)]
    Policy(PolicyCmd),

    /// Print the full command and subcommand hierarchy
    #[command(name = "commands")]
    ShowCommands {
        /// Output as JSON (for programmatic use by skills/agents)
        #[arg(long)]
        json: bool,
        /// Include hidden/internal commands
        #[arg(long)]
        all: bool,
    },

    /// Run a bash-compatible shell with per-command sandbox enforcement
    ///
    /// Every external command is executed through its own sandbox profile,
    /// looked up by binary name (e.g., `sandboxes["git"]`), falling back
    /// to the default sandbox when no command-specific profile exists.
    ///
    /// Modes: interactive REPL (no args), command string (-c), or script file.
    Shell {
        /// Execute a command string and exit (like bash -c)
        #[arg(short = 'c')]
        command: Option<String>,

        /// Working directory for sandbox path resolution
        #[arg(long, default_value = ".")]
        cwd: String,

        /// Default sandbox name from the policy (used when no rule-specific sandbox matches)
        #[arg(long)]
        sandbox: Option<String>,

        /// Print the sandbox policy matched for each command before execution
        #[arg(long)]
        debug: bool,

        /// Script path and arguments
        #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
        args: Vec<String>,
    },

    /// Apply sandbox restrictions and exec commands
    #[command(subcommand, alias = "box")]
    Sandbox(SandboxCmd),

    /// Diagnose common setup issues and report fix instructions
    Doctor {
        /// Run interactive onboarding: diagnose issues and offer to fix them
        #[arg(long)]
        onboard: bool,
        /// Which coding agent to diagnose (default: claude)
        #[arg(long, default_value = "claude")]
        agent: crate::agents::AgentKind,
    },

    /// Debug policy enforcement: view logs, replay commands, inspect sandbox
    #[command(subcommand)]
    Debug(DebugCmd),

    /// View and export session traces
    #[command(subcommand)]
    Trace(TraceCmd),

    /// List, inspect, and locate session directories
    #[command(subcommand)]
    Session(SessionCmd),

    // --- Hidden/internal commands ---
    /// Agent hook callbacks
    #[command(hide = true)]
    Hook(HookCmd),

    /// Launch Claude Code with clash managing hooks and sandbox enforcement
    #[command(hide = true)]
    Launch {
        /// Path to policy file (default: ~/.clash/policy.star)
        #[arg(long)]
        policy: Option<String>,

        /// Arguments to pass through to Claude Code
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },

    /// Format Starlark policy files using ruff
    Fmt {
        /// Check formatting without modifying files (exit 1 if unformatted)
        #[arg(long)]
        check: bool,

        /// Policy files to format (default: all active policy files)
        #[arg(trailing_var_arg = true)]
        files: Vec<std::path::PathBuf>,
    },

    /// Explain which policy rule would match a given tool invocation
    Explain {
        /// Output as JSON instead of human-readable text
        #[arg(long)]
        json: bool,
        /// Show detailed decision trace with per-condition match details
        #[arg(long)]
        trace: bool,
        /// Tool type: bash, read, write, edit, tool (or full tool name like Bash, Read, etc.)
        tool: String,
        /// The command, file path, or noun to check (remaining args joined)
        #[arg(trailing_var_arg = true)]
        args: Vec<String>,
    },

    /// Update clash to the latest release (or a specific version)
    Update {
        /// Only check for updates, don't install
        #[arg(long)]
        check: bool,

        /// Skip confirmation prompt
        #[arg(long, short = 'y')]
        yes: bool,

        /// Update to a specific version (e.g., 0.4.0)
        #[arg(long)]
        version: Option<String>,
    },

    /// Display clash status in the Claude Code status line
    #[command(subcommand)]
    Statusline(StatuslineCmd),

    /// Run the clash language server, or install editor configuration
    Lsp(LspCmd),

    /// File a bug report to the clash issue tracker
    #[command(alias = "rage", hide = true)]
    Bug {
        /// Short summary of the bug
        title: String,
        /// Detailed description of the bug
        #[arg(short, long)]
        description: Option<String>,
        /// Include the clash policy config in the report
        #[arg(long)]
        include_config: bool,
        /// Include recent debug logs in the report
        #[arg(long)]
        include_logs: bool,
        /// Include the session toolpath trace in the report
        #[arg(long)]
        include_trace: bool,
    },
}

#[derive(clap::Args, Debug)]
pub struct LspCmd {
    #[command(subcommand)]
    pub subcommand: Option<LspSubcommand>,
}

#[derive(Subcommand, Debug)]
pub enum LspSubcommand {
    /// Install editor configuration to use clash lsp
    Install {
        /// Which editor to configure
        #[arg(long, value_enum)]
        editor: Editor,
        /// Print the config that would be written without applying it
        #[arg(long)]
        dry_run: bool,
    },
}

#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub enum Editor {
    Vscode,
    Neovim,
    Helix,
    Zed,
}