tix-tracker 0.12.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
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
//! 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;

mod cli_analytics;
mod cli_beads;
mod cli_bulk;
mod cli_capacity;
mod cli_cycle_schedule;
mod cli_epic;
mod cli_health;
mod cli_initiative;
mod cli_mentions;
mod cli_milestone;
mod cli_project;
mod cli_recurring;
mod cli_roadmap;
mod cli_templates;
mod cli_time;
mod cli_triage;
mod cli_views;
mod cli_wip;
mod cli_workflow;
pub use cli_analytics::*;
pub use cli_beads::*;
pub use cli_bulk::*;
pub use cli_capacity::*;
pub use cli_cycle_schedule::*;
pub use cli_epic::*;
pub use cli_health::*;
pub use cli_initiative::*;
pub use cli_mentions::*;
pub use cli_milestone::*;
pub use cli_project::*;
pub use cli_recurring::*;
pub use cli_roadmap::*;
pub use cli_templates::*;
pub use cli_time::*;
pub use cli_triage::*;
pub use cli_views::*;
pub use cli_wip::*;
pub use cli_workflow::*;

/// 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]).
    ///
    /// When `bd` is on PATH and a beads workspace is reachable, an interactive
    /// run also offers the beads modes; `--beads` decides without a prompt, and a
    /// non-interactive run never prompts (it keeps `off` unless `--beads` says
    /// otherwise).
    Init {
        /// Beads mode to record: off | mirror | sync
        ///
        /// `mirror` reads a beads workspace through `bd` for viewing only;
        /// `sync` installs the `.beads/hooks` that pull beads changes into tix.
        #[arg(long, value_name = "off|mirror|sync")]
        beads: Option<String>,
    },
    /// Append or replace the tix block in AGENTS.md (idempotent)
    InitAgents {
        /// Overwrite an outdated block without prompting
        #[arg(long)]
        yes: bool,
    },
    /// Print the crate version and how this binary was built
    ///
    /// Answers the question `--version` cannot: whether the binary on disk came
    /// from the source on disk. It reports the commit it was built from and when,
    /// so a rebuild that did not happen is visible. Needs no `tix.toml`, so it
    /// works in any directory.
    Version,
    /// Read, or write, a [beads](https://github.com/gastownhall/beads) workspace
    /// through the `bd` CLI
    ///
    /// tix never opens the beads Dolt database: every verb here shells out to
    /// `bd`. The reads (`detect`, `status`, `list`, `show`, `watch`) write
    /// nothing anywhere; the writes (`push`, `pull`, `reconcile`) are refused
    /// while the beads mode is `mirror`, which is read-only by contract. See
    /// `docs/for-users/beads-integration.md`.
    Beads {
        #[command(subcommand)]
        action: BeadsAction,
    },
    /// 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>,
        /// Projects to associate the new issue with: ids or names, comma-separated
        ///
        /// Every reference is resolved through the project service **before** the
        /// issue is written, so an unknown id refuses the whole create rather than
        /// leaving a half-associated issue. This flag lives on the shared create
        /// path, which is the handoff point a future template surface (source issue
        /// #174) would populate (mission `first-class-projects-01M3BYBW`).
        #[arg(long, value_name = "ID")]
        projects: Option<String>,
        /// Epics the new issue references: ids or names, comma-separated
        ///
        /// Every reference is resolved through the epic service **before** the issue
        /// is written, so an unknown id refuses the whole create rather than leaving
        /// a half-referenced issue. This flag lives on the shared create path, which
        /// is the handoff point a future template surface (source issue #174) would
        /// populate. Referencing an epic never changes how the issue itself is
        /// navigated: it stays an ordinary issue (mission `epics-work-items-01M3BYW4`).
        #[arg(long, value_name = "ID")]
        epics: 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>,
        /// Related issues, comma-separated: a local number/selector, a relative
        /// or absolute path to another issue file, or a repository URL
        /// (`host/path#id`). Free-form; stored verbatim.
        #[arg(long)]
        related_issues: Option<String>,
        /// Issue type (e.g. `bug`, `feature`); `tix lint` warns on a value not in
        /// `custom_types`.
        #[arg(long)]
        r#type: Option<String>,
        /// Create from a stable template ID (`tix template list`)
        ///
        /// The template's defaults and prompts are merged with the flags above
        /// by the pure resolver, then the resolved request goes through the
        /// shared create core — there is no second issue writer. Resolution
        /// never prompts: a required prompt with no value is a diagnostic, the
        /// template and the store are left untouched, and no issue is written.
        #[arg(long, value_name = "STABLE-ID")]
        template: Option<String>,
        /// Template scope: `repository` | `board:<name>` | `team:<label>`
        ///
        /// Only meaningful with `--template` (clap requires it). An omitted
        /// scope is the explicit `repository` default, never an implicit
        /// inheritance. The selected template ID and scope are echoed on
        /// stderr so stdout keeps the `Created <file>` shape.
        #[arg(long, value_name = "SCOPE", requires = "template")]
        scope: 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: `3`, `3d`, `1 day`, `0.5-1 day`, `3 weeks 2 hours` (empty clears)
        #[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>,
        /// Associate the issue with a project (id or name); repeatable
        ///
        /// Idempotent: an already-present association is a no-op with no History
        /// entry. The reference is resolved through the project service before
        /// anything is written, so an unknown project refuses the edit and leaves
        /// the file byte-identical.
        #[arg(long, value_name = "ID")]
        add_project: Vec<String>,
        /// Dissociate the issue from a project (id or name); repeatable
        ///
        /// Drops only the association — the issue is never deleted. A known project
        /// that is not associated is a no-op; an unresolvable reference that the
        /// issue does not carry is refused as `unknown_project`.
        #[arg(long, value_name = "ID")]
        remove_project: Vec<String>,
        /// Replace the whole association list, comma-separated
        ///
        /// Only a blank value is accepted here: `--projects ""` clears every
        /// association, mirroring the empty-string-clears convention the other list
        /// flags follow. To add or drop individual associations use
        /// `--add-project` / `--remove-project`; a non-blank value is refused rather
        /// than guessed at.
        #[arg(long, value_name = "IDS")]
        projects: Option<String>,
        /// Add an epic reference (id or name); repeatable
        ///
        /// Idempotent: an already-present reference is a no-op with no History
        /// entry. The reference is resolved through the epic service before
        /// anything is written, so an unknown epic refuses the edit and leaves the
        /// file byte-identical.
        #[arg(long = "add-epic", value_name = "ID")]
        add_epic: Vec<String>,
        /// Remove an epic reference; repeatable
        ///
        /// Drops only the reference — the issue is never deleted. A known epic that
        /// is not referenced is a no-op; an unresolvable reference the issue does not
        /// carry is refused as `unknown_epic`. A retained stale id can still be
        /// removed by naming it verbatim.
        #[arg(long = "remove-epic", value_name = "ID")]
        remove_epic: Vec<String>,
        /// Clear every epic reference
        ///
        /// Only a blank value is accepted here: `--epics ""` clears every reference,
        /// mirroring the empty-string-clears convention `--projects` follows. To add
        /// or drop individual references use `--add-epic` / `--remove-epic`; a
        /// non-blank value is refused rather than guessed at.
        #[arg(long, value_name = "IDS")]
        epics: 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>,
        /// New related-issues list, comma-separated (`--related-issues ""` clears).
        /// A local number/selector, a relative or absolute path to another issue
        /// file, or a repository URL (`host/path#id`).
        #[arg(long)]
        related_issues: Option<String>,
        /// New issue type (`--type ""` clears it); `tix lint` warns on a value not
        /// in `custom_types`.
        #[arg(long)]
        r#type: Option<String>,
    },
    /// Move one or more issues to a column
    ///
    /// A single selector behaves exactly as before. More than one position,
    /// `--select`, `--filter` or `--search` moves the whole selection; a batch
    /// larger than one requires `--yes` to apply, and `--dry-run` previews it.
    Move {
        /// Issue selectors followed by the target column. The **last** value is
        /// the column; the preceding ones are selectors (number, filename
        /// fragment, unique title fragment, comma- or space-separated).
        #[arg(value_name = "ISSUE_OR_COLUMN", num_args = 1.., required = true)]
        args: Vec<String>,
        /// Comma-separated issue selectors (same grammar as the positional list)
        #[arg(long, value_name = "LIST")]
        select: Option<String>,
        /// A `--filter` query, in the existing filter grammar
        #[arg(long, value_name = "QUERY")]
        filter: Option<String>,
        /// A `--search` query, in the existing search grammar
        #[arg(long, value_name = "QUERY")]
        search: Option<String>,
        /// Print the batch plan and write nothing
        #[arg(long)]
        dry_run: bool,
        /// 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.
        ///
        /// For a selection larger than one, `--yes` is also the batch
        /// confirmation: without it the plan is printed and nothing is written.
        #[arg(long)]
        yes: bool,
        /// Authorize overriding a **blocking work-in-progress limit**
        ///
        /// `--override` is a request, not an authorization. The move only proceeds
        /// when `--reason` states why and `--yes` confirms it, and the override is
        /// recorded — actor, timestamp, reason and the limit it was authorized
        /// against — as a History entry on the issue. Without `--override` a move
        /// that would exceed a `block` limit is refused and nothing is written; a
        /// `warn` limit never needs one.
        #[arg(long)]
        r#override: bool,
    },
    /// Inspect or configure work-in-progress limits
    ///
    /// Limits live in `tix.toml` under `[kanban.<board>.wip]`: a column's ceilings
    /// (`max_items`, `max_estimate`), the unit an estimate ceiling counts in, and
    /// whether exceeding it `warn`s or `block`s. A board with no limits behaves
    /// exactly as it did before they existed.
    Wip {
        #[command(subcommand)]
        action: WipAction,
    },
    /// Print an issue, or manage saved views (#172)
    ///
    /// `tix view <issue>` prints the issue file, unchanged. Without an issue
    /// selector the subcommands below manage repository-owned **saved views**:
    /// named, stable-ID query definitions with explicit scope metadata and a
    /// normalized plan over the existing filter/sort/group/visibility grammar.
    ///
    /// The nine subcommand words (`list`, `show`, `create`, `update`,
    /// `duplicate`, `delete`, `apply`, `status`, `share`) are **reserved** on
    /// `tix view`: an issue whose selector is exactly one of them must be
    /// addressed by number, exactly as `tix link` reserves `edit` / `remove` /
    /// `list`.
    #[command(visible_alias = "show")]
    View {
        /// `list`, `show`, `create`, `update`, `duplicate`, `delete`, `apply`,
        /// `status`, or `share`. Omit to print an issue.
        #[command(subcommand)]
        action: Option<ViewAction>,
        /// [print] Issue number, filename fragment or unique title fragment
        issue: Option<String>,
        /// [print] 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>,
    },
    /// Manage recurring issue series (tix #175)
    ///
    /// A series is a **normal issue** that carries a `series:` table in its
    /// frontmatter: the issue holds the rule, the lifecycle state, and the
    /// template an occurrence is created from; each occurrence is another normal
    /// issue carrying the series id, the date and the idempotency key.
    ///
    /// `detect` is read-only and reports what is due; `generate` and every
    /// lifecycle action need `--yes`, because no refresh, timer or detection may
    /// change a schedule on its own.
    Recurring {
        #[command(subcommand)]
        action: RecurringAction,
    },
    /// One line per issue: number, id and title
    ///
    /// The default listing is **scoped**: your issues (the git author identity,
    /// when it can be derived) in the board's entry column — `todo` on the board
    /// `tix init` writes. `--all` drops the scope, and `--status`/`--filter`
    /// replace it. The title is cropped to the terminal's width, so every issue
    /// occupies exactly one line; the full board is `tix render`.
    List {
        /// Only issues in this status
        #[arg(long)]
        status: Option<String>,
        /// Token query (`cycle:`, `milestone:`, `reviewer:`, `overdue`, etc.)
        #[arg(long)]
        filter: Option<String>,
        /// Restrict the listing to one project (stable id, or a display name)
        ///
        /// Resolved through the project service and applied through the shared
        /// `project:` criterion, so `tix list --project <id>` and
        /// `tix search "project:<id>"` return the same matching set.
        #[arg(long)]
        project: Option<String>,
        /// Restrict the listing to one epic (stable id, or a display name)
        ///
        /// Resolved through the epic service and applied through the shared
        /// `epic:` criterion, so `tix list --epic <id>` and
        /// `tix search "epic:<id>"` return the same matching set. An unknown
        /// reference matches nothing, so a typo yields a visible empty listing
        /// rather than a silent unfiltered one.
        #[arg(long)]
        epic: 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`, `project`, `epic`, `status`, `priority`)
        #[arg(long)]
        sort: Option<String>,
        /// Group key (`cycle` | `milestone` | `project` | `epic`)
        #[arg(long)]
        group: Option<String>,
        /// Comma-separated columns to display
        ///
        /// The full set: `num`, `id`, `title`, `status`, `priority`, `cycle`,
        /// `milestone`, `reviewer`, `start`, `due`, `overdue`, `blocked`,
        /// `relations`, `progress`, `projects`, `epics`, `category`, `archived`,
        /// `wip`, `health`. The `value_name` used to list only the first ten, so a
        /// column this build had supported for two missions looked unsupported in
        /// `--help`; a column left out of this list is the same lie about a smaller
        /// set.
        #[arg(long, value_name = "COLUMNS")]
        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.
        ///
        /// `wip` adds the column's usage against its limit, and `health` adds the
        /// issue's health (its own value, with the derived rollup beside it when the
        /// two differ), read from the one portable health document.
        #[arg(long, value_name = "SHOW")]
        show: Option<String>,
        /// List every issue, ignoring the default scope
        ///
        /// The default listing is scoped to your issues in the board's entry
        /// column. `--all` drops both halves of that scope — the listing is then
        /// every active issue, exactly as it was before the scope existed.
        #[arg(long)]
        all: bool,
        /// Emit a structured document instead of the table: `xml`, `yml` or `toml`
        ///
        /// One record per issue, keyed by the columns being displayed, under the
        /// single root `issues` — so `--columns` chooses the fields. JSON is
        /// deliberately not one of them.
        #[arg(long, value_name = "FORMAT")]
        format: Option<String>,
    },
    /// The next issue to start: unblocked, highest priority first
    ///
    /// The `tix list` a working session opens with. It shows every issue that
    /// nothing blocks and that has not begun — a column the board maps to `backlog`
    /// or `unstarted`, no further along than the column new work lands in — ordered
    /// by priority (highest first, then oldest first), so the **first row** is the
    /// issue to pick up next. Blocked means an **open** blocker: the same graph the
    /// `blocked` column reads, so finishing a blocker returns its dependents here.
    Ready {
        /// Comma-separated columns to display
        ///
        /// The default set is `num,id,priority,title`: the identity pair, the
        /// priority the list is ordered by, and the title.
        #[arg(long, value_name = "COLUMNS")]
        columns: Option<String>,
        /// Show at most this many issues
        ///
        /// Applied after the ordering, so `--limit 1` is the single next issue.
        #[arg(long, value_name = "N")]
        limit: Option<usize>,
        /// Restrict the listing to one project (stable id, or a display name)
        #[arg(long)]
        project: Option<String>,
        /// Restrict the listing to one epic (stable id, or a display name)
        #[arg(long)]
        epic: Option<String>,
        /// Emit a structured document instead of the table: `xml`, `yml` or `toml`
        #[arg(long, value_name = "FORMAT")]
        format: 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` | `project` | `epic`)
        #[arg(long)]
        group: Option<String>,
        /// Add the health summary: issue counts per state, with diagnostics
        ///
        /// Read from the same portable health document `tix health board` and the
        /// TUI render, so the figures are the same figures. Off by default: the board
        /// summary is about columns, and health is metadata about the work (C-006).
        #[arg(long)]
        health: bool,
        /// Print one machine-readable JSON object instead of the table
        ///
        /// The object is the board summary: `columns` in board order, each with
        /// its count, and `total`. With `--health` the same `health` object MCP's
        /// `board_status` returns is added; without it the key is absent. The
        /// table without this flag is unchanged.
        #[arg(long)]
        json: bool,
    },
    /// Project and issue health: read a scope, roll it up, or record a change
    ///
    /// Health is **metadata**, not the board's status: it never replaces a status
    /// category and never means "done". The current value lives in an issue's
    /// frontmatter, every change is an append-only History entry carrying an actor, a
    /// date and a rationale, and a scope's derived value comes from what contributes
    /// to it under a versioned policy (`health-v1`).
    ///
    /// `set` and `override` are the mutations, and both refuse — having written
    /// nothing — when an audit field is missing. `show`, `rollup`, `history` and
    /// `board` read.
    Health {
        #[command(subcommand)]
        action: HealthAction,
    },
    /// Read and act on your `@mentions` (issue-mentions)
    ///
    /// A mention is `@handle` or `@name@host` in an issue's title or body, recorded
    /// per mentioned target under `docs/mentions/`. This command is the
    /// **non-interactive** surface: it lists what is pending for you and applies the
    /// three answers without a prompt, so the flow works from a script and without a
    /// TTY. The TUI has the same three answers on the bottom indicator row's chord.
    Mentions {
        #[command(subcommand)]
        action: MentionsAction,
    },
    /// 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,
    },
    /// Configure and inspect cycle, team and assignee capacity
    ///
    /// A ceiling is a scope (one cycle, one team label, or one assignee identity)
    /// with a non-negative value in an estimate unit the active board declares.
    /// `calculate` reports the shared committed/completed/remaining/overflow/
    /// utilization values and never mutates an issue; `snapshot` reads back the
    /// immutable evidence a cycle close captured.
    Capacity {
        #[command(subcommand)]
        command: CapacityCommand,
    },
    /// Record and review actual effort against issues, in whole minutes
    ///
    /// A time entry is a duration, an optional `YYYY-MM-DD` calendar date, an author
    /// and an optional note — there is no timer, no timezone conversion and no overlap
    /// rule. Current entries live in the issue's own frontmatter, every correction and
    /// deletion appends an attributable History event, and a deletion removes the
    /// current value only. `add`, `edit` and `delete` are the mutations (`edit` and
    /// `delete` require `--reason`; `delete` also requires `--confirm`), and `show`,
    /// `history` and `total` are reads whose numbers come from one shared calculation.
    Time {
        #[command(subcommand)]
        command: TimeCommand,
    },
    /// Manage milestones
    Milestone {
        #[command(subcommand)]
        command: MilestoneCommand,
    },
    /// Create, edit, list, inspect, delete and populate projects
    ///
    /// A project is a stable id (a registry key in `tix.toml`) with a mutable
    /// display name. An issue carries **project ids**, so a rename breaks no
    /// association: the id is the identity and the name is a label. Every listing
    /// prints the id beside the name, because without it a rename is
    /// indistinguishable from a new project.
    ///
    /// `delete` removes the **registry entry only**. The issues that referenced
    /// the project keep their references, which then read as diagnosable missing
    /// references (`tix lint` names each one), so nothing is destroyed by deleting
    /// a project and there is deliberately no `--cascade` and no bulk-delete of
    /// issues.
    ///
    /// `add`, `remove` and `bulk-add` process each issue selector
    /// **independently**: a rejection on one selector is reported and never aborts
    /// the rest. Their scope is project association only — general bulk editing is
    /// a different feature.
    Project {
        #[command(subcommand)]
        command: ProjectCommand,
    },
    /// Create, edit, list, inspect, navigate and delete epics; associate work items
    ///
    /// An epic is a stable id (a registry key in `tix.toml`) with a mutable
    /// display name. A work item references epic **ids**, so a rename breaks no
    /// reference: the id is the identity and the name is a label. Every listing
    /// prints the id beside the name, because without it a rename is
    /// indistinguishable from a new epic.
    ///
    /// A "task" is an ordinary issue: `tix edit <sel> --labels task --add-epic
    /// <id>` adds a reference to an issue. No task entity, file or frontmatter key
    /// is created, and direct issue navigation stays available from every view.
    ///
    /// `delete` removes the **registry entry only**. The issues that referenced the
    /// epic keep their references (which then read as missing references) and the
    /// child epics keep their recorded parent (which then reads as unresolved), so
    /// nothing is destroyed by deleting an epic and there is deliberately no
    /// `--cascade`.
    ///
    /// `add`, `remove` and `bulk-add` process each issue selector
    /// **independently**: a rejection on one selector is reported and never aborts
    /// the rest. Their scope is epic reference only — general bulk editing is a
    /// different feature.
    Epic {
        #[command(subcommand)]
        command: EpicCommand,
    },
    /// Create, edit, list, inspect, delete and associate roadmap initiatives
    ///
    /// An initiative is a stable id (a registry key in `tix.toml`) with a mutable
    /// display name, an optional target date/status/owner, and explicit
    /// project/epic/milestone associations. The id is the identity, so a rename
    /// breaks no association. Every listing prints the id, because without it a
    /// rename is indistinguishable from a new initiative.
    ///
    /// `delete` removes the **registry entry only**. The record's own references are
    /// reported and nothing cascades: no project, epic, milestone or issue is
    /// touched, and no association is silently repaired.
    ///
    /// `associate`/`dereference` name exactly one of `--project`, `--epic` or
    /// `--milestone`; a well-formed reference that names nothing is stored and stays
    /// diagnosable (`tix roadmap` and `tix lint` report it), and a repeated
    /// association is an idempotent no-op.
    Initiative {
        #[command(subcommand)]
        command: InitiativeCommand,
    },
    /// List and inspect the roadmap: initiatives ordered by target date
    ///
    /// Read-only. Each row carries the target date (or the explicit `undated`
    /// state), the source-attributed summary — one contribution per referenced
    /// project/epic/milestone with its own value and shared policy version — and the
    /// ordered diagnostics, so a missing reference is visible on the row and an
    /// empty summary is explicit. No figure is blended across sources.
    Roadmap {
        #[command(subcommand)]
        command: RoadmapCommand,
    },
    /// Read the burndown and scope analytics of a cycle or milestone, or write its
    /// deterministic chart document
    ///
    /// Read-only. `burndown` prints the daily remaining/completed series the shared fold
    /// produces, `projection` the read-only end-date forecast at the caller's `--as-of`,
    /// and `export` the versioned local chart document (WP04's target, called by this
    /// verb rather than re-serialized). The period comes from the cycle/milestone's own
    /// planning data and `--from`/`--to` replace the bound they name; count and estimate
    /// modes are explicit and an estimate without a compatible unit is refused rather
    /// than guessed. A value the record cannot support prints as `-` and never as a zero,
    /// a day with no recorded history is explicit about its coverage, and nothing here
    /// mutates an issue, a cycle or a snapshot. The remote `gitlab`/`linear` export
    /// namespaces are a different command (`tix export`) and are never consulted.
    Analytics {
        #[command(subcommand)]
        command: AnalyticsCommand,
    },
    /// Export local issues to an external tracker via glab/linear-cli, or write
    /// them into a beads workspace via `bd`
    Export {
        /// Target tracker: gitlab | linear | ics | beads
        #[arg(long, value_name = "gitlab|linear|ics|beads")]
        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>,
        /// List the per-issue diagnostics — which local fields beads cannot hold
        ///
        /// Off by default: a board of a few thousand issues produces hundreds of
        /// them, and a run that sends three issues should not rehearse the notes
        /// for the other thousand. The counts are always reported either way.
        #[arg(long)]
        verbose: bool,
    },
    /// Import open issues from an external tracker via glab/linear-cli, mirror a
    /// local GitHub Spec Kit project, or pull a beads workspace through `bd`
    Import {
        /// Target: gitlab | linear (remote trackers) | speckit (local mirror) |
        /// beads (a beads workspace, through `bd`)
        #[arg(long, value_name = "gitlab|linear|speckit|beads")]
        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,
    /// Prune the centralized backups and remove the scattered ones
    ///
    /// Backups live in `.tix-backups/` beside the issues directory (#1581);
    /// `--keep` (default 10) bounds how many are kept per issue. A legacy
    /// `*.tixbak` or `*.md.bak` from an older release, still beside an issue, is
    /// removed too — by default each such file is confirmed interactively.
    Clean {
        /// Remove every legacy scattered backup without prompting
        #[arg(short, long)]
        force: bool,
        /// Backups to keep per issue in `.tix-backups/`
        #[arg(long, default_value_t = 10)]
        keep: usize,
    },
    /// 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
    ///
    /// Every finding renders as a rustc-style diagnostic on stderr: the file and
    /// line, the offending value, and a `help:` line naming the fix. An **error**
    /// sets the exit code (a broken file); a **warning** does not (a valid file
    /// that is worth a look) — so a store with warnings still exits `0`.
    ///
    /// What is checked:
    ///
    /// - per issue: `status` against the board's columns; `priority`, `title`,
    ///   `type`, `created`/`updated`, `estimate`; the planning fields `cycles`,
    ///   `milestones`, `start_date`, `due_date`; a `## History` section that is
    ///   not first in the body (fenced code examples are skipped) or an entry the
    ///   grammar cannot read; and unrecognised top-level keys (a warning, since
    ///   the key is preserved on write);
    /// - the typed relationships: self-links, missing or conflicting targets,
    ///   cycles, an unknown kind, and the retired `links:` key;
    /// - the `parent:` hierarchy: `self_parent`, `unresolved_parent`,
    ///   `unknown_parent`, `cycle`;
    /// - `related_issues` entries: blank, or a local selector that resolves to
    ///   nothing (paths and URLs are accepted verbatim);
    /// - the configuration: board column/category mapping, `[layout]` drift, and
    ///   a `status:` that contradicts the issue's own recorded History.
    ///
    /// Graph identity findings (`ambiguous_target`, `duplicate_identity`,
    /// `missing_target`, `unresolved_parent`) are repaired by pointing the
    /// reference at one canonical issue id. Run `tix migrate issue-graph` to
    /// preview conversion of legacy numeric endpoints.
    ///
    /// Exit: `0` clean or warnings only, `1` any error, `2` usage or an internal
    /// failure.
    Lint {
        /// Do not lint the foreign repositories reachable from `related_issues`
        /// for this run (overrides `lint_foreign_repositories` in tix.toml).
        #[arg(long)]
        no_foreign: bool,
    },
    /// Inspect or migrate the configured on-disk issue layout (`[layout]`)
    Layout {
        #[command(subcommand)]
        action: LayoutAction,
    },
    /// Migrate local issue data to the canonical issue graph
    Migrate {
        #[command(subcommand)]
        action: MigrateAction,
    },
    /// Serve the MCP protocol (JSON-RPC 2.0 over stdio) for agent tools
    Mcp,
    /// Manage stable-ID issue/form templates
    ///
    /// Templates live in `[issue_templates.<id>]` in `tix.toml`, keyed by an
    /// immutable stable ID with a mutable display name and an explicit scope.
    /// `list`/`show` are read-only; `create`/`update`/`duplicate`/`delete`
    /// persist through one atomic save, and a refused operation writes nothing.
    Template {
        #[command(subcommand)]
        action: TemplateAction,
    },
}

/// Process entry: route a parsed [`Cli`] through config resolution, store
/// opening and dispatch, then return the exit code for `main` to exit with.
#[allow(clippy::too_many_lines)]
pub fn run(cli: Cli) -> u8 {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    match &cli.command {
        Some(Command::Lint { no_foreign }) => run_lint(&cwd, *no_foreign),
        Some(Command::Mcp) => match run_mcp(&cwd) {
            Ok(()) => ExitCode::Success as u8,
            Err(e) => {
                eprintln!("{}", crate::error::render_error(&e));
                exit_code_for(&e) as u8
            }
        },
        Some(Command::Render) => match run_render(&cwd) {
            Ok(()) => ExitCode::Success as u8,
            Err(e) => {
                eprintln!("{}", crate::error::render_error(&e));
                exit_code_for(&e) as u8
            }
        },
        // A batch move is the second command whose **status** is a result rather
        // than an error: it applies each item independently and exits non-zero
        // when any item was refused. Routed here, like `tix bulk`, where the exit
        // code is decided.
        Some(Command::Move {
            args,
            select,
            filter,
            search,
            dry_run,
            commit,
            reason,
            yes,
            r#override,
        }) => {
            let result = resolve(&cwd).and_then(|(config, store)| {
                commands::mv::run_batch(
                    &config,
                    &store,
                    args,
                    select.as_deref(),
                    filter.as_deref(),
                    search.as_deref(),
                    commit.as_deref(),
                    reason.as_deref(),
                    *yes,
                    *r#override,
                    *dry_run,
                )
            });
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&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!("{}", crate::error::render_error(&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!("{}", crate::error::render_error(&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)
        }
        // `tix project` needs a **mutable** `Config` — an accepted create/edit/delete
        // *is* `tix.toml` changing — which `commands::dispatch` (whose arms all borrow
        // `&Config`) cannot express, exactly as `tix wip` and `tix view <subcommand>`
        // do. Its batch verbs (`add`, `remove`, `bulk-add`) also carry a **status**
        // rather than an error: each selector is independent and a partly-successful
        // run exits non-zero. Both properties are why it is routed here, where the
        // config is owned and the exit code is decided.
        Some(Command::Project { command }) => {
            let result = resolve(&cwd).and_then(|(mut config, store)| {
                commands::project::run(&mut config, &store, command)
            });
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        // `tix epic` shares `tix project`'s two properties exactly: its lifecycle
        // verbs (`create`/`edit`/`delete`) mutate `tix.toml`, so it needs the
        // **mutable** `Config` only `run` owns, and its batch verbs
        // (`add`/`remove`/`bulk-add`) carry a **status** rather than an error,
        // because each selector is independent and a partly-successful run exits
        // non-zero. Both are why it is routed here.
        Some(Command::Epic { command }) => {
            let result = resolve(&cwd)
                .and_then(|(mut config, store)| commands::epic::run(&mut config, &store, command));
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        // `tix initiative` shares `tix project`'s property: its lifecycle verbs
        // (`create`/`edit`/`delete`) and its association verbs mutate `tix.toml`, so
        // it needs the **mutable** `Config` only `run` owns, and an accepted change
        // is written through the registry's atomic boundary. `tix roadmap` is
        // read-only and fits `commands::dispatch`, so it is routed there.
        Some(Command::Initiative { command }) => {
            let result = resolve(&cwd).and_then(|(mut config, store)| {
                commands::roadmap::run_initiative(&mut config, &store, command)
            });
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        // Only `tix cycle schedule …` needs the **mutable** config: an accepted
        // `schedule create|edit|delete` *is* `tix.toml` changing, and
        // `commands::dispatch` (whose arms all borrow `&Config`) cannot provide it.
        // The frozen legacy verbs are deliberately **not** intercepted: they fall
        // through to `run_subcommand`, so they keep `commands::dispatch`'s legacy
        // arm *and* the rollover advisory that every `tix cycle …` emitted at the
        // baseline — behavior WP06 must not change.
        Some(Command::Cycle {
            command: CycleCommand::Schedule { command },
        }) => {
            let result = resolve(&cwd).and_then(|(mut config, store)| {
                commands::cycle::run_schedule(&mut config, &store, command)
            });
            match result {
                Ok(()) => ExitCode::Success as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        // `tix capacity set|delete` mutate `tix.toml`, so they need the **mutable**
        // `Config` only the process entry owns — the same reason `tix wip` is routed
        // here. The read verbs (`list`/`show`/`calculate`/`snapshot`) ride along so
        // the family has one boundary, and none of them writes.
        Some(Command::Capacity { command }) => {
            let result = resolve(&cwd).and_then(|(mut config, store)| {
                commands::capacity::run(&mut config, &store, command)
            });
            match result {
                Ok(()) => ExitCode::Success as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        Some(Command::Export {
            target,
            dry_run,
            project,
            cycle,
            output,
            verbose,
        }) => {
            let result = resolve(&cwd).and_then(|(config, store)| {
                commands::export::run(
                    &config,
                    &store,
                    target,
                    *dry_run,
                    project.as_deref(),
                    cycle.as_deref(),
                    output.as_deref(),
                    *verbose,
                )
            });
            match result {
                Ok(code) => code as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        // `tix template`: management mutates `tix.toml`, so it needs a **mutable**
        // config and the path it came from — neither of which `commands::dispatch`
        // carries. Routed here, before the store is opened, exactly like the TUI
        // and `tix mcp`.
        Some(Command::Template { action }) => match commands::templates::run(&cwd, action) {
            Ok(()) => ExitCode::Success as u8,
            Err(e) => {
                eprintln!("{}", crate::error::render_error(&e));
                exit_code_for(&e) as u8
            }
        },
        // `tix version` needs neither a store nor a config, so it is answered
        // before any repository resolution: it works in a directory where every
        // other command would refuse to start, which is exactly where someone
        // checking "did this build?" may be standing.
        Some(Command::Version) => {
            commands::version::print();
            ExitCode::Success as u8
        }
        Some(Command::Beads { action }) => {
            let result = resolve(&cwd)
                .and_then(|(config, store)| commands::beads::run(&config, &store, action));
            match result {
                Ok(()) => ExitCode::Success as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&e));
                    exit_code_for(&e) as u8
                }
            }
        }
        _ => {
            let result = match &cli.command {
                None => run_tui(&cwd),
                Some(Command::New) => run_tui_new(&cwd),
                Some(Command::Init { beads }) => commands::init::run_with(&cwd, beads.as_deref()),
                Some(Command::InitAgents { yes }) => {
                    let root = Config::project_root(&cwd).unwrap_or(cwd.clone());
                    commands::agents::run(&root, *yes).map(|_| ())
                }
                Some(cmd) => run_subcommand(&cwd, cmd),
            };
            match result {
                Ok(()) => ExitCode::Success as u8,
                Err(e) => {
                    eprintln!("{}", crate::error::render_error(&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!("{}", crate::error::render_error(&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, no_foreign: bool) -> u8 {
    let (config, store) = match resolve(cwd) {
        Ok(pair) => pair,
        Err(e) => {
            eprintln!("{}", crate::error::render_error(&e));
            return 2;
        }
    };
    match commands::lint::run_with(&config, &store, !no_foreign) {
        Ok(true) => 1,
        Ok(false) => 0,
        Err(e) => {
            eprintln!("{}", crate::error::render_error(&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).
///
/// tix #1632: on a terminal, a missing `tix.toml` is offered a one-key escape —
/// create the default configuration and continue into the TUI — rather than
/// being turned away with a message naming a command to run. A declined prompt,
/// and a stdin that cannot be asked (not a terminal), both keep the exact
/// contract message.
fn run_tui(cwd: &Path) -> Result<()> {
    let config = tui_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 = tui_config(cwd)?;
    crate::app::run_new_issue(&config)
}

/// Repository resolution for the TUI commands, offering to scaffold a repository
/// first when none is reachable (tix #1632).
fn tui_config(cwd: &Path) -> Result<Config> {
    if !offer_first_run_init(cwd)? {
        return Err(TixError::Config(
            "no tix.toml found — run \"tix init\" first".into(),
        ));
    }
    repo_config(cwd)
}

/// Ask, once, whether a missing `tix.toml` should be created with the defaults.
///
/// Returns `true` when the caller may proceed (a repository was already there, or
/// the user said yes to `tix init` default values). Returns `false` when there is
/// no repository and the user declined — or could not be asked at all, since a
/// non-terminal stdin cannot consent, and silently writing a project into a pipe's
/// directory would be the wrong answer.
fn offer_first_run_init(cwd: &Path) -> Result<bool> {
    use std::io::IsTerminal;

    if Config::project_root(cwd).is_some() {
        return Ok(true);
    }
    if !std::io::stdin().is_terminal() {
        return Ok(false);
    }
    eprint!("tix: no tix.toml found — create one with default settings? [Y/n] ");
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .map_err(TixError::Io)?;
    let answer = line.trim();
    if answer.is_empty() || answer.eq_ignore_ascii_case("y") || answer.eq_ignore_ascii_case("yes") {
        commands::init::run_with(cwd, Some("off"))?;
        return Ok(true);
    }
    eprintln!("tix: aborted — run \"tix init\" when you are ready");
    Ok(false)
}

/// 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()))?;
    let mut config = Config::load(&root)?;
    // `tags_dir`, `[repos]` and `parent_repo` are relative to the project root
    // (tix #1529/#1530), so the TUI can spawn tix in a child from anywhere.
    config.resolve_repo_paths(&root);
    Ok(config)
}

/// `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));
    }
    // `tags_dir`, `[repos]` and `parent_repo` resolve against the same base.
    config.resolve_repo_paths(root.as_deref().unwrap_or(cwd));
    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 (mut config, store) = resolve(cwd)?;
    // `tix view <subcommand>` is the one command tree that needs the config
    // **mutably**: an accepted view mutation *is* `config.views` changing, and
    // `commands::dispatch` (whose every arm borrows `&Config`) cannot express
    // that. Routed here, at the process boundary where the config is owned, for
    // the same reason `tix bulk` and `tix triage` are routed in `run`.
    if let Command::View {
        action: Some(action),
        ..
    } = cmd
    {
        return commands::views::run(&mut config, &store, action);
    }
    // `tix wip set/unset/unit` mutate `tix.toml`, so they are routed here for the
    // same reason the view mutations are: `commands::dispatch`'s arms borrow
    // `&Config`, and an accepted WIP edit *is* the configuration changing.
    if let Command::Wip { action } = cmd {
        return commands::wip::run(&mut config, &store, action);
    }
    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)
}