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
//! Thin dispatch: route a parsed CLI [`Command`] to its per-command handler
//! module. Also owns the shared `<issue>` selector resolution and priority
//! validation that several commands reuse.
//!
//! Selector precedence follows `contracts/cli.md` §Selection grammar: a bare
//! number wins, then a unique filename fragment, then a title fragment that
//! matches exactly one issue. Non-unique matches are a hard error listing
//! the candidates (exit 2 like target-not-found, per the exit-code table).

use std::collections::HashSet;
use std::path::Path;

use crate::cli::Command;
use crate::config::Config;
use crate::error::{Result, TixError};
use crate::model::Priority;
use crate::storage::{IssueSelector, Store};

pub mod agents;
pub mod analytics;
pub mod archive;
pub mod beads;
pub mod bulk;
pub mod capacity;
pub mod clean;
pub mod create;
pub mod cycle;
pub mod delete;
pub mod edit;
pub mod epic;
pub mod export;
pub mod health;
pub mod import;
pub mod init;
pub mod layout;
pub mod link;
pub mod lint;
pub mod list;
pub mod mentions;
pub mod migrate;
pub mod milestone;
pub mod mv;
pub mod parent;
pub mod project;
pub mod recurring;
pub mod render;
pub mod roadmap;
pub mod rollover;
pub mod search;
pub mod status;
pub mod templates;
pub mod time;
pub mod triage;
pub mod version;
pub mod view;
pub mod views;
pub mod wip;
pub mod workflow;

/// Message prefix shared with `cli::exit_code_for` so selection ambiguity is
/// routed to the `2` exit bucket alongside target-not-found.
pub const AMBIGUITY_PREFIX: &str = "ambiguous selector";

/// Insert or replace a marker-delimited managed block in `existing`.
///
/// Shared by `tix init-agents` (`AGENTS.md`, `<!-- tix:start -->` /
/// `<!-- tix:end -->`) and `tix init` (`.gitignore`, `# tix:start` / `# tix:end`)
/// so the two never drift into two block formats:
///
/// - both markers found → replace everything between them, inclusive;
/// - an already byte-identical block (ignoring surrounding whitespace) → return
///   `existing` unchanged, so re-runs are fully idempotent;
/// - only one marker → treat the file as unrelated and append a fresh block;
/// - no markers → append a fresh block.
pub fn upsert_block(existing: &str, block: &str, start_marker: &str, end_marker: &str) -> String {
    let has_start = existing.contains(start_marker);
    let has_end = existing.contains(end_marker);

    match (has_start, has_end) {
        (true, true) => {
            let start = existing.find(start_marker).unwrap();
            let end = existing.find(end_marker).unwrap() + end_marker.len();
            if existing[start..end].trim() == block.trim() {
                return existing.to_string();
            }
            format!("{}{}{}", &existing[..start], block, &existing[end..])
        }
        (true, false) | (false, true) => {
            format!("{}\n{}\n", existing.trim_end(), block)
        }
        (false, false) => {
            let trimmed = existing.trim_end();
            if trimmed.is_empty() {
                format!("{block}\n")
            } else {
                format!("{trimmed}\n\n{block}\n")
            }
        }
    }
}

/// Atomic file write: write `content` to a sibling temp file, then rename it
/// over `path`, so a crash mid-write cannot leave a truncated file.
pub fn atomic_write(path: &Path, content: &str) -> Result<()> {
    let parent = path.parent().unwrap_or_else(|| Path::new("."));
    let file_name = path.file_name().map_or_else(
        || ".tix-tmp".to_string(),
        |name| format!(".{}.tix-tmp", name.to_string_lossy()),
    );
    let tmp = parent.join(file_name);
    std::fs::write(&tmp, content)?;
    std::fs::rename(&tmp, path)?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Shared project refusals (WP09 item E)
// ---------------------------------------------------------------------------
//
// Three user-facing refusals are spelled in both the CLI and MCP. Each predicate
// and its message live here, in one place, and both sides call them, so a
// rewording cannot leave one surface saying something the other does not. This is
// the same discipline `projects::ProjectError` follows for the service refusals;
// these three are *command-level* rules the service never sees.

/// The refusal `tix project edit` prints when no field flag was given.
///
/// `--projects` is not one of the edit flags — it belongs to `tix edit` — so a
/// caller with no field change has asked for nothing and is told which flags
/// exist rather than silently rewriting the record.
pub fn project_edit_requires_a_field() -> TixError {
    TixError::InvalidInput(
        "no fields to change; pass at least one of --name, --description, --status, \
         --lead, --start-date or --due-date"
            .to_string(),
    )
}

/// Whether a `--projects` value on `tix edit` is the **clear-everything**
/// spelling (blank after trimming), per the empty-string-clears convention.
pub fn edit_projects_clears(value: &str) -> bool {
    value.trim().is_empty()
}

/// The refusal for a non-blank `--projects` on `tix edit`.
///
/// Setting associations has exactly one spelling (`--add-project` /
/// `--remove-project`); a non-blank list here is refused rather than guessed at,
/// so a typo cannot silently replace an association set.
pub fn edit_projects_must_be_clear(value: &str) -> TixError {
    TixError::InvalidInput(format!(
        "--projects on `tix edit` only clears associations (`--projects \"\"`); use \
         --add-project / --remove-project to change them, not `--projects {value}`"
    ))
}

/// The refusal for `--projects` beside `--template`.
///
/// Returns `Some` only for a non-blank value; an omitted or blank `--projects`
/// narrows nothing and is allowed. Refused rather than dropped: silently ignoring
/// it would create an issue the caller believes is associated, and the template
/// surface (source issue #174) owns wiring the field through its own crate.
pub fn projects_beside_template_refused(projects: Option<&str>) -> Option<TixError> {
    projects.filter(|value| !value.trim().is_empty()).map(|_| {
        TixError::InvalidInput(
            "--projects cannot be combined with --template yet; create without \
                 the template and add the association with `tix project add`"
                .to_string(),
        )
    })
}

/// Whether an `--epics` value on `tix edit` is the **clear-everything** spelling
/// (blank after trimming), per the empty-string-clears convention.
pub fn edit_epics_clears(value: &str) -> bool {
    value.trim().is_empty()
}

/// The refusal for a non-blank `--epics` on `tix edit`.
///
/// Setting references has exactly one spelling (`--add-epic` / `--remove-epic`);
/// a non-blank list here is refused rather than guessed at, so a typo cannot
/// silently replace a reference set.
pub fn edit_epics_must_be_clear(value: &str) -> TixError {
    TixError::InvalidInput(format!(
        "--epics on `tix edit` only clears references (`--epics \"\"`); use \
         --add-epic / --remove-epic to change them, not `--epics {value}`"
    ))
}

/// The refusal for `--epics` beside `--template`.
///
/// Mirrors [`projects_beside_template_refused`] and is refused rather than dropped
/// for the same reason: silently ignoring it would create an issue the caller
/// believes references the epic, and the template surface (source issue #174) owns
/// wiring the field through its own crate.
pub fn epics_beside_template_refused(epics: Option<&str>) -> Option<TixError> {
    epics.filter(|value| !value.trim().is_empty()).map(|_| {
        TixError::InvalidInput(
            "--epics cannot be combined with --template yet; create without \
                 the template and add the reference with `tix epic add`"
                .to_string(),
        )
    })
}

/// One argument per `tix.toml`-backed field; the flag count mirrors the
/// frozen command surface in `contracts/cli.md`.
#[allow(clippy::too_many_arguments)]
/// The data-level action for one `tix mentions` verb.
///
/// A projection, not a second definition: the enum in `cli.rs` is the flag grammar
/// and this module owns the behavior, so the two cannot drift into a verb that parses
/// and does nothing.
fn mentions_action(action: &crate::cli::MentionsAction) -> mentions::Action<'_> {
    use crate::cli::MentionsAction as Cli;
    match action {
        Cli::List => mentions::Action::List,
        Cli::Show { id } => mentions::Action::Show(id),
        Cli::Read { id } => mentions::Action::Read(id),
        Cli::Ignore { id } => mentions::Action::Ignore(id),
        Cli::Jump { id } => mentions::Action::Jump(id),
    }
}

#[allow(clippy::too_many_lines)]
pub fn dispatch(cmd: &Command, config: &Config, store: &Store) -> Result<()> {
    match cmd {
        Command::Init { beads: _ } => unreachable!("init is handled before dispatch"),
        Command::InitAgents { yes: _ } => unreachable!("init-agents is handled before dispatch"),
        Command::Triage { .. } => unreachable!("triage is handled before dispatch"),
        Command::Version => unreachable!("version is handled before dispatch"),
        // `tix beads` reaches the `bd` CLI, writes its own state file and refuses
        // writes under `mirror`, so it is routed in `cli::run` where the exit code
        // is decided — the same boundary `triage` and `bulk` use.
        Command::Beads { .. } => unreachable!("beads is handled before dispatch"),
        // `tix mentions` reads and writes only the mention store, so it fits
        // `dispatch`'s `&Config` borrow. Its verbs carry no batch status: one mention
        // is one record, and an unknown id is a plain `not found`.
        Command::Mentions { action } => mentions::run(store, &mentions_action(action)),
        // `tix analytics` is read-only over the shared series/projection DTOs and the
        // chart document WP04 owns, so it fits `dispatch`'s `&Config` borrow. Its
        // `burndown`/`projection` verbs print and write nothing at all; its `export`
        // verb writes only the caller's own `--output` path, and never an issue, a
        // cycle, a milestone or a snapshot.
        Command::Analytics { command } => analytics::run(config, store, command),
        Command::Health { action } => health::run(config, store, action),
        // `tix roadmap` is read-only, so it fits `dispatch`'s `&Config` borrow and is
        // routed here. `tix initiative` mutates `tix.toml` and so is routed by
        // `cli::run`, where the mutable config is owned — the arm is here anyway so
        // the match stays exhaustive and a caller reaching `dispatch` with one is
        // told why rather than being quietly dropped.
        Command::Roadmap { command } => roadmap::run_roadmap(config, store, command).map(|_| ()),
        Command::Initiative { .. } => unreachable!("initiative is handled before dispatch"),
        Command::Mcp => unreachable!("mcp is handled before dispatch"),
        Command::New => unreachable!("new is handled before dispatch"),
        Command::Create {
            title,
            body,
            status,
            priority,
            assignee,
            labels,
            files,
            estimate,
            cycles,
            milestones,
            projects,
            epics,
            reviewer,
            start_date,
            due_date,
            parent,
            related_issues,
            r#type,
            template,
            scope,
        } => {
            // One branch, and the no-template branch is the untouched
            // `create::run` call: `tix create` without `--template` behaves
            // exactly as before (byte-identical output and files). `--scope`
            // cannot reach the else branch with a value — clap requires
            // `--template` when `--scope` is present.
            if let Some(template_id) = template {
                // `--projects` is deliberately refused beside `--template` rather
                // than dropped: silently ignoring it would create an issue the user
                // believes is associated, and the template surface (source issue
                // #174) owns wiring the field through its own crate. The predicate
                // and wording live in one shared helper so MCP cannot diverge.
                if let Some(error) = projects_beside_template_refused(projects.as_deref()) {
                    return Err(error);
                }
                if let Some(error) = epics_beside_template_refused(epics.as_deref()) {
                    return Err(error);
                }
                templates::create_from_template(
                    config,
                    store,
                    template_id,
                    scope.as_deref(),
                    &templates::CreateFields {
                        title: title.as_deref(),
                        body: body.as_deref(),
                        status: status.as_deref(),
                        priority: priority.as_deref(),
                        assignee: assignee.as_deref(),
                        labels: labels.as_deref(),
                        files: files.as_deref(),
                        estimate: estimate.as_deref(),
                        cycles: cycles.as_deref(),
                        milestones: milestones.as_deref(),
                        reviewer: reviewer.as_deref(),
                        start_date: start_date.as_deref(),
                        due_date: due_date.as_deref(),
                        parent: parent.as_deref(),
                        related_issues: related_issues.as_deref(),
                        type_: r#type.as_deref(),
                    },
                )
            } else {
                create::run(
                    config,
                    store,
                    title.as_deref(),
                    body.as_deref(),
                    status.as_deref(),
                    priority.as_deref(),
                    assignee.as_deref(),
                    labels.as_deref(),
                    files.as_deref(),
                    estimate.as_deref(),
                    cycles.as_deref(),
                    milestones.as_deref(),
                    projects.as_deref(),
                    epics.as_deref(),
                    reviewer.as_deref(),
                    start_date.as_deref(),
                    due_date.as_deref(),
                    parent.as_deref(),
                    related_issues.as_deref(),
                    r#type.as_deref(),
                )
            }
        }
        Command::Parent { action } => parent::run(store, action),
        Command::Link {
            action,
            from,
            to,
            r#type,
        } => link::run(
            store,
            action.as_ref(),
            from.as_deref(),
            to.as_deref(),
            r#type.as_deref(),
        ),
        Command::Unlink { from, to, r#type } => {
            link::unlink_cli(store, from, to, r#type.as_deref())
        }
        Command::Chain { issue } => link::chain(store, issue),
        // Routed by `cli::run`, not here: a bulk batch's exit code is a **result**,
        // and every other arm of this match is `Result<()>`. The arm is here so the
        // match stays exhaustive and so a caller that reaches `dispatch` with a bulk
        // command is told why rather than being quietly dropped.
        Command::Bulk { .. } => Err(TixError::InvalidInput(
            "`tix bulk` is routed by the process entry, not by dispatch — a partial \
             batch reports a non-zero status rather than an error"
                .to_string(),
        )),
        Command::Edit {
            issue,
            title,
            body,
            status,
            priority,
            assignee,
            labels,
            files,
            estimate,
            cycles,
            milestones,
            add_project,
            remove_project,
            projects,
            add_epic,
            remove_epic,
            epics,
            reviewer,
            parent,
            start_date,
            due_date,
            commit,
            reason,
            related_issues,
            r#type,
        } => edit::run(
            config,
            store,
            issue,
            title.as_deref(),
            body.as_deref(),
            status.as_deref(),
            priority.as_deref(),
            assignee.as_deref(),
            labels.as_deref(),
            files.as_deref(),
            estimate.as_deref(),
            cycles.as_deref(),
            milestones.as_deref(),
            add_project,
            remove_project,
            projects.as_deref(),
            add_epic,
            remove_epic,
            epics.as_deref(),
            reviewer.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
            commit.as_deref(),
            parent.as_deref(),
            // `--reason` is not an editable field — it only qualifies a
            // `--status` transition — so it is kept out of the editable-field
            // ordering and `edit::run`'s "was any field supplied" check.
            reason.as_deref(),
            related_issues.as_deref(),
            r#type.as_deref(),
        ),
        Command::Move {
            args,
            select,
            filter,
            search,
            dry_run,
            commit,
            reason,
            yes,
            r#override,
        } => 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,
        )
        // The binary routes `tix move` through `cli::run` so a partial batch's
        // exit status survives; dispatch cannot carry that status. Reaching this
        // arm means an in-process caller asked for the move and only wants
        // whether it ran at all, so the status is dropped here.
        .map(|_| ()),
        // `tix wip` mutates `tix.toml`, so it is routed by `cli::run_subcommand`,
        // which owns the mutable `Config` this dispatch cannot borrow. The arm is
        // here so the match stays exhaustive and a caller that reaches `dispatch`
        // with it is told why.
        // `tix project` mutates `tix.toml` (create/edit/delete) and carries a
        // partial-batch **status** for `add`/`remove`/`bulk-add`, so it is routed by
        // `cli::run`, which owns the mutable config and decides the exit code. The
        // arm is here so the match stays exhaustive and a caller that reaches
        // `dispatch` with it is told why.
        Command::Project { .. } => Err(TixError::InvalidInput(
            "`tix project` is routed by the process entry, not by dispatch".to_string(),
        )),
        // `tix epic` shares `tix project`'s routing reason: its lifecycle verbs
        // mutate `tix.toml` and its batch verbs carry a partial-batch status, so
        // `cli::run` owns both the mutable config and the exit code.
        Command::Epic { .. } => Err(TixError::InvalidInput(
            "`tix epic` is routed by the process entry, not by dispatch".to_string(),
        )),
        Command::Wip { .. } => Err(TixError::InvalidInput(
            "`tix wip` is routed by the process entry, not by dispatch".to_string(),
        )),
        Command::View {
            action,
            issue,
            show,
        } => match (action, issue) {
            // `tix view <subcommand>` is routed by `cli::run_subcommand`, which
            // owns the mutable `Config` a view mutation needs. The arm is here so
            // the match stays exhaustive and a caller that reaches `dispatch` with
            // a saved-view subcommand is told why rather than being quietly
            // treated as an issue selector.
            (Some(_), _) => Err(TixError::InvalidInput(
                "`tix view <subcommand>` is routed by the process entry, not by dispatch"
                    .to_string(),
            )),
            (None, Some(issue)) => view::run(store, issue, show.as_deref()),
            (None, None) => Err(TixError::InvalidInput(
                "`tix view` needs an issue selector or a subcommand; run `tix view --help`"
                    .to_string(),
            )),
        },
        Command::List {
            status,
            filter,
            project,
            epic,
            sort,
            group,
            columns,
            show,
            with_archived,
            all,
            format,
        } => list::run(
            store,
            status.as_deref(),
            filter.as_deref(),
            project.as_deref(),
            epic.as_deref(),
            sort.as_deref(),
            group.as_deref(),
            columns.as_deref(),
            show.as_deref(),
            *with_archived,
            *all,
            format.as_deref(),
            None,
        ),
        Command::Ready {
            columns,
            limit,
            project,
            epic,
            format,
        } => list::ready(
            store,
            columns.as_deref(),
            *limit,
            project.as_deref(),
            epic.as_deref(),
            format.as_deref(),
        ),
        Command::Workflow { action } => match action {
            crate::cli::WorkflowAction::Categories => workflow::categories(config),
            crate::cli::WorkflowAction::Show { board } => workflow::show(config, board.as_deref()),
            crate::cli::WorkflowAction::Transitions => workflow::transitions(config),
        },
        Command::Status {
            filter,
            sort,
            group,
            health,
            json,
        } => status::run(
            config,
            store,
            filter.as_deref(),
            sort.as_deref(),
            group.as_deref(),
            *health,
            *json,
        ),
        // `tix time` reads and writes the issue store only, so it fits this dispatch: a
        // mutation goes through the shared service, and none of the verbs needs the
        // mutable config the process entry owns or a partial-batch status.
        Command::Time { command } => time::run(store, command),
        Command::Delete { issue, yes } => delete::run(store, issue, *yes),
        // The recurrence surface: a thin adapter over `recurrence::{series,detect,
        // generate,lifecycle}`. `create` needs `&Config` (it goes through the shared
        // create core), which `dispatch` already borrows immutably.
        Command::Recurring { action } => recurring::run(config, store, action),
        // Routed by `cli::run`, not here: an archive/restore batch reports one
        // outcome per item and exits non-zero if any failed, which is a
        // *status* rather than a `Result<()>` (`contracts/cli-surface.md`, the
        // same shape `tix bulk` and `tix triage` use). The arms keep the match
        // exhaustive and tell a caller that reaches `dispatch` why.
        Command::Archive { .. } | Command::Restore { .. } => Err(TixError::InvalidInput(
            "`tix archive`/`tix restore` are routed by the process entry, not by dispatch — \
             a partial batch reports a non-zero status rather than an error"
                .to_string(),
        )),
        // Routed by `cli::run`, not here: management mutates `tix.toml` and so
        // needs a mutable config and the path it was read from, which
        // `dispatch`'s `&Config` cannot provide. The arm keeps the match
        // exhaustive and explains why rather than dropping the command.
        Command::Template { .. } => Err(TixError::InvalidInput(
            "`tix template` is routed by the process entry, not by dispatch — management \
             writes `tix.toml` through a mutable config"
                .to_string(),
        )),
        // The frozen legacy `tix cycle create|list|edit|delete` verbs route here,
        // exactly as before. Only the new `schedule` namespace mutates `tix.toml`
        // and is routed by `cli::run`; a schedule command can never reach this arm.
        Command::Cycle { command } => cycle::run_legacy(config, store, command),
        // Routed by `cli::run`, not here: `set`/`delete` mutate `tix.toml` and need the
        // mutable config only the process entry owns. The arm is here so the match
        // stays exhaustive and a caller that reaches `dispatch` with one is told why
        // rather than being quietly dropped.
        Command::Capacity { .. } => unreachable!("capacity is handled before dispatch"),
        Command::Milestone { command } => milestone::run(config, store, command),
        Command::Export {
            target,
            dry_run,
            project,
            cycle,
            output,
            verbose,
        } => export::run(
            config,
            store,
            target,
            *dry_run,
            project.as_deref(),
            cycle.as_deref(),
            output.as_deref(),
            *verbose,
        )
        .map(|_| ()),
        Command::Import {
            target,
            triage_policy,
        } => {
            // Target first, then the policy — the order WP07 froze (T036): a bad
            // `--target` must still report what an older `tix` reported and never
            // a triage diagnostic. `Tool::from_target` is the exact call
            // `run_core_with_policy` makes a line later, so this cannot accept a
            // target that one would reject; it only fixes which of two bad flags
            // is named first. `speckit` and `beads` are **local** readers rather
            // than remote `Tool`s — they shell out to no tracker API and hold no
            // token — so both are exempt here and validate themselves.
            if target != "speckit" && target != "beads" {
                crate::sync::Tool::from_target(target)?;
            }
            let policy = triage_policy
                .as_deref()
                .map(crate::triage::import_policy::ImportPolicy::parse)
                .transpose()?
                .unwrap_or_default();
            import::run_with_policy(config, store, target, policy)
        }
        Command::Rollover { cycle, yes } => rollover::run(config, store, cycle.as_deref(), *yes),
        Command::Search {
            string,
            with_archived,
        } => search::run(store, string, *with_archived),
        Command::Render => render::run(config, store),
        Command::Clean { force, keep } => clean::run(store, *force, *keep),
        Command::Lint { no_foreign } => lint::run_with(config, store, !no_foreign).map(|_| ()),
        Command::Layout { action } => layout::run(config, store, action),
        Command::Migrate { action } => migrate::run(store, action),
    }
}

/// The one sentence every surface uses to say an issue is blocked (FR-003,
/// FR-004).
///
/// `contracts/cli.md` and `contracts/surface-parity.md` §2 require the CLI
/// warning, the TUI warning, `tix list --show relationships`, and the detail view
/// to carry the **same** text, and the service's [`BlockedState::reason`] is the
/// only string that is allowed to produce it. Each surface composing its own
/// phrasing is how four surfaces come to say four different things about one
/// graph.
///
/// Returns `None` when the issue is not blocked, so a caller cannot accidentally
/// print an empty "blocked: " prefix.
pub fn blocked_note(state: &crate::relationships::BlockedState) -> Option<String> {
    if !state.is_blocked {
        return None;
    }
    Some(format!("blocked: {}", state.reason))
}

/// The issue set plus the board's configured completion column, with a
/// [`RelationshipGraph`] over the pair.
///
/// One place for every surface to obtain a graph (C-003, parity §3). A surface
/// that reached past the service to re-derive direction handling, cycle
/// detection, or blocked state would be the defect this contract exists to
/// prevent, and giving each surface its own graph construction is how that starts
/// to happen.
pub fn graph_over<'a>(
    issues: &'a [crate::model::Issue],
    done_column: &str,
) -> crate::relationships::RelationshipGraph<'a> {
    use crate::model::Issue;
    use crate::relationships::IssueView;
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    crate::relationships::RelationshipGraph::new(&views, done_column)
}

/// Resolve an `<issue>` selector string per `contracts/cli.md` §Selection
/// grammar (number → unique filename fragment → unique title fragment).
pub fn parse_selector(store: &Store, raw: &str) -> Result<IssueSelector> {
    if let Ok(number) = raw
        .trim()
        .strip_prefix('#')
        .unwrap_or(raw.trim())
        .parse::<u32>()
    {
        let matched: Vec<crate::model::Issue> = store
            .list_all()?
            .into_iter()
            .filter(|issue| issue.number == number)
            .collect();
        return match matched.as_slice() {
            [_] => Ok(IssueSelector::Number(number)),
            [] => Err(TixError::NotFound(format!("issue #{number}"))),
            many => Err(TixError::InvalidInput(format!(
                "{AMBIGUITY_PREFIX} #{number}: {}",
                many.iter()
                    .map(|issue| crate::id::canonical_ref(issue).to_string())
                    .collect::<Vec<_>>()
                    .join(", ")
            ))),
        };
    }
    // An 8-character Crockford base32 id is the canonical identity. It is never
    // all digits (see [`crate::id`]), so this can only be reached after the
    // numeric fast path above has declined, and it is resolved *before* the
    // filename/title fragment scan so a selector that is exactly an id resolves
    // that issue rather than merely matching its (id-prefixed) filename.
    if crate::id::is_issue_id(raw) {
        let issues = store.list_all()?;
        let matched: Vec<&crate::model::Issue> = issues
            .iter()
            .filter(|i| {
                i.id.as_deref()
                    .is_some_and(|id| id.eq_ignore_ascii_case(raw))
            })
            .collect();
        return match matched.as_slice() {
            [one] => Ok(IssueSelector::Filename(one.filename.clone())),
            [] => Err(TixError::NotFound(format!("issue with id '{raw}'"))),
            _ => Err(TixError::InvalidInput(format!(
                "{AMBIGUITY_PREFIX} id '{raw}': {}",
                matched
                    .iter()
                    .map(|i| format!("#{} ({})", i.number, i.filename))
                    .collect::<Vec<_>>()
                    .join(", ")
            ))),
        };
    }
    // `list_all`: a selector must resolve an archived issue too (issue #1492).
    // Hiding archived issues here would make `tix show <fragment>` and
    // `tix archive <fragment>` fail on an issue the user can name.
    let issues = store.list_all()?;
    let by_filename: Vec<&String> = issues
        .iter()
        .filter(|i| i.filename.contains(raw))
        .map(|i| &i.filename)
        .collect();
    if by_filename.len() == 1 {
        return Ok(IssueSelector::Filename(by_filename[0].clone()));
    }
    let by_title: Vec<&crate::model::Issue> =
        issues.iter().filter(|i| i.title.contains(raw)).collect();
    if by_title.len() == 1 {
        return Ok(IssueSelector::Filename(by_title[0].filename.clone()));
    }
    if by_filename.len() > 1 || by_title.len() > 1 {
        let mut seen: HashSet<u32> = HashSet::new();
        let candidates: Vec<String> = issues
            .iter()
            .filter(|i| i.filename.contains(raw) || i.title.contains(raw))
            .filter(|i| seen.insert(i.number))
            .map(|i| format!("#{} ({})", i.number, i.filename))
            .collect();
        return Err(TixError::InvalidInput(format!(
            "{AMBIGUITY_PREFIX} '{raw}': {}",
            candidates.join(", ")
        )));
    }
    Err(TixError::NotFound(format!(
        "issue matching '{raw}' by number, filename or title"
    )))
}

/// Strict priority validation for user input: only `low`/`medium`/`high`
/// are accepted (`contracts/cli.md` enumerates exactly these three).
pub fn parse_priority(raw: &str) -> Result<Priority> {
    match raw.to_ascii_lowercase().as_str() {
        "low" => Ok(Priority::Low),
        "medium" => Ok(Priority::Medium),
        "high" => Ok(Priority::High),
        // An explicitly unset priority. Without this, the state `tix lint` accepts
        // could only be reached by hand-editing a file, which would make the
        // lint exemption a read-only fiction. Omitting `--priority` entirely is a
        // different thing and still yields the default `medium`, because the CLI
        // argument is `Option<String>` and `None` never reaches here.
        "" => Ok(Priority::Other(String::new())),
        _ => Err(TixError::InvalidInput(format!(
            "invalid priority '{raw}' — use '' (unset), low, medium or high"
        ))),
    }
}

/// Split a comma-separated list, trimming whitespace and dropping empty
/// entries (shared by `labels`, `links` and `files` parsing; D3).
pub fn parse_csv_list(raw: &str) -> Vec<String> {
    raw.split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

/// Resolve a `--commit auto` request for `issue`: the commit that last
/// touched its file, falling back to `HEAD` (see [`crate::git`]). This lets a
/// closure hash be back-filled after the closing commit has landed. Errors
/// when neither is available (not a git repository, or the file has never
/// been committed).
pub fn resolve_auto_commit(store: &Store, issue: &crate::model::Issue) -> Result<String> {
    let cwd = std::env::current_dir().unwrap_or_default();
    let path = store.issues_dir.join(&issue.filename);
    crate::git::resolve_closing_commit(&cwd, &path).ok_or_else(|| {
        TixError::InvalidInput(
            "could not resolve a commit hash for `auto` — not a git repository or the issue file is uncommitted"
                .to_string(),
        )
    })
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn make_store() -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    fn write_issue(store: &Store, name: &str, number: u32, title: &str) {
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nbody"
        );
        fs::write(store.issues_dir.join(name), contents).unwrap();
    }

    /// Like [`write_issue`], with an `id:` line (the new schema).
    fn write_issue_with_id(store: &Store, name: &str, number: u32, title: &str, id: &str) {
        let contents = format!(
            "---\nnumber: {number}\nid: {id}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n---\n\nbody"
        );
        fs::write(store.issues_dir.join(name), contents).unwrap();
    }

    #[test]
    fn parse_priority_accepts_an_unset_value_and_still_rejects_typos() {
        // Without the empty case, the state `tix lint` accepts could only be
        // reached by hand-editing a file — the exemption would be read-only.
        let undefined = parse_priority("").unwrap();
        assert!(undefined.is_undefined());
        assert_eq!(undefined.to_string(), "");

        // Omitting `--priority` never reaches here at all (the CLI argument is
        // `Option<String>` and `create` uses `unwrap_or_default()`), so accepting
        // `''` here does not make "unset" the default.
        assert_eq!(parse_priority("medium").unwrap(), Priority::default());

        for typo in ["hih", "urgent", "0", "lowest"] {
            assert!(
                parse_priority(typo).is_err(),
                "{typo:?} must still be rejected"
            );
        }
    }

    #[test]
    fn selector_bare_number_wins() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue(&store, "2026-01-02-ticket-55.md", 55, "Ticket 55");
        assert_eq!(
            parse_selector(&store, "55").unwrap(),
            IssueSelector::Number(55)
        );
    }

    #[test]
    fn selector_unique_filename_fragment() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue(&store, "2026-05-10-add-docs.md", 1, "Add documentation");
        assert_eq!(
            parse_selector(&store, "add-doc").unwrap(),
            IssueSelector::Filename("2026-05-10-add-docs.md".into())
        );
    }

    #[test]
    fn selector_unique_title_fragment() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue(&store, "2026-01-01-fix-login.md", 1, "Fix login bug");
        assert_eq!(
            parse_selector(&store, "login").unwrap(),
            IssueSelector::Filename("2026-01-01-fix-login.md".into())
        );
    }

    #[test]
    fn selector_unique_filename_fragment_matches_grouped_relative_path() {
        let (tmp, store) = make_store();
        let _ = tmp;
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        write_issue(
            &store,
            "alice/2026-05-10-add-docs.md",
            1,
            "Add documentation",
        );
        assert_eq!(
            parse_selector(&store, "add-doc").unwrap(),
            IssueSelector::Filename("alice/2026-05-10-add-docs.md".into())
        );
    }

    #[test]
    fn selector_full_grouped_relative_path_resolves() {
        let (tmp, store) = make_store();
        let _ = tmp;
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        write_issue(
            &store,
            "alice/2026-05-10-add-docs.md",
            1,
            "Add documentation",
        );
        assert_eq!(
            parse_selector(&store, "alice/2026-05-10-add-docs.md").unwrap(),
            IssueSelector::Filename("alice/2026-05-10-add-docs.md".into())
        );
    }

    #[test]
    fn selector_ambiguous_lists_candidates() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue(&store, "2026-01-01-a.md", 1, "Fix bug A");
        write_issue(&store, "2026-01-02-b.md", 2, "Fix bug B");
        let err = parse_selector(&store, "bug").unwrap_err();
        assert!(
            matches!(&err, TixError::InvalidInput(m) if m.starts_with(AMBIGUITY_PREFIX)),
            "got {err:?}"
        );
        assert!(err.to_string().contains("#1"));
        assert!(err.to_string().contains("#2"));
    }

    #[test]
    fn selector_missing_is_not_found() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue(&store, "2026-01-01-a.md", 1, "Fix bug A");
        assert!(matches!(
            parse_selector(&store, "zzz-nonexistent").unwrap_err(),
            TixError::NotFound(_)
        ));
    }

    #[test]
    fn selector_resolves_an_issue_id_case_insensitively() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue_with_id(
            &store,
            "2026-01-01-A1B2C3D4-fix-login.md",
            1,
            "Fix login",
            "A1B2C3D4",
        );
        for raw in ["A1B2C3D4", "a1b2c3d4", "a1B2c3D4"] {
            assert_eq!(
                parse_selector(&store, raw).unwrap(),
                IssueSelector::Filename("2026-01-01-A1B2C3D4-fix-login.md".into()),
                "{raw} must resolve the id"
            );
        }
    }

    #[test]
    fn selector_unknown_wellformed_id_is_not_found() {
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue_with_id(
            &store,
            "2026-01-01-A1B2C3D4-fix-login.md",
            1,
            "Fix login",
            "A1B2C3D4",
        );
        // A well-formed id that matches nothing is a not-found, not a fragment scan.
        assert!(matches!(
            parse_selector(&store, "ZZZZZZZZ").unwrap_err(),
            TixError::NotFound(_)
        ));
    }

    #[test]
    fn an_all_digits_selector_stays_a_number_not_an_id() {
        // Ids are never all digits (see `crate::id`), so an 8-digit selector must
        // keep meaning the number, and must not scan for an id.
        let (tmp, store) = make_store();
        let _ = tmp;
        write_issue(&store, "2026-01-01-a.md", 12_345_678, "Big number");
        assert_eq!(
            parse_selector(&store, "12345678").unwrap(),
            IssueSelector::Number(12_345_678)
        );
    }

    #[test]
    fn priority_accepts_the_three_named_values_and_an_explicit_unset() {
        assert_eq!(parse_priority("low").unwrap(), Priority::Low);
        assert_eq!(parse_priority("HIGH").unwrap(), Priority::High);
        assert_eq!(parse_priority("medium").unwrap(), Priority::Medium);
        assert!(parse_priority("urgent").is_err());
        // The empty string is the TUI form's own default (`ui/form.rs` seeds
        // `priority: String::new()`), so rejecting it flagged every issue the
        // TUI created. `parse_priority_accepts_an_unset_value_and_still_rejects_typos`
        // covers this case in more depth.
        assert!(parse_priority("").unwrap().is_undefined());
    }
}