Skip to main content

beads_rs/cli/
mod.rs

1//! CLI surface for beads-rs.
2//!
3//! Goal:
4//! - Beads-go parity for the "main set" commands we care about now
5//! - Extensible command tree + thin handlers
6//! - LLM-robust parsing (aliases, boolish flags, case/dash tolerance)
7
8use std::ffi::OsString;
9use std::path::PathBuf;
10
11use clap::{ArgAction, Args, Parser, Subcommand, builder::BoolishValueParser};
12
13use crate::core::{BeadId, BeadType, DepKind, Priority};
14use crate::daemon::ipc::{Request, Response, ResponsePayload, send_request};
15use crate::daemon::query::{QueryResult, SortField};
16use crate::{Error, Result};
17
18mod commands;
19mod render;
20
21// =============================================================================
22// Entry + global options
23// =============================================================================
24
25#[derive(Parser, Debug)]
26#[command(
27    name = "bd",
28    version,
29    about = "Beads distributed issue tracker",
30    infer_subcommands = true,
31    infer_long_args = true,
32    arg_required_else_help = true
33)]
34pub struct Cli {
35    /// Machine-readable JSON output (default: false; use `--json` for scripting).
36    #[arg(
37        long,
38        global = true,
39        default_value_t = false,
40        num_args = 0..=1,
41        value_parser = BoolishValueParser::new()
42    )]
43    pub json: bool,
44
45    /// Repository path (default: discover from cwd).
46    #[arg(long, global = true, value_name = "PATH")]
47    pub repo: Option<PathBuf>,
48
49    /// Actor identity (applies when daemon starts).
50    #[arg(long, global = true, value_name = "ACTOR")]
51    pub actor: Option<String>,
52
53    /// Errors only.
54    #[arg(
55        short = 'q',
56        long,
57        global = true,
58        default_value_t = false,
59        num_args = 0..=1,
60        value_parser = BoolishValueParser::new()
61    )]
62    pub quiet: bool,
63
64    /// Debug output (repeat for more).
65    #[arg(short = 'v', long, global = true, action = ArgAction::Count)]
66    pub verbose: u8,
67
68    #[command(subcommand)]
69    pub command: Commands,
70}
71
72#[derive(Subcommand, Debug)]
73pub enum Commands {
74    /// Initialize beads store in this repo.
75    Init,
76
77    /// Create a new bead.
78    #[command(alias = "new")]
79    Create(CreateArgs),
80
81    /// Show a bead.
82    Show(ShowArgs),
83
84    /// List beads.
85    List(ListArgs),
86
87    /// Search beads by text (alias for list QUERY).
88    Search(SearchArgs),
89
90    /// List beads that are ready to work on.
91    Ready(ReadyArgs),
92
93    /// Show blocked issues.
94    Blocked,
95
96    /// Show stale issues (not updated recently).
97    Stale(StaleArgs),
98
99    /// Count issues matching filters.
100    Count(CountArgs),
101
102    /// Show deleted (tombstoned) issues.
103    Deleted(DeletedArgs),
104
105    /// Wait for debounced sync flush to complete.
106    Sync,
107
108    /// Upgrade bd to the latest version.
109    Upgrade(UpgradeArgs),
110
111    /// Update a bead.
112    Update(UpdateArgs),
113
114    /// Close a bead.
115    Close(CloseArgs),
116
117    /// Reopen a bead.
118    Reopen { id: String },
119
120    /// Delete a bead.
121    Delete(DeleteArgs),
122
123    /// Claim a bead for work (lease).
124    Claim(ClaimArgs),
125
126    /// Release claim on a bead.
127    Unclaim { id: String },
128
129    /// Comments (alias for notes).
130    #[command(alias = "notes")]
131    Comments(CommentsArgs),
132
133    /// Add a comment (compat alias).
134    #[command(alias = "note")]
135    Comment(CommentAddArgs),
136
137    /// Dependency operations.
138    Dep {
139        #[command(subcommand)]
140        cmd: DepCmd,
141    },
142
143    /// Label operations.
144    Label {
145        #[command(subcommand)]
146        cmd: LabelCmd,
147    },
148
149    /// Epic operations.
150    Epic {
151        #[command(subcommand)]
152        cmd: EpicCmd,
153    },
154
155    /// Status overview.
156    Status,
157
158    /// Output AI-optimized workflow context.
159    Prime,
160
161    /// Display instructions for configuring AGENTS.md.
162    Onboard(OnboardArgs),
163
164    /// Setup integration with AI editors.
165    Setup {
166        #[command(subcommand)]
167        cmd: SetupCmd,
168    },
169
170    /// Internal migration tooling (hidden from global help).
171    #[command(hide = true)]
172    Migrate {
173        #[command(subcommand)]
174        cmd: MigrateCmd,
175    },
176
177    /// Daemon control (hidden). `bd daemon run` starts the service.
178    #[command(hide = true)]
179    Daemon {
180        #[command(subcommand)]
181        cmd: DaemonCmd,
182    },
183}
184
185#[derive(Subcommand, Debug)]
186pub enum DaemonCmd {
187    /// Run the daemon in the foreground (internal).
188    Run,
189}
190
191// =============================================================================
192// Per-command args
193// =============================================================================
194
195#[derive(Args, Debug)]
196pub struct CreateArgs {
197    /// Title (positional).
198    #[arg(value_name = "TITLE", required = false)]
199    pub title: Option<String>,
200
201    /// Title (compat: `--title`).
202    #[arg(long = "title", alias = "title-flag", value_name = "TITLE")]
203    pub title_flag: Option<String>,
204
205    /// Create multiple issues from a markdown file.
206    #[arg(short = 'f', long = "file", value_name = "PATH")]
207    pub file: Option<PathBuf>,
208
209    /// Issue type.
210    #[arg(short = 't', long = "type", alias = "issue-type", value_parser = parse_bead_type)]
211    pub bead_type: Option<BeadType>,
212
213    /// Priority 0-4 or words like "high".
214    #[arg(short = 'p', long, value_parser = parse_priority)]
215    pub priority: Option<Priority>,
216
217    /// Description.
218    #[arg(short = 'd', long, allow_hyphen_values = true)]
219    pub description: Option<String>,
220
221    /// Alias for --description (GitHub CLI convention).
222    #[arg(long = "body", hide = true, allow_hyphen_values = true)]
223    pub body: Option<String>,
224
225    /// Assignee (compat; only supports current actor).
226    #[arg(short = 'a', long)]
227    pub assignee: Option<String>,
228
229    /// Labels (comma-separated or repeat).
230    #[arg(short = 'l', long = "labels", value_delimiter = ',', num_args = 0..)]
231    pub labels: Vec<String>,
232
233    /// Alias for --labels.
234    #[arg(long = "label", hide = true, value_delimiter = ',', num_args = 0..)]
235    pub label: Vec<String>,
236
237    /// Design text.
238    #[arg(long, allow_hyphen_values = true)]
239    pub design: Option<String>,
240
241    /// Acceptance criteria text.
242    #[arg(
243        long = "acceptance",
244        alias = "acceptance-criteria",
245        allow_hyphen_values = true
246    )]
247    pub acceptance: Option<String>,
248
249    /// External reference (e.g., "gh-9", "jira-ABC").
250    #[arg(long = "external-ref")]
251    pub external_ref: Option<String>,
252
253    /// Explicit issue ID (partitioning).
254    #[arg(long)]
255    pub id: Option<String>,
256
257    /// Parent bead id (adds `parent` dep).
258    #[arg(long)]
259    pub parent: Option<String>,
260
261    /// Dependencies (repeat or comma-separated): "type:id" or "id" (defaults to blocks).
262    #[arg(long = "deps", value_delimiter = ',', num_args = 0..)]
263    pub deps: Vec<String>,
264
265    /// Time estimate in minutes.
266    #[arg(short = 'e', long)]
267    pub estimate: Option<u32>,
268
269    /// No-op (compat). beads-rs doesn't require forcing.
270    #[arg(long)]
271    pub force: bool,
272}
273
274#[derive(Args, Debug)]
275pub struct UpgradeArgs {
276    /// Run upgrade in the background (internal).
277    #[arg(long, hide = true, default_value_t = false)]
278    pub background: bool,
279}
280
281#[derive(Args, Debug)]
282pub struct ShowArgs {
283    pub id: String,
284
285    /// No-op for compatibility (children are always shown).
286    #[arg(long, hide = true)]
287    pub children: bool,
288}
289
290#[derive(Args, Debug)]
291pub struct ListArgs {
292    /// Status filter (open, in_progress, closed).
293    #[arg(short = 's', long, value_parser = parse_status)]
294    pub status: Option<String>,
295
296    /// Type filter.
297    #[arg(short = 't', long = "type", alias = "issue-type", value_parser = parse_bead_type)]
298    pub bead_type: Option<BeadType>,
299
300    /// Priority filter.
301    #[arg(short = 'p', long, value_parser = parse_priority)]
302    pub priority: Option<Priority>,
303
304    /// Assignee filter.
305    #[arg(short = 'a', long)]
306    pub assignee: Option<String>,
307
308    /// Label filter (repeat or comma-separated).
309    #[arg(short = 'l', long = "label", alias = "labels", value_delimiter = ',', num_args = 0..)]
310    pub labels: Vec<String>,
311
312    /// Show labels in output.
313    #[arg(short = 'L', long = "show-labels")]
314    pub show_labels: bool,
315
316    /// Limit results.
317    #[arg(short = 'n', long)]
318    pub limit: Option<usize>,
319
320    /// Sort field (priority|created|updated|title) with optional :asc/:desc.
321    #[arg(long)]
322    pub sort: Option<String>,
323
324    /// Filter by parent epic ID (shows children of this epic).
325    #[arg(long)]
326    pub parent: Option<String>,
327
328    /// Optional text query (matches title/description).
329    #[arg(value_name = "QUERY", num_args = 0..)]
330    pub query: Vec<String>,
331}
332
333#[derive(Args, Debug)]
334pub struct SearchArgs {
335    /// Search query (multiple words allowed).
336    #[arg(num_args = 1..)]
337    pub query: Vec<String>,
338
339    /// Limit results.
340    #[arg(short = 'n', long)]
341    pub limit: Option<usize>,
342}
343
344#[derive(Args, Debug)]
345pub struct ReadyArgs {
346    /// Limit results.
347    #[arg(short = 'n', long)]
348    pub limit: Option<usize>,
349}
350
351#[derive(Args, Debug)]
352pub struct StaleArgs {
353    /// Issues not updated in this many days.
354    #[arg(short = 'd', long, default_value_t = 30)]
355    pub days: u32,
356
357    /// Filter by status (open|in_progress|blocked).
358    #[arg(short = 's', long)]
359    pub status: Option<String>,
360
361    /// Maximum issues to show.
362    #[arg(short = 'n', long, default_value_t = 50)]
363    pub limit: usize,
364}
365
366#[derive(Args, Debug)]
367pub struct CountArgs {
368    /// Filter by status (open, in_progress, blocked, closed).
369    #[arg(short = 's', long)]
370    pub status: Option<String>,
371
372    /// Filter by priority (0-4).
373    #[arg(short = 'p', long, value_parser = parse_priority)]
374    pub priority: Option<Priority>,
375
376    /// Filter by assignee.
377    #[arg(short = 'a', long)]
378    pub assignee: Option<String>,
379
380    /// Filter by type (bug, feature, task, epic, chore).
381    #[arg(short = 't', long = "type", alias = "issue-type", value_parser = parse_bead_type)]
382    pub bead_type: Option<BeadType>,
383
384    /// Filter by labels (AND: must have ALL). Repeat or comma-separated.
385    #[arg(short = 'l', long = "label", value_delimiter = ',', num_args = 0..)]
386    pub labels: Vec<String>,
387
388    /// Filter by labels (OR: must have AT LEAST ONE). Repeat or comma-separated.
389    #[arg(long = "label-any", value_delimiter = ',', num_args = 0..)]
390    pub labels_any: Vec<String>,
391
392    /// Filter by title text (case-insensitive substring match).
393    #[arg(long)]
394    pub title: Option<String>,
395
396    /// Filter by specific issue IDs (comma-separated).
397    #[arg(long)]
398    pub id: Option<String>,
399
400    /// Filter by title substring.
401    #[arg(long = "title-contains")]
402    pub title_contains: Option<String>,
403
404    /// Filter by description substring.
405    #[arg(long = "desc-contains")]
406    pub desc_contains: Option<String>,
407
408    /// Filter by notes substring.
409    #[arg(long = "notes-contains")]
410    pub notes_contains: Option<String>,
411
412    /// Filter issues created after date (YYYY-MM-DD or RFC3339).
413    #[arg(long = "created-after")]
414    pub created_after: Option<String>,
415
416    /// Filter issues created before date (YYYY-MM-DD or RFC3339).
417    #[arg(long = "created-before")]
418    pub created_before: Option<String>,
419
420    /// Filter issues updated after date (YYYY-MM-DD or RFC3339).
421    #[arg(long = "updated-after")]
422    pub updated_after: Option<String>,
423
424    /// Filter issues updated before date (YYYY-MM-DD or RFC3339).
425    #[arg(long = "updated-before")]
426    pub updated_before: Option<String>,
427
428    /// Filter issues closed after date (YYYY-MM-DD or RFC3339).
429    #[arg(long = "closed-after")]
430    pub closed_after: Option<String>,
431
432    /// Filter issues closed before date (YYYY-MM-DD or RFC3339).
433    #[arg(long = "closed-before")]
434    pub closed_before: Option<String>,
435
436    /// Filter issues with empty description.
437    #[arg(long = "empty-description")]
438    pub empty_description: bool,
439
440    /// Filter issues with no assignee.
441    #[arg(long = "no-assignee")]
442    pub no_assignee: bool,
443
444    /// Filter issues with no labels.
445    #[arg(long = "no-labels")]
446    pub no_labels: bool,
447
448    /// Filter by minimum priority (inclusive).
449    #[arg(long = "priority-min", value_parser = parse_priority)]
450    pub priority_min: Option<Priority>,
451
452    /// Filter by maximum priority (inclusive).
453    #[arg(long = "priority-max", value_parser = parse_priority)]
454    pub priority_max: Option<Priority>,
455
456    /// Group count by status.
457    #[arg(long = "by-status")]
458    pub by_status: bool,
459
460    /// Group count by priority.
461    #[arg(long = "by-priority")]
462    pub by_priority: bool,
463
464    /// Group count by issue type.
465    #[arg(long = "by-type")]
466    pub by_type: bool,
467
468    /// Group count by assignee.
469    #[arg(long = "by-assignee")]
470    pub by_assignee: bool,
471
472    /// Group count by label.
473    #[arg(long = "by-label")]
474    pub by_label: bool,
475}
476
477#[derive(Args, Debug)]
478pub struct DeletedArgs {
479    /// Optional issue id to show details.
480    #[arg(value_name = "ISSUE_ID", required = false)]
481    pub id: Option<String>,
482
483    /// Show deletions within this time range (e.g., 7d, 30d, 2w).
484    #[arg(long, default_value = "7d")]
485    pub since: String,
486
487    /// Show all tracked deletions.
488    #[arg(long)]
489    pub all: bool,
490}
491
492#[derive(Args, Debug)]
493pub struct UpdateArgs {
494    pub id: String,
495
496    /// Reparent the bead (adds/removes `parent` dependency).
497    #[arg(long)]
498    pub parent: Option<String>,
499
500    /// Remove any existing parent relationship.
501    #[arg(long = "no-parent", conflicts_with = "parent")]
502    pub no_parent: bool,
503
504    #[arg(long)]
505    pub title: Option<String>,
506
507    #[arg(short = 'd', long, allow_hyphen_values = true)]
508    pub description: Option<String>,
509
510    /// Alias for --description (GitHub CLI convention).
511    #[arg(long = "body", hide = true, allow_hyphen_values = true)]
512    pub body: Option<String>,
513
514    #[arg(long, allow_hyphen_values = true)]
515    pub design: Option<String>,
516
517    #[arg(
518        long = "acceptance",
519        alias = "acceptance-criteria",
520        allow_hyphen_values = true
521    )]
522    pub acceptance: Option<String>,
523
524    /// External reference (e.g., "gh-9", "jira-ABC").
525    #[arg(long = "external-ref")]
526    pub external_ref: Option<String>,
527
528    /// Time estimate in minutes.
529    #[arg(short = 'e', long)]
530    pub estimate: Option<u32>,
531
532    #[arg(short = 's', long, value_parser = parse_status)]
533    pub status: Option<String>,
534
535    /// Close reason (only valid with --status=closed).
536    #[arg(long, allow_hyphen_values = true)]
537    pub reason: Option<String>,
538
539    #[arg(short = 'p', long, value_parser = parse_priority)]
540    pub priority: Option<Priority>,
541
542    /// Change the issue type (bug, feature, task, epic, chore).
543    #[arg(short = 't', long = "type", alias = "issue-type", value_parser = parse_bead_type)]
544    pub bead_type: Option<BeadType>,
545
546    /// Compat: assignee/claim.
547    #[arg(short = 'a', long)]
548    pub assignee: Option<String>,
549
550    #[arg(long = "add-label", alias = "add_label", value_delimiter = ',', num_args = 0..)]
551    pub add_label: Vec<String>,
552
553    #[arg(long = "remove-label", alias = "remove_label", value_delimiter = ',', num_args = 0..)]
554    pub remove_label: Vec<String>,
555
556    /// Add a note.
557    #[arg(long = "notes", alias = "note", allow_hyphen_values = true)]
558    pub notes: Option<String>,
559
560    /// Dependencies to add (repeat or comma-separated): "type:id" or "id" (defaults to blocks).
561    #[arg(long = "deps", value_delimiter = ',', num_args = 0..)]
562    pub deps: Vec<String>,
563}
564
565#[derive(Args, Debug)]
566pub struct CloseArgs {
567    pub id: String,
568
569    #[arg(long)]
570    pub reason: Option<String>,
571}
572
573#[derive(Args, Debug)]
574pub struct DeleteArgs {
575    /// One or more issue IDs to delete.
576    #[arg(required = true, num_args = 1..)]
577    pub ids: Vec<String>,
578
579    #[arg(long)]
580    pub reason: Option<String>,
581}
582
583#[derive(Args, Debug)]
584pub struct ClaimArgs {
585    pub id: String,
586
587    /// Lease duration in seconds.
588    #[arg(long, default_value_t = 3600)]
589    pub lease_secs: u64,
590}
591
592#[derive(Args, Debug)]
593pub struct CommentsArgs {
594    /// Optional subcommand.
595    #[command(subcommand)]
596    pub cmd: Option<CommentsCmd>,
597
598    /// Issue ID (lists comments when provided without a subcommand).
599    #[arg(value_name = "ID", required = false)]
600    pub id: Option<String>,
601}
602
603#[derive(Subcommand, Debug)]
604pub enum CommentsCmd {
605    /// Add a comment to an issue.
606    Add(CommentAddArgs),
607}
608
609#[derive(Args, Debug)]
610pub struct CommentAddArgs {
611    pub id: String,
612
613    /// Comment content (rest of args). If empty, reads stdin.
614    #[arg(trailing_var_arg = true, num_args = 0..)]
615    pub content: Vec<String>,
616}
617
618#[derive(Subcommand, Debug)]
619pub enum DepCmd {
620    /// Add a dependency: FROM depends on TO (FROM waits for TO to complete).
621    Add(DepAddArgs),
622    /// Remove a dependency between two issues.
623    Rm(DepRmArgs),
624    /// Show dependency tree for an issue.
625    Tree { id: String },
626}
627
628#[derive(Args, Debug)]
629pub struct DepAddArgs {
630    /// Issue that depends on another (waits for TO to complete).
631    pub from: String,
632    /// Issue that must complete first (blocks FROM).
633    pub to: String,
634    #[arg(long, alias = "type", value_parser = parse_dep_kind)]
635    pub kind: Option<DepKind>,
636}
637
638#[derive(Args, Debug)]
639pub struct DepRmArgs {
640    pub from: String,
641    pub to: String,
642    #[arg(long, alias = "type", value_parser = parse_dep_kind)]
643    pub kind: Option<DepKind>,
644}
645
646#[derive(Subcommand, Debug)]
647pub enum LabelCmd {
648    /// Add a label to one or more issues.
649    Add(LabelBatchArgs),
650    /// Remove a label from one or more issues.
651    Remove(LabelBatchArgs),
652    /// List labels for an issue.
653    List { id: String },
654    /// List all labels in the repo.
655    #[command(name = "list-all")]
656    ListAll,
657}
658
659#[derive(Args, Debug)]
660pub struct LabelBatchArgs {
661    /// Arguments in the form: `<issue-id...> <label>` (label is last).
662    #[arg(trailing_var_arg = true, num_args = 2..)]
663    pub args: Vec<String>,
664}
665
666#[derive(Subcommand, Debug)]
667pub enum EpicCmd {
668    /// Show epic completion status.
669    Status(EpicStatusArgs),
670    /// Close epics where all children are complete.
671    #[command(name = "close-eligible")]
672    CloseEligible(EpicCloseEligibleArgs),
673}
674
675#[derive(Subcommand, Debug)]
676pub enum SetupCmd {
677    /// Setup Claude Code integration (hooks for SessionStart/PreCompact).
678    Claude(SetupClaudeArgs),
679    /// Setup Cursor IDE integration (rules file).
680    Cursor(SetupCursorArgs),
681    /// Setup Aider integration (config + instructions).
682    Aider(SetupAiderArgs),
683}
684
685#[derive(Args, Debug)]
686pub struct SetupClaudeArgs {
687    /// Install for this project only (not globally).
688    #[arg(long)]
689    pub project: bool,
690
691    /// Check if Claude integration is installed.
692    #[arg(long)]
693    pub check: bool,
694
695    /// Remove bd hooks from Claude settings.
696    #[arg(long)]
697    pub remove: bool,
698}
699
700#[derive(Args, Debug)]
701pub struct SetupCursorArgs {
702    /// Check if Cursor integration is installed.
703    #[arg(long)]
704    pub check: bool,
705
706    /// Remove bd rules from Cursor.
707    #[arg(long)]
708    pub remove: bool,
709}
710
711#[derive(Args, Debug)]
712pub struct SetupAiderArgs {
713    /// Check if Aider integration is installed.
714    #[arg(long)]
715    pub check: bool,
716
717    /// Remove bd config from Aider.
718    #[arg(long)]
719    pub remove: bool,
720}
721
722#[derive(Args, Debug)]
723pub struct EpicStatusArgs {
724    /// Show only epics eligible for closure.
725    #[arg(long)]
726    pub eligible_only: bool,
727}
728
729#[derive(Args, Debug)]
730pub struct EpicCloseEligibleArgs {
731    /// Preview what would be closed without writing.
732    #[arg(long)]
733    pub dry_run: bool,
734}
735
736#[derive(Args, Debug)]
737pub struct OnboardArgs {
738    /// Generate BD_GUIDE.md at the specified path instead of printing instructions.
739    #[arg(long, value_name = "PATH")]
740    pub output: Option<PathBuf>,
741}
742
743// =============================================================================
744// Migrate (hidden/internal)
745// =============================================================================
746
747#[derive(Subcommand, Debug)]
748pub enum MigrateCmd {
749    /// Show current store format and whether migration is needed.
750    Detect,
751
752    /// Migrate canonical store to a target format version.
753    To(MigrateToArgs),
754
755    /// Import/migrate from beads-go export.
756    FromGo(MigrateFromGoArgs),
757}
758
759#[derive(Args, Debug)]
760pub struct MigrateToArgs {
761    /// Target format version.
762    pub to: u32,
763
764    /// Preview changes without writing commits.
765    #[arg(long)]
766    pub dry_run: bool,
767
768    /// Skip safety checks.
769    #[arg(long)]
770    pub force: bool,
771
772    /// Do not push to remote.
773    #[arg(long)]
774    pub no_push: bool,
775}
776
777#[derive(Args, Debug)]
778pub struct MigrateFromGoArgs {
779    /// Path to beads-go issues.jsonl (or export bundle).
780    #[arg(long, value_name = "PATH")]
781    pub input: PathBuf,
782
783    /// Override the bead ID root slug during import (e.g. `myrepo` for `myrepo-abc123`).
784    ///
785    /// When omitted, the importer preserves whatever slug is present in the export IDs.
786    #[arg(long, value_name = "SLUG")]
787    pub root_slug: Option<String>,
788
789    /// Preview without writing.
790    #[arg(long)]
791    pub dry_run: bool,
792
793    /// Skip safety checks.
794    #[arg(long)]
795    pub force: bool,
796
797    /// Do not push to remote.
798    #[arg(long)]
799    pub no_push: bool,
800}
801
802// =============================================================================
803// Public API
804// =============================================================================
805
806/// Parse CLI from raw args, applying normalization for LLM robustness.
807pub fn parse_from<I, T>(args: I) -> Cli
808where
809    I: IntoIterator<Item = T>,
810    T: Into<OsString> + Clone,
811{
812    let raw: Vec<OsString> = args.into_iter().map(|t| t.into()).collect();
813    Cli::parse_from(normalize_args(raw))
814}
815
816/// Run the CLI (used by bin).
817pub fn run(cli: Cli) -> Result<()> {
818    if !matches!(cli.command, Commands::Daemon { .. } | Commands::Upgrade(_)) {
819        crate::upgrade::maybe_spawn_auto_upgrade();
820    }
821
822    match cli.command {
823        Commands::Daemon { cmd } => match cmd {
824            DaemonCmd::Run => crate::daemon::run_daemon(),
825        },
826        // Prime is special: doesn't require repo, silently succeeds if not in beads project
827        Commands::Prime => commands::prime::handle(),
828        // Setup doesn't require an initialized beads repo
829        Commands::Setup { cmd } => match cmd {
830            SetupCmd::Claude(args) => {
831                commands::setup::handle_claude(args.project, args.check, args.remove)
832            }
833            SetupCmd::Cursor(args) => commands::setup::handle_cursor(args.check, args.remove),
834            SetupCmd::Aider(args) => commands::setup::handle_aider(args.check, args.remove),
835        },
836        // Onboard doesn't require an initialized beads repo
837        Commands::Onboard(args) => commands::onboard::handle(args.output.as_deref()),
838        Commands::Upgrade(args) => commands::upgrade::handle(cli.json, args.background),
839        cmd => {
840            let repo = resolve_repo(cli.repo)?;
841            let ctx = Ctx {
842                repo,
843                json: cli.json,
844            };
845
846            match cmd {
847                Commands::Init => commands::init::handle(&ctx),
848                Commands::Create(args) => commands::create::handle(&ctx, args),
849                Commands::Show(args) => commands::show::handle(&ctx, args),
850                Commands::List(args) => commands::list::handle_list(&ctx, args),
851                Commands::Search(args) => commands::list::handle_search(&ctx, args),
852                Commands::Ready(args) => commands::ready::handle(&ctx, args),
853                Commands::Blocked => commands::blocked::handle(&ctx),
854                Commands::Stale(args) => commands::stale::handle(&ctx, args),
855                Commands::Count(args) => commands::count::handle(&ctx, args),
856                Commands::Deleted(args) => commands::deleted::handle(&ctx, args),
857                Commands::Sync => commands::sync::handle(&ctx),
858                Commands::Update(args) => commands::update::handle(&ctx, args),
859                Commands::Close(args) => commands::close::handle(&ctx, args),
860                Commands::Reopen { id } => commands::reopen::handle(&ctx, id),
861                Commands::Delete(args) => commands::delete::handle(&ctx, args),
862                Commands::Claim(args) => commands::claim::handle(&ctx, args),
863                Commands::Unclaim { id } => commands::unclaim::handle(&ctx, id),
864                Commands::Comments(args) => commands::comments::handle_comments(&ctx, args),
865                Commands::Comment(args) => commands::comments::handle_comment_add(&ctx, args),
866                Commands::Dep { cmd } => commands::dep::handle(&ctx, cmd),
867                Commands::Label { cmd } => commands::label::handle(&ctx, cmd),
868                Commands::Epic { cmd } => commands::epic::handle(&ctx, cmd),
869                Commands::Status => commands::status::handle(&ctx),
870                Commands::Migrate { cmd } => commands::migrate::handle(&ctx, cmd),
871                // Daemon, Prime, Setup, Onboard, and Upgrade handled above.
872                Commands::Daemon { .. }
873                | Commands::Prime
874                | Commands::Setup { .. }
875                | Commands::Onboard(_)
876                | Commands::Upgrade(_) => Ok(()),
877            }
878        }
879    }
880}
881
882// =============================================================================
883// Context + helpers
884// =============================================================================
885
886#[derive(Clone)]
887struct Ctx {
888    repo: PathBuf,
889    json: bool,
890}
891
892fn resolve_repo(repo: Option<PathBuf>) -> Result<PathBuf> {
893    let p = if let Some(p) = repo {
894        p
895    } else {
896        let (_repo, path) = crate::repo::discover()?;
897        path
898    };
899
900    let abs = if p.is_absolute() {
901        p
902    } else {
903        let cwd = std::env::current_dir().map_err(|e| {
904            Error::Ipc(crate::daemon::IpcError::DaemonUnavailable(format!(
905                "failed to get cwd: {e}"
906            )))
907        })?;
908        cwd.join(p)
909    };
910
911    Ok(std::fs::canonicalize(&abs).unwrap_or(abs))
912}
913
914pub(super) fn normalize_bead_id(id: &str) -> Result<String> {
915    normalize_bead_id_for("id", id)
916}
917
918pub(super) fn normalize_bead_id_for(field: &str, id: &str) -> Result<String> {
919    let parsed = BeadId::parse(id).map_err(|e| {
920        Error::Op(crate::daemon::OpError::ValidationFailed {
921            field: field.into(),
922            reason: e.to_string(),
923        })
924    })?;
925    Ok(parsed.as_str().to_string())
926}
927
928pub(super) fn normalize_bead_ids(ids: Vec<String>) -> Result<Vec<String>> {
929    ids.into_iter().map(|id| normalize_bead_id(&id)).collect()
930}
931
932pub(super) fn normalize_dep_specs(specs: Vec<String>) -> Result<Vec<String>> {
933    let mut out = Vec::new();
934    for spec in specs {
935        for part in spec.split(',') {
936            let p = part.trim();
937            if p.is_empty() {
938                continue;
939            }
940
941            let (kind_opt, id_raw) = if let Some((k, id)) = p.split_once(':') {
942                let kind = parse_dep_kind(k).map_err(|msg| {
943                    Error::Op(crate::daemon::OpError::ValidationFailed {
944                        field: "deps".into(),
945                        reason: msg,
946                    })
947                })?;
948                (Some(kind), id.trim())
949            } else {
950                (None, p)
951            };
952
953            let id = normalize_bead_id_for("deps", id_raw)?;
954            let entry = if let Some(kind) = kind_opt {
955                format!("{}:{}", kind.as_str(), id)
956            } else {
957                id
958            };
959            out.push(entry);
960        }
961    }
962    Ok(out)
963}
964
965fn print_ok(payload: &ResponsePayload, json: bool) -> Result<()> {
966    let s = if json {
967        serde_json::to_string_pretty(payload).map_err(crate::daemon::IpcError::from)?
968    } else {
969        render::render_human(payload)
970    };
971
972    use std::io::Write;
973    let mut stdout = std::io::stdout().lock();
974    if let Err(e) = writeln!(stdout, "{s}")
975        && e.kind() != std::io::ErrorKind::BrokenPipe
976    {
977        return Err(crate::daemon::IpcError::from(e).into());
978    }
979    Ok(())
980}
981
982fn send(req: &Request) -> Result<ResponsePayload> {
983    match send_request(req) {
984        Ok(Response::Ok { ok }) => Ok(ok),
985        Ok(Response::Err { err }) => {
986            tracing::error!("error: {} - {}", err.code, err.message);
987            if let Some(details) = err.details {
988                tracing::error!("details: {}", details);
989            }
990            std::process::exit(1);
991        }
992        Err(e) => Err(e.into()),
993    }
994}
995
996fn fetch_issue(ctx: &Ctx, id: &str) -> Result<crate::api::Issue> {
997    let req = Request::Show {
998        repo: ctx.repo.clone(),
999        id: id.to_string(),
1000    };
1001    match send(&req)? {
1002        ResponsePayload::Query(QueryResult::Issue(issue)) => Ok(issue),
1003        other => Err(Error::Ipc(crate::daemon::IpcError::DaemonUnavailable(
1004            format!("unexpected response for show: {other:?}"),
1005        ))),
1006    }
1007}
1008
1009fn fetch_issue_summary(ctx: &Ctx, id: &str) -> Result<crate::api::IssueSummary> {
1010    let issue = fetch_issue(ctx, id)?;
1011    Ok(crate::api::IssueSummary::from_issue(&issue))
1012}
1013
1014// =============================================================================
1015// Parsing helpers (LLM robust)
1016// =============================================================================
1017
1018fn normalize_args(mut raw: Vec<OsString>) -> Vec<OsString> {
1019    if raw.is_empty() {
1020        return raw;
1021    }
1022
1023    let mut out = Vec::with_capacity(raw.len());
1024    out.push(raw.remove(0)); // program name
1025
1026    for arg in raw {
1027        let s = arg.to_string_lossy();
1028        if s.starts_with("--") {
1029            let mut pieces = s.splitn(2, '=');
1030            let flag = pieces.next().unwrap_or("");
1031            let val = pieces.next();
1032            let mut canon = flag.to_lowercase().replace('_', "-");
1033            canon = canonical_flag(&canon).to_string();
1034            if let Some(v) = val {
1035                out.push(OsString::from(format!("{canon}={v}")));
1036            } else {
1037                out.push(OsString::from(canon));
1038            }
1039        } else {
1040            out.push(arg);
1041        }
1042    }
1043    out
1044}
1045
1046fn canonical_flag(flag: &str) -> &str {
1047    match flag {
1048        "--issue-type" | "--bead-type" => "--type",
1049        "--prio" => "--priority",
1050        "--acceptance-criteria" => "--acceptance",
1051        "--addlabel" => "--add-label",
1052        "--removelabel" => "--remove-label",
1053        other => other,
1054    }
1055}
1056
1057fn parse_bead_type(raw: &str) -> std::result::Result<BeadType, String> {
1058    let s = raw.trim().to_lowercase();
1059    match s.as_str() {
1060        "bug" | "bugs" => Ok(BeadType::Bug),
1061        "feature" | "feat" | "features" => Ok(BeadType::Feature),
1062        "task" | "todo" | "tasks" => Ok(BeadType::Task),
1063        "epic" | "epics" => Ok(BeadType::Epic),
1064        "chore" | "chores" | "maintenance" => Ok(BeadType::Chore),
1065        _ => Err(format!("unknown bead type `{raw}`")),
1066    }
1067}
1068
1069fn parse_priority(raw: &str) -> std::result::Result<Priority, String> {
1070    let s = raw.trim().to_lowercase();
1071
1072    // Numeric, allow p1/P2 forms.
1073    let num_str = s.trim_start_matches('p');
1074    if let Ok(n) = num_str.parse::<u8>() {
1075        return Priority::new(n).map_err(|e| e.to_string());
1076    }
1077
1078    match s.as_str() {
1079        "critical" | "crit" => Ok(Priority::CRITICAL),
1080        "high" => Ok(Priority::HIGH),
1081        "medium" | "med" => Ok(Priority::MEDIUM),
1082        "low" => Ok(Priority::LOW),
1083        "backlog" | "lowest" => Ok(Priority::LOWEST),
1084        _ => Err(format!("invalid priority `{raw}`")),
1085    }
1086}
1087
1088fn parse_status(raw: &str) -> std::result::Result<String, String> {
1089    let s = raw.trim().to_lowercase().replace(['-', ' '], "_");
1090    let canon = match s.as_str() {
1091        "open" | "todo" => "open",
1092        "inprogress" | "in_progress" | "doing" | "wip" => "in_progress",
1093        "closed" | "done" | "complete" => "closed",
1094        other => other,
1095    };
1096    Ok(canon.to_string())
1097}
1098
1099fn parse_dep_kind(raw: &str) -> std::result::Result<DepKind, String> {
1100    DepKind::parse(raw).map_err(|e| e.to_string())
1101}
1102
1103fn parse_sort(raw: &str) -> std::result::Result<(SortField, bool), String> {
1104    let mut s = raw.trim().to_lowercase();
1105    let mut ascending = false;
1106
1107    if s.starts_with('-') {
1108        s = s.trim_start_matches('-').to_string();
1109        ascending = false;
1110    }
1111
1112    let tmp = s.clone();
1113    if let Some((field, dir)) = tmp.split_once(':') {
1114        s = field.to_string();
1115        ascending = matches!(dir, "asc" | "ascending");
1116    }
1117
1118    let field = match s.as_str() {
1119        "priority" | "prio" => SortField::Priority,
1120        "created" | "created_at" | "createdat" => SortField::CreatedAt,
1121        "updated" | "updated_at" | "updatedat" => SortField::UpdatedAt,
1122        "title" | "name" => SortField::Title,
1123        _ => return Err(format!("invalid sort field `{raw}`")),
1124    };
1125    Ok((field, ascending))
1126}
1127
1128fn parse_dep_edge(
1129    kind_flag: Option<DepKind>,
1130    from_raw: &str,
1131    to_raw: &str,
1132) -> std::result::Result<(DepKind, String, String), String> {
1133    let (kind_from, from_raw) = split_kind_id(from_raw)?;
1134    let (kind_to, to_raw) = split_kind_id(to_raw)?;
1135
1136    let kind = kind_flag
1137        .or(kind_from)
1138        .or(kind_to)
1139        .unwrap_or(DepKind::Blocks);
1140
1141    let from = BeadId::parse(&from_raw)
1142        .map_err(|e| format!("invalid from id {from_raw:?}: {e}"))?
1143        .as_str()
1144        .to_string();
1145    let to = BeadId::parse(&to_raw)
1146        .map_err(|e| format!("invalid to id {to_raw:?}: {e}"))?
1147        .as_str()
1148        .to_string();
1149
1150    Ok((kind, from, to))
1151}
1152
1153fn split_kind_id(raw: &str) -> std::result::Result<(Option<DepKind>, String), String> {
1154    if let Some((k, id)) = raw.split_once(':') {
1155        Ok((Some(parse_dep_kind(k)?), id.trim().to_string()))
1156    } else {
1157        Ok((None, raw.trim().to_string()))
1158    }
1159}
1160
1161fn current_actor_string() -> String {
1162    if let Ok(a) = std::env::var("BD_ACTOR")
1163        && !a.is_empty()
1164    {
1165        return a;
1166    }
1167    let username = whoami::username();
1168    let hostname = whoami::fallible::hostname().unwrap_or_else(|_| "unknown".into());
1169    format!("{}@{}", username, hostname)
1170}