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