clash 0.5.3

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
//! Self-describing schema for the policy format.
//!
//! Provides a structured representation of the Starlark/JSON policy
//! language and companion YAML configuration. Used by `clash policy schema`
//! to make the CLI self-documenting.

use serde::Serialize;

/// A single field in a configuration section.
#[derive(Debug, Clone, Serialize)]
pub struct SchemaField {
    /// Key or syntax name.
    pub key: &'static str,
    /// Human-readable type (e.g. "bool", "integer", "string", "enum", "form").
    #[serde(rename = "type")]
    pub type_name: &'static str,
    /// What this field does.
    pub description: &'static str,
    /// Default value, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default: Option<serde_json::Value>,
    /// Valid values for enum types.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub values: Option<Vec<&'static str>>,
    /// Whether this field is required (no default).
    pub required: bool,
    /// Nested fields for object types.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fields: Option<Vec<SchemaField>>,
}

/// A top-level section of the configuration.
#[derive(Debug, Clone, Serialize)]
pub struct SchemaSection {
    /// Section key.
    pub key: &'static str,
    /// What this section configures.
    pub description: &'static str,
    /// Fields in this section.
    pub fields: Vec<SchemaField>,
}

/// Description of the JSON rule syntax.
#[derive(Debug, Clone, Serialize)]
pub struct RuleSyntax {
    /// Format string showing rule structure.
    pub format: &'static str,
    /// Available effects.
    pub effects: Vec<&'static str>,
    /// Capability domains.
    pub domains: Vec<SchemaField>,
    /// Pattern types used in matchers.
    pub patterns: Vec<SchemaField>,
    /// Path filter types for fs rules.
    pub path_filters: Vec<SchemaField>,
    /// Filesystem operation names.
    pub fs_operations: Vec<&'static str>,
}

/// Complete schema output.
#[derive(Debug, Clone, Serialize)]
pub struct PolicySchema {
    pub sections: Vec<SchemaSection>,
    pub rule_syntax: RuleSyntax,
}

// ---------------------------------------------------------------------------
// Schema registry
// ---------------------------------------------------------------------------

/// Build the complete policy schema.
pub fn policy_schema() -> PolicySchema {
    PolicySchema {
        sections: vec![policy_section(), notifications_section(), audit_section()],
        rule_syntax: rule_syntax(),
    }
}

fn policy_section() -> SchemaSection {
    SchemaSection {
        key: "policy",
        description: "Starlark policy file (policy.star) — defines rules compiled to JSON IR",
        fields: vec![
            SchemaField {
                key: "policy(default=effect)",
                type_name: "form",
                description: "Sets the default effect (allow/deny/ask) via the policy() constructor",
                default: Some(serde_json::json!("policy(default=deny)")),
                values: None,
                required: true,
                fields: None,
            },
            SchemaField {
                key: "def main(): return policy(...)",
                type_name: "form",
                description: "A main() function that returns a policy() value with rules",
                default: None,
                values: None,
                required: true,
                fields: None,
            },
            SchemaField {
                key: "load(\"@clash//lib.star\", ...)",
                type_name: "form",
                description: "Import rules or helpers from another Starlark module",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
        ],
    }
}

fn notifications_section() -> SchemaSection {
    SchemaSection {
        key: "notifications",
        description: "How you get notified about permission prompts (configured in companion policy.yaml)",
        fields: vec![
            SchemaField {
                key: "desktop",
                type_name: "bool",
                description: "Enable desktop notifications for permission prompts",
                default: Some(serde_json::json!(false)),
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "desktop_timeout_secs",
                type_name: "integer",
                description: "Seconds to wait for a response on desktop notification prompts",
                default: Some(serde_json::json!(120)),
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "zulip",
                type_name: "object",
                description: "Zulip bot for remote permission resolution — posts ask prompts to a Zulip stream and polls for approve/deny replies",
                default: None,
                values: None,
                required: false,
                fields: Some(vec![
                    SchemaField {
                        key: "server_url",
                        type_name: "string",
                        description: "Zulip server URL (e.g. https://your-org.zulipchat.com)",
                        default: None,
                        values: None,
                        required: true,
                        fields: None,
                    },
                    SchemaField {
                        key: "bot_email",
                        type_name: "string",
                        description: "Bot email address for API authentication",
                        default: None,
                        values: None,
                        required: true,
                        fields: None,
                    },
                    SchemaField {
                        key: "bot_api_key",
                        type_name: "string",
                        description: "Bot API key for authentication",
                        default: None,
                        values: None,
                        required: true,
                        fields: None,
                    },
                    SchemaField {
                        key: "stream",
                        type_name: "string",
                        description: "Zulip stream (channel) to post permission requests to",
                        default: None,
                        values: None,
                        required: true,
                        fields: None,
                    },
                    SchemaField {
                        key: "topic",
                        type_name: "string",
                        description: "Topic within the stream for permission messages",
                        default: Some(serde_json::json!("permissions")),
                        values: None,
                        required: false,
                        fields: None,
                    },
                    SchemaField {
                        key: "timeout_secs",
                        type_name: "integer",
                        description: "Seconds to wait for a Zulip response before giving up",
                        default: Some(serde_json::json!(120)),
                        values: None,
                        required: false,
                        fields: None,
                    },
                ]),
            },
        ],
    }
}

fn audit_section() -> SchemaSection {
    SchemaSection {
        key: "audit",
        description: "Audit logging — records every policy decision to a JSON Lines file (configured in companion policy.yaml)",
        fields: vec![
            SchemaField {
                key: "enabled",
                type_name: "bool",
                description: "Enable audit logging",
                default: Some(serde_json::json!(false)),
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "path",
                type_name: "string",
                description: "Path to the audit log file",
                default: Some(serde_json::json!("~/.clash/audit.jsonl")),
                values: None,
                required: false,
                fields: None,
            },
        ],
    }
}

fn rule_syntax() -> RuleSyntax {
    RuleSyntax {
        format: "exe(\"bin\").allow() / cwd().allow(read=True) / domains({...})",
        effects: vec!["allow", "deny", "ask"],
        domains: vec![
            SchemaField {
                key: "exec",
                type_name: "capability",
                description: "Command execution: exe(\"binary\", args=[...]). Matches Bash tool invocations.",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "fs",
                type_name: "capability",
                description: "Filesystem access: cwd().allow(read=True, write=True). Matches Read, Write, Edit, Glob, Grep tools.",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "net",
                type_name: "capability",
                description: "Network access: domains({\"example.com\": allow}). Matches WebFetch and WebSearch tools.",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "tool",
                type_name: "capability",
                description: "Agent tool access: tool([\"Name\"]). Matches tools not covered by exec/fs/net (e.g. Skill, Task, AskUserQuestion, EnterPlanMode, ExitPlanMode).",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
        ],
        patterns: vec![
            SchemaField {
                key: "*",
                type_name: "pattern",
                description: "Wildcard — matches anything",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "\"literal\"",
                type_name: "pattern",
                description: "Exact string match (quoted)",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "/regex/",
                type_name: "pattern",
                description: "Regular expression match",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "any_of([p1, p2, ...])",
                type_name: "combinator",
                description: "Match any of the listed patterns",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "not_(p)",
                type_name: "combinator",
                description: "Negate a pattern",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
        ],
        path_filters: vec![
            SchemaField {
                key: "path(\"/dir\").recurse()",
                type_name: "filter",
                description: "Recursive subtree match. Use path(env=\"VAR\") for environment variables.",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "\"path\"",
                type_name: "filter",
                description: "Exact file path match (quoted)",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
            SchemaField {
                key: "/regex/",
                type_name: "filter",
                description: "Regex match on resolved path",
                default: None,
                values: None,
                required: false,
                fields: None,
            },
        ],
        fs_operations: vec!["read", "write", "create", "delete"],
    }
}

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

    #[test]
    fn schema_serializes_to_json() {
        let schema = policy_schema();
        let json = serde_json::to_string_pretty(&schema).unwrap();
        assert!(!json.is_empty());
        // Verify it's valid JSON by parsing it back.
        let _: serde_json::Value = serde_json::from_str(&json).unwrap();
    }

    #[test]
    fn schema_has_all_sections() {
        let schema = policy_schema();
        let keys: Vec<&str> = schema.sections.iter().map(|s| s.key).collect();
        assert!(keys.contains(&"policy"), "missing 'policy' section");
        assert!(
            keys.contains(&"notifications"),
            "missing 'notifications' section"
        );
        assert!(keys.contains(&"audit"), "missing 'audit' section");
    }

    #[test]
    fn notifications_section_includes_zulip() {
        let schema = policy_schema();
        let notif = schema
            .sections
            .iter()
            .find(|s| s.key == "notifications")
            .unwrap();
        let zulip = notif.fields.iter().find(|f| f.key == "zulip").unwrap();
        assert_eq!(zulip.type_name, "object");
        let zulip_fields = zulip.fields.as_ref().unwrap();
        let zulip_keys: Vec<&str> = zulip_fields.iter().map(|f| f.key).collect();
        assert!(zulip_keys.contains(&"server_url"));
        assert!(zulip_keys.contains(&"bot_email"));
        assert!(zulip_keys.contains(&"bot_api_key"));
        assert!(zulip_keys.contains(&"stream"));
        assert!(zulip_keys.contains(&"topic"));
        assert!(zulip_keys.contains(&"timeout_secs"));
    }

    #[test]
    fn notification_field_count_matches_config_struct() {
        // NotificationConfig has 3 fields: desktop, desktop_timeout_secs, zulip
        let schema = policy_schema();
        let notif = schema
            .sections
            .iter()
            .find(|s| s.key == "notifications")
            .unwrap();
        assert_eq!(
            notif.fields.len(),
            3,
            "NotificationConfig field count mismatch — did you add a field to the struct without updating the schema?"
        );
    }

    #[test]
    fn zulip_field_count_matches_config_struct() {
        // ZulipConfig has 6 fields: server_url, bot_email, bot_api_key, stream, topic, timeout_secs
        let schema = policy_schema();
        let notif = schema
            .sections
            .iter()
            .find(|s| s.key == "notifications")
            .unwrap();
        let zulip = notif.fields.iter().find(|f| f.key == "zulip").unwrap();
        let zulip_fields = zulip.fields.as_ref().unwrap();
        assert_eq!(
            zulip_fields.len(),
            6,
            "ZulipConfig field count mismatch — did you add a field to the struct without updating the schema?"
        );
    }

    #[test]
    fn audit_field_count_matches_config_struct() {
        // AuditConfig has 2 fields: enabled, path
        let schema = policy_schema();
        let audit = schema.sections.iter().find(|s| s.key == "audit").unwrap();
        assert_eq!(
            audit.fields.len(),
            2,
            "AuditConfig field count mismatch — did you add a field to the struct without updating the schema?"
        );
    }

    #[test]
    fn rule_syntax_has_all_effects() {
        let schema = policy_schema();
        assert_eq!(schema.rule_syntax.effects, vec!["allow", "deny", "ask"]);
    }

    #[test]
    fn rule_syntax_has_all_domains() {
        let schema = policy_schema();
        let domain_keys: Vec<&str> = schema.rule_syntax.domains.iter().map(|d| d.key).collect();
        assert!(domain_keys.contains(&"exec"));
        assert!(domain_keys.contains(&"fs"));
        assert!(domain_keys.contains(&"net"));
        assert!(domain_keys.contains(&"tool"));
    }

    #[test]
    fn rule_syntax_has_all_fs_operations() {
        let schema = policy_schema();
        assert_eq!(
            schema.rule_syntax.fs_operations,
            vec!["read", "write", "create", "delete"]
        );
    }
}