Skip to main content

grex_cli/cli/
args.rs

1use clap::{Args, Parser, Subcommand};
2
3#[derive(Parser, Debug)]
4#[command(
5    name = "grex",
6    version,
7    about = "grex — nested meta-repo manager. Pack-based, agent-native, Rust-fast.",
8    long_about = "grex manages trees of git repositories as a single addressable graph. \
9        Each node is a \"pack\" — a plain git repo plus a `.grex/` contract — and every \
10        pack is a meta-pack by construction (zero children = leaf, N children = orchestrator \
11        of N more packs, recursively). One uniform command surface (`sync`, `add`, `rm`, \
12        `update`, `status`, `import`, `doctor`, `teardown`, `exec`, `run`, `serve`) operates \
13        over the whole graph regardless of depth."
14)]
15pub struct Cli {
16    #[command(flatten)]
17    pub global: GlobalFlags,
18
19    #[command(subcommand)]
20    pub verb: Verb,
21}
22
23#[derive(Args, Debug)]
24pub struct GlobalFlags {
25    /// Emit output as JSON.
26    #[arg(long, global = true, conflicts_with = "plain")]
27    pub json: bool,
28
29    /// Emit plain (non-color, non-table) output.
30    #[arg(long, global = true)]
31    pub plain: bool,
32
33    /// Show planned actions without executing them.
34    #[arg(long, global = true)]
35    pub dry_run: bool,
36
37    /// Filter packs by expression.
38    #[arg(long, global = true)]
39    pub filter: Option<String>,
40}
41
42#[derive(Subcommand, Debug)]
43pub enum Verb {
44    /// Initialize a grex workspace.
45    Init(InitArgs),
46    /// Register and clone a pack.
47    Add(AddArgs),
48    /// Teardown and remove a pack.
49    Rm(RmArgs),
50    /// List registered packs.
51    Ls(LsArgs),
52    /// Report drift vs lockfile.
53    Status(StatusArgs),
54    /// Git fetch and pull (recurse by default).
55    Sync(SyncArgs),
56    /// Sync plus re-run install on lock change.
57    Update(UpdateArgs),
58    /// Run integrity checks.
59    Doctor(DoctorArgs),
60    /// Start MCP stdio server.
61    Serve(ServeArgs),
62    /// Import legacy REPOS.json.
63    Import(ImportArgs),
64    /// Run a named action across packs.
65    Run(RunArgs),
66    /// Execute a shell command in pack context.
67    Exec(ExecArgs),
68    /// Tear down a pack tree (reverse of `sync`/`install`).
69    Teardown(TeardownArgs),
70}
71
72#[derive(Args, Debug)]
73pub struct InitArgs {}
74
75#[derive(Args, Debug)]
76pub struct AddArgs {
77    /// Git URL of the pack repo.
78    pub url: String,
79    /// Optional local path (defaults to repo name).
80    pub path: Option<String>,
81}
82
83#[derive(Args, Debug)]
84pub struct RmArgs {
85    /// Local path of the pack to remove.
86    pub path: String,
87}
88
89#[derive(Args, Debug)]
90pub struct LsArgs {
91    /// Pack root. Directory holding `.grex/pack.yaml`, or the YAML file
92    /// itself. Defaults to the current working directory.
93    pub pack_root: Option<std::path::PathBuf>,
94}
95
96#[derive(Args, Debug)]
97pub struct StatusArgs {}
98
99#[derive(Args, Debug)]
100pub struct SyncArgs {
101    /// Recurse into child packs.
102    #[arg(long, default_value_t = true)]
103    pub recursive: bool,
104
105    /// Pack root. Directory holding `.grex/pack.yaml`, or the YAML file
106    /// itself. When omitted, `sync` prints the legacy M1 stub and exits 0.
107    pub pack_root: Option<std::path::PathBuf>,
108
109    /// Override the workspace root. Defaults to the parent pack's root
110    /// directory; children resolve as flat siblings.
111    #[arg(long)]
112    pub workspace: Option<std::path::PathBuf>,
113
114    /// Plan actions without touching the filesystem.
115    #[arg(long, short = 'n')]
116    pub dry_run: bool,
117
118    /// Suppress per-action log lines.
119    #[arg(long, short = 'q')]
120    pub quiet: bool,
121
122    /// Skip plan-phase validators. Debug-only escape hatch.
123    #[arg(long)]
124    pub no_validate: bool,
125
126    /// Override the default ref for every pack in this sync invocation.
127    /// Accepts a branch, tag, or commit SHA. Empty strings are rejected.
128    #[arg(long = "ref", value_name = "REF", value_parser = non_empty_string)]
129    pub ref_override: Option<String>,
130
131    /// Restrict sync to packs whose workspace-relative path (or name)
132    /// matches the glob. Repeat the flag to OR-combine multiple patterns
133    /// (standard `*`/`**`/`?` semantics). Non-matching packs are skipped
134    /// entirely — no action execution, no lockfile write.
135    #[arg(long = "only", value_name = "GLOB", value_parser = non_empty_string)]
136    pub only: Vec<String>,
137
138    /// Re-execute every pack even when its `actions_hash` is unchanged
139    /// from the prior lockfile. Overrides the M4-B skip-on-hash
140    /// short-circuit; dry-run semantics are unchanged.
141    #[arg(long)]
142    pub force: bool,
143
144    /// Max parallel pack ops during this sync run (feat-m6-1).
145    ///
146    /// Semantics:
147    /// * Absent → default `num_cpus::get()` resolved in `verbs::sync`.
148    /// * `0` → unbounded (`Semaphore::MAX_PERMITS`).
149    /// * `1` → serial fast-path (preserves pre-M6 wall-order).
150    /// * `2..=1024` → bounded parallel.
151    ///
152    /// Env fallback: `GREX_PARALLEL` is honoured only when the flag is
153    /// absent. Clap reads the env var automatically via `env`.
154    ///
155    /// Distinct from the global `--parallel` on [`GlobalFlags`]; that
156    /// knob is documented as the harness-level worker cap and rejects
157    /// `0`. Sync parallelism uses `0` as the "unbounded" sentinel per
158    /// `.omne/cfg/concurrency.md`.
159    #[arg(
160        long = "parallel",
161        env = "GREX_PARALLEL",
162        value_parser = clap::value_parser!(u32).range(0..=1024),
163    )]
164    pub parallel: Option<u32>,
165}
166
167/// Clap `value_parser` that rejects empty or whitespace-only strings.
168/// Keeps `--ref ""`, `--ref " "`, `--only ""`, `--only "\t"` off the
169/// fast path. Whitespace-only values are rejected because they
170/// degrade silently inside the walker / globset layers rather than
171/// producing a useful error.
172fn non_empty_string(s: &str) -> Result<String, String> {
173    if s.trim().is_empty() {
174        Err("value must not be empty or whitespace-only".to_string())
175    } else {
176        Ok(s.to_string())
177    }
178}
179
180#[derive(Args, Debug)]
181pub struct UpdateArgs {
182    /// Optional pack path; if omitted, update all.
183    pub pack: Option<String>,
184}
185
186#[derive(Args, Debug)]
187pub struct DoctorArgs {
188    /// Heal gitignore drift by re-emitting the managed block. Safety:
189    /// NEVER touches the manifest or the filesystem on other checks.
190    #[arg(long)]
191    pub fix: bool,
192
193    /// Run the opt-in config-lint check (`openspec/config.yaml` +
194    /// `.omne/cfg/*.md`). Skipped by default.
195    #[arg(long = "lint-config")]
196    pub lint_config: bool,
197}
198
199#[derive(Args, Debug)]
200pub struct ServeArgs {
201    /// Path to the `grex.jsonl` event-log manifest. Captured at server
202    /// launch and immutable for the session (per spec §"Manifest binding").
203    /// Defaults to `<cwd>/grex.jsonl` when omitted.
204    #[arg(long, value_name = "PATH")]
205    pub manifest: Option<std::path::PathBuf>,
206
207    /// Workspace root the MCP server resolves relative paths against.
208    /// Defaults to the current working directory when omitted.
209    #[arg(long, value_name = "PATH")]
210    pub workspace: Option<std::path::PathBuf>,
211
212    /// Harness-level worker cap inherited by the MCP server's
213    /// `Scheduler` (feat-m7-1 stage 8.3). `1` = serial; range `1..=1024`.
214    /// Defaults to `std::thread::available_parallelism()` when omitted.
215    /// Distinct from `sync --parallel` which uses `0` = unbounded.
216    #[arg(
217        long = "parallel",
218        value_parser = clap::value_parser!(u32).range(1..=1024),
219    )]
220    pub parallel: Option<u32>,
221}
222
223#[derive(Args, Debug)]
224pub struct ImportArgs {
225    /// Path to a legacy REPOS.json file.
226    #[arg(long)]
227    pub from_repos_json: Option<std::path::PathBuf>,
228
229    /// Target manifest (`grex.jsonl`). Defaults to `<cwd>/grex.jsonl`.
230    #[arg(long, value_name = "PATH")]
231    pub manifest: Option<std::path::PathBuf>,
232
233    /// Verb-scoped dry-run. Alias for the global `--dry-run`; either
234    /// flag short-circuits before any manifest write.
235    #[arg(long = "dry-run", short = 'n')]
236    pub dry_run: bool,
237}
238
239#[derive(Args, Debug)]
240pub struct RunArgs {
241    /// Action name to run.
242    pub action: String,
243}
244
245#[derive(Args, Debug)]
246pub struct ExecArgs {
247    /// Shell command and args to execute.
248    #[arg(trailing_var_arg = true)]
249    pub cmd: Vec<String>,
250}
251
252#[derive(Args, Debug)]
253pub struct TeardownArgs {
254    /// Pack root. Directory holding `.grex/pack.yaml`, or the YAML file
255    /// itself. When omitted, `teardown` prints a usage stub and exits 0.
256    pub pack_root: Option<std::path::PathBuf>,
257
258    /// Override the workspace root. Defaults to the parent pack's root
259    /// directory; children resolve as flat siblings.
260    #[arg(long)]
261    pub workspace: Option<std::path::PathBuf>,
262
263    /// Suppress per-action log lines.
264    #[arg(long, short = 'q')]
265    pub quiet: bool,
266
267    /// Skip plan-phase validators. Debug-only escape hatch.
268    #[arg(long)]
269    pub no_validate: bool,
270}
271
272#[cfg(test)]
273mod tests {
274    //! Direct-parse unit tests. These bypass the spawned binary and hit
275    //! `Cli::try_parse_from` in-process — much faster than `assert_cmd`.
276    use super::*;
277    use clap::Parser;
278
279    fn parse(args: &[&str]) -> Result<Cli, clap::Error> {
280        // clap's `try_parse_from` expects argv[0] to be the binary name.
281        let mut full = vec!["grex"];
282        full.extend_from_slice(args);
283        Cli::try_parse_from(full)
284    }
285
286    #[test]
287    fn init_parses_to_init_variant() {
288        let cli = parse(&["init"]).expect("init parses");
289        assert!(matches!(cli.verb, Verb::Init(_)));
290    }
291
292    #[test]
293    fn add_parses_url_and_optional_path() {
294        let cli = parse(&["add", "https://example.com/repo.git"]).expect("add url parses");
295        match cli.verb {
296            Verb::Add(a) => {
297                assert_eq!(a.url, "https://example.com/repo.git");
298                assert!(a.path.is_none());
299            }
300            _ => panic!("expected Add variant"),
301        }
302
303        let cli = parse(&["add", "https://example.com/repo.git", "local"])
304            .expect("add url + path parses");
305        match cli.verb {
306            Verb::Add(a) => {
307                assert_eq!(a.url, "https://example.com/repo.git");
308                assert_eq!(a.path.as_deref(), Some("local"));
309            }
310            _ => panic!("expected Add variant"),
311        }
312    }
313
314    #[test]
315    fn rm_parses_path() {
316        let cli = parse(&["rm", "pack-a"]).expect("rm parses");
317        match cli.verb {
318            Verb::Rm(a) => assert_eq!(a.path, "pack-a"),
319            _ => panic!("expected Rm variant"),
320        }
321    }
322
323    #[test]
324    fn sync_recursive_defaults_to_true() {
325        let cli = parse(&["sync"]).expect("sync parses");
326        match cli.verb {
327            Verb::Sync(a) => assert!(a.recursive, "sync should default to recursive=true"),
328            _ => panic!("expected Sync variant"),
329        }
330    }
331
332    #[test]
333    fn update_pack_is_optional() {
334        let cli = parse(&["update"]).expect("update parses bare");
335        match cli.verb {
336            Verb::Update(a) => assert!(a.pack.is_none()),
337            _ => panic!("expected Update variant"),
338        }
339
340        let cli = parse(&["update", "mypack"]).expect("update parses w/ pack");
341        match cli.verb {
342            Verb::Update(a) => assert_eq!(a.pack.as_deref(), Some("mypack")),
343            _ => panic!("expected Update variant"),
344        }
345    }
346
347    #[test]
348    fn exec_collects_trailing_args() {
349        let cli = parse(&["exec", "echo", "hi", "there"]).expect("exec parses");
350        match cli.verb {
351            Verb::Exec(a) => assert_eq!(a.cmd, vec!["echo", "hi", "there"]),
352            _ => panic!("expected Exec variant"),
353        }
354    }
355
356    #[test]
357    fn universal_flags_populate_on_any_verb() {
358        // `--json` and `--plain` are mutually exclusive, so split into two
359        // parses to exercise the remaining flags on both modes.
360        let cli = parse(&["ls", "--json", "--dry-run", "--filter", "kind=git"])
361            .expect("ls w/ json+dry-run+filter parses");
362        assert!(cli.global.json);
363        assert!(!cli.global.plain);
364        assert!(cli.global.dry_run);
365        assert_eq!(cli.global.filter.as_deref(), Some("kind=git"));
366
367        let cli = parse(&["ls", "--plain", "--dry-run"]).expect("ls w/ plain+dry-run parses");
368        assert!(!cli.global.json);
369        assert!(cli.global.plain);
370    }
371
372    #[test]
373    fn json_and_plain_conflict() {
374        let err =
375            parse(&["init", "--json", "--plain"]).expect_err("--json and --plain must conflict");
376        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
377    }
378
379    #[test]
380    fn parallel_not_global_rejected_on_non_sync_verb() {
381        // feat-m6 B2 — `--parallel` is sync-scoped only; it must NOT
382        // be accepted as a global flag on verbs like `init`/`ls`.
383        let err =
384            parse(&["init", "--parallel", "1"]).expect_err("--parallel on non-sync verb must fail");
385        assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
386    }
387
388    #[test]
389    fn sync_parallel_one_accepted() {
390        let cli = parse(&["sync", "--parallel", "1"]).expect("sync --parallel 1 parses");
391        match cli.verb {
392            Verb::Sync(a) => assert_eq!(a.parallel, Some(1)),
393            _ => panic!("expected Sync variant"),
394        }
395    }
396
397    #[test]
398    fn sync_parallel_max_accepted() {
399        let cli = parse(&["sync", "--parallel", "1024"]).expect("sync --parallel 1024 parses");
400        match cli.verb {
401            Verb::Sync(a) => assert_eq!(a.parallel, Some(1024)),
402            _ => panic!("expected Sync variant"),
403        }
404    }
405
406    #[test]
407    fn sync_parallel_over_max_rejected() {
408        let err =
409            parse(&["sync", "--parallel", "1025"]).expect_err("sync --parallel 1025 must fail");
410        assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
411    }
412
413    #[test]
414    fn import_from_repos_json_parses_as_pathbuf() {
415        let cli =
416            parse(&["import", "--from-repos-json", "./REPOS.json"]).expect("import parses path");
417        match cli.verb {
418            Verb::Import(a) => {
419                assert_eq!(
420                    a.from_repos_json.as_deref(),
421                    Some(std::path::Path::new("./REPOS.json"))
422                );
423            }
424            _ => panic!("expected Import variant"),
425        }
426    }
427
428    #[test]
429    fn run_requires_action() {
430        let err = parse(&["run"]).expect_err("run w/o action must fail");
431        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
432    }
433
434    #[test]
435    fn unknown_verb_fails() {
436        let err = parse(&["nope"]).expect_err("unknown verb must fail");
437        assert_eq!(err.kind(), clap::error::ErrorKind::InvalidSubcommand);
438    }
439
440    #[test]
441    fn unknown_flag_fails() {
442        let err = parse(&["init", "--not-a-flag"]).expect_err("unknown flag must fail");
443        assert_eq!(err.kind(), clap::error::ErrorKind::UnknownArgument);
444    }
445
446    #[test]
447    fn cli_non_empty_string_rejects_whitespace() {
448        // F8: `--ref " "` / `--only "\t"` must be rejected by the value
449        // parser, not silently threaded into the walker / globset layer
450        // where they degrade into useless errors.
451        for bad in ["", " ", "\t", "  ", "\n"] {
452            let err =
453                parse(&["sync", ".", "--ref", bad]).expect_err("whitespace --ref must be rejected");
454            assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation, "for {bad:?}");
455
456            let err = parse(&["sync", ".", "--only", bad])
457                .expect_err("whitespace --only must be rejected");
458            assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation, "for {bad:?}");
459        }
460    }
461}