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
use crate::config::Config;
use crate::error::Result;
use crate::model::Issue;
use crate::planning::Planner;
use crate::search::control_token;
use crate::storage::Store;
use serde::Serialize;
use std::collections::BTreeMap;

/// The board summary (FR-009): one `(column, count)` pair per configured
/// column and the total issue count, computed by the [`board`] core for the
/// `board_status` MCP tool (WP04) and rendered by the CLI [`run`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoardSummary {
    /// Each configured column with its issue count, in config order.
    pub columns: Vec<(String, usize)>,
    /// Total number of issues in the store.
    pub total: usize,
}

/// One configured column and how many counted issues sit in it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ColumnCount {
    pub column: String,
    pub count: usize,
}

/// The JSON board document: `tix status --json` stdout and MCP
/// `board_status` `structuredContent`, built once here.
///
/// The fields are declared in the contracted order rather than assembled through
/// `json!`: `serde_json` is built without `preserve_order`, so a `json!` map would
/// print alphabetically (`columns`, `health`, `total`). `health` is skipped
/// entirely when absent, so a consumer can tell "not asked for" from "empty".
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct StatusDocument {
    pub columns: Vec<ColumnCount>,
    pub total: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub health: Option<serde_json::Value>,
}

/// What [`evaluate`] returns: the table the CLI has always printed, and the
/// document both surfaces expose.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusOutcome {
    pub text: String,
    pub document: StatusDocument,
}

/// `tix status`: the board summary (`contracts/cli.md`, FR-009) — a header
/// row, one row per configured column with its issue count, and a `Total`
/// row. Columns separated by exactly two spaces.
///
/// With `json`, the same board is printed as one JSON object
/// ([`StatusDocument`]) instead. The table is untouched by this flag.
pub fn run(
    config: &Config,
    store: &Store,
    filter: Option<&str>,
    sort: Option<&str>,
    group: Option<&str>,
    health: bool,
    json: bool,
) -> Result<()> {
    let outcome = evaluate(config, store, filter, sort, group, health)?;
    if json {
        let text = serde_json::to_string_pretty(&outcome.document).map_err(|error| {
            crate::error::TixError::Parse(format!("board document cannot be serialized: {error}"))
        })?;
        // One write of the fully built document: a strict parser sees exactly one
        // value, and no second print can slip in between.
        println!("{text}");
    } else {
        print!("{}", outcome.text);
    }
    Ok(())
}

/// The one evaluation behind both status surfaces.
///
/// `tix status` and MCP's `board_status` must answer with the same counts, so the
/// whole decision sequence — list, filter, sort, count, optional health — lives
/// here and each caller only chooses how to render the result. The text branch is
/// the pre-existing [`render`]; the document is built beside it from the same
/// [`BoardSummary`], so changing one cannot silently change the other.
///
/// A refused filter (or an unavailable health document) is an `Err` returned
/// **before** either rendering exists, which is what keeps the CLI from printing a
/// partial object and MCP from reporting a half-built answer.
pub fn evaluate(
    config: &Config,
    store: &Store,
    filter: Option<&str>,
    sort: Option<&str>,
    group: Option<&str>,
    health: bool,
) -> Result<StatusOutcome> {
    let mut issues = store.list()?;
    if let Some(filter) = filter {
        // `parent:` is a selector and `category:` is derived; neither can be matched
        // from the file's bytes. Both are resolved here into the pair
        // `matches_issue` needs (WP08 T035). Going through `query_matches` would
        // report **unfiltered** counts for a filter the user believes is applied —
        // a summary that looks like an answer.
        //
        // The same two lines appear in `commands::list::query` and
        // `commands::search::find`. They are repeated rather than shared because
        // each takes its filter from a different argument and `this` module's
        // `sort_key`/`group_key` below still read the **outer** `filter` for
        // `sort:`/`group:`; a helper spanning four call-site-specific shapes is a
        // helper nobody reads. The inner names are suffixed so shadowing cannot make
        // the `control_token` calls below silently start reading a rewritten query.
        let (resolved, criteria) = crate::search::resolve_filter_criteria(store, filter)?;
        let (_, resolution) = crate::workflow::active_resolution(config);
        issues.retain(|i| {
            crate::search::matches_issue(
                &resolved,
                &criteria,
                i,
                &i.to_file_contents(),
                &resolution,
            )
        });
    }
    let sort_key = sort
        .map(str::to_string)
        .or_else(|| filter.and_then(|q| control_token(q, "sort")));
    sort_issues(&mut issues, sort_key.as_deref());
    let summary = board_for_issues(config, &issues);
    let group_key = group
        .map(str::to_string)
        .or_else(|| filter.and_then(|q| control_token(q, "group")));
    let show_controls = filter.is_some() || sort_key.is_some() || group_key.is_some();
    // Opt-in, and built from the one health document (C-007): the summary counts the
    // same scopes the TUI and MCP render, so a state cannot be counted twice on one
    // surface and once on another.
    let health_summary = if health {
        Some(crate::commands::health::HealthSummary::of(
            &crate::commands::export::run_health_core(config)?,
        ))
    } else {
        None
    };
    let text = render(
        config,
        store,
        &issues,
        &summary,
        show_controls,
        group_key.as_deref(),
        health_summary.as_ref(),
    );
    let document = StatusDocument {
        columns: summary
            .columns
            .iter()
            .map(|(column, count)| ColumnCount {
                column: column.clone(),
                count: *count,
            })
            .collect(),
        total: summary.total,
        // The same summary the text renderer just consumed: one health document,
        // two renderings, so the JSON block and the sentence cannot disagree.
        health: health_summary.as_ref().map(health_value),
    };
    Ok(StatusOutcome { text, document })
}

/// The `health` object both surfaces publish: MCP's `board_status` has returned
/// this shape since the health summary existed, and the CLI's `--json` mode is
/// required to match it field for field.
fn health_value(summary: &crate::commands::health::HealthSummary) -> serde_json::Value {
    serde_json::json!({
        "policy_version": summary.policy_version,
        "issues": summary.issues,
        "derived": summary.derived,
        "diagnostics": summary.diagnostics,
        "states": summary.by_state,
    })
}

/// Render the board summary, as text.
///
/// WP04: **one** renderer for both surfaces. `tix status` and MCP's `board_status`
/// are required to be byte-identical (NFR-005, `surface-parity.md`), and until this
/// existed they were two hand-maintained copies of the same table — each with its own
/// `Overdue` calculation, its own group rollup, and its own idea of which column
/// means done. The parity test caught the divergence the moment the CLI's label
/// changed to `complete` and MCP's did not, which is exactly what a duplicated
/// renderer invites.
///
/// The parameters are the *decisions* rather than the raw flags, so a caller cannot
/// present a combination the CLI would not: `show_controls` and `group_key` are
/// already resolved from `filter`/`sort`/`group` by [`run`].
pub fn render(
    config: &Config,
    store: &Store,
    issues: &[Issue],
    summary: &BoardSummary,
    show_controls: bool,
    group_key: Option<&str>,
    health: Option<&crate::commands::health::HealthSummary>,
) -> String {
    let planner = Planner::from_config(config.clone(), std::path::PathBuf::from("."));
    // WP04 T019: completion through the service (C-004). This used to compare against
    // `effective_done_column().unwrap_or("done")` — a column *name* resolved in the
    // command, with a literal `"done"` as the fallback.
    //
    // The fallback was the defect, not a convenience. A board that configures no
    // `done_column` resolved to the literal string `done`, so an issue in a column
    // actually named `done` counted as complete on a board that had declared nothing,
    // while the same board's `tix mv` would not have recorded that move as reaching
    // completion. `is_completed` never errors: an issue in a column the board does not
    // configure is simply not complete, which is the honest answer for a board that
    // declared no completion column.
    let (_, resolution) = crate::workflow::active_resolution(config);

    let column_width = config
        .default_config()
        .columns
        .iter()
        .map(|c| c.chars().count())
        .chain([6, 5])
        .max()
        .unwrap()
        .min(30);
    let count_width = summary.total.to_string().len().max(5).max(1);
    let mut out = String::new();
    let mut row = |column: String, count: String| {
        out.push_str(&format!("{column:<column_width$}  {count:<count_width$}\n"));
    };

    row("COLUMN".into(), "COUNT".into());
    // WP02 of `configurable-wip-limits-01M3C6WX`: when the board configures limits,
    // a column row carries its usage beside its count. One shared snapshot for the
    // whole table, and a board that configures **no** limit renders exactly what it
    // rendered before this mission — which is what keeps `tix status` and MCP's
    // `board_status` byte-identical (NFR-005) for every repository that does not opt
    // in.
    let wip = crate::wip::WipSnapshot::build(config.default_config(), issues);
    for (column, count) in &summary.columns {
        match wip.column(column).filter(|usage| usage.limit.is_some()) {
            Some(usage) => row(column.clone(), format!("{count}  {}", usage.cell())),
            None => row(column.clone(), count.to_string()),
        }
    }
    row("Total".into(), summary.total.to_string());
    if show_controls {
        let today = crate::model::today();
        let overdue = issues
            .iter()
            .filter(|i| {
                i.due_date
                    .as_deref()
                    .is_some_and(|due| due < today.as_str())
                    && !crate::workflow::is_completed(i, &resolution)
            })
            .count();
        row("Overdue".into(), overdue.to_string());
    }
    if let Some(group_key) =
        group_key.filter(|g| *g == "cycle" || *g == "milestone" || *g == "project" || *g == "epic")
    {
        // The project partition's labels are the service's, read once from the shared
        // index, so `tix status --group project` buckets a project exactly as
        // `tix list --group project` and the board do (WP09 item D, C-006).
        let memberships = if group_key == "project" {
            crate::projects::ProjectIndex::build(config, issues).resolved_memberships()
        } else {
            std::collections::HashMap::new()
        };
        // The epic partition's labels come from the same shared inverse-membership
        // helper the board's partition and `tix list --group epic` read, so the three
        // surfaces cannot bucket an epic two ways (WP09 item C).
        let epic_memberships = if group_key == "epic" {
            crate::epics::memberships_by_issue(config, issues)
        } else {
            std::collections::HashMap::new()
        };
        let mut groups: BTreeMap<String, (usize, usize)> = BTreeMap::new();
        for issue in issues {
            let group = match group_key {
                "cycle" => issue
                    .cycles
                    .as_ref()
                    .and_then(|v| v.first().cloned())
                    .unwrap_or_else(|| "(none)".to_string()),
                "milestone" => issue
                    .milestones
                    .as_ref()
                    .and_then(|v| v.first().cloned())
                    .unwrap_or_else(|| "(none)".to_string()),
                "project" => {
                    let ids = memberships.get(&issue.number).cloned().unwrap_or_default();
                    crate::projects::project_bucket_label(&ids)
                }
                "epic" => {
                    let ids = epic_memberships
                        .get(&issue.number)
                        .cloned()
                        .unwrap_or_default();
                    crate::search::epic_bucket_label(&ids)
                }
                _ => "(none)".to_string(),
            };
            let entry = groups.entry(group).or_insert((0, 0));
            entry.1 += 1;
            // The service's completion decision, for the same reason as the `Overdue`
            // row: a group header must mean the same thing as a `--progress` figure
            // and as `tix list`'s rollup.
            if crate::workflow::is_completed(issue, &resolution) {
                entry.0 += 1;
            }
        }
        for (group, (done, total)) in groups {
            let pct = (done * 100).checked_div(total).unwrap_or(0);
            // WP04: the word is `complete`, not `done`. The old label named a column,
            // and a board whose completion column is `shipped` was reporting `3/4 done`
            // — describing a column the board does not have.
            out.push_str(&format!(
                "{group_key} {group}: {done}/{total} complete ({pct}%)\n"
            ));
        }
    }
    // The `show_progress` gate lives here rather than in the caller, so the two
    // surfaces cannot disagree about when the section appears.
    let show_progress = issues.iter().any(|i| {
        i.cycles.as_ref().is_some_and(|v| !v.is_empty())
            || i.milestones.as_ref().is_some_and(|v| !v.is_empty())
    });
    if show_progress {
        for cycle in planner.cycle_names() {
            let progress = planner.cycle_progress(store, &cycle);
            if progress.total > 0 {
                // `complete`, not `done`: the figure already comes from the service
                // (`Planner::is_done_issue` delegates to `workflow::is_completed`), so
                // the label was the last thing still naming a column.
                out.push_str(&format!(
                    "cycle {cycle}: {}/{} complete\n",
                    progress.done, progress.total
                ));
            }
        }
        for milestone in planner.milestone_names().unwrap_or_default() {
            let progress = planner.milestone_progress(store, &milestone);
            if progress.total > 0 {
                out.push_str(&format!(
                    "milestone {milestone}: {}/{} complete\n",
                    progress.done, progress.total
                ));
            }
        }
    }
    // The health summary last, and only when it was asked for: the board is about
    // columns, and health is metadata about the work (C-006). The line itself is
    // [`HealthSummary::render`]'s, so every surface that has a summary prints the
    // same sentence.
    if let Some(health) = health {
        out.push_str(&health.render());
    }
    out
}

/// The status core (WP03): count issues per configured column plus the total.
///
/// This is what MCP's `board_status` tool (WP04) calls. Side-effect policy
/// (C-005): the core returns the [`BoardSummary`] data structure; the CLI
/// renders it in [`run`] with the exact layout as before.
pub fn board(config: &Config, store: &Store) -> Result<BoardSummary> {
    let issues = store.list()?;
    Ok(board_for_issues(config, &issues))
}

/// The summary for a given issue set.
///
/// WP04: `pub` because MCP's `board_status` used to keep its own copy of this
/// counting, alongside its own copy of the *rendering*. Two copies of the counting
/// and two of the rendering is four places for one table to drift; the parity test
/// caught the rendering pair the moment the CLI's label changed.
pub fn board_for_issues(config: &Config, issues: &[Issue]) -> BoardSummary {
    let total = issues.len();
    let columns = config
        .default_config()
        .columns
        .iter()
        .map(|column| {
            let count = issues.iter().filter(|i| i.status.is(column)).count();
            (column.clone(), count)
        })
        .collect();
    BoardSummary { columns, total }
}

fn sort_issues(issues: &mut [Issue], sort: Option<&str>) {
    match sort.unwrap_or("created") {
        "due" => issues.sort_by(|a, b| a.due_date.cmp(&b.due_date).then(a.number.cmp(&b.number))),
        "start" => issues.sort_by(|a, b| {
            a.start_date
                .cmp(&b.start_date)
                .then(a.number.cmp(&b.number))
        }),
        "reviewer" => {
            issues.sort_by(|a, b| a.reviewer.cmp(&b.reviewer).then(a.number.cmp(&b.number)))
        }
        "cycle" => issues.sort_by(|a, b| {
            a.cycles
                .as_ref()
                .and_then(|v| v.first())
                .cmp(&b.cycles.as_ref().and_then(|v| v.first()))
                .then(a.number.cmp(&b.number))
        }),
        "milestone" => issues.sort_by(|a, b| {
            a.milestones
                .as_ref()
                .and_then(|v| v.first())
                .cmp(&b.milestones.as_ref().and_then(|v| v.first()))
                .then(a.number.cmp(&b.number))
        }),
        "status" => issues.sort_by(|a, b| {
            a.status
                .display()
                .cmp(b.status.display())
                .then(a.number.cmp(&b.number))
        }),
        "priority" => issues.sort_by(|a, b| {
            a.priority
                .to_string()
                .cmp(&b.priority.to_string())
                .then(a.number.cmp(&b.number))
        }),
        _ => issues.sort_by(|a, b| a.created.cmp(&b.created).then(a.number.cmp(&b.number))),
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::{Issue, Priority, Status};
    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 seed(store: &Store, number: u32, title: &str, status: &str) {
        let mut issue = Issue {
            projects: None,
            id: None,
            number,
            title: title.to_string(),
            status: Status::new(status.to_string()),
            labels: vec![],
            priority: Priority::default(),
            assignee: Some("alice".to_string()),
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".to_string(),
            type_: None,
            updated: "2026-01-01".to_string(),
            filename: String::new(),
            body: "body".to_string(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            time_entries: vec![],
            parent: None,
            series: None,
            health: None,
            epics: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        issue.filename = format!("alice/2026-01-01-{}.md", crate::slug::slugify(title));
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();
    }

    #[test]
    fn board_counts_columns_and_total() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "One", "todo");
        seed(&store, 2, "Two", "todo");
        seed(&store, 3, "Three", "in progress");
        seed(&store, 4, "Four", "done");
        let summary = board(&store.config, &store).unwrap();
        assert_eq!(
            summary
                .columns
                .iter()
                .map(|(c, n)| (c.as_str(), *n))
                .collect::<Vec<_>>(),
            vec![
                ("todo", 2),
                ("in progress", 1),
                ("in review", 0),
                ("done", 1),
            ],
            "columns in config order with per-column counts"
        );
        assert_eq!(summary.total, 4);
    }

    #[test]
    fn document_columns_are_board_order_with_zeros() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "One", "todo");
        seed(&store, 2, "Two", "in progress");
        let outcome = evaluate(&store.config, &store, None, None, None, false).unwrap();
        assert_eq!(
            outcome
                .document
                .columns
                .iter()
                .map(|c| (c.column.as_str(), c.count))
                .collect::<Vec<_>>(),
            vec![
                ("todo", 1),
                ("in progress", 1),
                ("in review", 0),
                ("done", 0),
            ],
            "every configured column, in board order, zeros included"
        );
        assert_eq!(outcome.document.total, 2);
    }

    #[test]
    fn document_omits_health_key_unless_requested() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "One", "todo");
        let plain = serde_json::to_value(
            &evaluate(&store.config, &store, None, None, None, false)
                .unwrap()
                .document,
        )
        .unwrap();
        assert!(
            plain.get("health").is_none(),
            "health is absent, not null, when it was not requested"
        );
        let with_health = serde_json::to_value(
            &evaluate(&store.config, &store, None, None, None, true)
                .unwrap()
                .document,
        )
        .unwrap();
        let health = with_health.get("health").expect("health object");
        for key in [
            "policy_version",
            "issues",
            "derived",
            "diagnostics",
            "states",
        ] {
            assert!(health.get(key).is_some(), "health.{key} missing");
        }
    }

    #[test]
    fn evaluate_rejects_an_unresolvable_filter() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "One", "todo");
        // `archived:` takes a boolean; `1` is refused before anything is counted.
        let error = evaluate(&store.config, &store, Some("archived:1"), None, None, false);
        assert!(error.is_err(), "an unreadable filter must be refused");
    }

    #[test]
    fn evaluate_propagates_a_health_failure() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "One", "todo");
        // `Store::list` — the board's view — skips archived files from the directory
        // entry, before opening them. The health document reads **every** issue, so a
        // broken archived file is invisible to the table and fatal to the health
        // summary: that isolates the health branch instead of merely failing the read
        // the board already performs.
        fs::write(
            store.issues_dir.join("alice/.broken.md"),
            "---\nnumber: not-a-number\n---\n\nbody\n",
        )
        .unwrap();
        assert!(store.list().is_ok(), "the board never reads archived files");
        assert!(
            evaluate(&store.config, &store, None, None, None, false).is_ok(),
            "the plain board does not depend on the health document"
        );
        assert!(
            evaluate(&store.config, &store, None, None, None, true).is_err(),
            "an unavailable health document is an error, not an empty summary"
        );
    }
}