eval-magic 0.5.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
//! Cross-field descriptor invariants — the load-time form of the old
//! cross-harness adapter tests, applied to every descriptor so user-supplied
//! files inherit the same checks as the built-ins.

use regex::Regex;

use crate::adapters::guard;

use super::{DescriptorError, HarnessDescriptor, render_staged_slug, stage_name_error};

/// The placeholders a slug template must carry to keep cleanup prefix-scans
/// and per-cell uniqueness working.
const SLUG_PLACEHOLDERS: [&str; 4] = ["{prefix}", "{iteration}", "{condition}", "{skill_name}"];

/// Check every cross-field invariant, returning the first violation with an
/// actionable message.
pub(super) fn validate_descriptor(
    d: &HarnessDescriptor,
    source: &str,
) -> Result<(), DescriptorError> {
    let fail = |message: String| {
        Err(DescriptorError::Invariant {
            path: source.to_string(),
            message,
        })
    };

    // Guard capability and post-arm banner move in lockstep: `--guard` gates
    // on the capability, and an armed guard the user is never told about (or a
    // banner with no guard behind it) misleads the dispatch session.
    if d.run.supports_guard != d.guard.is_some() {
        return fail(format!(
            "run.supports_guard is {} but the [guard] table is {}; the guard capability and \
             the armed banner must move in lockstep — declare both or neither",
            d.run.supports_guard,
            if d.guard.is_some() {
                "present"
            } else {
                "absent"
            },
        ));
    }

    // Native staging and the write guard both live under the skills dir:
    // staging copies skills into it, and the guard keeps its marker/manifest
    // there. Without a skills_dir neither has anywhere to operate.
    if d.skills_dir.is_none() {
        if d.staging.is_configured() {
            return fail(
                "[staging] is configured but skills_dir is not declared; native staging \
                 copies skills into skills_dir — declare it, or drop [staging] and let \
                 runs fall back to --no-stage"
                    .into(),
            );
        }
        if d.guard.is_some() {
            return fail(
                "[guard] is declared but skills_dir is not; the guard's marker and \
                 teardown manifest live under skills_dir — declare it, or drop the \
                 guard and rely on the detect-stray-writes audit"
                    .into(),
            );
        }
    }

    // Slug shape: one source of truth, all four placeholders, and the
    // generated slug must satisfy the descriptor's own naming rules.
    if d.staging.slug_template.is_some() && d.staging.slug_capability.is_some() {
        return fail(
            "declare either staging.slug_template or staging.slug_capability, not both".into(),
        );
    }
    if let Some(template) = &d.staging.slug_template {
        for placeholder in SLUG_PLACEHOLDERS {
            if !template.contains(placeholder) {
                return fail(format!(
                    "staging.slug_template must contain {placeholder} — cleanup prefix-scans \
                     and per-cell uniqueness rely on all four placeholders"
                ));
            }
        }
    }
    let stage_regex = match &d.staging.stage_name_pattern {
        Some(pattern) => match Regex::new(pattern) {
            Ok(regex) => Some(regex),
            Err(e) => {
                return fail(format!("staging.stage_name_pattern does not compile: {e}"));
            }
        },
        None => None,
    };
    let sample = render_staged_slug(&d.staging, "slow-powers-eval-", 2, "with_skill", "my-skill");
    if !sample.starts_with("slow-powers-eval-") {
        return fail(format!(
            "the staged slug must preserve the prefix (cleanup prefix-scans rely on it); \
             sample slug: \"{sample}\""
        ));
    }
    if let Some(message) = stage_name_error(&d.staging, stage_regex.as_ref(), &sample) {
        return fail(format!(
            "the staged slug \"{sample}\" fails its own stage-name rules ({message}); \
             align staging.slug_template/slug_capability with the naming rules"
        ));
    }

    // The skills dir must live under a declared config dir, or staging's
    // sibling-asset filter would copy a checked-in copy into staged envs.
    if let Some(skills_dir) = &d.skills_dir {
        let top = skills_dir.split('/').next().unwrap_or_default();
        if !d.config_dirs.iter().any(|dir| dir == top) {
            return fail(format!(
                "config_dirs {:?} misses \"{top}\", the parent of skills_dir — staging's \
                 sibling-asset filter and the guard tamper rules key off config_dirs",
                d.config_dirs
            ));
        }
    }

    // The guard block is rendered by the generic engine at arm/verdict time,
    // and the guard fails open — so every data contract is proven here, before
    // any run arms the hook.
    if let Some(guard) = &d.guard {
        // Every tool the guard hooks must be declared in the vocabulary, or
        // the write-guard arbiter would silently wave it through.
        let vocabulary: Vec<&str> = d
            .tools
            .write
            .iter()
            .chain(&d.tools.patch)
            .chain(&d.tools.shell)
            .map(String::as_str)
            .collect();
        for token in guard.matcher.split('|') {
            let token = token.trim_matches(['^', '$']);
            if !vocabulary.contains(&token) {
                return fail(format!(
                    "the guard matcher hooks tool \"{token}\" but [tools] does not declare it \
                     in write/patch/shell — the write-guard arbiter would not recognize it"
                ));
            }
        }

        if guard.hooks_file.starts_with('/')
            || guard
                .hooks_file
                .split('/')
                .any(|seg| seg.is_empty() || seg == "." || seg == "..")
        {
            return fail(format!(
                "guard.hooks_file must be a relative `/`-separated path without \".\" or \
                 \"..\" segments (got \"{}\") — it resolves under the staged env root",
                guard.hooks_file
            ));
        }

        for placeholder in ["{exe}", "{marker}"] {
            if !guard.command_template.contains(placeholder) {
                return fail(format!(
                    "guard.command_template must reference {placeholder} — the armed hook \
                     invokes this binary with the marker path"
                ));
            }
        }

        match serde_json::from_str::<serde_json::Value>(&guard.hook_entry) {
            Err(e) => {
                return fail(format!(
                    "guard.hook_entry does not parse as JSON ({e}); it is the hook object \
                     appended to the harness's hook config"
                ));
            }
            Ok(entry) => {
                if !entry.is_object() {
                    return fail(
                        "guard.hook_entry must be a JSON object — it is appended to the hook \
                         config's hooks.PreToolUse array"
                            .into(),
                    );
                }
                for placeholder in ["{matcher}", "{command}"] {
                    if !guard::any_string_value_contains(&entry, placeholder) {
                        return fail(format!(
                            "guard.hook_entry must reference the {placeholder} placeholder in \
                             a string value — placeholders substitute into string values only, \
                             so anywhere else would render an inert hook"
                        ));
                    }
                }
            }
        }

        match serde_json::from_str::<serde_json::Value>(&guard.verdict_template) {
            Err(e) => {
                return fail(format!(
                    "guard.verdict_template does not parse as JSON ({e}); it is printed \
                     verbatim as the deny verdict"
                ));
            }
            Ok(verdict) => {
                if !guard::any_string_value_contains(&verdict, "{reason}") {
                    return fail(
                        "guard.verdict_template must reference the {reason} placeholder in a \
                         string value — a deny verdict that hides the reason is undebuggable"
                            .into(),
                    );
                }
            }
        }
    }

    // A transcript parser without a write/shell vocabulary makes the
    // stray-writes audit a silent no-op.
    if d.transcript.is_some() && (d.tools.write.is_empty() || d.tools.shell.is_empty()) {
        return fail(
            "[transcript] is declared but [tools] write/shell are empty; \
             detect-stray-writes would audit nothing — declare the harness's tool names"
                .into(),
        );
    }

    // Transcript ingest reads through exactly one tier: a named code parser
    // or the declarative extract block.
    if let Some(transcript) = &d.transcript {
        match (&transcript.parser, &transcript.extract) {
            (Some(_), Some(_)) => {
                return fail(
                    "[transcript] declares both a parser and an extract block; ingest reads \
                     through exactly one — drop one of them. Layered overrides merge fields \
                     and cannot delete an inherited parser, so moving a harness from parser \
                     to extract needs a new label rather than an overlay"
                        .into(),
                );
            }
            (None, None) => {
                return fail(
                    "[transcript] declares neither a parser nor an extract block; declare \
                     exactly one — name a parser capability or add [transcript.extract] — \
                     or drop the table and let llm_judge carry the grading"
                        .into(),
                );
            }
            _ => {}
        }
        if let Some(extract) = &transcript.extract {
            if extract.tools.is_none()
                && extract.final_text.is_none()
                && extract.tokens.is_none()
                && extract.duration.is_none()
            {
                return fail(
                    "[transcript.extract] declares none of tools/final_text/tokens/duration; \
                     an empty extract block parses nothing — declare at least one output"
                        .into(),
                );
            }
            if let Some(duration) = &extract.duration
                && duration.field.is_some() == duration.timestamp_spread.is_some()
            {
                return fail(
                    "[transcript.extract.duration] must declare exactly one of field \
                     (a millisecond pick) or timestamp_spread (last minus first timestamp)"
                        .into(),
                );
            }
        }
    }

    // Tool roles are disjoint: one name in two roles would double-classify
    // invocations in the stray-writes audit.
    let mut seen: Vec<&str> = Vec::new();
    for name in d
        .tools
        .write
        .iter()
        .chain(&d.tools.patch)
        .chain(&d.tools.shell)
        .chain(&d.tools.read)
    {
        if seen.contains(&name.as_str()) {
            return fail(format!(
                "tool \"{name}\" appears in more than one [tools] role — \
                 write/patch/shell/read must be disjoint"
            ));
        }
        seen.push(name);
    }

    // The judge command line splices into the shared judge recipe; its
    // contract (see cli_command::render_judge_dispatch_recipe) is checkable
    // here rather than at render time.
    if let Some(judge) = &d.dispatch.judge_command_template {
        if d.model.is_none() {
            return fail(
                "dispatch.judge_command_template requires model.flag — the judge recipe \
                 splices \"$model_arg\" from each task's model via the model flag"
                    .into(),
            );
        }
        if d.dispatch.capture_prefix.is_none() {
            return fail(
                "dispatch.judge_command_template requires dispatch.capture_prefix — it names \
                 the per-task $response_base capture files"
                    .into(),
            );
        }
        if !judge.contains("$model_arg") {
            return fail(
                "dispatch.judge_command_template must reference $model_arg (empty when a task \
                 declares no model)"
                    .into(),
            );
        }
        if !judge.contains("{cwd}") {
            return fail(
                "dispatch.judge_command_template must contain {cwd} — judges run from the \
                 iteration dir"
                    .into(),
            );
        }
        if !judge.ends_with(" \\") {
            return fail(
                "dispatch.judge_command_template must end with a shell line continuation \
                 (\" \\\") so the recipe's prompt line follows it"
                    .into(),
            );
        }
    }

    // Placeholders must have a backing field, or the template renders with the
    // token left in (the artifact tests' `!contains(\"{{\")` rule, at load time).
    let dispatch = &d.dispatch;
    let pairings: [(&Option<String>, &str, &str, bool); 7] = [
        (
            &dispatch.next_steps_template,
            "next_steps_template",
            "{exec_command}",
            dispatch.exec_template.is_some(),
        ),
        (
            &dispatch.next_steps_template,
            "next_steps_template",
            "{model_note}",
            dispatch.model_note.is_some(),
        ),
        (
            &dispatch.manifest_template,
            "manifest_template",
            "{exec_command}",
            dispatch.exec_template.is_some(),
        ),
        (
            &dispatch.manifest_template,
            "manifest_template",
            "{parallel_recipe}",
            dispatch.parallel_command_template.is_some(),
        ),
        (
            &dispatch.exec_template,
            "exec_template",
            "{guard_args}",
            dispatch.guard_args.is_some(),
        ),
        (
            &dispatch.parallel_command_template,
            "parallel_command_template",
            "{guard_args}",
            dispatch.guard_args.is_some(),
        ),
        (
            &dispatch.judge_command_template,
            "judge_command_template",
            "{guard_args}",
            dispatch.guard_args.is_some(),
        ),
    ];
    for (template, template_name, placeholder, backed) in pairings {
        if template.as_deref().is_some_and(|t| t.contains(placeholder)) && !backed {
            return fail(format!(
                "dispatch.{template_name} references {placeholder} but the field that fills \
                 it is not set"
            ));
        }
    }

    // The manifest template is spliced as `split('\n')` lines; exactly one
    // trailing newline reproduces the section's closing blank line.
    if let Some(manifest) = &d.dispatch.manifest_template
        && (!manifest.ends_with('\n') || manifest.ends_with("\n\n"))
    {
        return fail(
            "dispatch.manifest_template must end with exactly one trailing newline — it \
             becomes the manifest section's closing blank line"
                .into(),
        );
    }

    // A skills-block item that never names the skill renders an unusable list.
    if let Some(block) = &d.skills_block
        && !block.item.contains("{name}")
    {
        return fail("skills_block.item must contain {name}".into());
    }

    Ok(())
}

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

    /// Load through the full pipeline so each rejection test proves the
    /// invariant fires on a descriptor that already passed the schema gate.
    fn err_of(toml_src: &str) -> String {
        load_descriptor(toml_src, "test.toml")
            .expect_err("descriptor should be rejected")
            .to_string()
    }

    const MINIMAL: &str = r#"
label = "demo"
skills_dir = ".demo/skills"
config_dirs = [".demo"]
"#;

    /// A guard-wired descriptor whose tool vocabulary covers its matcher; the
    /// base for guard/matcher mutation tests.
    const GUARDED: &str = r#"
label = "demo"
skills_dir = ".demo/skills"
config_dirs = [".demo"]

[run]
supports_guard = true

[tools]
write = ["Edit", "MultiEdit", "NotebookEdit", "Write"]
shell = ["Bash"]

[guard]
hooks_file = ".demo/hooks.json"
matcher = "Write|Edit|MultiEdit|NotebookEdit|Bash"
command_template = '"{exe}" guard-hook --harness demo "{marker}"'
hook_entry = '{"matcher":"{matcher}","hooks":[{"type":"command","command":"{command}"}]}'
verdict_template = '{"decision":"block","reason":"{reason}"}'
armed_message = "guard armed"
"#;

    #[test]
    fn rejects_guard_support_without_guard_table() {
        let err = err_of(&format!("{MINIMAL}\n[run]\nsupports_guard = true\n"));
        assert!(err.contains("run.supports_guard"), "{err}");
        assert!(err.contains("lockstep"), "{err}");
    }

    #[test]
    fn rejects_guard_table_without_guard_support() {
        let err = err_of(&GUARDED.replace("supports_guard = true", "supports_guard = false"));
        assert!(err.contains("run.supports_guard"), "{err}");
        assert!(err.contains("lockstep"), "{err}");
    }

    #[test]
    fn rejects_slug_template_missing_a_placeholder() {
        let err = err_of(&format!(
            "{MINIMAL}\n[staging]\nslug_template = \"{{prefix}}{{iteration}}-{{condition}}\"\n"
        ));
        assert!(err.contains("staging.slug_template"), "{err}");
        assert!(err.contains("{skill_name}"), "{err}");
    }

    #[test]
    fn rejects_slug_template_and_capability_together() {
        let err = err_of(&format!(
            "{MINIMAL}\n[staging]\nslug_template = \"{{prefix}}{{iteration}}-{{condition}}__{{skill_name}}\"\nslug_capability = \"opencode\"\n"
        ));
        assert!(err.contains("not both"), "{err}");
    }

    #[test]
    fn rejects_slug_that_fails_its_own_stage_name_rules() {
        // The default slug shape emits `__`, which the single-hyphen pattern
        // rejects — the staged-slug↔naming-rules invariant.
        let err = err_of(&format!(
            "{MINIMAL}\n[staging]\nslug_template = \"{{prefix}}{{iteration}}-{{condition}}__{{skill_name}}\"\nstage_name_pattern = \"^[a-z0-9]+(-[a-z0-9]+)*$\"\nstage_name_max_len = 64\n"
        ));
        assert!(err.contains("stage-name rules"), "{err}");
    }

    #[test]
    fn rejects_config_dirs_missing_skills_dir_parent() {
        let err = err_of(&MINIMAL.replace("[\".demo\"]", "[\".other\"]"));
        assert!(err.contains("parent of skills_dir"), "{err}");
        assert!(err.contains(".demo"), "{err}");
    }

    #[test]
    fn rejects_guard_matcher_tool_missing_from_vocabulary() {
        // The matcher hooks Write|Edit|MultiEdit|NotebookEdit|Bash; drop Bash
        // from the shell vocabulary and the arbiter would wave it through.
        let err = err_of(&GUARDED.replace("shell = [\"Bash\"]", "shell = [\"Shell\"]"));
        assert!(err.contains("Bash"), "{err}");
        assert!(err.contains("[tools]"), "{err}");
    }

    #[test]
    fn rejects_hook_entry_that_is_not_json() {
        let err = err_of(&GUARDED.replace(
            r#"hook_entry = '{"matcher":"{matcher}","hooks":[{"type":"command","command":"{command}"}]}'"#,
            "hook_entry = 'not json'",
        ));
        assert!(err.contains("guard.hook_entry"), "{err}");
        assert!(err.contains("JSON"), "{err}");
    }

    #[test]
    fn rejects_hook_entry_missing_a_placeholder() {
        // {command} in a JSON *key* must not count: only string values are
        // substituted, so a key-side placeholder would render an inert hook.
        for (mutated, needle) in [
            (
                r#"hook_entry = '{"matcher":"{matcher}","hooks":[{"type":"command","{command}":"x"}]}'"#,
                "{command}",
            ),
            (
                r#"hook_entry = '{"matcher":"Write","hooks":[{"type":"command","command":"{command}"}]}'"#,
                "{matcher}",
            ),
        ] {
            let err = err_of(&GUARDED.replace(
                r#"hook_entry = '{"matcher":"{matcher}","hooks":[{"type":"command","command":"{command}"}]}'"#,
                mutated,
            ));
            assert!(err.contains("guard.hook_entry"), "{err}");
            assert!(err.contains(needle), "expected {needle} in: {err}");
        }
    }

    #[test]
    fn rejects_verdict_template_that_is_not_json() {
        let err = err_of(&GUARDED.replace(
            r#"verdict_template = '{"decision":"block","reason":"{reason}"}'"#,
            "verdict_template = 'block it'",
        ));
        assert!(err.contains("guard.verdict_template"), "{err}");
        assert!(err.contains("JSON"), "{err}");
    }

    #[test]
    fn rejects_verdict_template_without_reason_placeholder() {
        let err = err_of(&GUARDED.replace(
            r#"verdict_template = '{"decision":"block","reason":"{reason}"}'"#,
            r#"verdict_template = '{"decision":"block"}'"#,
        ));
        assert!(err.contains("guard.verdict_template"), "{err}");
        assert!(err.contains("{reason}"), "{err}");
    }

    #[test]
    fn rejects_command_template_missing_exe_or_marker() {
        for (mutated, needle) in [
            (
                r#"command_template = 'eval-magic guard-hook "{marker}"'"#,
                "{exe}",
            ),
            (
                r#"command_template = '"{exe}" guard-hook --harness demo'"#,
                "{marker}",
            ),
        ] {
            let err = err_of(&GUARDED.replace(
                r#"command_template = '"{exe}" guard-hook --harness demo "{marker}"'"#,
                mutated,
            ));
            assert!(err.contains("guard.command_template"), "{err}");
            assert!(err.contains(needle), "expected {needle} in: {err}");
        }
    }

    #[test]
    fn rejects_hooks_file_that_escapes_the_env() {
        for mutated in [
            "hooks_file = \"/etc/hooks.json\"",
            "hooks_file = \"../hooks.json\"",
            "hooks_file = \"./hooks.json\"",
        ] {
            let err = err_of(&GUARDED.replace("hooks_file = \".demo/hooks.json\"", mutated));
            assert!(err.contains("guard.hooks_file"), "{err}");
            assert!(err.contains("relative"), "{err}");
        }
    }

    #[test]
    fn rejects_transcript_without_write_and_shell_tools() {
        let err = err_of(&format!(
            "{MINIMAL}\n[transcript]\nevents_filename = \"demo-events.jsonl\"\nparser = \"codex-items\"\n"
        ));
        assert!(err.contains("detect-stray-writes"), "{err}");
    }

    /// Transcript-shape tests need a tool vocabulary so only the shape rule
    /// under test can fire.
    const TOOLED: &str = r#"
label = "demo"
skills_dir = ".demo/skills"
config_dirs = [".demo"]

[tools]
write = ["file_change"]
shell = ["command_execution"]
"#;

    #[test]
    fn rejects_extract_transcript_without_write_and_shell_tools() {
        let err = err_of(&format!(
            "{MINIMAL}\n[transcript]\nevents_filename = \"demo-events.jsonl\"\n\n\
             [transcript.extract.final_text]\nfield = \"text\"\n"
        ));
        assert!(err.contains("detect-stray-writes"), "{err}");
    }

    #[test]
    fn rejects_transcript_with_parser_and_extract() {
        let err = err_of(&format!(
            "{TOOLED}\n[transcript]\nevents_filename = \"demo-events.jsonl\"\nparser = \"codex-items\"\n\n\
             [transcript.extract.final_text]\nfield = \"text\"\n"
        ));
        assert!(err.contains("exactly one"), "{err}");
        assert!(err.contains("new label"), "{err}");
    }

    #[test]
    fn rejects_transcript_with_neither_parser_nor_extract() {
        let err = err_of(&format!(
            "{TOOLED}\n[transcript]\nevents_filename = \"demo-events.jsonl\"\n"
        ));
        assert!(err.contains("exactly one"), "{err}");
        assert!(err.contains("llm_judge"), "{err}");
    }

    #[test]
    fn rejects_empty_extract_block() {
        let err = err_of(&format!(
            "{TOOLED}\n[transcript]\nevents_filename = \"demo-events.jsonl\"\n\n[transcript.extract]\n"
        ));
        assert!(err.contains("[transcript.extract]"), "{err}");
        assert!(err.contains("at least one"), "{err}");
    }

    #[test]
    fn rejects_duration_with_both_variants_or_neither() {
        for duration_block in [
            "field = \"elapsed_ms\"\ntimestamp_spread = \"timestamp\"\n",
            "",
        ] {
            let err = err_of(&format!(
                "{TOOLED}\n[transcript]\nevents_filename = \"demo-events.jsonl\"\n\n\
                 [transcript.extract.duration]\n{duration_block}"
            ));
            assert!(err.contains("duration"), "{err}");
            assert!(err.contains("exactly one"), "{err}");
        }
    }

    #[test]
    fn rejects_tool_declared_in_more_than_one_role() {
        let err = err_of(&format!(
            "{MINIMAL}\n[tools]\nwrite = [\"Edit\"]\nshell = [\"Edit\"]\n"
        ));
        assert!(err.contains("more than one [tools] role"), "{err}");
        assert!(err.contains("Edit"), "{err}");
    }

    #[test]
    fn rejects_judge_template_without_model_flag() {
        let err = err_of(&format!(
            "{MINIMAL}\n[dispatch]\ncapture_prefix = \"demo\"\njudge_command_template = '    demo --cd \"{{cwd}}\" $model_arg \\'\n"
        ));
        assert!(err.contains("model.flag"), "{err}");
    }

    #[test]
    fn rejects_judge_template_violating_the_recipe_contract() {
        for (template, needle) in [
            ("'    demo --cd \"{cwd}\" \\'", "$model_arg"),
            ("'    demo $model_arg \\'", "{cwd}"),
            ("'    demo --cd \"{cwd}\" $model_arg'", "line continuation"),
        ] {
            let err = err_of(&format!(
                "{MINIMAL}\n[model]\nflag = \"-m\"\n\n[dispatch]\ncapture_prefix = \"demo\"\njudge_command_template = {template}\n"
            ));
            assert!(err.contains(needle), "expected {needle} in: {err}");
        }
    }

    #[test]
    fn rejects_judge_template_without_capture_prefix() {
        let err = err_of(&format!(
            "{MINIMAL}\n[model]\nflag = \"-m\"\n\n[dispatch]\njudge_command_template = '    demo --cd \"{{cwd}}\" $model_arg \\'\n"
        ));
        assert!(err.contains("capture_prefix"), "{err}");
    }

    #[test]
    fn rejects_template_placeholders_without_backing_fields() {
        for (dispatch_body, needle) in [
            (
                "next_steps_template = \"do {exec_command} now\"",
                "{exec_command}",
            ),
            (
                "next_steps_template = \"go.{model_note} then\"",
                "{model_note}",
            ),
            ("exec_template = \"demo{guard_args} run\"", "{guard_args}"),
            (
                "exec_template = \"demo run\"\nmanifest_template = \"use:\\n{exec_command}\\n{parallel_recipe}\\n\"",
                "{parallel_recipe}",
            ),
        ] {
            let err = err_of(&format!("{MINIMAL}\n[dispatch]\n{dispatch_body}\n"));
            assert!(err.contains(needle), "expected {needle} in: {err}");
        }
    }

    #[test]
    fn rejects_manifest_template_without_single_trailing_newline() {
        for manifest in [
            "\"use:\\n{exec_command}\"",
            "\"use:\\n{exec_command}\\n\\n\"",
        ] {
            let err = err_of(&format!(
                "{MINIMAL}\n[dispatch]\nexec_template = \"demo run\"\nmanifest_template = {manifest}\n"
            ));
            assert!(err.contains("exactly one trailing newline"), "{err}");
        }
    }

    #[test]
    fn rejects_skills_block_item_without_name_placeholder() {
        let err = err_of(&format!(
            "{MINIMAL}\n[skills_block]\nheader = \"Skills:\"\nitem = \"- {{description}}\"\n"
        ));
        assert!(err.contains("{name}"), "{err}");
    }

    #[test]
    fn rejects_stage_name_pattern_that_does_not_compile() {
        let err = err_of(&format!(
            "{MINIMAL}\n[staging]\nstage_name_pattern = \"[unclosed\"\n"
        ));
        assert!(err.contains("does not compile"), "{err}");
    }
}