clash 0.5.2

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
//! Policy discovery, evaluation, and compilation.
//!
//! This module extracts the policy loading pipeline from [`crate::settings`]:
//!
//! 1. **Discovery** — finding `policy.json` / `policy.star` files at user/project/session levels
//! 2. **Validation** — checking file metadata (size, permissions, type)
//! 3. **Evaluation** — running Starlark `.star` files through `clash_starlark`,
//!    or parsing `.json` manifests (with optional `includes`)
//! 4. **Compilation** — compiling evaluated JSON sources into a [`CompiledPolicy`] tree

use std::path::Path;

use anyhow::{Context, Result};
use tracing::{error, warn};

#[cfg(test)]
use tracing::info;

use crate::policy::compile;
use crate::policy::match_tree::{CompiledPolicy, PolicyManifest};
use crate::settings::{LoadedPolicy, PolicyLevel};

/// Maximum policy file size (1 MiB).
pub const MAX_POLICY_SIZE: u64 = 1024 * 1024;

/// Outcome of attempting to load a single policy file.
///
/// On success, carries both the evaluated JSON source (needed for compilation)
/// and the [`LoadedPolicy`] metadata.
pub struct ValidatedPolicy {
    /// The evaluated JSON source text.
    pub json_source: String,
    /// The loaded policy metadata.
    pub loaded: LoadedPolicy,
}

/// Evaluate a `.star` policy file through the Starlark evaluator and return
/// the compiled JSON source text.
pub fn evaluate_star_policy(path: &Path) -> Result<String> {
    let source = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    let base_dir = path.parent().unwrap_or(Path::new("."));

    let output = clash_starlark::evaluate(&source, &path.display().to_string(), base_dir)?;

    Ok(output.json)
}

/// Migrate legacy string-style capability values in a policy JSON to the
/// current array format.
///
/// Old format: `"caps": "read + write"`, `"default": "all - delete"`
/// New format: `"caps": ["read", "write"]`, `"default": ["read", "write", "create", "execute"]`
///
/// If any values are migrated, the fixed JSON is written back to disk so
/// the migration is transparent and one-time.
fn migrate_legacy_caps(path: &Path, raw: String) -> Result<String> {
    let mut value: serde_json::Value = serde_json::from_str(&raw)
        .with_context(|| format!("failed to parse {}", path.display()))?;

    let mut changed = false;

    if let Some(sandboxes) = value.get_mut("sandboxes").and_then(|v| v.as_object_mut()) {
        for (_name, sandbox) in sandboxes.iter_mut() {
            let Some(sandbox_obj) = sandbox.as_object_mut() else {
                continue;
            };

            // Migrate "default" field
            if let Some(default_val) = sandbox_obj.get("default") {
                if let Some(migrated) = migrate_cap_value(default_val) {
                    sandbox_obj.insert("default".into(), migrated);
                    changed = true;
                }
            }

            // Migrate "caps" in each rule
            if let Some(rules) = sandbox_obj.get_mut("rules").and_then(|v| v.as_array_mut()) {
                for rule in rules.iter_mut() {
                    if let Some(rule_obj) = rule.as_object_mut() {
                        if let Some(caps_val) = rule_obj.get("caps") {
                            if let Some(migrated) = migrate_cap_value(caps_val) {
                                rule_obj.insert("caps".into(), migrated);
                                changed = true;
                            }
                        }
                    }
                }
            }
        }
    }

    if !changed {
        return Ok(raw);
    }

    let fixed =
        serde_json::to_string_pretty(&value).context("failed to serialize migrated policy")?;

    // Write the migrated policy back so this is a one-time fixup.
    if let Err(e) = std::fs::write(path, &fixed) {
        warn!(path = %path.display(), error = %e, "Failed to write migrated policy back to disk");
    } else {
        warn!(
            path = %path.display(),
            "Migrated legacy string-style caps to array format"
        );
    }

    Ok(fixed)
}

/// If a JSON value is a string that looks like a legacy cap expression
/// (e.g. "read + write"), parse it and return the equivalent array value.
/// Returns `None` if the value is already an array or not a valid cap string.
fn migrate_cap_value(value: &serde_json::Value) -> Option<serde_json::Value> {
    use crate::policy::sandbox_types::Cap;

    let s = value.as_str()?;
    let cap = Cap::parse(s).ok()?;
    let names: Vec<serde_json::Value> = cap
        .to_list()
        .into_iter()
        .map(|n| serde_json::Value::String(n.into()))
        .collect();
    Some(serde_json::Value::Array(names))
}

/// Load a `policy.json` manifest: parse the JSON, resolve includes, and return
/// a merged JSON source string suitable for [`compile::compile_to_tree`].
pub fn load_json_policy(path: &Path) -> Result<String> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    // Migrate legacy string-style caps (e.g. "read + write") to array format
    // (e.g. ["read", "write"]) before parsing. Writes the fixed file back if changed.
    let raw = migrate_legacy_caps(path, raw)?;

    let manifest: PolicyManifest = serde_json::from_str(&raw)
        .with_context(|| format!("failed to parse {}", path.display()))?;

    if manifest.includes.is_empty() {
        // No includes — the manifest JSON is the policy source directly.
        return Ok(raw);
    }

    // Merge: inline tree nodes come first (highest precedence), then includes in order.
    let base_dir = path.parent().unwrap_or(Path::new("."));
    merge_manifest_with_includes(&manifest, base_dir)
}

/// Merge a [`PolicyManifest`]'s inline policy with its `includes`.
///
/// Inline tree nodes come first (first-match wins), followed by included
/// policies in declaration order.
fn merge_manifest_with_includes(manifest: &PolicyManifest, base_dir: &Path) -> Result<String> {
    let mut merged = manifest.policy.clone();

    for include in &manifest.includes {
        let json_source = evaluate_include(&include.path, base_dir)?;
        let included: CompiledPolicy = serde_json::from_str(&json_source)
            .with_context(|| format!("failed to parse included policy {:?}", include.path))?;

        // Append included rules after inline rules (lower precedence).
        merged.tree.extend(included.tree);
        // Merge sandboxes (inline wins on conflict).
        for (k, v) in included.sandboxes {
            merged.sandboxes.entry(k).or_insert(v);
        }
    }

    serde_json::to_string(&merged).context("failed to serialize merged policy")
}

/// Evaluate an include entry and return the compiled JSON source.
///
/// For `.star` files (local or `@clash//` stdlib), evaluates through Starlark.
/// Local `.star` includes must define a `main()` function that returns a policy.
fn evaluate_include(include_path: &str, base_dir: &Path) -> Result<String> {
    if include_path.starts_with("@clash//") {
        // Stdlib includes are library modules — they export values, not main().
        // Wrap in a minimal Starlark policy that loads the export and returns it.
        evaluate_stdlib_include(include_path)
    } else {
        // Local .star file — must define main().
        let resolved = base_dir.join(include_path);
        evaluate_star_policy(&resolved)
    }
}

/// Evaluate a `@clash//` stdlib module by wrapping it in a Starlark policy.
///
/// The wrapper loads the module, imports its `builtins` export (a list of rule
/// nodes), and returns them wrapped in a `policy()` from `main()`.
fn evaluate_stdlib_include(include_path: &str) -> Result<String> {
    let wrapper = format!(
        "load(\"{include_path}\", \"builtins\")\n\
         load(\"@clash//std.star\", \"deny\", \"policy\")\n\
         def main():\n    return policy(default=deny(), rules=builtins)\n"
    );
    let output = clash_starlark::evaluate(&wrapper, "<include>", Path::new("."))
        .with_context(|| format!("failed to evaluate stdlib include {include_path}"))?;
    Ok(output.json)
}

/// Read and parse a `policy.json` file into a [`PolicyManifest`].
///
/// This does NOT resolve includes — call [`load_json_policy`] for full loading.
pub fn read_manifest(path: &Path) -> Result<PolicyManifest> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    serde_json::from_str(&raw).with_context(|| format!("failed to parse {}", path.display()))
}

/// Resolve includes and return the combined included policy plus any warnings.
///
/// Evaluates each include entry and merges their rules and sandboxes.
/// Returns the merged included content (without the inline policy) and a list
/// of warnings for includes that failed to evaluate or parse.
/// Rules/sandboxes from includes should be treated as read-only in the TUI.
pub fn resolve_includes(
    manifest: &PolicyManifest,
    base_dir: &Path,
) -> Result<(CompiledPolicy, Vec<String>)> {
    use std::collections::HashMap;

    let mut merged = CompiledPolicy {
        sandboxes: HashMap::new(),
        tree: vec![],
        default_effect: manifest.policy.default_effect,
        default_sandbox: None,
    };

    let mut warnings = Vec::new();

    for include in &manifest.includes {
        match evaluate_include(&include.path, base_dir) {
            Ok(json_source) => match serde_json::from_str::<CompiledPolicy>(&json_source) {
                Ok(included) => {
                    for mut node in included.tree {
                        node.stamp_source(&include.path);
                        merged.tree.push(node);
                    }
                    for (k, v) in included.sandboxes {
                        merged.sandboxes.entry(k).or_insert(v);
                    }
                }
                Err(e) => {
                    warnings.push(format!("{}: parse error: {e}", include.path));
                }
            },
            Err(e) => {
                warnings.push(format!("{}: {e:#}", include.path));
            }
        }
    }

    if !warnings.is_empty() {
        tracing::warn!("include resolution warnings: {}", warnings.join("; "));
    }

    Ok((merged, warnings))
}

/// Write a [`PolicyManifest`] to disk as pretty-printed JSON.
pub fn write_manifest(path: &Path, manifest: &PolicyManifest) -> Result<()> {
    let json =
        serde_json::to_string_pretty(manifest).context("failed to serialize policy manifest")?;
    std::fs::write(path, json).with_context(|| format!("failed to write {}", path.display()))
}

/// Validate a policy file's metadata (existence, type, size, permissions).
///
/// Returns `Some(metadata)` when the file is suitable for loading.
/// Returns `None` when the file is missing, is a directory, or exceeds the
/// size limit.
fn validate_policy_file(path: &Path, level: PolicyLevel) -> Option<std::fs::Metadata> {
    match validate_policy_file_with_diagnostics(path) {
        Ok(metadata) => {
            #[cfg(unix)]
            check_permissions_warning(path, level, &metadata);
            Some(metadata)
        }
        Err(ValidationError::NotFound) => None,
        Err(e) => {
            warn!(path = %path.display(), level = %level, "Policy file invalid: {e}");
            None
        }
    }
}

/// Validate a policy file with rich diagnostic messages suitable for user display.
///
/// Returns `Ok(metadata)` when the file is suitable for loading, or a
/// [`ValidationError`] describing exactly what is wrong.
fn validate_policy_file_with_diagnostics(
    path: &Path,
) -> Result<std::fs::Metadata, ValidationError> {
    let metadata = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(ValidationError::NotFound);
        }
        Err(e) => {
            return Err(ValidationError::IoError(format!(
                "Cannot read policy file at {}: {}",
                path.display(),
                e
            )));
        }
    };

    if metadata.is_dir() {
        return Err(ValidationError::IsDirectory(format!(
            "{} is a directory, not a file. Remove it and run `clash init` to create a policy.",
            path.display()
        )));
    }

    if metadata.len() > MAX_POLICY_SIZE {
        return Err(ValidationError::TooLarge(format!(
            "policy file is too large ({} bytes, max {} bytes). Check that {} is the correct file.",
            metadata.len(),
            MAX_POLICY_SIZE,
            path.display()
        )));
    }

    Ok(metadata)
}

/// Emit a warning if the policy file is readable by other users.
#[cfg(unix)]
fn check_permissions_warning(path: &Path, level: PolicyLevel, metadata: &std::fs::Metadata) {
    use std::os::unix::fs::PermissionsExt;
    let mode = metadata.permissions().mode();
    if mode & 0o044 != 0 {
        warn!(
            path = %path.display(),
            level = %level,
            mode = format!("{:o}", mode),
            "policy file is readable by other users; consider `chmod 600`"
        );
    }
}

/// Reason a policy file failed metadata validation.
enum ValidationError {
    /// File does not exist (not an error — just absent).
    NotFound,
    /// I/O error reading metadata.
    IoError(String),
    /// Path is a directory, not a file.
    IsDirectory(String),
    /// File exceeds the size limit.
    TooLarge(String),
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValidationError::NotFound => write!(f, "file not found"),
            ValidationError::IoError(msg)
            | ValidationError::IsDirectory(msg)
            | ValidationError::TooLarge(msg) => write!(f, "{msg}"),
        }
    }
}

/// Try to load and validate a policy file, returning the evaluated JSON source
/// and a [`LoadedPolicy`] on success.
///
/// Returns `None` when the file is missing, is a directory, exceeds the size
/// limit, or fails Starlark evaluation. Writes diagnostics to `policy_error`
/// on evaluation failure.
pub fn try_load_policy(
    level: PolicyLevel,
    path: &Path,
    policy_error: &mut Option<String>,
) -> Option<ValidatedPolicy> {
    let _metadata = validate_policy_file(path, level)?;

    let is_json = path.extension().is_some_and(|ext| ext == "json");
    let result = if is_json {
        load_json_policy(path)
    } else {
        evaluate_star_policy(path)
    };

    match result {
        Ok(json_source) => {
            let loaded = LoadedPolicy {
                level,
                path: path.to_path_buf(),
                source: json_source.clone(),
            };
            Some(ValidatedPolicy {
                json_source,
                loaded,
            })
        }
        Err(e) => {
            let kind = if is_json { "JSON" } else { "starlark" };
            error!(
                path = %path.display(),
                level = %level,
                error = %e,
                "Failed to evaluate {kind} policy"
            );
            *policy_error = Some(format!("Failed to evaluate {}: {}", path.display(), e));
            None
        }
    }
}

/// Compile one or more evaluated policy JSON sources into a [`CompiledPolicy`] tree.
///
/// Each tuple is `(level, json_source, source_display_path)`.
/// When a single source is provided, uses `compile_to_tree`. When multiple
/// sources are provided, uses `compile_multi_level_to_tree` to merge them
/// with level-based precedence.
pub fn compile_policies(level_sources: &[(PolicyLevel, String, String)]) -> Result<CompiledPolicy> {
    let level_refs: Vec<(PolicyLevel, &str, &str)> = level_sources
        .iter()
        .map(|(l, s, p)| (*l, s.as_str(), p.as_str()))
        .collect();
    compile::compile_multi_level_to_tree(&level_refs)
}

/// Compile a raw policy JSON source string directly into a [`CompiledPolicy`] tree.
///
/// This is a thin wrapper around [`compile::compile_to_tree`] for callers that
/// have a single source string rather than level-tagged sources.
pub fn compile_source(source: &str) -> Result<CompiledPolicy> {
    compile::compile_to_tree(source)
}

/// Validate and load a policy file with full diagnostics, then compile it.
///
/// Produces detailed error messages suitable for surfacing to users.
/// Used by the test-only `load_policy_from_path` in settings.
#[cfg(test)]
pub fn load_and_compile_single(
    path: &Path,
    policy_error: &mut Option<String>,
) -> Option<CompiledPolicy> {
    let metadata = match validate_policy_file_with_diagnostics(path) {
        Ok(m) => m,
        Err(ValidationError::NotFound) => return None,
        Err(e) => {
            warn!(path = %path.display(), "Policy file invalid: {e}");
            *policy_error = Some(e.to_string());
            return None;
        }
    };

    #[cfg(unix)]
    check_permissions_warning(path, PolicyLevel::User, &metadata);
    #[cfg(not(unix))]
    let _ = metadata;

    let is_json = path.extension().is_some_and(|ext| ext == "json");
    let eval_result = if is_json {
        load_json_policy(path)
    } else {
        evaluate_star_policy(path)
    };

    match eval_result {
        Ok(json_source) => match compile::compile_to_tree(&json_source) {
            Ok(tree) => {
                info!(path = %path.display(), "Loaded policy");
                Some(tree)
            }
            Err(e) => {
                let msg = format!("Failed to compile policy: {}", e);
                warn!(path = %path.display(), error = %e, "Failed to compile policy");
                *policy_error = Some(msg);
                None
            }
        },
        Err(e) => {
            let msg = format!("Failed to evaluate policy: {}", e);
            warn!(path = %path.display(), error = %e, "Failed to evaluate policy");
            *policy_error = Some(msg);
            None
        }
    }
}

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

    #[test]
    fn load_json_policy_without_includes() {
        let dir = tempfile::tempdir().unwrap();
        let json_path = dir.path().join("policy.json");
        std::fs::write(
            &json_path,
            r#"{
                "default_effect": "deny",
                "sandboxes": {},
                "tree": [{
                    "condition": {
                        "observe": "tool_name",
                        "pattern": {"literal": {"literal": "Bash"}},
                        "children": [{"decision": {"allow": null}}]
                    }
                }]
            }"#,
        )
        .unwrap();

        let source = load_json_policy(&json_path).unwrap();
        let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();
        assert_eq!(policy.tree.len(), 1);
    }

    #[test]
    fn load_json_policy_with_star_include() {
        let dir = tempfile::tempdir().unwrap();

        // Write a local .star include file.
        let star_path = dir.path().join("extra.star");
        std::fs::write(
            &star_path,
            r#"
load("@clash//std.star", "tool", "policy", "deny")
def main():
    return policy(default = deny(), rules = [tool("Read").allow()])
"#,
        )
        .unwrap();

        // Write policy.json that includes extra.star and has its own inline rule.
        let json_path = dir.path().join("policy.json");
        std::fs::write(
            &json_path,
            r#"{
                "default_effect": "deny",
                "sandboxes": {},
                "includes": [{"path": "extra.star"}],
                "tree": [{
                    "condition": {
                        "observe": "tool_name",
                        "pattern": {"literal": {"literal": "Bash"}},
                        "children": [{"decision": {"allow": null}}]
                    }
                }]
            }"#,
        )
        .unwrap();

        let source = load_json_policy(&json_path).unwrap();
        let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();
        // Should have inline (Bash) + included (Read) rules.
        assert!(
            policy.tree.len() >= 2,
            "expected at least 2 rules, got {}",
            policy.tree.len()
        );
    }

    #[test]
    fn load_json_policy_with_stdlib_include() {
        let dir = tempfile::tempdir().unwrap();
        let json_path = dir.path().join("policy.json");
        std::fs::write(
            &json_path,
            r#"{
                "default_effect": "deny",
                "sandboxes": {},
                "includes": [{"path": "@clash//builtin.star"}],
                "tree": []
            }"#,
        )
        .unwrap();

        let source = load_json_policy(&json_path).unwrap();
        let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();
        // builtin.star exports rules for clash commands + claude tools.
        assert!(
            !policy.tree.is_empty(),
            "builtin.star should contribute rules"
        );
    }

    #[test]
    fn manifest_roundtrip() {
        let dir = tempfile::tempdir().unwrap();
        let json_path = dir.path().join("policy.json");

        let manifest = PolicyManifest {
            includes: vec![crate::policy::match_tree::IncludeEntry {
                path: "@clash//builtin.star".into(),
            }],
            policy: CompiledPolicy {
                sandboxes: std::collections::HashMap::new(),
                tree: vec![],
                default_effect: crate::policy::Effect::Deny,
                default_sandbox: None,
            },
        };

        write_manifest(&json_path, &manifest).unwrap();
        let loaded = read_manifest(&json_path).unwrap();
        assert_eq!(loaded.includes.len(), 1);
        assert_eq!(loaded.includes[0].path, "@clash//builtin.star");
    }

    #[test]
    fn migrate_legacy_string_caps_to_array() {
        let dir = tempfile::tempdir().unwrap();
        let json_path = dir.path().join("policy.json");
        std::fs::write(
            &json_path,
            r#"{
                "default_effect": "deny",
                "sandboxes": {
                    "dev": {
                        "default": "read + execute",
                        "rules": [
                            {
                                "effect": "allow",
                                "caps": "all - delete",
                                "path": "/tmp",
                                "path_match": "subpath"
                            }
                        ]
                    }
                },
                "tree": []
            }"#,
        )
        .unwrap();

        let source = load_json_policy(&json_path).unwrap();
        let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();

        // The sandbox should have parsed successfully after migration.
        let dev = policy.sandboxes.get("dev").expect("dev sandbox");
        assert_eq!(
            dev.default,
            crate::policy::sandbox_types::Cap::READ | crate::policy::sandbox_types::Cap::EXECUTE
        );
        assert_eq!(
            dev.rules[0].caps,
            crate::policy::sandbox_types::Cap::READ
                | crate::policy::sandbox_types::Cap::WRITE
                | crate::policy::sandbox_types::Cap::CREATE
                | crate::policy::sandbox_types::Cap::EXECUTE
        );

        // The file on disk should have been rewritten with array format.
        let on_disk: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&json_path).unwrap()).unwrap();
        let dev_default = &on_disk["sandboxes"]["dev"]["default"];
        assert!(dev_default.is_array(), "default should be an array on disk");
        let rule_caps = &on_disk["sandboxes"]["dev"]["rules"][0]["caps"];
        assert!(rule_caps.is_array(), "caps should be an array on disk");
    }

    #[test]
    fn no_migration_when_already_array_format() {
        let dir = tempfile::tempdir().unwrap();
        let json_path = dir.path().join("policy.json");
        let original = r#"{
                "default_effect": "deny",
                "sandboxes": {
                    "dev": {
                        "default": ["read", "execute"],
                        "rules": []
                    }
                },
                "tree": []
            }"#;
        std::fs::write(&json_path, original).unwrap();

        let _source = load_json_policy(&json_path).unwrap();

        // File should not have been rewritten (content preserved exactly).
        let on_disk = std::fs::read_to_string(&json_path).unwrap();
        assert_eq!(on_disk, original);
    }
}