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