1use 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
24pub fn run() -> anyhow::Result<()> {
28 let cli = Cli::parse();
29 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 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
93pub(crate) fn run_context_from(args: &CommonArgs) -> anyhow::Result<RunContext> {
96 run_context_with_bootstrap(args, None)
97}
98
99pub(crate) fn run_context_with_bootstrap(
102 args: &CommonArgs,
103 bootstrap: Option<String>,
104) -> anyhow::Result<RunContext> {
105 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
119pub(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
129pub(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
147pub(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
179pub(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
193pub(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 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 #[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 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 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 #[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 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}