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    /// Show the instructions for sandbox 'on' or 'off'
382    #[arg(long, value_parser = ["on", "off"])]
383    pub sandbox: Option<String>,
384}
385
386#[derive(clap::Subcommand, Debug, PartialEq, Clone)]
387pub enum SkillAction {
388    /// Install the Claude Code skill
389    Install {
390        /// Install to repository instead of personal ~/.claude
391        #[arg(long)]
392        project: bool,
393
394        /// Overwrite even if existing skill was modified
395        #[arg(long)]
396        force: bool,
397
398        /// Also tell Claude Code to delegate implementation to blyte by default, in CLAUDE.md
399        #[arg(long, hide = true)]
400        default: bool,
401
402        /// Install the skill without making blyte the default in CLAUDE.md
403        #[arg(long)]
404        no_default: bool,
405
406        /// Do not set Claude Code's status line
407        #[arg(long)]
408        no_statusline: bool,
409
410        /// Do not set Claude Code's auto-compact window
411        #[arg(long)]
412        no_autocompact: bool,
413
414        /// Which orchestrator to set up: claude (Claude Code), codex (Codex CLI) or all
415        #[arg(
416            long,
417            default_value = "claude",
418            value_parser = ["claude", "codex", "all"]
419        )]
420        harness: String,
421
422        /// Default implementer model to write to the env file
423        #[arg(long, value_name = "ID")]
424        model: Option<String>,
425    },
426
427    /// Remove the skill and the CLAUDE.md block
428    Uninstall {
429        /// Remove from repository instead of personal ~/.claude
430        #[arg(long)]
431        project: bool,
432
433        /// Which orchestrator to set up: claude (Claude Code), codex (Codex CLI) or all
434        #[arg(
435            long,
436            default_value = "claude",
437            value_parser = ["claude", "codex", "all"]
438        )]
439        harness: String,
440    },
441
442    /// Print the skill markdown to stdout
443    Print,
444}
445
446#[derive(clap::Args, Debug, PartialEq, Clone)]
447pub struct SkillArgs {
448    #[command(subcommand)]
449    pub action: SkillAction,
450}
451
452#[derive(Parser, Debug, PartialEq)]
453#[command(
454    name = "blyte",
455    version = concat!(env!("CARGO_PKG_VERSION"), " (", env!("BLYTE_BUILD"), ")"),
456    about = "A lean coding-agent harness with a sealed verification gate\nBare `blyte` starts the live surface for the current repository.",
457    subcommand_precedence_over_arg = true
458)]
459pub struct Cli {
460    #[command(subcommand)]
461    pub command: Option<Command>,
462
463    /// Direct task prompt to run in single-shot / headless mode
464    #[arg(index = 1)]
465    pub prompt: Option<String>,
466
467    /// 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.
468    #[arg(short, long)]
469    pub gate: Option<String>,
470
471    /// Run blyte as the orchestrator: plan, dispatch implementers with `blyte dispatch`, review and merge
472    #[arg(long, conflicts_with = "gate")]
473    pub orchestrate: bool,
474
475    /// Command to run on the host when the orchestrator delegates work via the `dispatch` tool
476    #[arg(long, requires = "orchestrate")]
477    pub dispatch_cmd: Option<String>,
478
479    /// Context strategy: 'conversational' (append-all chat) or 'folded' (append-only chat, oldest half folded into digests past a budget)
480    #[arg(
481        long,
482        default_value = "folded",
483        value_parser = ["conversational", "folded"]
484    )]
485    pub context: String,
486
487    /// Model identifier or provider selection
488    #[arg(short, long)]
489    pub model: Option<String>,
490
491    /// Run inside an isolated container workspace instead of local host
492    #[arg(long)]
493    pub container: Option<String>,
494
495    /// Maximum turn budget
496    #[arg(long, default_value = "25")]
497    pub max_turns: usize,
498
499    /// Maximum verification gate attempts before failing
500    #[arg(long, default_value = "5")]
501    pub max_gates: usize,
502
503    /// Enable automatic rollback to baseline git commit if gate fails (disable with --rollback=false)
504    #[arg(
505        long,
506        default_value_t = true,
507        action = clap::ArgAction::Set,
508        num_args = 0..=1,
509        require_equals = true,
510        default_missing_value = "true",
511        value_parser = clap::builder::BoolishValueParser::new()
512    )]
513    pub rollback: bool,
514
515    /// Working directory inside the container when --container is set
516    #[arg(long, default_value = "/workspace")]
517    pub container_workdir: String,
518
519    /// Wall-clock budget in seconds; the run stops itself and reports when it is spent
520    #[arg(long)]
521    pub max_seconds: Option<u64>,
522
523    /// Maximum spend in USD; the run stops before a model call once reached
524    #[arg(long = "max-cost")]
525    pub max_cost_usd: Option<f64>,
526
527    /// Write a JSON run report to this path when the headless run exits
528    #[arg(long)]
529    pub report: Option<PathBuf>,
530
531    /// Approximate token budget for the verbatim tail before folding (folded context; default 48000)
532    #[arg(long)]
533    pub fold_budget: Option<usize>,
534
535    /// Sandbox the commands blyte runs on this machine (macOS Seatbelt, Linux Landlock): 'on' or 'off'
536    #[arg(
537        long,
538        default_value = "on",
539        value_parser = ["on", "off"]
540    )]
541    pub sandbox: String,
542
543    /// Let commands blyte runs connect out: 'on' or 'off' (default 'on', or 'off' under --orchestrate). 'off' needs the sandbox
544    #[arg(
545        long,
546        value_parser = ["on", "off"]
547    )]
548    pub network: Option<String>,
549
550    /// Let sandboxed commands read this path despite the credential deny-list (repeatable)
551    #[arg(long = "allow-read")]
552    pub allow_read: Vec<PathBuf>,
553
554    /// Pass this environment variable to commands even though it looks like a credential (repeatable)
555    #[arg(long = "pass-env")]
556    pub pass_env: Vec<String>,
557
558    /// Directory allowed for reading with the read and grep tools (repeatable)
559    #[arg(long = "read-root", value_name = "DIR")]
560    pub read_roots: Vec<PathBuf>,
561
562    /// Gates in this run do not take a machine-wide slot
563    #[arg(long)]
564    pub no_gate_slot: bool,
565
566    /// Whether this is a research run: periodically remind the model to keep report.md updated
567    #[arg(long)]
568    pub research: bool,
569
570    /// Research run: check report.md's claims against their cited lines
571    #[arg(long = "claim-check")]
572    pub claim_check: bool,
573
574    /// Run the verification gate once before the first model call and stop as blocked if it fails
575    #[arg(long = "base-check")]
576    pub base_check: bool,
577
578    #[arg(
579        long,
580        help = "Run the interactive terminal session instead of starting the live surface"
581    )]
582    pub terminal: bool,
583
584    #[arg(
585        long,
586        value_name = "N",
587        help = "Port for the live surface (0 picks a free port)"
588    )]
589    pub port: Option<u16>,
590
591    #[arg(long = "no-open", help = "Do not open the live surface in the browser")]
592    pub no_open: bool,
593
594    #[arg(
595        long,
596        value_name = "N",
597        value_parser = clap::value_parser!(u64).range(1..=31),
598        help = "How many days back to include finished runs in the live surface (1 to 31, default 14)"
599    )]
600    pub days: Option<u64>,
601}
602
603/// Turn and context defaults for `--orchestrate`. A flag the user gave explicitly wins.
604pub fn apply_orchestrate_defaults(cli: &mut Cli, matches: &clap::ArgMatches) {
605    if !cli.orchestrate {
606        return;
607    }
608    if matches.value_source("max_turns") == Some(clap::parser::ValueSource::DefaultValue) {
609        cli.max_turns = 1000;
610    }
611    if cli.fold_budget.is_none() {
612        cli.fold_budget = Some(100_000);
613    }
614}