eval-magic 0.6.0

One-stop CLI for running skill evals — measure whether an agent skill actually shifts behavior.
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! The write-guard engine: install + verdict rendered from a descriptor's
//! `[guard]` data block, with the install side selected by the block's
//! `engine` discriminator.
//!
//! `json-hooks` (Claude Code, Codex) merges one PreToolUse hook entry (the
//! descriptor's `hook_entry` JSON template) into the harness's hook-config
//! file (`hooks_file`). `opencode-plugin` stages an embedded JS project
//! plugin whole at `plugin_file` — OpenCode auto-loads project plugins by
//! directory convention, and the plugin blocks a tool call by throwing the
//! deny verdict's reason. Both arms stage the marker/manifest via
//! [`crate::sandbox::install`]. The verdict side is shared: it feeds a hook
//! payload through the shared arbiter ([`crate::sandbox::decide`]) and
//! serializes the descriptor's `verdict_template` on deny. Template key order
//! is authored in the descriptor and serialized verbatim (`serde_json` keeps
//! insertion order), so verdict bytes and hook-file shape are pinned by data,
//! not code.
//!
//! Guard blocks exist only in embedded built-in descriptors — the guard fails
//! open, so [`super::descriptor::layers::check_user_layer_restrictions`] bars
//! user layers from declaring one.

use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::time::Duration;

use serde_json::{Value, json};

use crate::sandbox::decide::{GuardMarker, decide};
use crate::sandbox::install::{
    GUARD_MANIFEST, GUARD_MARKER, write_json, write_manifest, write_marker,
};
use crate::sandbox::{now_ms, parse_tool_call};

use super::descriptor::{GuardEngine, GuardSection, subst};

/// Arm the write guard: marker + manifest under `skills_dir` (absolute,
/// resolved by the caller), then the engine-specific hook surface. Returns
/// the staged marker path.
///
/// Template parse failures panic (`expect`): descriptor validation proved the
/// templates at load time, and arming runs in the orchestrator where a loud
/// failure beats a silently unarmed guard.
pub(crate) fn install_guard(
    guard: &GuardSection,
    skills_dir: &Path,
    stage_root: &Path,
    guard_exe: &Path,
    ttl: Option<Duration>,
) -> io::Result<PathBuf> {
    fs::create_dir_all(skills_dir)?;

    let marker_path = skills_dir.join(GUARD_MARKER);
    write_marker(&marker_path, stage_root, ttl)?;

    match guard.engine {
        GuardEngine::JsonHooks => {
            install_json_hooks(guard, skills_dir, stage_root, guard_exe, &marker_path)
        }
        GuardEngine::OpencodePlugin => {
            install_opencode_plugin(guard, skills_dir, stage_root, guard_exe, &marker_path)
        }
    }
}

/// The embedded OpenCode project plugin. The `{exe}`/`{marker}` placeholders
/// substitute as JSON string literals (a JSON string is a valid JS string
/// literal), so any exe/marker path characters survive without hand-escaping.
/// The file's exact bytes are pinned in this module's tests — the staged
/// plugin is an on-disk contract.
const OPENCODE_GUARD_PLUGIN_TEMPLATE: &str =
    include_str!("../../harnesses/opencode-guard-plugin.js");

/// The opencode-plugin arm: the embedded JS template with `{exe}`/`{marker}`
/// substituted, staged whole at the descriptor's `plugin_file`. No merge —
/// OpenCode auto-loads project plugins by directory convention, and the
/// plugin blocks by throwing, so the file *is* the hook surface.
fn install_opencode_plugin(
    guard: &GuardSection,
    skills_dir: &Path,
    stage_root: &Path,
    guard_exe: &Path,
    marker_path: &Path,
) -> io::Result<PathBuf> {
    let plugin_path = resolve_rel(
        stage_root,
        guard
            .plugin_file
            .as_deref()
            .expect("guard.plugin_file is declared (proven at descriptor load)"),
    );
    if let Some(parent) = plugin_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let plugin_existed = plugin_path.exists();
    let backup = if plugin_existed {
        Some(fs::read_to_string(&plugin_path)?)
    } else {
        None
    };

    let exe = serde_json::to_string(&guard_exe.display().to_string())
        .expect("a path string serializes as JSON");
    let marker = serde_json::to_string(&marker_path.display().to_string())
        .expect("a path string serializes as JSON");
    let plugin = subst(
        OPENCODE_GUARD_PLUGIN_TEMPLATE,
        &[("exe", &exe), ("marker", &marker)],
    );
    fs::write(&plugin_path, plugin)?;

    write_manifest(
        &skills_dir.join(GUARD_MANIFEST),
        &plugin_path,
        plugin_existed,
        backup,
        marker_path,
    )?;

    Ok(marker_path.to_path_buf())
}

/// The json-hooks arm: one hook entry merged into the descriptor's
/// `hooks_file`.
fn install_json_hooks(
    guard: &GuardSection,
    skills_dir: &Path,
    stage_root: &Path,
    guard_exe: &Path,
    marker_path: &Path,
) -> io::Result<PathBuf> {
    let hooks_path = resolve_rel(
        stage_root,
        guard
            .hooks_file
            .as_deref()
            .expect("guard.hooks_file is declared (proven at descriptor load)"),
    );
    if let Some(parent) = hooks_path.parent() {
        fs::create_dir_all(parent)?;
    }
    let hooks_existed = hooks_path.exists();
    let backup = if hooks_existed {
        Some(fs::read_to_string(&hooks_path)?)
    } else {
        None
    };

    // Start from the existing hook config (or an empty object), preserving key
    // order, then append the rendered hook entry.
    let mut config: Value = backup
        .as_deref()
        .and_then(|s| serde_json::from_str(s).ok())
        .unwrap_or_else(|| json!({}));
    let exe = guard_exe.display().to_string();
    let marker = marker_path.display().to_string();
    let command = subst(
        guard
            .command_template
            .as_deref()
            .expect("guard.command_template is declared (proven at descriptor load)"),
        &[("exe", &exe), ("marker", &marker)],
    );
    let mut entry: Value = serde_json::from_str(
        guard
            .hook_entry
            .as_deref()
            .expect("guard.hook_entry is declared (proven at descriptor load)"),
    )
    .expect("guard.hook_entry parses as JSON (proven at descriptor load)");
    substitute_strings(
        &mut entry,
        &[
            (
                "matcher",
                guard
                    .matcher
                    .as_deref()
                    .expect("guard.matcher is declared (proven at descriptor load)"),
            ),
            ("command", &command),
        ],
    );

    let hooks = config
        .as_object_mut()
        .expect("hook config root is a JSON object")
        .entry("hooks")
        .or_insert_with(|| json!({}));
    let pre = hooks
        .as_object_mut()
        .expect("hooks is a JSON object")
        .entry("PreToolUse")
        .or_insert_with(|| json!([]));
    pre.as_array_mut()
        .expect("PreToolUse is an array")
        .push(entry);
    write_json(&hooks_path, &config)?;

    write_manifest(
        &skills_dir.join(GUARD_MANIFEST),
        &hooks_path,
        hooks_existed,
        backup,
        marker_path,
    )?;

    Ok(marker_path.to_path_buf())
}

/// Evaluate a PreToolUse hook `payload` against `marker`. Returns the deny
/// verdict to print on stdout (the descriptor's `verdict_template` with
/// `{reason}` filled), or `None` to allow (print nothing). Every error path —
/// empty/malformed payload, unrenderable template — fails open: the hook must
/// never brick a session.
pub(crate) fn guard_verdict(
    guard: &GuardSection,
    payload: &str,
    marker: Option<GuardMarker>,
) -> Option<String> {
    let (tool_name, tool_input) = parse_tool_call(payload)?;
    let decision = decide(&tool_name, &tool_input, marker.as_ref(), now_ms());
    if decision.allow {
        return None;
    }
    let mut verdict: Value = serde_json::from_str(&guard.verdict_template).ok()?;
    substitute_strings(
        &mut verdict,
        &[("reason", decision.reason.as_deref().unwrap_or(""))],
    );
    serde_json::to_string(&verdict).ok()
}

/// The hook-surface dir the install created outside the skills dir, which
/// teardown prunes when restoring the original file leaves it empty. Derived
/// from the data: the engine's staged file's parent dir (`hooks_file` for
/// json-hooks, `plugin_file` for opencode-plugin), unless the file is at the
/// env root (nothing to prune) or the parent is the skills dir or an ancestor
/// of it (staging already owns that tree).
pub(crate) fn hook_cleanup_dir(
    guard: &GuardSection,
    skills_dir_rel: Option<&str>,
    stage_root: &Path,
) -> Option<PathBuf> {
    let hook_file = match guard.engine {
        GuardEngine::JsonHooks => guard.hooks_file.as_deref(),
        GuardEngine::OpencodePlugin => guard.plugin_file.as_deref(),
    }?;
    let (parent, _) = hook_file.rsplit_once('/')?;
    if let Some(skills) = skills_dir_rel {
        // Component-wise ancestry: `.a` owns `.a/b/skills` but not `.ab/skills`.
        let is_ancestor = skills == parent
            || skills
                .strip_prefix(parent)
                .is_some_and(|rest| rest.starts_with('/'));
        if is_ancestor {
            return None;
        }
    }
    Some(resolve_rel(stage_root, parent))
}

/// True when any *string value* in `value` contains `token`. Descriptor
/// validation uses this to prove template placeholders sit where
/// [`substitute_strings`] will actually reach them (keys are never
/// substituted).
pub(crate) fn any_string_value_contains(value: &Value, token: &str) -> bool {
    match value {
        Value::String(s) => s.contains(token),
        Value::Array(items) => items.iter().any(|v| any_string_value_contains(v, token)),
        Value::Object(map) => map.values().any(|v| any_string_value_contains(v, token)),
        _ => false,
    }
}

/// Substitute `{token}` placeholders in every string value of `value`,
/// in place. Substituting after parsing (rather than into the template text)
/// lets values carry quotes without JSON-escaping concerns — the serializer
/// escapes them, exactly as `json!` used to.
fn substitute_strings(value: &mut Value, vars: &[(&str, &str)]) {
    match value {
        Value::String(s) if s.contains('{') => {
            *s = subst(s, vars);
        }
        Value::Array(items) => {
            for item in items {
                substitute_strings(item, vars);
            }
        }
        Value::Object(map) => {
            for item in map.values_mut() {
                substitute_strings(item, vars);
            }
        }
        _ => {}
    }
}

/// Resolve a `/`-separated descriptor-relative path under `root` — the same
/// idiom as [`super::descriptor_adapter::DescriptorAdapter::skills_dir`].
fn resolve_rel(root: &Path, rel: &str) -> PathBuf {
    rel.split('/')
        .fold(root.to_path_buf(), |path, segment| path.join(segment))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::adapters::descriptor::{EMBEDDED_DESCRIPTORS, HarnessDescriptor, load_descriptor};
    use crate::sandbox::guard_is_armed;
    use crate::sandbox::install::{iso_millis, teardown_guard};
    use chrono::DateTime;
    use tempfile::TempDir;

    struct Case {
        _tmp: TempDir,
        stage_root: PathBuf,
    }

    fn setup() -> Case {
        let tmp = TempDir::new().unwrap();
        let stage_root = tmp.path().join("stage");
        fs::create_dir_all(&stage_root).unwrap();
        Case {
            _tmp: tmp,
            stage_root,
        }
    }

    /// Load one embedded descriptor by label — engine tests run against the
    /// real shipped guard data, not fixtures.
    fn descriptor(label: &str) -> HarnessDescriptor {
        let (source, toml_src) = EMBEDDED_DESCRIPTORS
            .iter()
            .find(|(path, _)| path.ends_with(&format!("{label}.toml")))
            .unwrap_or_else(|| panic!("no embedded descriptor for {label}"));
        load_descriptor(toml_src, source).unwrap()
    }

    /// Arm the guard for `label` under `stage_root` via the engine, returning
    /// the marker path.
    fn install(label: &str, stage_root: &Path) -> PathBuf {
        let d = descriptor(label);
        let skills = resolve_rel(stage_root, d.skills_dir.as_deref().unwrap());
        install_guard(
            d.guard.as_ref().unwrap(),
            &skills,
            stage_root,
            Path::new("/g/eval-magic"),
            None,
        )
        .unwrap()
    }

    fn verdict(label: &str, payload: &str, marker: Option<GuardMarker>) -> Option<String> {
        let d = descriptor(label);
        guard_verdict(d.guard.as_ref().unwrap(), payload, marker)
    }

    fn claude_skills_dir(stage_root: &Path) -> PathBuf {
        stage_root.join(".claude").join("skills")
    }

    fn settings_path(stage_root: &Path) -> PathBuf {
        stage_root.join(".claude").join("settings.local.json")
    }

    fn codex_hooks_path(stage_root: &Path) -> PathBuf {
        stage_root.join(".codex").join("hooks.json")
    }

    fn read_json(path: &Path) -> Value {
        serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap()
    }

    fn absolutize(p: &Path) -> PathBuf {
        std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf())
    }

    /// A live marker (active, no expiry → unexpired) scoped to one root.
    fn marker() -> GuardMarker {
        GuardMarker {
            active: Some(true),
            allowed_roots: Some(vec!["/work/.eval-magic".to_string()]),
            expires_at: None,
        }
    }

    #[test]
    fn install_writes_an_active_marker_hook_and_manifest() {
        let c = setup();
        install("claude-code", &c.stage_root);

        let marker = read_json(&claude_skills_dir(&c.stage_root).join(GUARD_MARKER));
        assert_eq!(marker["active"], json!(true));
        let expires = marker["expiresAt"].as_str().unwrap();
        let exp_ms = DateTime::parse_from_rfc3339(expires)
            .unwrap()
            .timestamp_millis();
        assert!(exp_ms > now_ms());
        let env = absolutize(&c.stage_root).display().to_string();
        assert!(
            marker["allowedRoots"]
                .as_array()
                .unwrap()
                .iter()
                .any(|r| r.as_str().unwrap() == env)
        );

        let settings = read_json(&settings_path(&c.stage_root));
        let hook = &settings["hooks"]["PreToolUse"][0];
        assert!(hook["matcher"].as_str().unwrap().contains("Write"));
        assert!(
            hook["hooks"][0]["command"]
                .as_str()
                .unwrap()
                .contains("guard")
        );

        assert!(
            claude_skills_dir(&c.stage_root)
                .join(GUARD_MANIFEST)
                .exists()
        );
    }

    #[test]
    fn marker_scopes_allowed_roots_to_the_env_and_temp_only() {
        let c = setup();
        install("claude-code", &c.stage_root);

        let marker = read_json(&claude_skills_dir(&c.stage_root).join(GUARD_MARKER));
        let roots: Vec<String> = marker["allowedRoots"]
            .as_array()
            .unwrap()
            .iter()
            .map(|r| r.as_str().unwrap().to_string())
            .collect();

        // The guard boundary is the isolated env (stage_root) plus temp — nothing
        // above it. The parent workspace tree must NOT be an allowed root, or the
        // agent could write into sibling iterations / the meta dir above `env/`.
        let env = absolutize(&c.stage_root).display().to_string();
        let temp = absolutize(&std::env::temp_dir()).display().to_string();
        assert_eq!(roots, vec![env, temp]);
        assert!(
            !roots.iter().any(|r| r.ends_with(".eval-magic")),
            "workspace_root must not be an allowed root: {roots:?}"
        );
    }

    #[test]
    fn hook_command_invokes_the_binary_guard_subcommand() {
        let c = setup();
        let marker = install("claude-code", &c.stage_root);
        let settings = read_json(&settings_path(&c.stage_root));
        let command = settings["hooks"]["PreToolUse"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap()
            .to_string();
        assert_eq!(
            command,
            format!("\"/g/eval-magic\" guard \"{}\"", marker.display())
        );
    }

    #[test]
    fn teardown_deletes_settings_it_created() {
        let c = setup();
        install("claude-code", &c.stage_root);
        assert!(settings_path(&c.stage_root).exists());

        assert!(teardown_guard(&c.stage_root));
        assert!(!settings_path(&c.stage_root).exists());
        assert!(!claude_skills_dir(&c.stage_root).join(GUARD_MARKER).exists());
        assert!(
            !claude_skills_dir(&c.stage_root)
                .join(GUARD_MANIFEST)
                .exists()
        );
    }

    #[test]
    fn teardown_restores_a_pre_existing_settings_verbatim() {
        let c = setup();
        fs::create_dir_all(c.stage_root.join(".claude")).unwrap();
        let original = format!(
            "{}\n",
            serde_json::to_string_pretty(&json!({
                "permissions": { "allow": ["Bash(ls)"] }
            }))
            .unwrap()
        );
        fs::write(settings_path(&c.stage_root), &original).unwrap();

        install("claude-code", &c.stage_root);
        // hook present while armed
        assert!(
            fs::read_to_string(settings_path(&c.stage_root))
                .unwrap()
                .contains("PreToolUse")
        );

        teardown_guard(&c.stage_root);
        assert_eq!(
            fs::read_to_string(settings_path(&c.stage_root)).unwrap(),
            original
        );
    }

    #[test]
    fn guard_is_armed_ignores_missing_inactive_expired_and_malformed_markers() {
        let c = setup();
        let marker_path = claude_skills_dir(&c.stage_root).join(GUARD_MARKER);
        fs::create_dir_all(claude_skills_dir(&c.stage_root)).unwrap();

        assert!(!guard_is_armed(&c.stage_root));

        fs::write(
            &marker_path,
            serde_json::to_string(&json!({ "active": false })).unwrap(),
        )
        .unwrap();
        assert!(!guard_is_armed(&c.stage_root));

        fs::write(
            &marker_path,
            serde_json::to_string(&json!({
                "active": true,
                "expiresAt": iso_millis(now_ms() - 60_000),
            }))
            .unwrap(),
        )
        .unwrap();
        assert!(!guard_is_armed(&c.stage_root));

        fs::write(&marker_path, "not json").unwrap();
        assert!(!guard_is_armed(&c.stage_root));
    }

    #[test]
    fn teardown_sweeps_a_stray_marker_even_without_a_manifest() {
        let c = setup();
        fs::create_dir_all(claude_skills_dir(&c.stage_root)).unwrap();
        fs::write(claude_skills_dir(&c.stage_root).join(GUARD_MARKER), "{}").unwrap();
        assert!(teardown_guard(&c.stage_root));
        assert!(!claude_skills_dir(&c.stage_root).join(GUARD_MARKER).exists());
    }

    #[test]
    fn allows_returns_none() {
        let payload = r#"{ "tool_name": "Read", "tool_input": { "file_path": "/etc/passwd" } }"#;
        assert_eq!(verdict("claude-code", payload, Some(marker())), None);
    }

    #[test]
    fn deny_returns_pretooluse_deny_json() {
        let payload = r#"{ "tool_name": "Write", "tool_input": { "file_path": "/etc/passwd" } }"#;
        let out = verdict("claude-code", payload, Some(marker())).expect("should deny");
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["hookSpecificOutput"]["hookEventName"], "PreToolUse");
        assert_eq!(v["hookSpecificOutput"]["permissionDecision"], "deny");
        assert!(
            v["hookSpecificOutput"]["permissionDecisionReason"]
                .as_str()
                .unwrap()
                .contains("outside")
        );
    }

    /// Byte-pin of both deny verdicts: full-string equality against the exact
    /// serialization armed hooks have always read. Key order comes from the
    /// descriptor templates and must never drift.
    #[test]
    fn deny_verdict_bytes_match_the_on_disk_contract() {
        let payload = r#"{ "tool_name": "Write", "tool_input": { "file_path": "/etc/passwd" } }"#;
        assert_eq!(
            verdict("claude-code", payload, Some(marker())).expect("should deny"),
            "{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\
             \"permissionDecision\":\"deny\",\"permissionDecisionReason\":\
             \"eval guard: Write to /etc/passwd is outside the eval sandbox \
             (allowed: /work/.eval-magic)\"}}"
        );

        let payload =
            r#"{ "tool_name": "Bash", "tool_input": { "command": "npm install left-pad" } }"#;
        assert_eq!(
            verdict("codex", payload, Some(marker())).expect("should block"),
            "{\"decision\":\"block\",\"reason\":\"eval guard: blocked Bash \
             (package install/add) — runs outside the eval sandbox\"}"
        );
    }

    #[test]
    fn no_marker_allows_everything() {
        let payload = r#"{ "tool_name": "Write", "tool_input": { "file_path": "/etc/passwd" } }"#;
        assert_eq!(verdict("claude-code", payload, None), None);
    }

    #[test]
    fn empty_or_malformed_payload_fails_open() {
        assert_eq!(verdict("claude-code", "", Some(marker())), None);
        assert_eq!(verdict("claude-code", "not json", Some(marker())), None);
    }

    #[test]
    fn codex_install_writes_project_hook_marker_and_manifest() {
        let c = setup();
        install("codex", &c.stage_root);

        let marker = read_json(
            &c.stage_root
                .join(".agents")
                .join("skills")
                .join(GUARD_MARKER),
        );
        assert_eq!(marker["active"], json!(true));
        // The Codex guard shares the env-scoped roots: the staged `.agents/skills`
        // dir lives inside `stage_root`, so the single env root already covers it.
        let env = absolutize(&c.stage_root).display().to_string();
        assert!(
            marker["allowedRoots"]
                .as_array()
                .unwrap()
                .iter()
                .any(|r| r.as_str().unwrap() == env)
        );

        let hooks = read_json(&codex_hooks_path(&c.stage_root));
        let hook = &hooks["hooks"]["PreToolUse"][0];
        assert!(hook["matcher"].as_str().unwrap().contains("apply_patch"));
        assert!(
            hook["hooks"][0]["command"]
                .as_str()
                .unwrap()
                .contains("guard-codex")
        );
        assert!(
            c.stage_root
                .join(".agents")
                .join("skills")
                .join(GUARD_MANIFEST)
                .exists()
        );
    }

    #[test]
    fn codex_teardown_restores_pre_existing_hooks_json_verbatim() {
        let c = setup();
        fs::create_dir_all(c.stage_root.join(".codex")).unwrap();
        let original = format!(
            "{}\n",
            serde_json::to_string_pretty(&json!({
                "hooks": {
                    "PostToolUse": [
                        {
                            "matcher": "Bash",
                            "hooks": [{ "type": "command", "command": "echo ok" }]
                        }
                    ]
                }
            }))
            .unwrap()
        );
        fs::write(codex_hooks_path(&c.stage_root), &original).unwrap();

        install("codex", &c.stage_root);
        assert!(
            fs::read_to_string(codex_hooks_path(&c.stage_root))
                .unwrap()
                .contains("guard-codex")
        );

        teardown_guard(&c.stage_root);
        assert_eq!(
            fs::read_to_string(codex_hooks_path(&c.stage_root)).unwrap(),
            original
        );
    }

    #[test]
    fn codex_deny_returns_decision_block_json() {
        let payload = r#"{ "hook_event_name": "PreToolUse", "tool_name": "Bash", "tool_input": { "command": "npm install left-pad" } }"#;
        let out = verdict("codex", payload, Some(marker())).expect("should block");
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["decision"], "block");
        assert!(v["reason"].as_str().unwrap().contains("blocked Bash"));
    }

    #[test]
    fn codex_apply_patch_outside_allowed_roots_blocks() {
        let payload = r#"{ "hook_event_name": "PreToolUse", "tool_name": "apply_patch", "tool_input": { "files": ["/etc/passwd"] } }"#;
        let out = verdict("codex", payload, Some(marker())).expect("should block");
        let v: Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["decision"], "block");
        assert!(v["reason"].as_str().unwrap().contains("apply_patch"));
    }

    #[test]
    fn codex_apply_patch_inside_allowed_roots_allows() {
        let payload = r#"{ "hook_event_name": "PreToolUse", "tool_name": "apply_patch", "tool_input": { "files": ["/work/.eval-magic/out.md"] } }"#;
        assert_eq!(verdict("codex", payload, Some(marker())), None);
    }

    /// The cleanup dir is derived from the guard data: the hook surface file's
    /// parent, unless the file sits at the env root or inside the skills dir's
    /// ancestry (staging already owns that tree).
    #[test]
    fn hook_cleanup_dir_derivation_table() {
        let root = Path::new("/env");
        let with = |hooks_file: &str| {
            let mut guard = descriptor("codex").guard.unwrap();
            guard.hooks_file = Some(hooks_file.to_string());
            guard
        };
        let with_plugin = |plugin_file: &str| {
            let mut guard = descriptor("opencode").guard.unwrap();
            guard.plugin_file = Some(plugin_file.to_string());
            guard
        };

        // Claude: `.claude` is the skills dir's parent — staging owns it.
        assert_eq!(
            hook_cleanup_dir(
                &with(".claude/settings.local.json"),
                Some(".claude/skills"),
                root
            ),
            None
        );
        // Codex: `.codex` is created for the hook alone — prune it.
        assert_eq!(
            hook_cleanup_dir(&with(".codex/hooks.json"), Some(".agents/skills"), root),
            Some(PathBuf::from("/env/.codex"))
        );
        // Hook file at the env root: never prune the env itself.
        assert_eq!(
            hook_cleanup_dir(&with("hooks.json"), Some(".agents/skills"), root),
            None
        );
        // Parent is an ancestor of the skills dir (not merely a string prefix:
        // `.a` vs `.ab/skills` stays prunable).
        assert_eq!(
            hook_cleanup_dir(&with(".a/hooks.json"), Some(".a/b/skills"), root),
            None
        );
        assert_eq!(
            hook_cleanup_dir(&with(".a/hooks.json"), Some(".ab/skills"), root),
            Some(PathBuf::from("/env/.a"))
        );

        // OpenCode: `.opencode/plugins` is created for the plugin alone (the
        // skills dir is its sibling, not inside it) — prune it.
        assert_eq!(
            hook_cleanup_dir(
                &with_plugin(".opencode/plugins/slow-powers-eval-guard.js"),
                Some(".opencode/skills"),
                root
            ),
            Some(PathBuf::from("/env/.opencode/plugins"))
        );
        // A plugin file directly under the skills dir's ancestor stays.
        assert_eq!(
            hook_cleanup_dir(
                &with_plugin(".opencode/guard.js"),
                Some(".opencode/skills"),
                root
            ),
            None
        );
        // Plugin file at the env root: never prune the env itself.
        assert_eq!(
            hook_cleanup_dir(&with_plugin("guard.js"), Some(".opencode/skills"), root),
            None
        );
    }

    // ── opencode-plugin engine ────────────────────────────────────────────

    fn opencode_skills_dir(stage_root: &Path) -> PathBuf {
        stage_root.join(".opencode").join("skills")
    }

    fn opencode_plugin_path(stage_root: &Path) -> PathBuf {
        stage_root
            .join(".opencode")
            .join("plugins")
            .join("slow-powers-eval-guard.js")
    }

    /// The staged plugin file, byte-for-byte: the embedded template with
    /// `{exe}`/`{marker}` substituted as JSON string literals. Written out
    /// here in full so any template edit forces a reviewed re-pin — the file
    /// is the on-disk contract armed envs run.
    const EXPECTED_PLUGIN_TEMPLATE: &str = r#"// slow-powers eval write guard — staged by `eval-magic` into this env's
// project plugins; removed by `eval-magic teardown-guard` (or the next run).
// Do not edit: re-staging overwrites, and teardown restores the original.
//
// Dumb forwarder by design: every tool call goes to
// `eval-magic guard-hook --harness opencode <marker>` on stdin and the shared
// arbiter inside the binary classifies it. Empty stdout allows; non-empty
// stdout is the deny verdict JSON whose reason blocks the call.
import { spawnSync } from "node:child_process";

const EXE = {exe};
const MARKER = {marker};

export const SlowPowersEvalGuard = async () => {
  return {
    "tool.execute.before": async (input, output) => {
      const payload = JSON.stringify({
        tool_name: input.tool,
        tool_input: output?.args ?? {},
      });
      const result = spawnSync(EXE, ["guard-hook", "--harness", "opencode", MARKER], {
        input: payload,
        encoding: "utf8",
        timeout: 10000,
        stdio: ["pipe", "pipe", "ignore"],
      });
      const stdout = (result.stdout ?? "").trim();
      if (!stdout) {
        return; // allow — also the fail-open path on spawn error or timeout
      }
      let reason = stdout;
      try {
        const verdict = JSON.parse(stdout);
        if (typeof verdict?.reason === "string") {
          reason = verdict.reason;
        }
      } catch {
        // Not the verdict shape — surface the raw stdout as the reason.
      }
      throw new Error(reason);
    },
  };
};
"#;

    fn expected_plugin(marker_path: &Path) -> String {
        let exe = serde_json::to_string("/g/eval-magic").unwrap();
        let marker = serde_json::to_string(&marker_path.display().to_string()).unwrap();
        subst(
            EXPECTED_PLUGIN_TEMPLATE,
            &[("exe", &exe), ("marker", &marker)],
        )
    }

    #[test]
    fn opencode_install_stages_the_byte_exact_plugin_marker_and_manifest() {
        let c = setup();
        let marker_path = install("opencode", &c.stage_root);

        let marker = read_json(&opencode_skills_dir(&c.stage_root).join(GUARD_MARKER));
        assert_eq!(marker["active"], json!(true));
        let env = absolutize(&c.stage_root).display().to_string();
        assert!(
            marker["allowedRoots"]
                .as_array()
                .unwrap()
                .iter()
                .any(|r| r.as_str().unwrap() == env)
        );

        let plugin = fs::read_to_string(opencode_plugin_path(&c.stage_root)).unwrap();
        assert_eq!(plugin, expected_plugin(&marker_path));
        // The substitution lands the generic guard-hook entry point with the
        // opencode harness and the staged marker path.
        assert!(plugin.contains("\"guard-hook\""), "{plugin}");
        assert!(plugin.contains("\"opencode\""), "{plugin}");

        assert!(
            opencode_skills_dir(&c.stage_root)
                .join(GUARD_MANIFEST)
                .exists()
        );
    }

    #[test]
    fn opencode_teardown_removes_the_plugin_and_prunes_the_plugins_dir() {
        let c = setup();
        install("opencode", &c.stage_root);
        assert!(opencode_plugin_path(&c.stage_root).exists());

        assert!(teardown_guard(&c.stage_root));
        assert!(!opencode_plugin_path(&c.stage_root).exists());
        assert!(
            !c.stage_root.join(".opencode").join("plugins").exists(),
            "the dir created for the plugin alone is pruned"
        );
        assert!(
            !opencode_skills_dir(&c.stage_root)
                .join(GUARD_MARKER)
                .exists()
        );
        assert!(
            !opencode_skills_dir(&c.stage_root)
                .join(GUARD_MANIFEST)
                .exists()
        );
    }

    #[test]
    fn opencode_teardown_restores_a_pre_existing_plugin_verbatim() {
        let c = setup();
        fs::create_dir_all(c.stage_root.join(".opencode").join("plugins")).unwrap();
        let original = "// the user's own plugin\nexport const Theirs = async () => ({});\n";
        fs::write(opencode_plugin_path(&c.stage_root), original).unwrap();

        install("opencode", &c.stage_root);
        assert!(
            fs::read_to_string(opencode_plugin_path(&c.stage_root))
                .unwrap()
                .contains("SlowPowersEvalGuard")
        );

        teardown_guard(&c.stage_root);
        assert_eq!(
            fs::read_to_string(opencode_plugin_path(&c.stage_root)).unwrap(),
            original
        );
    }

    /// Byte-pin of the opencode deny verdict: the verdict path is the shared
    /// `guard-hook` rendering, so this characterizes the shape the staged
    /// plugin parses (`decision`/`reason`) against the real descriptor data.
    #[test]
    fn opencode_deny_verdict_bytes_match_the_on_disk_contract() {
        let payload = r#"{ "tool_name": "write", "tool_input": { "filePath": "/etc/passwd" } }"#;
        assert_eq!(
            verdict("opencode", payload, Some(marker())).expect("should block"),
            "{\"decision\":\"block\",\"reason\":\"eval guard: write to /etc/passwd is \
             outside the eval sandbox (allowed: /work/.eval-magic)\"}"
        );
    }

    #[test]
    fn opencode_allows_an_in_bounds_write() {
        let payload =
            r#"{ "tool_name": "write", "tool_input": { "filePath": "/work/.eval-magic/out.md" } }"#;
        assert_eq!(verdict("opencode", payload, Some(marker())), None);
    }
}