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