pinto-cli 0.1.0

A lightweight, local-first, Git-friendly Scrum backlog and Kanban board for the CLI and TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Argument definition with clap.

use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};
use clap_complete::Shell;
use pinto::i18n::Localizer;

/// Parse the date and time accepted by `--start` and `--end` as UTC.
///
/// Accept `YYYY-MM-DDTHH:MM`, `YYYY-MM-DD HH:MM`, or the same forms with seconds. A date-only
/// value (`YYYY-MM-DD`) is interpreted as midnight. Persistence and display use UTC consistently.
fn parse_utc_datetime(s: &str) -> Result<chrono::DateTime<chrono::Utc>, String> {
    use chrono::{NaiveDate, NaiveDateTime, TimeZone, Utc};

    const DT_FORMATS: [&str; 3] = ["%Y-%m-%dT%H:%M", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S"];
    for fmt in DT_FORMATS {
        if let Ok(dt) = NaiveDateTime::parse_from_str(s, fmt) {
            return Ok(Utc.from_utc_datetime(&dt));
        }
    }
    if let Ok(d) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        let midnight = d.and_hms_opt(0, 0, 0).expect("midnight is always valid");
        return Ok(Utc.from_utc_datetime(&midnight));
    }
    Err(format!(
        "invalid date/time: {s:?} (expected `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`)"
    ))
}

/// Interpret a count of 1 or more (to provide early guidance on specifying 0 for `--recent`).
fn parse_positive_usize(s: &str) -> Result<usize, String> {
    let value = s
        .parse::<usize>()
        .map_err(|_| format!("invalid positive integer: {s:?}"))?;
    if value == 0 {
        return Err("must be at least 1".to_string());
    }
    Ok(value)
}

/// A lightweight scrum backlog/kanban board.
#[derive(Debug, Parser)]
#[command(name = "pinto", version, about, long_about = None)]
pub(super) struct Cli {
    #[command(subcommand)]
    pub(super) command: Command,
}

/// Create localized clap commands in Fluent.
///
/// Keep the syntax and validation generated by `clap`; localize only help text and headings at
/// runtime. Syntax errors produced by `clap` remain unchanged.
pub(super) fn localized_command(localizer: &Localizer) -> clap::Command {
    localize_command(Cli::command(), localizer, "pinto")
}

/// Parse process arguments using localized command help.
pub(super) fn try_parse_localized(localizer: &Localizer) -> Result<Cli, clap::Error> {
    let matches = localized_command(localizer).try_get_matches()?;
    Cli::from_arg_matches(&matches)
}

fn localize_command(command: clap::Command, localizer: &Localizer, path: &str) -> clap::Command {
    let about_key = format!("cli-command-{path}");
    let arguments_heading = localizer
        .lookup("cli-heading-arguments")
        .unwrap_or_else(|| "Arguments".to_string());
    let options_heading = localizer
        .lookup("cli-heading-options")
        .unwrap_or_else(|| "Options".to_string());
    let commands_heading = localizer
        .lookup("cli-heading-commands")
        .unwrap_or_else(|| "Commands".to_string());

    let command = if let Some(about) = localizer.lookup(&about_key) {
        command.about(about.clone()).long_about(about)
    } else {
        command
    };
    let about = command
        .get_about()
        .map(|text| terminate_help(&text.to_string()));
    let long_about = command
        .get_long_about()
        .map(|text| terminate_help(&text.to_string()));
    let command = match about {
        Some(about) => command.about(about),
        None => command,
    };
    let command = match long_about {
        Some(long_about) => command.long_about(long_about),
        None => command,
    };
    let command = command
        .subcommand_help_heading(commands_heading)
        .mut_args(|arg| {
            let key = format!("cli-arg-{path}-{}", arg.get_id());
            let heading = if arg.is_positional() {
                arguments_heading.clone()
            } else {
                options_heading.clone()
            };
            let arg = if let Some(help) = localizer.lookup(&key) {
                arg.help(help.clone()).long_help(help)
            } else {
                arg
            };
            let help = arg.get_help().map(|text| terminate_help(&text.to_string()));
            let long_help = arg
                .get_long_help()
                .map(|text| terminate_help(&text.to_string()));
            let arg = match help {
                Some(help) => arg.help(help),
                None => arg,
            };
            let arg = match long_help {
                Some(long_help) => arg.long_help(long_help),
                None => arg,
            };
            arg.help_heading(heading)
        });

    command.mut_subcommands(|subcommand| {
        let child_path = format!("{path}-{}", subcommand.get_name());
        localize_command(subcommand, localizer, &child_path)
    })
}

fn terminate_help(text: &str) -> String {
    let mut text = text.trim_end().to_string();
    if !text.ends_with(['.', '!', '?', '', '', '']) {
        text.push('.');
    }
    text
}

#[derive(Debug, Subcommand)]
pub(super) enum Command {
    /// Initialize the board (.pinto/) in the current directory.
    Init,
    /// Add PBI to backlog.
    #[command(visible_alias = "a")]
    Add(AddArgs),
    /// List PBIs in the backlog.
    #[command(visible_alias = "ls")]
    List(ListArgs),
    /// View PBI details for a given ID.
    #[command(visible_alias = "s")]
    Show(ShowArgs),
    /// Transition the state (column) of PBI.
    #[command(visible_alias = "mv")]
    Move(MoveArgs),
    /// Sort the priority (rank) of PBI (without changing the `status`).
    #[command(visible_alias = "ro")]
    Reorder(ReorderArgs),
    /// Update fields in an existing PBI.
    #[command(visible_alias = "e")]
    Edit(EditArgs),
    /// Archive (default) or physically delete PBI.
    #[command(visible_alias = "rm")]
    Remove(RemoveArgs),
    /// Set and release dependencies between PBIs.
    #[command(visible_alias = "d")]
    Dep(DepArgs),
    /// Associate/remove Git commits (SHA) with PBI and automatically pick them up from the history.
    #[command(visible_alias = "ln")]
    Link(LinkArgs),
    /// Reference, set, and delete DoD (Definition of Done) common to all PBIs.
    #[command(visible_alias = "dd")]
    Dod(DodArgs),
    /// Manage sprints (create, start, close, assign, list).
    #[command(visible_alias = "sp")]
    Sprint(SprintArgs),
    /// Display the board (PBI by column).
    #[command(visible_alias = "b")]
    Board(BoardArgs),
    /// Aggregate Cycle Time / Lead Time of completed PBI.
    #[command(name = "cycletime", visible_alias = "ct")]
    CycleTime(CycleTimeArgs),
    /// Reassign oversized ranks within each status/parent sibling scope while preserving order.
    #[command(visible_alias = "reb")]
    Rebalance(RebalanceArgs),
    /// Migrate storage backends (file/git/sqlite interop).
    #[command(visible_alias = "mig")]
    Migrate(MigrateArgs),
    /// Execute the structured plan generated by the AI agent sequentially as an existing command.
    #[command(visible_alias = "auto")]
    Automate(AutomateArgs),
    /// Start an interactive shell (REPL) and perform continuous operations with one command per line.
    Shell,
    /// Launch Interactive Kanban (TUI).
    #[command(visible_alias = "k")]
    Kanban(KanbanArgs),
    /// Generates a completion script for the specified shell to standard output.
    Completion(CompletionArgs),
}

/// Startup options for the `kanban` subcommand.
#[derive(Debug, Args)]
pub(super) struct KanbanArgs {
    /// Display only the specified workflow columns. Multiple values can follow one option or be
    /// supplied with repeated options; explicit values override `[tui].hidden_columns`.
    #[arg(long, short = 'c', num_args = 1..)]
    pub(super) column: Option<Vec<String>>,
    /// Maximize and display selected columns from startup.
    #[arg(long, short = 'm')]
    pub(super) maximize: bool,
    /// Filter cards by a literal substring or, with `--regex`, a regular expression.
    #[arg(long, short = 'F')]
    pub(super) search: Option<String>,
    /// Interpret `--search` as a regular expression.
    #[arg(long, short = 'R', requires = "search")]
    pub(super) regex: bool,
}

/// Arguments for the `completion` subcommand.
#[derive(Debug, Args)]
pub(super) struct CompletionArgs {
    /// Target shell (`bash` / `zsh` / `fish` / `powershell` / `elvish`) to generate completion for.
    pub(super) shell: Shell,
}

/// Arguments for the `automate` subcommand.
#[derive(Debug, Args)]
pub(super) struct AutomateArgs {
    /// Inline JSON, a plan file path, or `-` to read the JSON plan from standard input. Connection information such as API keys will not be accepted.
    #[arg(
        long,
        short = 'p',
        value_name = "JSON|PATH|-",
        help = "Inline JSON, a plan file path, or `-` to read the JSON plan from standard input."
    )]
    pub(super) plan: String,
    /// Validate every command and report planned changes without modifying the board.
    #[arg(long, short = 'n')]
    pub(super) dry_run: bool,
    /// Output a structured result instead of human-readable messages.
    #[arg(long, short = 'j')]
    pub(super) json: bool,
}

/// `cycletime` Subcommand argument (filtering condition).
#[derive(Debug, Args)]
pub(super) struct CycleTimeArgs {
    /// Filter by assigned sprint. If the sprint does not exist, the filter matches no PBIs.
    #[arg(long, short = 'S')]
    pub(super) sprint: Option<String>,
    /// Lower completion date and time (only PBIs completed after this date and time).
    /// `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM` (UTC/minutes).
    #[arg(long, short = 's', value_parser = parse_utc_datetime)]
    pub(super) since: Option<chrono::DateTime<chrono::Utc>>,
    /// Completion date/time limit (only for PBIs completed before this date/time).
    /// `YYYY-MM-DD` or `YYYY-MM-DDTHH:MM` (UTC/minutes).
    #[arg(long, short = 'u', value_parser = parse_utc_datetime)]
    pub(super) until: Option<chrono::DateTime<chrono::Utc>>,
    /// Output machine-readable JSON instead of human-readable formatting.
    #[arg(long, short = 'j')]
    pub(super) json: bool,
}

/// Arguments for the `rebalance` subcommand.
#[derive(Debug, Args)]
pub(super) struct RebalanceArgs {
    /// Preview the affected sibling scopes and rank-length changes without rewriting the board.
    #[arg(long, short = 'n')]
    pub(super) dry_run: bool,
}

/// Arguments for the `migrate` subcommand.
#[derive(Debug, Args)]
pub(super) struct MigrateArgs {
    /// Destination backend. `sqlite` can only be selected when building with `--features sqlite`.
    #[arg(long = "to", short = 't', value_enum)]
    pub(super) to: MigrateTarget,
}

/// Value of `migrate --to` at the CLI layer, mapped to [`pinto::config::StorageBackend`].
///
/// Keep `sqlite` in `--help` even in builds without the feature, then report the missing feature
/// clearly at runtime instead of changing the help text between builds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(super) enum MigrateTarget {
    /// Local-file backend.
    File,
    /// Git backend (commit each change).
    Git,
    /// SQLite (only for `--features sqlite` builds).
    Sqlite,
}

/// Arguments for the `board` subcommand.
#[derive(Debug, Args)]
pub(super) struct BoardArgs {
    /// Display only PBIs without a parent; child PBIs are omitted.
    #[arg(long, short = 'P')]
    pub(super) roots_only: bool,
    /// Display only PBIs assigned to the specified sprint. In long mode, omit the value to show
    /// the SPRINT column without filtering.
    #[arg(long, short = 'S', num_args = 0..=1)]
    pub(super) sprint: Option<Option<String>>,
    /// Filter by one or more labels. Multiple labels use OR by default; use `--all-labels` for AND.
    /// In long mode, omit the values to show the LABELS column without filtering.
    #[arg(long, short = 'L', num_args = 0..)]
    pub(super) label: Option<Vec<String>>,
    /// Require every label supplied to `--label` (AND instead of the default OR).
    #[arg(long = "all-labels", short = 'a', requires = "label")]
    pub(super) all_labels: bool,
    /// Display only the specified statuses (columns). Multiple values can follow one option or be
    /// supplied with repeated options. Only columns in `config.toml` are allowed.
    #[arg(long, short = 's', num_args = 1..)]
    pub(super) status: Vec<String>,
    /// Root/sibling sort key (`rank` / `done` / `created`) within each column; the parent/child
    /// hierarchy is always preserved. Default is per column: the completion column by completion
    /// time descending, others by ascending rank (the same hierarchical order as `list`).
    #[arg(long, short = 'o', value_enum)]
    pub(super) sort: Option<SortArg>,
    /// Sort in descending order (valid only when `--sort` is specified).
    #[arg(long, short = 'r')]
    pub(super) reverse: bool,
    /// Display the same detailed columns as `list --long` for each board column.
    #[arg(long, short = 'l')]
    pub(super) long: bool,
    /// Display the full text of long sentences without omitting them (disable truncation to fit the terminal width).
    #[arg(long = "no-truncate", short = 'f', visible_alias = "full")]
    pub(super) no_truncate: bool,
    /// Output machine-readable JSON instead of human-readable formatting.
    #[arg(long, short = 'j')]
    pub(super) json: bool,
    /// Disable WIP limit checking (no exceedance warnings).
    #[arg(long = "no-wip-check", short = 'w')]
    pub(super) no_wip_check: bool,
    /// Filter cards by a literal substring or, with `--regex`, a regular expression.
    #[arg(long, short = 'F')]
    pub(super) search: Option<String>,
    /// Interpret `--search` as a regular expression.
    #[arg(long, short = 'R', requires = "search")]
    pub(super) regex: bool,
}

/// Key for `board --sort` (CLI layer; maps to [`pinto::service::SortKey`] in the domain).
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(super) enum SortArg {
    /// Backlog order (ascending rank).
    Rank,
    /// Sorted by completion time.
    Done,
    /// Sorted by creation time.
    Created,
}

/// Arguments for the `sprint` subcommand.
#[derive(Debug, Args)]
pub(super) struct SprintArgs {
    #[command(subcommand)]
    pub(super) command: SprintCommand,
}

/// `sprint` operations (creation, editing, deletion, state transition, assignment, list).
#[derive(Debug, Subcommand)]
pub(super) enum SprintCommand {
    /// Create a new Sprint (`planned` state).
    #[command(visible_alias = "n")]
    New {
        /// Sprint ID (an ASCII slug using alphanumeric characters, `-`, or `_`; for example,
        /// `S-1`).
        id: String,
        /// Sprint title.
        title: String,
        /// Sprint goal (free description).
        #[arg(long, short = 'g', conflicts_with = "template")]
        goal: Option<String>,
        /// The template name (`.pinto/templates/sprint/<name>.md`) to apply to the sprint goal.
        #[arg(long, short = 't', conflicts_with = "goal")]
        template: Option<String>,
        /// Planned start date and time (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`, in UTC minutes).
        /// Specify in conjunction with `--end`. Used during burndown period.
        #[arg(long, short = 's', requires = "end", value_parser = parse_utc_datetime)]
        start: Option<chrono::DateTime<chrono::Utc>>,
        /// Planned end date and time (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`, in UTC minutes).
        /// Specify in conjunction with `--start`. Used during burndown period.
        #[arg(long, short = 'e', requires = "start", value_parser = parse_utc_datetime)]
        end: Option<chrono::DateTime<chrono::Utc>>,
    },
    /// Edit an existing sprint's title, goal, or planned period.
    #[command(visible_alias = "e")]
    Edit {
        /// ID of the sprint to edit.
        id: String,
        /// Replacement sprint title.
        #[arg(long, short = 't')]
        title: Option<String>,
        /// Replacement sprint goal. Pass an empty value to clear the goal.
        #[arg(long, short = 'g')]
        goal: Option<String>,
        /// Replacement planned start date and time (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`, in UTC).
        #[arg(long, short = 's', requires = "end", value_parser = parse_utc_datetime)]
        start: Option<chrono::DateTime<chrono::Utc>>,
        /// Replacement planned end date and time (`YYYY-MM-DD` or `YYYY-MM-DDTHH:MM`, in UTC).
        #[arg(long, short = 'e', requires = "start", value_parser = parse_utc_datetime)]
        end: Option<chrono::DateTime<chrono::Utc>>,
    },
    /// Remove a sprint and release any assigned PBIs back to the backlog.
    #[command(visible_alias = "rm")]
    Remove {
        /// ID of the sprint to remove.
        id: String,
    },
    /// Start a sprint (`planned` → `active`).
    #[command(visible_alias = "s")]
    Start {
        /// ID of the sprint to start.
        id: String,
    },
    /// Close a sprint (`active` → `closed`).
    #[command(visible_alias = "c")]
    Close {
        /// ID of the sprint to close.
        id: String,
    },
    /// Assign a PBI to a sprint, or assign ranked PBIs from a workflow status in bulk.
    #[command(visible_alias = "a")]
    Add {
        /// The ID of the sprint to assign the PBI to (e.g. `S-1`).
        sprint_id: String,
        /// ID of the PBI to assign (e.g. `T-1`). Omit this when using `--status`.
        #[arg(required_unless_present = "status", conflicts_with = "status")]
        item_id: Option<String>,
        /// Assign PBIs in this workflow status, in backlog rank order.
        #[arg(long, short = 's', conflicts_with = "item_id")]
        status: Option<String>,
        /// Maximum number of new assignments. Omit to assign every matching PBI.
        #[arg(long, short = 'n', requires = "status", value_parser = parse_positive_usize)]
        limit: Option<usize>,
    },
    /// Unassign the PBI from its sprint assignment.
    #[command(visible_alias = "u")]
    Unassign {
        /// ID of the sprint from which to remove the assignment (for example, `S-1`).
        sprint_id: String,
        /// ID of the PBI to be unassigned (e.g. `T-1`).
        item_id: String,
    },
    /// List sprints.
    #[command(visible_alias = "ls")]
    List {
        /// Output machine-readable JSON instead of human-readable formatting.
        #[arg(long, short = 'j')]
        json: bool,
    },
    /// Draw a sprint burndown chart in the terminal.
    #[command(visible_alias = "bd")]
    Burndown {
        /// ID of the target sprint (e.g. `S-1`). A planning schedule (`--start`/`--end`) is required.
        id: String,
        /// Output machine-readable JSON instead of human-readable formatting.
        #[arg(long, short = 'j')]
        json: bool,
    },
    /// Aggregate completion points (velocity) for each sprint.
    #[command(visible_alias = "v")]
    Velocity {
        /// Number of recent sprints to aggregate (default: 5).
        #[arg(long, short = 'n', default_value_t = 5, value_parser = parse_positive_usize)]
        recent: usize,
    },
    /// Set and display available work time for sprints.
    #[command(visible_alias = "cap")]
    Capacity {
        /// ID of the target sprint (e.g. `S-1`).
        id: String,
        /// Hours worked per day. All other setting values are also required when setting.
        #[arg(long, short = 'H', requires_all = ["holidays", "deduction_factor"])]
        daily_hours: Option<f64>,
        /// Number of holidays within the period including the start date and end date. All other setting values are also required when setting.
        #[arg(long, short = 'd', requires_all = ["daily_hours", "deduction_factor"])]
        holidays: Option<u32>,
        /// Deduction rate (0 to 1) for meetings, etc. All other setting values are also required when setting.
        #[arg(long, short = 'f', requires_all = ["daily_hours", "holidays"])]
        deduction_factor: Option<f64>,
        /// Output machine-readable JSON instead of human-readable formatting.
        #[arg(long, short = 'j')]
        json: bool,
    },
}

/// Arguments for the `dep` subcommand.
#[derive(Debug, Args)]
pub(super) struct DepArgs {
    #[command(subcommand)]
    pub(super) command: DepCommand,
}

/// `dep` operations (add/delete).
#[derive(Debug, Subcommand)]
pub(super) enum DepCommand {
    /// Add a dependency relationship where `<id>` depends on `<depends-on>`.
    #[command(visible_alias = "a")]
    Add {
        /// ID of the relying PBI (e.g. `T-2`).
        id: String,
        /// ID of the PBI that is being relied upon (for example, `T-1`).
        depends_on: String,
    },
    /// Remove the dependency of `<id>` on `<depends-on>`.
    #[command(visible_alias = "r")]
    Rm {
        /// ID of the relying PBI (e.g. `T-2`).
        id: String,
        /// ID of the dependent PBI to remove (e.g. `T-1`).
        depends_on: String,
    },
}

/// Arguments for the `link` subcommand.
#[derive(Debug, Args)]
pub(super) struct LinkArgs {
    #[command(subcommand)]
    pub(super) command: LinkCommand,
}

/// `link` operations (add/delete/traverse).
#[derive(Debug, Subcommand)]
pub(super) enum LinkCommand {
    /// Add related commit `<sha>...` to `<id>` (SHAs are plain text; Git is not required).
    #[command(visible_alias = "a")]
    Add {
        /// ID of the PBI to associate (e.g. `T-1`).
        id: String,
        /// Commit SHAs to associate; multiple values are accepted.
        #[arg(required = true)]
        shas: Vec<String>,
    },
    /// Remove related commit `<sha>...` from `<id>` (shortened SHAs match by prefix).
    #[command(visible_alias = "r")]
    Rm {
        /// ID of the PBI (e.g. `T-1`).
        id: String,
        /// Commit SHAs to remove; multiple values are accepted and matched by prefix.
        #[arg(required = true)]
        shas: Vec<String>,
    },
    /// Scan `git log` and associate PBIs whose IDs appear in commit messages (requires Git).
    #[command(visible_alias = "s")]
    Scan {
        /// Scan only within this range (`<since>..HEAD`). If omitted, full history.
        #[arg(long, short = 's')]
        since: Option<String>,
    },
}

/// Arguments for the `dod` subcommand. If the subcommand is omitted, the current common DoD is displayed.
#[derive(Debug, Args)]
pub(super) struct DodArgs {
    #[command(subcommand)]
    pub(super) command: Option<DodCommand>,
}

/// `dod` operation (setting/deleting). Displayed if omitted.
#[derive(Debug, Subcommand)]
pub(super) enum DodCommand {
    /// Set common DoD (all replacement).
    #[command(visible_alias = "s")]
    Set {
        /// DoD body (Markdown, such as common parts of acceptance conditions).
        ///
        /// DoD often begins with a hyphen, such as `- [ ] ...`, so remove the leading hyphen.
        /// Receive it as a value instead of mistaking it as an option.
        #[arg(allow_hyphen_values = true)]
        text: String,
    },
    /// Delete common DoD.
    #[command(visible_alias = "c")]
    Clear,
}

/// Arguments for the `show` subcommand.
#[derive(Debug, Args)]
pub(super) struct ShowArgs {
    /// IDs of the PBIs to display in the specified order (e.g. `T-1 T-2`).
    #[arg(value_name = "ID", num_args = 1..)]
    pub(super) ids: Vec<String>,
    /// Output machine-readable JSON instead of human-readable formatting.
    #[arg(long, short = 'j')]
    pub(super) json: bool,
    /// Show the raw Markdown body instead of the rendered display (opt out of
    /// Markdown rendering for this invocation).
    #[arg(long, short = 'p')]
    pub(super) plain: bool,
}

/// Arguments for the `reorder` subcommand. Specify exactly one out of four destinations.
///
/// Reorder changes order only **within a sibling group** (PBIs sharing the same parent
/// and column); rank is sibling-local. To move a PBI between groups, change its parent
/// with `edit --parent`. Moving a parent carries its whole subtree.
#[derive(Debug, Args)]
#[command(group(clap::ArgGroup::new("target").required(true).multiple(false)))]
pub(super) struct ReorderArgs {
    /// ID of the PBI to reorder (e.g. `T-1`).
    pub(super) id: String,
    /// Move to just before the specified sibling (e.g. `--before T-3`). The reference must
    /// share this PBI's parent and column.
    #[arg(long, short = 'b', group = "target", value_name = "ID")]
    pub(super) before: Option<String>,
    /// Move to immediately after the specified sibling (e.g. `--after T-3`). The reference
    /// must share this PBI's parent and column.
    #[arg(long, short = 'a', group = "target", value_name = "ID")]
    pub(super) after: Option<String>,
    /// Move to the front of this PBI's sibling group.
    #[arg(long, short = 't', group = "target")]
    pub(super) top: bool,
    /// Move to the back of this PBI's sibling group.
    #[arg(long, short = 'B', group = "target")]
    pub(super) bottom: bool,
}

/// Arguments for the `move` subcommand.
#[derive(Debug, Args)]
pub(super) struct MoveArgs {
    /// IDs of the PBIs to transition, followed by the destination status.
    /// Like Unix `mv`, the last operand is the destination column and the rest
    /// are the PBIs to move (e.g. `T-1 T-2 in-progress`). Only columns in
    /// `config.toml` are allowed as the destination.
    #[arg(required = true, num_args = 2.., value_name = "ID_OR_STATUS")]
    pub(super) operands: Vec<String>,
    /// Disable WIP limit checking on this move (do not issue exceedance warning).
    #[arg(long = "no-wip-check", short = 'w')]
    pub(super) no_wip_check: bool,
}

impl MoveArgs {
    /// Split the operands into the destination status and the source IDs,
    /// mirroring Unix `mv` where the last operand is the destination.
    ///
    /// Returns `None` only when fewer than two operands are given, which clap
    /// rejects up front via `num_args = 2..`.
    pub(super) fn destination_and_ids(&self) -> Option<(&str, &[String])> {
        self.operands
            .split_last()
            .map(|(status, ids)| (status.as_str(), ids))
    }
}

/// `list` Subcommand argument (filtering condition).
#[derive(Debug, Args)]
pub(super) struct ListArgs {
    /// Display only PBIs without a parent; child PBIs are omitted.
    #[arg(long, short = 'P')]
    pub(super) roots_only: bool,
    /// Filter by status (column). Multiple values can follow one option or be supplied with
    /// repeated options.
    #[arg(long, short = 's', num_args = 1..)]
    pub(super) status: Vec<String>,
    /// Filter by assigned sprint. In long mode, omit the value to show the SPRINT column without
    /// filtering.
    #[arg(long, short = 'S', num_args = 0..=1)]
    pub(super) sprint: Option<Option<String>>,
    /// Filter by one or more labels. Multiple labels use OR by default; use `--all-labels` for AND.
    /// In long mode, omit the values to show the LABELS column without filtering.
    #[arg(long, short = 'L', num_args = 0..)]
    pub(super) label: Option<Vec<String>>,
    /// Require every label supplied to `--label` (AND instead of the default OR).
    #[arg(long = "all-labels", short = 'a', requires = "label")]
    pub(super) all_labels: bool,
    /// Display ID, title, status, points, assignee, and creation/update dates in a table.
    /// Add LABELS or SPRINT with the corresponding option. Ignored with `--json`.
    #[arg(long, short = 'l')]
    pub(super) long: bool,
    /// Output machine-readable JSON instead of human-readable formatting.
    #[arg(long, short = 'j')]
    pub(super) json: bool,
    /// Filter by a literal substring or, with `--regex`, a regular expression.
    #[arg(long, short = 'F')]
    pub(super) search: Option<String>,
    /// Interpret `--search` as a regular expression.
    #[arg(long, short = 'R', requires = "search")]
    pub(super) regex: bool,
}

/// Arguments for the `add` subcommand.
#[derive(Debug, Args)]
pub(super) struct AddArgs {
    /// PBI title (required).
    pub(super) title: String,
    /// Story points.
    #[arg(long, short = 'p')]
    pub(super) points: Option<u32>,
    /// Label (multiple can be specified).
    #[arg(long = "label", short = 'l')]
    pub(super) labels: Vec<String>,
    /// Assign the PBI to a sprint.
    #[arg(long, short = 'S')]
    pub(super) sprint: Option<String>,
    /// Parent PBI ID.
    #[arg(long, short = 'P')]
    pub(super) parent: Option<String>,
    /// PBI IDs this item depends on (multiple values are accepted).
    #[arg(long = "depends-on", short = 'd', num_args = 1..)]
    pub(super) depends_on: Vec<String>,
    /// Body (acceptance conditions, etc.).
    #[arg(long, short = 'b', conflicts_with = "edit")]
    pub(super) body: Option<String>,
    /// Open the editor and make the saved content the main text. When `--template` is specified, the template is used as the initial content.
    #[arg(long, short = 'E')]
    pub(super) edit: bool,
    /// Template name (`.pinto/templates/item/<name>.md`) to apply to the body.
    #[arg(long, short = 't')]
    pub(super) template: Option<String>,
}

#[cfg(test)]
mod add_tests {
    use super::*;

    #[test]
    fn add_parses_long_and_short_edit_flags() {
        for flag in ["--edit", "-E"] {
            let cli =
                Cli::try_parse_from(["pinto", "add", "Task", flag]).expect("add edit flag parses");
            let Command::Add(args) = cli.command else {
                panic!("expected add command");
            };
            assert!(args.edit);
        }
    }

    #[test]
    fn add_rejects_body_with_edit() {
        let error = Cli::try_parse_from(["pinto", "add", "Task", "--body", "initial", "--edit"])
            .expect_err("--body and --edit must conflict");

        let message = error.to_string();
        assert!(
            message.contains("--body"),
            "error mentions --body: {message}"
        );
        assert!(
            message.contains("--edit"),
            "error mentions --edit: {message}"
        );
    }
}

#[cfg(test)]
mod help_punctuation_tests {
    use super::*;

    fn is_sentence_terminated(text: &str) -> bool {
        text.trim_end().ends_with(['.', '!', '?', '', '', ''])
    }

    fn assert_help_is_terminated(command: &clap::Command, path: &str) {
        if let Some(about) = command.get_about() {
            assert!(
                is_sentence_terminated(&about.to_string()),
                "command `{path}` has unterminated help: {about}"
            );
        }
        for arg in command.get_arguments() {
            if let Some(help) = arg.get_help() {
                assert!(
                    is_sentence_terminated(&help.to_string()),
                    "argument `{path} {}` has unterminated help: {help}",
                    arg.get_id()
                );
            }
            if let Some(help) = arg.get_long_help() {
                assert!(
                    is_sentence_terminated(&help.to_string()),
                    "argument `{path} {}` has unterminated long help: {help}",
                    arg.get_id()
                );
            }
        }
        for child in command.get_subcommands() {
            assert_help_is_terminated(child, &format!("{path} {}", child.get_name()));
        }
    }

    #[test]
    fn every_localized_command_and_argument_help_ends_as_a_sentence() {
        for locale in ["en-US", "ja-JP"] {
            let localizer = pinto::i18n::localizer_from(Some(locale), None);
            let command = localized_command(&localizer);
            assert_help_is_terminated(&command, &format!("pinto ({locale})"));
        }
    }
}

#[cfg(test)]
mod abbreviation_tests {
    use super::*;

    fn assert_nested_subcommands_have_aliases(command: &clap::Command, path: &str) {
        for subcommand in command.get_subcommands() {
            // `help` is generated by clap and is not a pinto-owned subcommand.
            if subcommand.get_name() == "help" {
                continue;
            }
            let child_path = format!("{path} {}", subcommand.get_name());
            assert!(
                subcommand.get_visible_aliases().next().is_some(),
                "subcommand `{child_path}` has no visible alias"
            );
            assert_nested_subcommands_have_aliases(subcommand, &child_path);
        }
    }

    fn assert_long_options_have_short_forms(command: &clap::Command, path: &str) {
        for argument in command.get_arguments() {
            let Some(long) = argument.get_long() else {
                continue;
            };
            if matches!(long, "help" | "version") {
                continue;
            }
            assert!(
                argument.get_short().is_some(),
                "option `{path} --{long}` has no short form"
            );
        }
        for subcommand in command.get_subcommands() {
            if subcommand.get_name() == "help" {
                continue;
            }
            assert_long_options_have_short_forms(
                subcommand,
                &format!("{path} {}", subcommand.get_name()),
            );
        }
    }

    #[test]
    fn every_non_top_level_subcommand_has_a_visible_alias() {
        let command = Cli::command();
        for subcommand in command.get_subcommands() {
            if subcommand.get_name() == "help" {
                continue;
            }
            assert_nested_subcommands_have_aliases(
                subcommand,
                &format!("pinto {}", subcommand.get_name()),
            );
        }
    }

    #[test]
    fn every_pinto_long_option_has_a_short_form() {
        assert_long_options_have_short_forms(&Cli::command(), "pinto");
    }
}

/// Arguments for the `edit` subcommand; only supplied fields are updated.
#[derive(Debug, Args)]
pub(super) struct EditArgs {
    /// ID of the PBI to edit (e.g. `T-1`).
    pub(super) id: String,
    /// New title.
    #[arg(long, short = 't')]
    pub(super) title: Option<String>,
    /// Story points.
    #[arg(long, short = 'p')]
    pub(super) points: Option<u32>,
    /// Labels to set; supplying any labels replaces the existing set.
    #[arg(long = "label", short = 'l')]
    pub(super) labels: Vec<String>,
    /// Assignee.
    #[arg(long, short = 'a')]
    pub(super) assignee: Option<String>,
    /// Sprint ID assignment.
    #[arg(long, short = 'S')]
    pub(super) sprint: Option<String>,
    /// Markdown body, including Acceptance Criteria.
    #[arg(long, short = 'b')]
    pub(super) body: Option<String>,
    /// Set the parent PBI (for example, `T-1`). Parent-child cycles are rejected.
    #[arg(long, short = 'P', conflicts_with = "no_parent")]
    pub(super) parent: Option<String>,
    /// Unset the parent PBI.
    #[arg(long, short = 'N')]
    pub(super) no_parent: bool,
}

/// Arguments for the `rm` subcommand.
#[derive(Debug, Args)]
pub(super) struct RemoveArgs {
    /// IDs of the PBIs to delete (e.g. `T-1 T-2`).
    #[arg(required = true, value_name = "ID")]
    pub(super) ids: Vec<String>,
    /// Physically delete without saving archives (irreversible).
    #[arg(long, short = 'f')]
    pub(super) force: bool,
}