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