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