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
//! OpenCode-harness behavior: `.opencode/skills` staging, slug sanitization,
//! native `<available_skills>` dispatch rendering, plan-mode approximation, and
//! the write guard's project-plugin install. Characterization tests pinning
//! current behavior so the run-mode refactor stays behavior-preserving.

use crate::helpers::*;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use std::fs;
use std::path::Path;

/// The sanitized slug the staged skill-under-test gets for `(iteration 1,
/// with_skill, mr-review)`: underscores in the condition become hyphens.
const OPENCODE_SLUG: &str = "slow-powers-eval-1-with-skill-mr-review";

#[test]
fn opencode_no_stage_keeps_inline_fallback() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
            "--no-stage",
            "--dry-run",
        ])
        .assert()
        .success();

    let dispatch = read_json(&iteration_dir(&cwd).join("dispatch.json"));
    let conditions = read_json(&iteration_dir(&cwd).join("conditions.json"));
    assert_eq!(dispatch["harness"], "opencode");
    assert_eq!(conditions["harness"], "opencode");
    assert!(!cwd.join(".claude/skills").exists());
    assert!(!cwd.join(".agents/skills").exists());
    assert!(!cwd.join(".opencode/skills").exists());
}

#[test]
fn opencode_stages_repo_local_skills_under_opencode() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    let helper = skill_dir.join("release-notes");
    fs::create_dir_all(&helper).unwrap();
    fs::write(
        helper.join("SKILL.md"),
        "---\nname: release-notes\ndescription: draft release notes\n---\n\nnotes\n",
    )
    .unwrap();
    fs::write(helper.join("helper.md"), "helper guidance").unwrap();

    skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
            "--dry-run",
        ])
        .assert()
        .success();

    // OpenCode rides Cli dispatch → per-(group, condition) envs; the skill stages
    // into the with_skill env.
    let opencode_skills = cli_env_dir(&cwd, "g1", "with_skill").join(".opencode/skills");
    assert!(
        read_str(&opencode_skills.join(OPENCODE_SLUG).join("SKILL.md"))
            .contains(&format!("name: {OPENCODE_SLUG}"))
    );
    assert_eq!(
        read_str(&opencode_skills.join("release-notes/helper.md")),
        "helper guidance"
    );
    assert!(!opencode_skills.join("release-notes/evals").exists());
    assert!(!cwd.join(".claude/skills").exists());
    assert!(!cwd.join(".agents/skills").exists());

    let dispatch = read_json(&iteration_dir(&cwd).join("dispatch.json"));
    let task = dispatch["tasks"]
        .as_array()
        .unwrap()
        .iter()
        .find(|t| t["condition"] == "with_skill")
        .unwrap();
    let prompt = read_str(Path::new(task["dispatch_prompt_path"].as_str().unwrap()));
    // OpenCode's native skill surface: an <available_skills> XML block. The
    // skill-under-test is advertised under its staged slug — OpenCode's skill
    // tool lists frontmatter names, and staging rewrites the frontmatter `name:`
    // to the slug (siblings keep their natural names).
    assert!(prompt.contains("<available_skills>"));
    assert!(prompt.contains("</available_skills>"));
    assert!(prompt.contains(&format!("<name>{OPENCODE_SLUG}</name>")));
    assert!(!prompt.contains("<name>mr-review</name>"));
    assert!(prompt.contains("<description>review merge requests</description>"));
    assert!(prompt.contains("<name>release-notes</name>"));
    assert!(prompt.contains("<description>draft release notes</description>"));
    // Neutral slug-disambiguation framing for OpenCode points at the real identifier.
    assert!(prompt.contains(&format!("identifier `{OPENCODE_SLUG}`")));
    assert!(prompt.contains("as an OpenCode skill"));
    // Must not leak the Claude Code or Codex skill surfaces.
    assert!(!prompt.contains("The following skills are available for use with the Skill tool:"));
    assert!(!prompt.contains("## Skills"));
}

#[test]
fn opencode_plan_mode_injects_profile_and_records_flag() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
            "--plan-mode",
            "--dry-run",
        ])
        .assert()
        .success();

    let dispatch = read_json(&iteration_dir(&cwd).join("dispatch.json"));
    assert_eq!(dispatch["plan_mode"], true);
    for task in dispatch["tasks"].as_array().unwrap() {
        let prompt = read_str(Path::new(task["dispatch_prompt_path"].as_str().unwrap()));
        if task["condition"] == "with_skill" {
            assert!(prompt.contains("<available_skills>"));
        }
        assert!(prompt.contains("<system-reminder>"));
        // Shared, harness-agnostic profile: same text every harness sees.
        assert!(prompt.contains("Plan mode is active"));
        assert!(!prompt.contains("ExitPlanMode"));
    }
}

#[test]
fn opencode_guard_installs_project_plugin() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
            "--guard",
        ])
        .assert()
        .success();

    // The guard installs into each per-(group, condition) env (the
    // agent-under-test's cwd): the project plugin OpenCode auto-loads at
    // startup, plus the marker that arms the arbiter.
    for condition in ["with_skill", "without_skill"] {
        let env = cli_env_dir(&cwd, "g1", condition);
        let plugin = env.join(".opencode/plugins/slow-powers-eval-guard.js");
        let content = read_str(&plugin);
        assert!(
            content.contains("guard-hook"),
            "{condition}: the plugin forwards to the guard-hook entry point: {content}"
        );
        assert!(
            content.contains(r#""opencode""#),
            "{condition}: the plugin names the opencode harness: {content}"
        );
        assert!(
            content.contains("tool.execute.before"),
            "{condition}: the plugin hooks tool.execute.before: {content}"
        );
        assert!(
            env.join(".opencode/skills/.slow-powers-eval-guard.json")
                .exists(),
            "{condition}: guard marker staged"
        );
    }
}

#[test]
fn opencode_default_run_auto_arms_guard() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    // No guard flag: opencode declares guard support, so the bare run arms it
    // (#126 — enhancements are provided, not opted into) and prints the armed
    // banner naming the plugin file.
    let assert = skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.contains("guard: armed"),
        "the run plan reports the armed guard: {stdout}"
    );
    assert!(
        stdout.contains(".opencode/plugins/slow-powers-eval-guard.js"),
        "the armed banner names the plugin file: {stdout}"
    );

    assert!(
        cli_env_dir(&cwd, "g1", "with_skill")
            .join(".opencode/plugins/slow-powers-eval-guard.js")
            .exists(),
        "opencode guard plugin staged in the env"
    );
}

#[test]
fn opencode_no_guard_installs_no_plugin() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    let assert = skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
            "--no-guard",
        ])
        .assert()
        .success();
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(
        !stdout.contains("guard: armed"),
        "opted out, so no armed guard in the run plan: {stdout}"
    );

    let env = cli_env_dir(&cwd, "g1", "with_skill");
    assert!(
        !env.join(".opencode/plugins/slow-powers-eval-guard.js")
            .exists()
    );
    assert!(
        !env.join(".opencode/skills/.slow-powers-eval-guard.json")
            .exists()
    );
}

#[test]
fn opencode_rejects_invalid_stage_name() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
            "--stage-name",
            "Bad_Name",
            "--dry-run",
        ])
        .assert()
        .failure()
        .stderr(contains("OpenCode skill name \"Bad_Name\" is invalid"));
}

#[test]
fn opencode_warns_when_live_skill_shadows_staged_skill() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    let fake_home = tmp.path().join("home");
    // The cross-harness vector: a skill installed for Claude Code is visible
    // to OpenCode sessions by default.
    let live_skill = fake_home.join(".claude/skills/different-folder");
    fs::create_dir_all(&live_skill).unwrap();
    fs::write(
        live_skill.join("SKILL.md"),
        "---\nname: mr-review\ndescription: installed copy\n---\n\nlive\n",
    )
    .unwrap();

    skill_eval()
        .current_dir(&cwd)
        .env("HOME", &fake_home)
        .env("XDG_CONFIG_HOME", fake_home.join("xdg"))
        .env("OPENCODE_CONFIG_DIR", tmp.path().join("opencode-config"))
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args(["--skill", "mr-review", "--harness", "opencode", "--dry-run"])
        .assert()
        .success()
        .stderr(contains("OpenCode skill-shadow warning"))
        .stderr(contains("opencode run"))
        .stderr(contains("docs/opencode-notes.md"));

    let report = read_json(&iteration_dir(&cwd).join("plugin-shadow.json"));
    assert_eq!(report["shadowed"][0]["kind"], "global-skill");
    assert_eq!(report["shadowed"][0]["skill_name"], "mr-review");
    assert_eq!(
        report["shadowed"][0]["path"],
        live_skill.to_string_lossy().as_ref()
    );
}

/// Resolve a dispatch.json path field (absolute, or relative to the run cwd).
fn resolve(cwd: &Path, path: &str) -> std::path::PathBuf {
    let path = Path::new(path);
    if path.is_absolute() {
        path.to_path_buf()
    } else {
        cwd.join(path)
    }
}

/// The tasks[] array from the iteration's dispatch.json.
fn dispatch_tasks(cwd: &Path) -> Vec<serde_json::Value> {
    read_json(&iteration_dir(cwd).join("dispatch.json"))["tasks"]
        .as_array()
        .expect("dispatch.json carries tasks[]")
        .clone()
}

#[test]
fn opencode_ingest_parses_events_and_code_checks_the_skill_invocation() {
    let tmp = tempfile::TempDir::new().unwrap();
    let (skill_dir, cwd) = setup(tmp.path(), DEFAULT_EVALS);
    skill_eval()
        .current_dir(&cwd)
        .args(["run", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--mode",
            "new-skill",
            "--harness",
            "opencode",
        ])
        .assert()
        .success();

    // Simulate `opencode run --format json` dispatches: a bash call, the staged
    // skill loaded through the native `skill` tool, two text parts, and a
    // step_finish token report. No final-message.md — the transcript's last
    // text is the final-message fallback.
    for task in dispatch_tasks(&cwd) {
        let outputs = resolve(&cwd, task["outputs_dir"].as_str().unwrap());
        fs::create_dir_all(&outputs).unwrap();
        let slug_line = format!(
            r#"{{"type":"tool_use","timestamp":3000,"sessionID":"ses_1","part":{{"id":"p3","type":"tool","tool":"skill","state":{{"status":"completed","input":{{"name":"{OPENCODE_SLUG}"}},"output":"<skill/>","title":"skill","metadata":{{}},"time":{{"start":2900,"end":3000}}}}}}}}"#
        );
        fs::write(
            outputs.join("opencode-events.jsonl"),
            [
                r#"{"type":"step_start","timestamp":1000,"sessionID":"ses_1","part":{"id":"p1","type":"step-start"}}"#.to_string(),
                r#"{"type":"tool_use","timestamp":2000,"sessionID":"ses_1","part":{"id":"p2","type":"tool","tool":"bash","state":{"status":"completed","input":{"command":"ls"},"output":"ok","title":"ls","metadata":{},"time":{"start":1900,"end":2000}}}}"#.to_string(),
                slug_line,
                r#"{"type":"text","timestamp":4000,"sessionID":"ses_1","part":{"id":"p4","type":"text","text":"First."}}"#.to_string(),
                r#"{"type":"text","timestamp":5000,"sessionID":"ses_1","part":{"id":"p5","type":"text","text":"Final."}}"#.to_string(),
                r#"{"type":"step_finish","timestamp":6000,"sessionID":"ses_1","part":{"id":"p6","type":"step-finish","reason":"stop","cost":0.002,"tokens":{"input":100,"output":20,"reasoning":5,"cache":{"read":75,"write":0}}}}"#.to_string(),
            ]
            .join("\n")
                + "\n",
        )
        .unwrap();
    }

    skill_eval()
        .current_dir(&cwd)
        .args(["ingest", "--skill-dir"])
        .arg(&skill_dir)
        .args([
            "--skill",
            "mr-review",
            "--harness",
            "opencode",
            "--iteration",
            "1",
        ])
        .assert()
        .success()
        .stderr(contains("no transcript parser").not());

    for task in dispatch_tasks(&cwd) {
        let record = read_json(&resolve(&cwd, task["run_record_path"].as_str().unwrap()));
        let invocations = record["tool_invocations"].as_array().unwrap();
        assert_eq!(
            invocations
                .iter()
                .map(|i| i["name"].as_str().unwrap())
                .collect::<Vec<_>>(),
            ["bash", "skill"],
            "{record}"
        );
        assert_eq!(
            invocations[1]["args"],
            serde_json::json!({"name": OPENCODE_SLUG})
        );
        assert_eq!(
            record["final_message"], "Final.",
            "the transcript's last text is the final-message fallback: {record}"
        );

        let timing = read_json(&resolve(&cwd, task["timing_path"].as_str().unwrap()));
        assert_eq!(timing["total_tokens"], 125, "{timing}");
        assert_eq!(timing["duration_ms"], 5_000, "{timing}");

        if task["condition"] == "with_skill" {
            let meta = read_json(
                &resolve(&cwd, task["run_record_path"].as_str().unwrap())
                    .parent()
                    .unwrap()
                    .join("judge-responses/__skill_invoked.json"),
            );
            assert_eq!(meta["passed"], true, "{meta}");
            assert_eq!(meta["grader"], "transcript_check", "{meta}");
        }
    }
}