Skip to main content

eval_magic/cli/
mod.rs

1//! CLI surface: command-tree definition and dispatch.
2//!
3//! A `clap` derive tree owns flag parsing and the generated help.
4//!
5//! The command tree lives in [`args`]; the per-command handlers live in
6//! [`commands`], grouped by concern. This module is the thin coordinator: parse,
7//! dispatch, and the shared context/iteration helpers the handlers reuse.
8
9use std::path::{Path, PathBuf};
10
11use anyhow::{anyhow, bail};
12use clap::Parser;
13
14use crate::core::{DetectInput, Harness, RunContext, detect_run_context};
15
16mod args;
17mod commands;
18mod help;
19mod run;
20
21use args::{Cli, Commands, CommonArgs, RunArgs};
22use commands::*;
23
24/// Parse process arguments, initialize the harness descriptor registry (every
25/// layer, including an optional `--harness-file`), dispatch to the selected
26/// subcommand, and return its result. Called by the binary entry point.
27pub fn run() -> anyhow::Result<()> {
28    let cli = Cli::parse();
29    // The hidden guard hooks fire on every PreToolUse in a dispatched session
30    // and only ever need the embedded descriptors — skip layered discovery so
31    // a broken user descriptor can't add noise or latency per tool call (the
32    // lazy registry fallback serves them embedded-only).
33    let is_guard_hook = matches!(
34        cli.command,
35        Some(Commands::Guard { .. } | Commands::GuardCodex { .. } | Commands::GuardHook { .. })
36    );
37    if !is_guard_hook {
38        crate::adapters::registry::init_registry(cli.harness_file.as_deref().map(Path::new))?;
39    }
40    dispatch(cli.command)
41}
42
43fn dispatch(command: Option<Commands>) -> anyhow::Result<()> {
44    // No subcommand means the default `run` action.
45    let command = command.unwrap_or(Commands::Run(RunArgs {
46        common: CommonArgs {
47            skill_dir: None,
48            skill: None,
49            iteration: None,
50            mode: None,
51            harness: None,
52            workspace_dir: None,
53            only: None,
54            skip: None,
55            overwrite: false,
56        },
57        baseline: None,
58        bootstrap: None,
59        dry_run: false,
60        no_stage: false,
61        guard: false,
62        no_guard: false,
63        stage_name: None,
64        plan_mode: false,
65        runs: 1,
66        agent_model: None,
67        judge_model: None,
68        label: None,
69    }));
70
71    match command {
72        Commands::Run(args) => run_run(args),
73        Commands::Ingest(args) => run_ingest(args),
74        Commands::Finalize(args) => run_finalize(args),
75        Commands::Init(args) => run_init(args),
76        Commands::Validate(args) => run_validate(args),
77        Commands::TeardownGuard(_) => run_teardown_guard(),
78        Commands::Guard { marker } => run_guard(marker),
79        Commands::GuardCodex { marker } => run_guard_codex(marker),
80        Commands::GuardHook { harness, marker } => run_guard_hook(&harness, marker),
81        Commands::RecordRuns(args) => run_record_runs(args),
82        Commands::FillTranscripts(args) => run_fill_transcripts(args),
83        Commands::DetectStrayWrites(args) => run_detect_stray_writes(args),
84        Commands::Grade(args) => run_grade(args),
85        Commands::Aggregate(args) => run_aggregate(args),
86        Commands::Harness(args) => run_harness(args),
87        Commands::Snapshot(args) => run_snapshot(args),
88        Commands::Teardown(args) => run_teardown(args),
89        Commands::PromoteBaseline(args) => run_promote_baseline(args),
90    }
91}
92
93/// Resolve a [`RunContext`] from the shared flags (skill dir/name, workspace,
94/// harness). Used by every post-dispatch stage handler.
95pub(crate) fn run_context_from(args: &CommonArgs) -> anyhow::Result<RunContext> {
96    run_context_with_bootstrap(args, None)
97}
98
99/// Like [`run_context_from`], but threads an optional `--bootstrap` file (only
100/// the `run` orchestrator consumes it; post-dispatch stages pass `None`).
101pub(crate) fn run_context_with_bootstrap(
102    args: &CommonArgs,
103    bootstrap: Option<String>,
104) -> anyhow::Result<RunContext> {
105    // `--harness` parses as a plain string so runtime-loaded descriptors can
106    // name harnesses clap never saw; resolution against the registry happens
107    // here, after parsing.
108    let harness = args.harness.as_deref().map(Harness::resolve).transpose()?;
109    Ok(detect_run_context(DetectInput {
110        skill_dir: args.skill_dir.clone(),
111        skill: args.skill.clone(),
112        bootstrap,
113        workspace_dir: args.workspace_dir.clone(),
114        harness,
115        cwd: None,
116    })?)
117}
118
119/// Split a comma-separated `--only`/`--skip` value into trimmed, non-empty ids.
120pub(crate) fn parse_id_list(v: Option<&str>) -> Option<Vec<String>> {
121    v.map(|s| {
122        s.split(',')
123            .map(|x| x.trim().to_string())
124            .filter(|x| !x.is_empty())
125            .collect()
126    })
127}
128
129/// Render a fully self-sufficient target selector for the current run context.
130///
131/// Always names `--skill-dir`, `--skill`, and `--workspace-dir` (all three are
132/// always populated in [`RunContext`] and always re-resolve), so the printed
133/// "Next:" commands are copy-pasteable from any cwd — not just the one `run`
134/// happened to start in. The absolute `--workspace-dir` is what lets the human
135/// run `ingest`/`finalize` from a per-`(group, condition)` env dir: without it,
136/// `workspace_root` would default to `<cwd>/.eval-magic` (`detect_run_context`)
137/// and the iteration tree above the env would not resolve.
138pub(crate) fn command_target_args(ctx: &RunContext) -> String {
139    format!(
140        " --skill-dir {} --skill {} --workspace-dir {}",
141        ctx.skill_dir.display(),
142        ctx.skill_name,
143        ctx.workspace_root.display(),
144    )
145}
146
147/// Resolve the explicit iteration, or default to the latest existing
148/// `iteration-<n>` under `<workspace>/<skill>`.
149pub(crate) fn resolve_iteration(ctx: &RunContext, iteration: Option<u32>) -> anyhow::Result<u32> {
150    if let Some(iteration) = iteration {
151        return Ok(iteration);
152    }
153
154    let skill_workspace = ctx.workspace_root.join(&ctx.skill_name);
155    let entries = std::fs::read_dir(&skill_workspace).map_err(|_| {
156        anyhow!(
157            "missing --iteration (no iterations found for {})",
158            ctx.skill_name
159        )
160    })?;
161    entries
162        .flatten()
163        .filter_map(|entry| {
164            entry
165                .file_name()
166                .to_string_lossy()
167                .strip_prefix("iteration-")
168                .and_then(|n| n.parse::<u32>().ok())
169        })
170        .max()
171        .ok_or_else(|| {
172            anyhow!(
173                "missing --iteration (no iterations found for {})",
174                ctx.skill_name
175            )
176        })
177}
178
179/// The iteration directory for a run: `<workspace>/<skill>/iteration-<n>`.
180/// Defaults to the latest existing iteration when `--iteration` is absent.
181pub(crate) fn iteration_dir(ctx: &RunContext, iteration: Option<u32>) -> anyhow::Result<PathBuf> {
182    let iteration = resolve_iteration(ctx, iteration)?;
183    let dir = ctx
184        .workspace_root
185        .join(&ctx.skill_name)
186        .join(format!("iteration-{iteration}"));
187    if !dir.is_dir() {
188        bail!("not found: {}", dir.display());
189    }
190    Ok(dir)
191}
192
193/// The env directories a run staged under `iteration_dir`: one
194/// `env-<group>-<condition>/` per `(group, condition)`. A best-effort directory
195/// scan (returns empty when the dir can't be read), used by `teardown`/`finalize`
196/// to walk every env's write guard. Preferred over reading `dispatch.json` because
197/// it has no parse-failure mode, needs no path re-basing (recorded env dirs can be
198/// relative), and the only `env-*` children of an iteration dir are the staged envs.
199pub(crate) fn staged_env_roots(iteration_dir: &Path) -> Vec<PathBuf> {
200    let Ok(entries) = std::fs::read_dir(iteration_dir) else {
201        return Vec::new();
202    };
203    entries
204        .flatten()
205        .filter(|e| e.path().is_dir())
206        .filter(|e| {
207            let name = e.file_name();
208            let name = name.to_string_lossy();
209            name == "env" || name.starts_with("env-")
210        })
211        .map(|e| e.path())
212        .collect()
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use std::fs;
219    use std::path::Path;
220    use tempfile::TempDir;
221
222    /// Create `<root>/<parent>/<name>/SKILL.md` and return the skill subdir.
223    fn make_skill(root: &Path, parent: &str, name: &str) -> PathBuf {
224        let subdir = root.join(parent).join(name);
225        fs::create_dir_all(&subdir).unwrap();
226        fs::write(
227            subdir.join("SKILL.md"),
228            format!("---\nname: {name}\ndescription: test\n---\n\nbody\n"),
229        )
230        .unwrap();
231        subdir
232    }
233
234    /// The selector must be copy-pasteable: even when `run` was invoked from
235    /// inside the skill dir (the case that used to render an empty selector), it
236    /// must name both `--skill-dir` and `--skill`, and re-resolve to the same
237    /// skill from an unrelated cwd.
238    #[test]
239    fn target_args_are_self_sufficient_when_run_from_inside_skill_dir() {
240        let tmp = TempDir::new().unwrap();
241        let root = fs::canonicalize(tmp.path()).unwrap();
242        let skill_subdir = make_skill(&root, "skills", "mr-review");
243
244        // Mimic `run` started from inside the skill dir: no --skill-dir/--skill.
245        let ctx = detect_run_context(DetectInput {
246            cwd: Some(skill_subdir.clone()),
247            ..Default::default()
248        })
249        .unwrap();
250
251        let args = command_target_args(&ctx);
252        assert!(
253            args.contains("--skill-dir"),
254            "selector names --skill-dir: {args}"
255        );
256        assert!(
257            args.contains("--skill mr-review"),
258            "selector names --skill: {args}"
259        );
260
261        // Round-trip: feeding the rendered selector back from an unrelated cwd
262        // resolves the same skill.
263        let other = root.join("elsewhere");
264        fs::create_dir_all(&other).unwrap();
265        let resolved = detect_run_context(DetectInput {
266            skill_dir: Some(ctx.skill_dir.display().to_string()),
267            skill: Some(ctx.skill_name.clone()),
268            cwd: Some(other),
269            ..Default::default()
270        })
271        .unwrap();
272        assert_eq!(resolved.skill_subdir, ctx.skill_subdir);
273    }
274
275    /// The human runs `ingest`/`finalize` from a per-`(group, condition)` env dir.
276    /// Without an explicit workspace root those commands default `workspace_root`
277    /// to `<cwd>/.eval-magic` and bail "not found", so the selector must carry an
278    /// absolute `--workspace-dir` pointing at the real workspace above the env.
279    #[test]
280    fn target_args_carry_absolute_workspace_dir() {
281        let tmp = TempDir::new().unwrap();
282        let root = fs::canonicalize(tmp.path()).unwrap();
283        let skill_subdir = make_skill(&root, "skills", "mr-review");
284
285        let ctx = detect_run_context(DetectInput {
286            cwd: Some(skill_subdir),
287            ..Default::default()
288        })
289        .unwrap();
290
291        let args = command_target_args(&ctx);
292        assert!(
293            args.contains(&format!("--workspace-dir {}", ctx.workspace_root.display())),
294            "selector names absolute --workspace-dir: {args}"
295        );
296        assert!(
297            ctx.workspace_root.is_absolute(),
298            "workspace_root is absolute: {}",
299            ctx.workspace_root.display()
300        );
301
302        // Round-trip from an env-like cwd below the workspace: feeding the
303        // selector's roots back resolves the SAME workspace, not
304        // `<cwd>/.eval-magic`.
305        let env_like = ctx
306            .workspace_root
307            .join("mr-review")
308            .join("iteration-1")
309            .join("env");
310        fs::create_dir_all(&env_like).unwrap();
311        let resolved = detect_run_context(DetectInput {
312            skill_dir: Some(ctx.skill_dir.display().to_string()),
313            skill: Some(ctx.skill_name.clone()),
314            workspace_dir: Some(ctx.workspace_root.display().to_string()),
315            cwd: Some(env_like),
316            ..Default::default()
317        })
318        .unwrap();
319        assert_eq!(resolved.workspace_root, ctx.workspace_root);
320    }
321}