tix-tracker 0.5.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! 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 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 archive;
pub mod bulk;
pub mod create;
pub mod cycle;
pub mod delete;
pub mod edit;
pub mod export;
pub mod import;
pub mod init;
pub mod link;
pub mod lint;
pub mod list;
pub mod milestone;
pub mod mv;
pub mod parent;
pub mod render;
pub mod rollover;
pub mod search;
pub mod status;
pub mod triage;
pub mod view;
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";

/// One argument per `tix.toml`-backed field; the flag count mirrors the
/// frozen command surface in `contracts/cli.md`.
#[allow(clippy::too_many_arguments)]
pub fn dispatch(cmd: &Command, config: &Config, store: &Store) -> Result<()> {
    match cmd {
        Command::Init => unreachable!("init is handled before dispatch"),
        Command::InitAgents => unreachable!("init-agents is handled before dispatch"),
        Command::Triage { .. } => unreachable!("triage 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,
            reviewer,
            start_date,
            due_date,
            parent,
        } => 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(),
            reviewer.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
            parent.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,
            reviewer,
            parent,
            start_date,
            due_date,
            commit,
            reason,
        } => 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(),
            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 passed last and takes no place in
            // `edit::run`'s "was any field supplied" check.
            reason.as_deref(),
        ),
        Command::Move {
            issue,
            column,
            commit,
            reason,
            yes,
        } => mv::run(
            config,
            store,
            issue,
            column,
            commit.as_deref(),
            reason.as_deref(),
            *yes,
        ),
        Command::View { issue, show } => view::run(store, issue, show.as_deref()),
        Command::List {
            status,
            filter,
            sort,
            group,
            columns,
            show,
            with_archived,
        } => list::run(
            store,
            status.as_deref(),
            filter.as_deref(),
            sort.as_deref(),
            group.as_deref(),
            columns.as_deref(),
            show.as_deref(),
            *with_archived,
        ),
        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,
        } => status::run(
            config,
            store,
            filter.as_deref(),
            sort.as_deref(),
            group.as_deref(),
        ),
        Command::Delete { issue, yes } => delete::run(store, issue, *yes),
        // 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(),
        )),
        Command::Cycle { command } => cycle::run(config, store, command),
        Command::Milestone { command } => milestone::run(config, store, command),
        Command::Export {
            target,
            dry_run,
            project,
            cycle,
            output,
        } => export::run(
            config,
            store,
            target,
            *dry_run,
            project.as_deref(),
            cycle.as_deref(),
            output.as_deref(),
        ),
        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.
            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::Lint => lint::run(config, store).map(|_| ()),
    }
}

/// 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.parse::<u32>() {
        return Ok(IssueSelector::Number(number));
    }
    // `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 {
    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();
    }

    #[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 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());
    }
}