Skip to main content

blyte_cli/
cli.rs

1use clap::Parser;
2use serde::{Deserialize, Serialize};
3use std::path::PathBuf;
4
5#[derive(clap::Subcommand, Debug, PartialEq, Clone)]
6#[allow(clippy::large_enum_variant)]
7pub enum Command {
8    /// Detect this repository's checks and write blyte.toml
9    Init(InitArgs),
10    /// Serve a local dashboard of running and recent jobs
11    Dashboard(DashboardArgs),
12    /// Serve a local replay of recent runs
13    Mock(MockArgs),
14    /// Combine a request's passed runs on a work branch and run the repository's check
15    Combine(CombineArgs),
16    /// Run one task in its own git worktree (.wt/<id>, branch wip/<id>) and print a JSON summary
17    Dispatch(DispatchArgs),
18    /// Start a direct edit in its own git worktree (.wt/<id>, branch wip/<id>)
19    EditStart(EditStartArgs),
20    /// Verify and record a direct edit started with `blyte edit-start`
21    EditFinish(EditFinishArgs),
22    /// Show what a dispatched run did: commits, files, tree state, report, and optionally the diff
23    Review(ReviewArgs),
24    /// Remove finished worktrees and merged branches
25    Clean(CleanArgs),
26    /// Show what a dispatch is doing
27    Status {
28        id: String,
29        #[arg(long)]
30        json: bool,
31    },
32    /// Wait until dispatched runs finish (all of them, or the first with --any) and print one line per finished run
33    Wait {
34        /// Run ids, as given to `blyte dispatch`
35        #[arg(required = true, num_args = 1..)]
36        ids: Vec<String>,
37        /// Return as soon as at least one run has finished
38        #[arg(long)]
39        any: bool,
40        /// Give up after this many seconds (exit 2); stays under the 300 s shell-command limit
41        #[arg(long, default_value_t = 280)]
42        timeout: u64,
43    },
44    /// Install or print the Claude Code skill for the plan, delegate, review workflow
45    Skill(SkillArgs),
46    /// Replace this binary with the latest release (the old one is kept as blyte.prev)
47    Update {
48        /// Only show the installed and latest versions
49        #[arg(long, conflicts_with = "rollback")]
50        check: bool,
51        /// Swap back to the previous build (blyte.prev)
52        #[arg(long)]
53        rollback: bool,
54    },
55    /// Show orchestrator and implementer costs
56    Cost(CostArgs),
57    /// Print Claude Code's status line with blyte costs
58    Statusline(StatuslineArgs),
59    /// List a plan's tasks with their state and the command to dispatch each ready one
60    Plan(PlanArgs),
61    /// Fail when the working tree adds comments since a base commit
62    Comments(CommentsArgs),
63    /// Print the instructions the orchestrator is given
64    Instructions(InstructionsArgs),
65}
66
67#[derive(clap::Args, Debug, PartialEq, Clone)]
68pub struct InitArgs {
69    /// Overwrite an existing blyte.toml
70    #[arg(long)]
71    pub force: bool,
72
73    /// Print the file instead of writing it
74    #[arg(long)]
75    pub print: bool,
76
77    /// Skip gate verification on HEAD
78    #[arg(long)]
79    pub no_verify: bool,
80
81    /// Sandbox local command execution: 'on' or 'off' (default 'on')
82    #[arg(
83        long,
84        default_value = "on",
85        value_parser = ["on", "off"]
86    )]
87    pub sandbox: String,
88
89    /// Timeout in seconds for each verification step (default 600)
90    #[arg(long, default_value = "600", value_name = "SECONDS")]
91    pub step_timeout: u64,
92}
93
94#[derive(clap::Args, Debug, PartialEq, Clone)]
95pub struct DashboardArgs {
96    /// Port to listen on (0 for a free port)
97    #[arg(long, default_value = "7171", value_name = "N")]
98    pub port: u16,
99
100    /// Directory holding repositories or worktrees (repeatable)
101    #[arg(long = "root", value_name = "DIR")]
102    pub roots: Vec<PathBuf>,
103
104    /// Directory holding run logs and reports (repeatable)
105    #[arg(long = "runs-dir", value_name = "DIR")]
106    pub runs_dirs: Vec<PathBuf>,
107
108    /// How far back finished jobs are listed, in hours
109    #[arg(long, default_value = "24", value_name = "N")]
110    pub hours: u64,
111
112    /// Open the dashboard in the default browser
113    #[arg(long)]
114    pub open: bool,
115}
116
117#[derive(clap::Args, Debug, PartialEq, Clone)]
118pub struct SurfaceArgs {
119    #[arg(
120        long,
121        default_value_t = 0,
122        value_name = "N",
123        help = "Port to listen on (0 picks a free port)"
124    )]
125    pub port: u16,
126
127    #[arg(long, help = "Do not open the live surface in the browser")]
128    pub no_open: bool,
129
130    #[arg(
131        long,
132        default_value_t = 14,
133        value_name = "N",
134        value_parser = clap::value_parser!(u64).range(1..=31),
135        help = "How many days back to include finished runs (1 to 31)"
136    )]
137    pub days: u64,
138}
139
140impl Default for SurfaceArgs {
141    fn default() -> Self {
142        Self {
143            port: 0,
144            no_open: false,
145            days: 14,
146        }
147    }
148}
149
150#[derive(clap::Args, Debug, PartialEq, Clone)]
151pub struct MockArgs {
152    /// Port to listen on (0 for a free port)
153    #[arg(long, default_value = "7272", value_name = "N")]
154    pub port: u16,
155
156    /// How many days back to include finished runs (1 to 31)
157    #[arg(
158        long,
159        default_value = "7",
160        value_name = "N",
161        value_parser = clap::value_parser!(u64).range(1..=31)
162    )]
163    pub days: u64,
164
165    /// Directory holding repositories or worktrees (repeatable)
166    #[arg(long = "root", value_name = "DIR")]
167    pub roots: Vec<PathBuf>,
168}
169
170#[derive(clap::Args, Debug, PartialEq, Clone)]
171pub struct CombineArgs {
172    /// Request identifier whose passed runs should be combined
173    pub request: String,
174}
175
176#[derive(clap::Args, Debug, PartialEq, Clone)]
177pub struct EditStartArgs {
178    /// Identifier for this direct edit (used for worktree and branch wip/<id>)
179    pub id: String,
180
181    /// Short description of the requested change
182    #[arg(long, value_name = "TEXT")]
183    pub task: String,
184
185    /// The commit the new worktree starts from
186    #[arg(long, default_value = "HEAD")]
187    pub base: String,
188}
189
190#[derive(clap::Args, Debug, PartialEq, Clone)]
191pub struct EditFinishArgs {
192    /// Identifier given to `blyte edit-start`
193    pub id: String,
194
195    /// Request identifier this edit belongs to
196    #[arg(long, value_name = "ID")]
197    pub request: Option<String>,
198
199    /// Commit message used to commit uncommitted or untracked changes in the worktree
200    #[arg(long, value_name = "TEXT")]
201    pub message: Option<String>,
202}
203
204#[derive(clap::Args, Debug, PartialEq, Clone)]
205pub struct DispatchArgs {
206    /// Identifier for this dispatch (used for worktree and branch wip/<id>)
207    pub id: String,
208
209    /// Path to the task description markdown file; optional with --plan and --plan-task, which take the task from the plan
210    pub task_file: Option<PathBuf>,
211
212    /// The check command; several lines are several steps, all of which must pass
213    #[arg(short, long)]
214    pub gate: Option<String>,
215
216    /// Tag for this dispatch (repeatable)
217    #[arg(long = "tag", value_name = "TEXT")]
218    pub tags: Vec<String>,
219
220    /// Path to the plan file this dispatch belongs to
221    #[arg(long, value_name = "PATH")]
222    pub plan: Option<String>,
223
224    /// Plan task this dispatch implements
225    #[arg(long, value_name = "TEXT")]
226    pub plan_task: Option<String>,
227
228    /// Request identifier this dispatch belongs to
229    #[arg(long, value_name = "ID")]
230    pub request: Option<String>,
231
232    /// The commit a new worktree starts from
233    #[arg(long, default_value = "HEAD")]
234    pub base: String,
235
236    /// Run read-only research: scratch repository, report gate, findings in report.md
237    #[arg(long, conflicts_with = "gate", conflicts_with = "base")]
238    pub research: bool,
239
240    /// Copy the finished research report to this path (only with --research)
241    #[arg(long = "report-to", requires = "research", value_name = "PATH")]
242    pub report_to: Option<PathBuf>,
243
244    /// Model identifier or provider selection
245    #[arg(short, long)]
246    pub model: Option<String>,
247
248    /// Wall-clock budget in seconds (default 3600)
249    #[arg(long)]
250    pub max_seconds: Option<u64>,
251
252    /// Maximum turn budget (default 300)
253    #[arg(long)]
254    pub max_turns: Option<u32>,
255
256    /// Maximum spend in USD
257    #[arg(long = "max-cost")]
258    pub max_cost_usd: Option<f64>,
259
260    /// Approximate token budget for the verbatim tail before folding
261    #[arg(long)]
262    pub fold_budget: Option<usize>,
263
264    /// Sandbox local command execution: 'on' or 'off' (default 'on')
265    #[arg(
266        long,
267        default_value = "on",
268        value_parser = ["on", "off"]
269    )]
270    pub sandbox: String,
271
272    /// Outbound network mode: 'on' or 'off' (default 'on')
273    #[arg(
274        long,
275        value_parser = ["on", "off"]
276    )]
277    pub network: Option<String>,
278
279    /// Let sandboxed commands read this path despite credential deny-list (repeatable)
280    #[arg(long = "allow-read")]
281    pub allow_read: Vec<PathBuf>,
282
283    /// Start even if the task names paths outside the workspace and --allow-read
284    #[arg(long = "no-path-check")]
285    pub no_path_check: bool,
286
287    /// Research runs: no warning for missing brief sections, and allow a question that names an unverified report
288    #[arg(long = "no-brief-check")]
289    pub no_brief_check: bool,
290
291    /// Skip the model claim check on report.md for research runs
292    #[arg(long = "no-claim-check")]
293    pub no_claim_check: bool,
294
295    /// Skip the pre-run gate check on the untouched worktree
296    #[arg(long = "no-base-check")]
297    pub no_base_check: bool,
298
299    /// Pass this environment variable to commands (repeatable)
300    #[arg(long = "pass-env")]
301    pub pass_env: Vec<String>,
302}
303
304#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
305#[value(rename_all = "lowercase")]
306#[serde(rename_all = "lowercase")]
307pub enum ReviewVerdict {
308    Accepted,
309    Fixed,
310    Redone,
311}
312
313impl ReviewVerdict {
314    pub fn as_str(&self) -> &'static str {
315        match self {
316            Self::Accepted => "accepted",
317            Self::Fixed => "fixed",
318            Self::Redone => "redone",
319        }
320    }
321}
322
323impl std::fmt::Display for ReviewVerdict {
324    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
325        write!(f, "{}", self.as_str())
326    }
327}
328
329#[derive(clap::Args, Debug, PartialEq, Clone)]
330pub struct ReviewArgs {
331    pub id: String,
332
333    #[arg(long)]
334    pub diff: bool,
335
336    #[arg(long, value_enum)]
337    pub verdict: Option<ReviewVerdict>,
338
339    #[arg(long, value_name = "TEXT", requires = "verdict")]
340    pub notes: Option<String>,
341
342    /// Ask the implementer model for a first review of the diff against the task (trial)
343    #[arg(long, conflicts_with = "verdict")]
344    pub model_review: bool,
345}
346
347#[derive(clap::Args, Debug, PartialEq, Clone)]
348pub struct CleanArgs {
349    /// Show what would be removed without deleting anything
350    #[arg(long)]
351    pub dry_run: bool,
352
353    /// Worktrees older than this many days are removable without a verdict (default 14)
354    #[arg(long, default_value = "14", value_name = "DAYS")]
355    pub older_than: u64,
356
357    /// Clean every repository in the registry
358    #[arg(long)]
359    pub all: bool,
360
361    #[arg(long, hide = true, conflicts_with_all = ["all", "dry_run"])]
362    pub quiet: bool,
363
364    #[arg(long, hide = true, value_name = "ID", conflicts_with_all = ["all", "dry_run"])]
365    pub skip: Option<String>,
366}
367
368#[derive(clap::Args, Debug, PartialEq, Clone)]
369pub struct CostArgs {
370    /// Session identifier to filter by (an unknown session prints zero totals and exits 0)
371    #[arg(long, value_name = "ID")]
372    pub session: Option<String>,
373
374    /// Break down totals by session id
375    #[arg(long)]
376    pub by_session: bool,
377
378    /// Filter runs at or after this Unix timestamp in seconds
379    #[arg(long, value_name = "UNIX_SECS")]
380    pub since: Option<u64>,
381
382    /// Repository path to filter by
383    #[arg(long, value_name = "PATH")]
384    pub repo: Option<PathBuf>,
385
386    /// Output totals as JSON
387    #[arg(long)]
388    pub json: bool,
389}
390
391#[derive(clap::Args, Debug, PartialEq, Clone)]
392pub struct StatuslineArgs {
393    /// Command to generate the base line before appending blyte costs
394    #[arg(long, value_name = "COMMAND")]
395    pub after: Option<String>,
396}
397
398#[derive(clap::Args, Debug, PartialEq, Clone)]
399pub struct PlanArgs {
400    /// Path to the plan markdown file
401    pub plan: PathBuf,
402
403    /// Output task statuses as JSON
404    #[arg(long)]
405    pub json: bool,
406}
407
408#[derive(clap::Args, Debug, PartialEq, Clone)]
409pub struct CommentsArgs {
410    /// Base commit or revision to compare the working tree against
411    #[arg(long, value_name = "REV")]
412    pub base: String,
413}
414
415#[derive(clap::Args, Debug, PartialEq, Clone)]
416pub struct InstructionsArgs {
417    /// Print the built-in default process and exit
418    #[arg(long, conflicts_with_all = ["one_shot", "dispatch_tool"])]
419    pub default_process: bool,
420
421    /// Show the instructions for a one-shot run
422    #[arg(long)]
423    pub one_shot: bool,
424
425    /// Show the instructions for `--dispatch-cmd` mode
426    #[arg(long)]
427    pub dispatch_tool: bool,
428
429    /// Show the instructions for sandbox 'on' or 'off'
430    #[arg(long, value_parser = ["on", "off"])]
431    pub sandbox: Option<String>,
432}
433
434#[derive(clap::Subcommand, Debug, PartialEq, Clone)]
435pub enum SkillAction {
436    /// Install the Claude Code skill
437    Install {
438        /// Install to repository instead of personal ~/.claude
439        #[arg(long)]
440        project: bool,
441
442        /// Overwrite even if existing skill was modified
443        #[arg(long)]
444        force: bool,
445
446        /// Also tell Claude Code to delegate implementation to blyte by default, in CLAUDE.md
447        #[arg(long, hide = true)]
448        default: bool,
449
450        /// Install the skill without making blyte the default in CLAUDE.md
451        #[arg(long)]
452        no_default: bool,
453
454        /// Do not set Claude Code's status line
455        #[arg(long)]
456        no_statusline: bool,
457
458        /// Do not set Claude Code's auto-compact window
459        #[arg(long)]
460        no_autocompact: bool,
461
462        /// Which orchestrator to set up: claude (Claude Code), codex (Codex CLI) or all
463        #[arg(
464            long,
465            default_value = "claude",
466            value_parser = ["claude", "codex", "all"]
467        )]
468        harness: String,
469
470        /// Default implementer model to write to the env file
471        #[arg(long, value_name = "ID")]
472        model: Option<String>,
473    },
474
475    /// Remove the skill and the CLAUDE.md block
476    Uninstall {
477        /// Remove from repository instead of personal ~/.claude
478        #[arg(long)]
479        project: bool,
480
481        /// Which orchestrator to set up: claude (Claude Code), codex (Codex CLI) or all
482        #[arg(
483            long,
484            default_value = "claude",
485            value_parser = ["claude", "codex", "all"]
486        )]
487        harness: String,
488    },
489
490    /// Print the skill markdown to stdout
491    Print,
492}
493
494#[derive(clap::Args, Debug, PartialEq, Clone)]
495pub struct SkillArgs {
496    #[command(subcommand)]
497    pub action: SkillAction,
498}
499
500#[derive(Parser, Debug, PartialEq)]
501#[command(
502    name = "blyte",
503    version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("BLYTE_BUILD"), ")"),
504    about = "A lean coding-agent harness with a sealed verification gate\nBare `blyte` starts the live surface for the current repository.",
505    subcommand_precedence_over_arg = true
506)]
507pub struct Cli {
508    #[command(subcommand)]
509    pub command: Option<Command>,
510
511    /// Direct task prompt to run in single-shot / headless mode
512    #[arg(index = 1)]
513    pub prompt: Option<String>,
514
515    /// Verification gate command (e.g. 'pytest', 'cargo test'). Several steps may be given one per line: every step runs and all failures are reported together.
516    #[arg(short, long)]
517    pub gate: Option<String>,
518
519    /// Run blyte as the orchestrator: plan, dispatch implementers with `blyte dispatch`, review and merge
520    #[arg(long, conflicts_with = "gate")]
521    pub orchestrate: bool,
522
523    /// Command to run on the host when the orchestrator delegates work via the `dispatch` tool
524    #[arg(long, requires = "orchestrate")]
525    pub dispatch_cmd: Option<String>,
526
527    /// Context strategy: 'conversational' (append-all chat) or 'folded' (append-only chat, oldest half folded into digests past a budget)
528    #[arg(
529        long,
530        default_value = "folded",
531        value_parser = ["conversational", "folded"]
532    )]
533    pub context: String,
534
535    /// Model identifier or provider selection
536    #[arg(short, long)]
537    pub model: Option<String>,
538
539    /// Run inside an isolated container workspace instead of local host
540    #[arg(long)]
541    pub container: Option<String>,
542
543    /// Maximum turn budget
544    #[arg(long, default_value = "25")]
545    pub max_turns: usize,
546
547    /// Maximum verification gate attempts before failing
548    #[arg(long, default_value = "5")]
549    pub max_gates: usize,
550
551    /// Enable automatic rollback to baseline git commit if gate fails (disable with --rollback=false)
552    #[arg(
553        long,
554        default_value_t = true,
555        action = clap::ArgAction::Set,
556        num_args = 0..=1,
557        require_equals = true,
558        default_missing_value = "true",
559        value_parser = clap::builder::BoolishValueParser::new()
560    )]
561    pub rollback: bool,
562
563    /// Working directory inside the container when --container is set
564    #[arg(long, default_value = "/workspace")]
565    pub container_workdir: String,
566
567    /// Wall-clock budget in seconds; the run stops itself and reports when it is spent
568    #[arg(long)]
569    pub max_seconds: Option<u64>,
570
571    /// Maximum spend in USD; the run stops before a model call once reached
572    #[arg(long = "max-cost")]
573    pub max_cost_usd: Option<f64>,
574
575    /// Write a JSON run report to this path when the headless run exits
576    #[arg(long)]
577    pub report: Option<PathBuf>,
578
579    /// Approximate token budget for the verbatim tail before folding (folded context; default 48000)
580    #[arg(long)]
581    pub fold_budget: Option<usize>,
582
583    /// Sandbox the commands blyte runs on this machine (macOS Seatbelt, Linux Landlock): 'on' or 'off'
584    #[arg(
585        long,
586        default_value = "on",
587        value_parser = ["on", "off"]
588    )]
589    pub sandbox: String,
590
591    /// Let commands blyte runs connect out: 'on' or 'off' (default 'on', or 'off' under --orchestrate). 'off' needs the sandbox
592    #[arg(
593        long,
594        value_parser = ["on", "off"]
595    )]
596    pub network: Option<String>,
597
598    /// Let sandboxed commands read this path despite the credential deny-list (repeatable)
599    #[arg(long = "allow-read")]
600    pub allow_read: Vec<PathBuf>,
601
602    /// Pass this environment variable to commands even though it looks like a credential (repeatable)
603    #[arg(long = "pass-env")]
604    pub pass_env: Vec<String>,
605
606    /// Directory allowed for reading with the read and grep tools (repeatable)
607    #[arg(long = "read-root", value_name = "DIR")]
608    pub read_roots: Vec<PathBuf>,
609
610    /// Gates in this run do not take a machine-wide slot
611    #[arg(long)]
612    pub no_gate_slot: bool,
613
614    /// Whether this is a research run: periodically remind the model to keep report.md updated
615    #[arg(long)]
616    pub research: bool,
617
618    /// Research run: check report.md's claims against their cited lines
619    #[arg(long = "claim-check")]
620    pub claim_check: bool,
621
622    /// Run the verification gate once before the first model call and stop as blocked if it fails
623    #[arg(long = "base-check")]
624    pub base_check: bool,
625
626    /// Directory containing an untouched checkout of the base commit for running the base check beside the model's first turns
627    #[arg(long = "base-check-dir", value_name = "DIR")]
628    pub base_check_dir: Option<PathBuf>,
629
630    #[arg(
631        long,
632        help = "Run the interactive terminal session instead of starting the live surface"
633    )]
634    pub terminal: bool,
635
636    #[arg(
637        long,
638        value_name = "N",
639        help = "Port for the live surface (0 picks a free port)"
640    )]
641    pub port: Option<u16>,
642
643    #[arg(long = "no-open", help = "Do not open the live surface in the browser")]
644    pub no_open: bool,
645
646    #[arg(
647        long,
648        value_name = "N",
649        value_parser = clap::value_parser!(u64).range(1..=31),
650        help = "How many days back to include finished runs in the live surface (1 to 31, default 14)"
651    )]
652    pub days: Option<u64>,
653}
654
655/// Turn and context defaults for `--orchestrate`. A flag the user gave explicitly wins.
656pub fn apply_orchestrate_defaults(cli: &mut Cli, matches: &clap::ArgMatches) {
657    if !cli.orchestrate {
658        return;
659    }
660    if matches.value_source("max_turns") == Some(clap::parser::ValueSource::DefaultValue) {
661        cli.max_turns = 1000;
662    }
663    if cli.fold_budget.is_none() {
664        cli.fold_budget = Some(100_000);
665    }
666}