tix-tracker 0.5.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
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
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
//! The clap command tree, the frozen exit-code scheme, and the process
//! boundary that resolves config, opens the store and hands off to the
//! per-command handlers.
//!
//! The command tree and every long flag mirror `contracts/cli.md` exactly;
//! the exit-code table there is frozen: `0` success, `1` usage/config/
//! unknown-error, `2` target-not-found or selection-ambiguous, `3` external
//! tool missing (`glab`/`linear-cli`, reserved for WP05). Handlers return
//! [`Result<(), TixError>`]; [`exit_code_for`] maps the typed error surface
//! to the exit-code enum at the boundary. Human-readable errors go to
//! stderr; stdout stays clean for the parseability contract.

use std::path::{Path, PathBuf};

use clap::builder::NonEmptyStringValueParser;
use clap::{Args, Parser, Subcommand};

use crate::commands;
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::storage::Store;

/// Exit codes frozen by `contracts/cli.md`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExitCode {
    Success = 0,
    UsageConfig = 1,
    NotFoundAmbiguous = 2,
    ExternalTool = 3,
}

/// Map a domain error to the frozen exit-code table.
///
/// Selection ambiguity shares exit `2` with target-not-found, per the
/// contract's exit-code table ("2 target-not-found or selection-ambiguous");
/// the ambiguity marker is the [`commands::AMBIGUITY_PREFIX`] message prefix.
pub fn exit_code_for(err: &TixError) -> ExitCode {
    match err {
        TixError::NotFound(_) => ExitCode::NotFoundAmbiguous,
        TixError::InvalidInput(s) if s.starts_with(commands::AMBIGUITY_PREFIX) => {
            ExitCode::NotFoundAmbiguous
        }
        TixError::External(_) => ExitCode::ExternalTool,
        _ => ExitCode::UsageConfig,
    }
}

#[derive(Parser)]
#[command(
    name = "tix",
    version,
    about = "Terminal issue tracker: markdown issues with a kanban TUI and CLI"
)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Option<Command>,
}

#[derive(Subcommand)]
pub enum Command {
    /// Create a default tix.toml ([kanban.default], issues_dir, [export])
    Init,
    /// Append or replace the tix block in AGENTS.md (idempotent)
    InitAgents,
    /// Create an issue
    Create {
        /// Issue title (prompted when missing on a TTY)
        #[arg(long)]
        title: Option<String>,
        /// Issue body (markdown)
        #[arg(long)]
        body: Option<String>,
        /// Column name (default: first column)
        #[arg(long)]
        status: Option<String>,
        /// Priority: low | medium | high (default medium)
        #[arg(long)]
        priority: Option<String>,
        /// Assignee (@name)
        #[arg(long)]
        assignee: Option<String>,
        /// Labels, comma-separated
        #[arg(long)]
        labels: Option<String>,
        /// Files governing this issue, comma-separated
        #[arg(long)]
        files: Option<String>,
        /// Estimate
        #[arg(long)]
        estimate: Option<String>,
        /// Cycle names, comma-separated
        #[arg(long)]
        cycles: Option<String>,
        /// Milestone names, comma-separated
        #[arg(long)]
        milestones: Option<String>,
        /// Reviewer (free-form name/identity)
        #[arg(long)]
        reviewer: Option<String>,
        /// Start date (`YYYY-MM-DD`)
        #[arg(long)]
        start_date: Option<String>,
        /// Due date (`YYYY-MM-DD`); must be `>= start_date`
        #[arg(long)]
        due_date: Option<String>,
        /// Create as a child of this issue (number, filename or title fragment)
        ///
        /// At most one parent, so this takes a single selector and there is no list
        /// form (C-001). The parent must already exist; a selector that matches no
        /// issue is refused and nothing is created.
        #[arg(long, value_name = "SELECTOR")]
        parent: Option<String>,
    },
    /// Create, edit, remove, or list typed relationships
    ///
    /// Creating requires `--type`; there is no default kind, so an untyped
    /// relationship is never recorded by accident (C-001). Omit the
    /// subcommand to create: `tix link <from> <to> --type <kind>`.
    Link {
        /// `edit`, `remove`, or `list`. Omit to create a relationship.
        ///
        /// These three words are reserved on `tix link`: an issue whose number,
        /// filename, or title selector is exactly `edit`, `remove`, or `list`
        /// must be addressed by number.
        #[command(subcommand)]
        action: Option<LinkAction>,
        /// [create] Issue number, filename fragment or unique title fragment
        from: Option<String>,
        /// [create] Issue number, filename fragment or unique title fragment
        to: Option<String>,
        /// [create] Relationship kind: `blocks`, `blocked_by`, `duplicates`, `related`
        #[arg(long, value_name = "KIND")]
        r#type: Option<String>,
    },
    /// Batch editing over a selection
    ///
    /// Preview is the **default**; `--apply` writes. Name exactly one of `--select`,
    /// `--filter` or `--search` — they are different grammars, and a bulk operation
    /// will not guess which issues you meant.
    Bulk {
        #[command(subcommand)]
        action: BulkAction,
    },
    /// Remove a typed relationship between two issues
    Unlink {
        /// Issue number, filename fragment or unique title fragment
        from: String,
        /// Issue number, filename fragment or unique title fragment
        to: String,
        /// Relationship kind: `blocks`, `blocked_by`, `duplicates`, `related`
        #[arg(long, value_name = "KIND")]
        r#type: Option<String>,
    },
    /// Print the transitive dependency chain an issue holds up
    Chain {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
    },
    /// Inspect the issue hierarchy
    ///
    /// `show`, `children`, or `list`. Every figure comes from the hierarchy
    /// service's typed values, so the CLI, the TUI detail block and the MCP read
    /// tools report the same numbers for the same issue.
    Parent {
        /// `show`, `children`, or `list`
        #[command(subcommand)]
        action: ParentAction,
    },
    /// Edit an issue
    Edit {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// New title
        #[arg(long)]
        title: Option<String>,
        /// New body (markdown)
        #[arg(long)]
        body: Option<String>,
        /// New status
        ///
        /// Setting the status is a **move**, validated by the same service as
        /// `tix mv` and recorded as the same `TransitionDecision` — it is not a
        /// way around the transition policy. `--status ""` clears the field
        /// (matching every other field here) and is a plain field write, not a
        /// transition, because there is no target column to judge.
        #[arg(long)]
        status: Option<String>,
        /// New priority: low | medium | high
        #[arg(long)]
        priority: Option<String>,
        /// New assignee (@name)
        #[arg(long)]
        assignee: Option<String>,
        /// New label list, comma-separated
        #[arg(long)]
        labels: Option<String>,
        /// New files list, comma-separated
        #[arg(long)]
        files: Option<String>,
        /// New estimate
        #[arg(long)]
        estimate: Option<String>,
        /// New cycle list, comma-separated (`--cycles ""` clears)
        #[arg(long)]
        cycles: Option<String>,
        /// New milestone list, comma-separated (`--milestones ""` clears)
        #[arg(long)]
        milestones: Option<String>,
        /// New reviewer (`--reviewer ""` clears)
        #[arg(long)]
        reviewer: Option<String>,
        /// New start date (`YYYY-MM-DD`; `--start-date ""` clears)
        #[arg(long)]
        start_date: Option<String>,
        /// New due date (`YYYY-MM-DD`; `--due-date ""` clears)
        #[arg(long)]
        due_date: Option<String>,
        /// Commit hash to record (`auto` resolves it from git history, `clear` removes it)
        #[arg(long)]
        commit: Option<String>,
        /// Set or change the parent (number, filename or title fragment)
        ///
        /// `--parent ""` clears the parent, mirroring `--assignee ""`; omitting the
        /// flag leaves it untouched. Validated before any write, so a self-parent,
        /// an unknown parent, or a change that would close a cycle leaves the file
        /// byte-identical.
        #[arg(long, value_name = "SELECTOR")]
        parent: Option<String>,
        /// Why a transition policy is being overridden by `--status`
        ///
        /// `--status` is validated exactly as `tix mv` is, so moving an issue out
        /// of a terminal category needs the same reasoned override, and the reason
        /// is recorded in the same History decision. `--status` deliberately has
        /// no `--yes`: acknowledging blockers is spelled `tix move … --yes`, and
        /// giving this flag a second spelling would give the audit trail two.
        #[arg(long, value_name = "TEXT")]
        reason: Option<String>,
    },
    /// Move an issue to a column
    Move {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// Target column
        column: String,
        /// Commit hash to record when moving to a completion column (`auto`
        /// resolves it from git history; omitted, the current HEAD is captured
        /// automatically)
        ///
        /// "Completion" is whatever the board's category mapping calls
        /// `completed` — not a column literally named `done`. On a board with
        /// no `[kanban.<name>.category_map]` the board's `done_column` is the
        /// completion column.
        #[arg(long, value_name = "HASH")]
        commit: Option<String>,
        /// Why a transition policy is being overridden
        ///
        /// Required to move an issue *out of* a terminal category (`completed`
        /// or `canceled`) when the board declares a `category_map`. The reason
        /// is recorded in the issue's History, so the audit trail explains
        /// itself later. A blank value is not a reason and is refused.
        ///
        /// A board with no `category_map` has no transition policy to override:
        /// it keeps the completion definition and the commit rule, and moving
        /// out of `done` stays permitted.
        #[arg(long, value_name = "TEXT")]
        reason: Option<String>,
        /// Confirm without prompting
        ///
        /// Also the acknowledgement a move toward the board's completion column
        /// needs when the issue has open blockers. Without it that move is
        /// refused, and a recorded acknowledgement is appended to the issue's
        /// History so the decision stays auditable.
        #[arg(long)]
        yes: bool,
    },
    /// Print the full issue (frontmatter + body) to stdout
    #[command(visible_alias = "show")]
    View {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// Extra information to append, comma-separated
        ///
        /// `relationships` appends the service-derived relationship block, the
        /// transitive chain, and the blocked reason. Without it the issue file
        /// is printed verbatim, so `tix view <n> > file` still round-trips.
        #[arg(long, value_name = "relationships")]
        show: Option<String>,
    },
    /// Table of issues
    List {
        /// Only issues in this status
        #[arg(long)]
        status: Option<String>,
        /// Token query (`cycle:`, `milestone:`, `reviewer:`, `overdue`, etc.)
        #[arg(long)]
        filter: Option<String>,
        /// Include archived issues, marked with an ARCHIVED column
        ///
        /// Off by default, and off for a reason: archived issues are skipped
        /// without being read, so a repository with thousands of them lists fast.
        #[arg(long)]
        with_archived: bool,
        /// Sort key (`created`, `due`, `start`, `reviewer`, `cycle`, `milestone`, `status`, `priority`)
        #[arg(long)]
        sort: Option<String>,
        /// Group key (`cycle` | `milestone`)
        #[arg(long)]
        group: Option<String>,
        /// Comma-separated columns to display
        #[arg(
            long,
            value_name = "num,title,status,priority,cycle,milestone,reviewer,start,due,overdue"
        )]
        columns: Option<String>,
        /// Extra information to include, comma-separated
        ///
        /// `relationships` adds a relationship summary and a blocked marker
        /// per issue, read from the relationship service so the CLI and the
        /// TUI cannot disagree.
        ///
        /// `progress` adds a parent rollup; `category` adds the issue's resolved
        /// category label, read from the shared service so this surface and the
        /// TUI cannot spell one category two ways.
        #[arg(long, value_name = "SHOW")]
        show: Option<String>,
    },
    /// Inspect the status-category vocabulary, a board's mapping, and the
    /// effective transition policy
    ///
    /// A read-only surface. It never writes and never repairs, so it is safe to run
    /// on a repository whose `tix.toml` is mid-edit.
    Workflow {
        #[command(subcommand)]
        action: WorkflowAction,
    },
    /// Board summary: count per column + total
    Status {
        /// Token query (`cycle:`, `milestone:`, `reviewer:`, `overdue`, etc.)
        #[arg(long)]
        filter: Option<String>,
        /// Sort key (`created`, `due`, `start`, `reviewer`, `cycle`, `milestone`, `status`, `priority`)
        #[arg(long)]
        sort: Option<String>,
        /// Group key (`cycle` | `milestone`)
        #[arg(long)]
        group: Option<String>,
    },
    /// Triage the inbox: read-only queue views and the four decisions
    Triage {
        #[command(subcommand)]
        action: TriageAction,
    },
    /// Delete an issue file
    Delete {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// Confirm without prompting
        #[arg(long)]
        yes: bool,
    },
    /// Archive issue files: rename each in place to a dot-prefixed name
    ///
    /// The default views (`tix list`, `tix search`) skip archived issues; pass
    /// their `--with-archived` flag or the `archived:true` filter to see them.
    Archive {
        /// Issue numbers, filename fragments or unique title fragments
        #[arg(required = true, value_name = "ISSUE")]
        issues: Vec<String>,
    },
    /// Restore archived issue files: the inverse of `tix archive`
    Restore {
        /// Issue numbers, filename fragments or unique title fragments
        #[arg(required = true, value_name = "ISSUE")]
        issues: Vec<String>,
    },
    /// Manage planning cycles
    Cycle {
        #[command(subcommand)]
        command: CycleCommand,
    },
    /// Manage milestones
    Milestone {
        #[command(subcommand)]
        command: MilestoneCommand,
    },
    /// Export local issues to an external tracker via glab/linear-cli
    Export {
        /// Target tracker: gitlab | linear
        #[arg(long, value_name = "gitlab|linear|ics")]
        target: String,
        /// Print what would change without invoking the remote tracker
        #[arg(long)]
        dry_run: bool,
        /// Override the configured project path (gitlab) or team (linear)
        #[arg(long)]
        project: Option<String>,
        /// Cycle to export for ICS output
        #[arg(long)]
        cycle: Option<String>,
        /// Output path for ICS export
        #[arg(long)]
        output: Option<String>,
    },
    /// Import open issues from an external tracker via glab/linear-cli
    Import {
        /// Target tracker: gitlab | linear
        #[arg(long, value_name = "gitlab|linear")]
        target: String,
        /// Where an imported issue lands in the local triage inbox (WP07)
        ///
        /// `entry` routes into `[triage].entry_status` and refuses a project with
        /// no `[triage]` section instead of quietly falling back; `remote` keeps
        /// the column the remote mapping named. Absent is the documented default:
        /// route when the project has an inbox, otherwise leave the mapping alone.
        /// Either way the report names the mapping that was used.
        #[arg(long, value_name = "entry|remote")]
        triage_policy: Option<String>,
    },
    /// Roll open issues forward from expired cycles to the next successor
    Rollover {
        /// Restrict rollover to one source cycle
        #[arg(long)]
        cycle: Option<String>,
        /// Skip interactive confirmation
        #[arg(long)]
        yes: bool,
    },
    /// Search issue files for a string (case-insensitive substring over full markdown)
    Search {
        /// Case-insensitive substring to match against the full markdown of every issue
        #[arg(value_name = "STRING", value_parser = NonEmptyStringValueParser::new())]
        string: String,
        /// Include archived issues in the search corpus
        #[arg(long)]
        with_archived: bool,
    },
    /// Render the current board once and exit
    Render,
    /// Open the TUI with the create-issue form already open
    ///
    /// The session `tix` starts, with the modal that `n` opens already in front of
    /// you: one command to file an issue, instead of "start the board, then press
    /// n". It is the interactive twin of `tix create`, which never opens the TUI.
    New,
    /// Validate frontmatter option values in all issue files
    Lint,
    /// Serve the MCP protocol (JSON-RPC 2.0 over stdio) for agent tools
    Mcp,
}

/// The `tix triage` tree (`contracts/cli-surface.md`, WP05 T023–T025).
///
/// `list` and `status` are read-only queue views; the four decision verbs take a
/// single issue; `batch` is the selection-shaped twin of `tix bulk`, preview by
/// default and writing only under an explicit `--apply`.
///
/// ## Why the reason flag is `Option` on `accept` and the rest
///
/// `contracts/decision-history.md` splits it: decline, duplicate and defer
/// *require* a reason, accept records one when supplied. A required clap argument
/// on three of the four would make the fourth's absence look like an oversight,
/// and — more importantly — the enforcement belongs to the service, which refuses
/// `missing_reason` before any write on every surface (NFR-003). The flag is
/// therefore optional everywhere and the *rule* is the service's, so the CLI,
/// TUI and MCP cannot end up with three different ideas of which decision needs
/// one. `tix triage decline 1` with no `--reason` still fails, at the service,
/// with the contract's own kind.
#[derive(Subcommand)]
pub enum TriageAction {
    /// Read the inbox queue: one row per entry (FR-001)
    List {
        /// Sort by entry age, oldest first; an unknown age sorts last
        #[arg(long)]
        age: bool,
        /// Print the counts only, with no entries
        #[arg(long)]
        count: bool,
    },
    /// Read the inbox summary: decision counts and the age histogram (FR-005)
    Status,
    /// Accept: move into the normal workflow, validated by #183's transition policy
    Accept {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// Reason recorded in History; accept records one when supplied
        #[arg(long)]
        reason: Option<String>,
        /// Target column; defaults to `[triage].accepted_status`
        #[arg(long, value_name = "COLUMN")]
        to: Option<String>,
        /// Who decided; defaults to the git identity
        #[arg(long)]
        actor: Option<String>,
    },
    /// Decline: move to `[triage].declined_status`; never deletes or archives
    Decline {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// Why it is declined (required)
        #[arg(long)]
        reason: Option<String>,
        /// Who decided; defaults to the git identity
        #[arg(long)]
        actor: Option<String>,
    },
    /// Duplicate: record a typed `duplicates` relation; never merges files
    Duplicate {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// The issue this one duplicates
        #[arg(long, value_name = "ISSUE")]
        of: String,
        /// Why it is a duplicate (required)
        #[arg(long)]
        reason: Option<String>,
        /// Who decided; defaults to the git identity
        #[arg(long)]
        actor: Option<String>,
    },
    /// Defer: stay in the inbox with a refreshed entry time
    Defer {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
        /// Why it is deferred (required)
        #[arg(long)]
        reason: Option<String>,
        /// Who decided; defaults to the git identity
        #[arg(long)]
        actor: Option<String>,
    },
    /// One decision across a selection: preview by default, `--apply` to write
    Batch {
        /// Comma-separated selectors: number, filename or title fragment
        #[arg(long, value_name = "LIST")]
        select: Option<String>,
        /// A `tix list --filter` query selecting the issues
        #[arg(long, value_name = "QUERY")]
        filter: Option<String>,
        /// Which decision to make: accept | decline | duplicate | defer
        #[arg(long, value_name = "KIND")]
        decision: String,
        /// Reason recorded on every applied event; required for three of four
        #[arg(long)]
        reason: Option<String>,
        /// Who decided; defaults to the git identity
        #[arg(long)]
        actor: Option<String>,
        /// The duplicate target selector, for `--decision duplicate`
        #[arg(long, value_name = "ISSUE")]
        of: Option<String>,
        /// The accept target column, for `--decision accept`
        #[arg(long, value_name = "COLUMN")]
        to: Option<String>,
        /// Apply the previewed plan; without it nothing is written
        #[arg(long)]
        apply: bool,
    },
}

#[derive(Subcommand)]
pub enum CycleCommand {
    Create {
        #[arg(long)]
        name: Option<String>,
        #[arg(long)]
        description: Option<String>,
        #[arg(long = "start-date")]
        start_date: Option<String>,
        #[arg(long = "due-date")]
        due_date: Option<String>,
    },
    List,
    Edit {
        #[arg(long)]
        name: String,
        #[arg(long = "new-name")]
        new_name: Option<String>,
        #[arg(long)]
        description: Option<String>,
        #[arg(long = "start-date")]
        start_date: Option<String>,
        #[arg(long = "due-date")]
        due_date: Option<String>,
    },
    Delete {
        #[arg(long)]
        name: String,
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
pub enum MilestoneCommand {
    Create {
        #[arg(long)]
        name: String,
        #[arg(long = "target-date")]
        target_date: Option<String>,
        #[arg(long)]
        description: Option<String>,
    },
    List,
    Edit {
        #[arg(long)]
        name: String,
        #[arg(long = "new-name")]
        new_name: Option<String>,
        #[arg(long = "target-date")]
        target_date: Option<String>,
        #[arg(long)]
        description: Option<String>,
    },
    Delete {
        #[arg(long)]
        name: String,
        #[arg(long)]
        yes: bool,
    },
}

/// The `tix parent` subcommands.
///
/// A **required** subcommand, unlike `tix link`'s three optional verbs. `tix link`
/// has a meaningful bare form (create); `tix parent` with no argument is a user
/// mistake, and guessing which of three reports they wanted is worse than asking.
#[derive(Debug, Clone, Subcommand)]
pub enum ParentAction {
    /// Report the parent, direct children, child count and rollup for one issue
    Show {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
    },
    /// List an issue's direct children, ordered by issue number
    Children {
        /// Issue number, filename fragment or unique title fragment
        issue: String,
    },
    /// List every issue that has children, with a child count
    List,
}

/// The `tix workflow` verbs, per `contracts/cli-surface.md` §1.
///
/// A real `#[command(subcommand)]` tree rather than an optional-verb enum like
/// [`LinkAction`]: the three verbs share nothing but the prefix, and there is no
/// sensible bare `tix workflow`. Making the verb **required** means `tix workflow`
/// alone is a usage error rather than an empty success — printing the vocabulary
/// when the user asked for the policy would be guessing at their intent.
#[derive(Subcommand)]
pub enum WorkflowAction {
    /// The global category vocabulary, in order
    Categories,
    /// A board's columns, resolved categories, and where each resolution came from
    Show {
        /// Board name; omitted means the active board (`default`, or the first
        /// declared). A name that is not configured is an error listing the boards
        /// that are.
        board: Option<String>,
    },
    /// The effective transition policy and its override escape hatch
    Transitions,
}

/// The `tix link` subcommands.
///
/// `tix link <from> <to> --type <kind>` is the create form and carries no
/// subcommand, so the three verbs below are optional rather than required
/// (C-001 removes the old untyped symmetric form, not the bare create form the
/// CLI surface contract specifies).
#[derive(Subcommand)]
pub enum LinkAction {
    /// Retarget and/or re-kind an existing relationship, keeping its id
    Edit {
        /// Relationship id, as printed by `tix link list`
        id: String,
        /// New target issue number, filename fragment or unique title fragment
        #[arg(long)]
        to: Option<String>,
        /// New relationship kind: `blocks`, `blocked_by`, `duplicates`, `related`
        #[arg(long, value_name = "KIND")]
        r#type: Option<String>,
    },
    /// Remove a relationship by id. An absent id is an idempotent no-op
    Remove {
        /// Relationship id, as printed by `tix link list`
        id: String,
    },
    /// List relationships for one issue, or for the whole board
    List {
        /// Issue number, filename fragment or unique title fragment. Omit for every issue.
        issue: Option<String>,
        /// Only relationships of this kind
        #[arg(long, value_name = "KIND")]
        kind: Option<String>,
    },
}

/// `tix bulk <action>` — four actions, and each carries **its own** flags.
///
/// The flags are on the subcommand rather than on the parent, which is what makes the
/// surface unambiguous by construction rather than by a runtime check:
/// `tix bulk archive --priority high` is a **clap usage error**, not a command that
/// accepts a field flag and ignores it. `edit` is the only action with field flags,
/// `link`/`unlink` are the only ones with `--target`, and `archive` takes neither — so
/// there is no spelling of `tix bulk` that a flag can apply to by accident.
///
/// `archive` has no `--type`: archiving is not a relationship, and offering a kind
/// would suggest it is one.
/// The flags every `tix bulk` action carries: which issues, and whether to write.
///
/// Flattened into **each** action rather than held on `Command::Bulk`, because clap
/// parses a parent's flags *before* its subcommand — so a parent would spell the
/// contract's `tix bulk edit --select <...>` as `tix bulk --select <...> edit`, which
/// is a different surface from the one the contract names. Four `#[command(flatten)]`
/// of one struct gives the contract's spelling and one vocabulary, so a new flag
/// cannot be added to one action and forgotten on the other three.
#[derive(Args, Debug, Clone, PartialEq, Eq)]
pub struct BulkSelection {
    /// Comma-separated issue selectors: number, filename fragment or unique title
    /// fragment
    #[arg(long, value_name = "LIST")]
    pub select: Option<String>,
    /// A `--filter` query, in the existing filter grammar
    #[arg(long, value_name = "QUERY")]
    pub filter: Option<String>,
    /// A `--search` query, in the existing search grammar
    #[arg(long, value_name = "QUERY")]
    pub search: Option<String>,
    /// Which issues are in play: `active`, `active+archived` or `archived`
    #[arg(long, value_name = "SCOPE")]
    pub scope: Option<String>,
    /// Write the batch. Omit for a preview, which is the default.
    #[arg(long)]
    pub apply: bool,
}

impl BulkAction {
    /// The shared selection flags, whichever action carries them.
    ///
    /// One accessor for four flattened fields, so the routing code reads the flags
    /// once and a new action cannot forget to pass them.
    pub fn selection(&self) -> &BulkSelection {
        match self {
            Self::Edit { selection, .. }
            | Self::Link { selection, .. }
            | Self::Unlink { selection, .. }
            | Self::Archive { selection } => selection,
        }
    }

    /// Whether `--apply` was given. A preview is the default, so this is a positive
    /// question rather than "is this not a preview".
    pub fn is_apply(&self) -> bool {
        self.selection().apply
    }
}

#[derive(Subcommand, Debug, Clone, PartialEq, Eq)]
pub enum BulkAction {
    /// Apply a typed field patch to every selected issue
    Edit {
        #[command(flatten)]
        selection: BulkSelection,
        /// Target column
        #[arg(long, value_name = "COLUMN")]
        status: Option<String>,
        /// `low`, `medium`, `high`, or `` for unset
        #[arg(long, value_name = "PRIORITY")]
        priority: Option<String>,
        /// Bare handle or full identity
        #[arg(long, value_name = "ASSIGNEE")]
        assignee: Option<String>,
        /// Comma-separated labels
        #[arg(long, value_name = "LABELS")]
        labels: Option<String>,
        /// `YYYY-MM-DD`
        #[arg(long, value_name = "DATE")]
        start_date: Option<String>,
        /// `YYYY-MM-DD`
        #[arg(long, value_name = "DATE")]
        due_date: Option<String>,
        /// Free-form estimate
        #[arg(long, value_name = "ESTIMATE")]
        estimate: Option<String>,
        /// Comma-separated cycle names
        #[arg(long, value_name = "CYCLES")]
        cycles: Option<String>,
        /// Comma-separated milestone names
        #[arg(long, value_name = "MILESTONES")]
        milestones: Option<String>,
        /// Empty a field. Takes one of the clearable field names.
        #[arg(long, value_name = "FIELD")]
        clear: Option<String>,
    },
    /// Link every selected issue to `--target`
    Link {
        #[command(flatten)]
        selection: BulkSelection,
        /// The other end of the relationship
        #[arg(long, value_name = "SELECTOR")]
        target: String,
        /// Relationship kind: `blocks`, `blocked_by`, `duplicates`, `related`
        #[arg(long, value_name = "KIND")]
        r#type: Option<String>,
    },
    /// Unlink every selected issue from `--target`
    Unlink {
        #[command(flatten)]
        selection: BulkSelection,
        /// The other end of the relationship
        #[arg(long, value_name = "SELECTOR")]
        target: String,
        /// Relationship kind: `blocks`, `blocked_by`, `duplicates`, `related`
        #[arg(long, value_name = "KIND")]
        r#type: Option<String>,
    },
    /// Ask the archive service to archive every selected issue
    Archive {
        #[command(flatten)]
        selection: BulkSelection,
    },
}

/// Process entry: route a parsed [`Cli`] through config resolution, store
/// opening and dispatch, then return the exit code for `main` to exit with.
pub fn run(cli: Cli) -> u8 {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    match &cli.command {
        Some(Command::Lint) => run_lint(&cwd),
        Some(Command::Mcp) => match run_mcp(&cwd) {
            Ok(()) => ExitCode::Success as u8,
            Err(e) => {
                eprintln!("tix: {e}");
                exit_code_for(&e) as u8
            }
        },
        Some(Command::Render) => match run_render(&cwd) {
            Ok(()) => ExitCode::Success as u8,
            Err(e) => {
                eprintln!("tix: {e}");
                exit_code_for(&e) as u8
            }
        },
        // A bulk batch is the one command whose **status** is a result rather than an
        // error: a partial batch completes and reports non-zero, with every outcome
        // retained (`contracts/cli-surface.md`). So it is routed here, where the exit
        // code is decided, and not through `commands::dispatch`, whose arms are all
        // `Result<()>`.
        Some(Command::Bulk { action }) => {
            let result = resolve(&cwd).and_then(|(_, store)| {
                commands::bulk::run(
                    &store,
                    action,
                    action.selection(),
                    if action.is_apply() {
                        commands::bulk::Mode::Apply
                    } else {
                        commands::bulk::Mode::Preview
                    },
                )
            });
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("tix: {e}");
                    exit_code_for(&e) as u8
                }
            }
        }
        // `tix triage` shares bulk's exit-code shape for the same reason: a batch
        // that partly succeeded is a *completed* command with a status, not an
        // error, so `--apply` can print one outcome per selected issue and still
        // exit non-zero (T026). It is routed here rather than through
        // `commands::dispatch`, whose arms are all `Result<()>`.
        Some(Command::Triage { action }) => {
            let result = resolve(&cwd).and_then(|(_, store)| commands::triage::run(&store, action));
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("tix: {e}");
                    exit_code_for(&e) as u8
                }
            }
        }
        // `tix archive`/`tix restore` share the batch exit-code shape: every
        // selector is processed independently, a failure on one does not roll back
        // another, and the process still exits non-zero if any failed. Routed here
        // for the same reason `tix bulk` and `tix triage` are.
        Some(Command::Archive { issues }) => {
            route_archive(&cwd, commands::archive::Action::Archive, issues)
        }
        Some(Command::Restore { issues }) => {
            route_archive(&cwd, commands::archive::Action::Restore, issues)
        }
        _ => {
            let result = match &cli.command {
                None => run_tui(&cwd),
                Some(Command::New) => run_tui_new(&cwd),
                Some(Command::Init) => commands::init::run(&cwd),
                Some(Command::InitAgents) => {
                    let root = Config::project_root(&cwd).unwrap_or(cwd.clone());
                    commands::agents::run(&root).map(|_| ())
                }
                Some(cmd) => run_subcommand(&cwd, cmd),
            };
            match result {
                Ok(()) => ExitCode::Success as u8,
                Err(e) => {
                    eprintln!("tix: {e}");
                    exit_code_for(&e) as u8
                }
            }
        }
    }
}

/// Process one `tix archive`/`tix restore` batch and map it to an exit code.
///
/// Each selector is independent: an outcome is printed per item and a failure on
/// one item neither aborts the rest nor rolls back a successful rename. The
/// process exits with the first failure's code, or `0` when every item succeeded.
fn route_archive(cwd: &Path, action: commands::archive::Action, issues: &[String]) -> u8 {
    match resolve(cwd).and_then(|(_, store)| commands::archive::run(&store, action, issues)) {
        Ok(code) => code as u8,
        Err(e) => {
            eprintln!("tix: {e}");
            exit_code_for(&e) as u8
        }
    }
}

/// `tix lint` owns its own boundary: its exit-code table (`0` healthy, `1`
/// findings, `2` usage/internal) does not match the generic
/// [`exit_code_for`] mapping, which would collapse internal errors into `1`.
fn run_lint(cwd: &Path) -> u8 {
    let (config, store) = match resolve(cwd) {
        Ok(pair) => pair,
        Err(e) => {
            eprintln!("tix: {e}");
            return 2;
        }
    };
    match commands::lint::run(&config, &store) {
        Ok(true) => 1,
        Ok(false) => 0,
        Err(e) => {
            eprintln!("tix: {e}");
            2
        }
    }
}

/// `tix` with no subcommand: launch the TUI, or fail with the contract's
/// exact message when no `tix.toml` is reachable (exit 1).
fn run_tui(cwd: &Path) -> Result<()> {
    let config = repo_config(cwd)?;
    crate::app::run(&config)
}

/// `tix new`: the same session, opened on the create-issue form instead of the
/// board. Same repository resolution as [`run_tui`], so a missing `tix.toml` fails
/// with the same message rather than opening a form that could not be submitted.
fn run_tui_new(cwd: &Path) -> Result<()> {
    let config = repo_config(cwd)?;
    crate::app::run_new_issue(&config)
}

/// Strict repository resolution shared by the TUI and `tix mcp` (FR-015):
/// upward `tix.toml` discovery, failing with the contract's exact `no
/// tix.toml found` guidance (exit 1) when no repository is reachable —
/// never a guessed default store. This is the "CLI hot path" that
/// `contracts/mcp-protocol.md` §7 requires `tix mcp` to reuse.
fn repo_config(cwd: &Path) -> Result<Config> {
    let root = Config::project_root(cwd)
        .ok_or_else(|| TixError::Config("no tix.toml found — run \"tix init\" first".into()))?;
    Config::load(&root)
}

/// `tix mcp`: strict repository resolution (same hot path as `tix` with no
/// subcommand), then serve the MCP protocol synchronously over stdio. Outside
/// a repository the process fails with exit 1 BEFORE reading any protocol
/// bytes (FR-016, `contracts/mcp-protocol.md` §7).
fn run_mcp(cwd: &Path) -> Result<()> {
    let config = repo_config(cwd)?;
    let store = Store::open(&config)?;
    // Absolutize milestones against the same project root as issues_dir so the
    // MCP `create_issue`/`update_issue` planning validators and the CLI resolve
    // milestone files to the identical directory (parity cross-checker).
    let mut config = config;
    if config.milestones_dir().is_relative() {
        let root = Config::project_root(cwd).unwrap_or_else(|| cwd.to_path_buf());
        let configured = config.milestones_dir();
        config.milestones_dir = Some(root.join(configured));
    }
    crate::mcp::serve(&config, &store)
}

/// `tix render`: strict repository resolution like `tix`/`tix mcp` so the
/// command fails with the same no-config guidance outside a repository.
fn run_render(cwd: &Path) -> Result<()> {
    let config = repo_config(cwd)?;
    let store = Store::open(&config)?;
    commands::dispatch(&Command::Render, &config, &store)
}

/// Config resolution for subcommands: defaults when no `tix.toml` exists
/// (relative to the project root via upward walk), with a one-time stderr
/// notice. Only explicit per-command requirements fail hard.
fn resolve(cwd: &Path) -> Result<(Config, Store)> {
    let root = Config::project_root(cwd);
    let mut config = match &root {
        Some(r) => Config::load(r)?,
        None => Config::default(),
    };
    // Resolve a relative issues_dir against the project root (or cwd when
    // unconfigured) so subcommands behave identically from any subdirectory.
    if config.issues_dir.is_relative() {
        let base = root.as_deref().unwrap_or(cwd);
        config.issues_dir = base.join(&config.issues_dir);
    }
    // Milestones resolve against the same base as issues_dir: the planning
    // validators (create/edit) and `lint` must agree on where milestone
    // registry files live regardless of the invocation directory.
    if config.milestones_dir().is_relative() {
        let base = root.as_deref().unwrap_or(cwd);
        let configured = config.milestones_dir();
        config.milestones_dir = Some(base.join(configured));
    }
    if root.is_none() {
        eprintln!("tix: no tix.toml found (run 'tix init' to create one)");
    }
    let store = Store::open(&config)?;
    Ok((config, store))
}

fn run_subcommand(cwd: &Path, cmd: &Command) -> Result<()> {
    let (config, store) = resolve(cwd)?;
    if !matches!(cmd, Command::Rollover { .. }) {
        let planner = crate::planning::Planner::from_config(config.clone(), cwd.to_path_buf());
        let plan = planner.rollover_plan(&store, &crate::model::today());
        if let Some(first) = plan.first() {
            eprintln!(
                "hint: rollover of {} issue(s) from \"{}\" to \"{}\" is suggested; run 'tix rollover' to apply",
                first.issues.len(),
                first.from_cycle,
                first.to_cycle
            );
        }
    }
    commands::dispatch(cmd, &config, &store)
}