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