tix-tracker 0.6.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
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::search::control_token;
use crate::storage::Store;
use std::collections::BTreeMap;
use std::io::IsTerminal;
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

const FALLBACK_WIDTH: usize = 0;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListColumn {
    Num,
    Title,
    Status,
    Priority,
    Cycle,
    Milestone,
    Reviewer,
    Start,
    Due,
    Overdue,
    /// The service-derived blocked reason. Empty when the issue is not blocked.
    Blocked,
    /// The issue's relationships as `kind -> #target`, in the service's order.
    Relations,
    /// The child count, and the rollup for a parent, from the hierarchy service.
    Progress,
    /// The issue's resolved category label, from the service (WP04 T019).
    Category,
    /// Whether the issue is archived (issue #1492). Derived from the filename,
    /// never stored; appended to the default columns only when at least one row
    /// is archived.
    Archived,
}

/// The relationship facts the `--show relationships` columns render, computed
/// once per issue from the service.
///
/// Both fields are precomputed strings rather than something `cell` derives,
/// because deriving blocked state or direction here is exactly the boundary
/// breach `contracts/surface-parity.md` ยง3 forbids.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RelationshipCells {
    /// The blocked reason, empty when the issue is not blocked.
    pub blocked: String,
    /// `kind -> #target` for every relationship, in the service's order.
    pub relationships: String,
}

impl ListColumn {
    fn parse(value: &str) -> Result<Self> {
        match value.to_ascii_lowercase().as_str() {
            "num" => Ok(Self::Num),
            "title" => Ok(Self::Title),
            "status" => Ok(Self::Status),
            "priority" => Ok(Self::Priority),
            "cycle" => Ok(Self::Cycle),
            "milestone" => Ok(Self::Milestone),
            "reviewer" => Ok(Self::Reviewer),
            "start" => Ok(Self::Start),
            "due" => Ok(Self::Due),
            "overdue" => Ok(Self::Overdue),
            "blocked" => Ok(Self::Blocked),
            "relations" | "relationships" => Ok(Self::Relations),
            "progress" | "children" => Ok(Self::Progress),
            // WP04 T019: `--show category`, per `contracts/cli-surface.md` ยง3.
            "category" => Ok(Self::Category),
            "archived" => Ok(Self::Archived),
            _ => Err(TixError::InvalidInput(format!(
                "unknown list column `{value}`; expected one of num,title,status,priority,cycle,milestone,reviewer,start,due,overdue,blocked,relations,progress,category,archived"
            ))),
        }
    }

    fn header(self) -> &'static str {
        match self {
            Self::Num => "NUM",
            Self::Title => "TITLE",
            Self::Status => "STATUS",
            Self::Priority => "PRIORITY",
            Self::Cycle => "CYCLE",
            Self::Milestone => "MILESTONE",
            Self::Reviewer => "REVIEWER",
            Self::Start => "START",
            Self::Due => "DUE",
            Self::Overdue => "OVERDUE",
            Self::Blocked => "BLOCKED",
            Self::Relations => "RELATIONS",
            Self::Progress => "CHILDREN",
            // The header names the *concept*; the cell carries the service's own
            // `label()`, so the CLI and the TUI cannot spell it differently.
            Self::Category => "CATEGORY",
            Self::Archived => "ARCHIVED",
        }
    }

    fn cap(self) -> usize {
        match self {
            Self::Num => 6,
            Self::Title => 40,
            Self::Status => 16,
            Self::Priority => 12,
            Self::Cycle | Self::Milestone | Self::Reviewer => 20,
            Self::Start | Self::Due => 10,
            Self::Overdue => 7,
            Self::Blocked | Self::Relations => 40,
            // `3  1/3` โ€” the count and the rollup, side by side.
            Self::Progress => 16,
            // The longest current label is "Not started" (12); 14 leaves a little
            // room so a future label does not silently truncate into a lie.
            Self::Category => 14,
            // "ARCHIVED" is the whole cell value, so the cap is its width.
            Self::Archived => 8,
        }
    }
}

pub fn parse_columns(value: &str) -> Result<Vec<ListColumn>> {
    if value.trim().is_empty() {
        return Err(TixError::InvalidInput(
            "list columns must not be empty".to_string(),
        ));
    }
    let mut columns = Vec::new();
    for value in value.split(',') {
        let column = ListColumn::parse(value.trim())?;
        if columns.contains(&column) {
            return Err(TixError::InvalidInput(format!(
                "duplicate list column `{}`",
                value.trim()
            )));
        }
        columns.push(column);
    }
    Ok(columns)
}

fn default_columns(issues: &[Issue]) -> Vec<ListColumn> {
    let expanded = issues.iter().any(|issue| {
        issue.cycles.as_ref().is_some_and(|v| !v.is_empty())
            || issue.milestones.as_ref().is_some_and(|v| !v.is_empty())
            || issue.reviewer.as_deref().is_some_and(|v| !v.is_empty())
            || issue.start_date.is_some()
            || issue.due_date.is_some()
    });
    let mut columns = vec![
        ListColumn::Num,
        ListColumn::Title,
        ListColumn::Status,
        ListColumn::Priority,
    ];
    if expanded {
        columns.extend([
            ListColumn::Cycle,
            ListColumn::Milestone,
            ListColumn::Reviewer,
            ListColumn::Start,
            ListColumn::Due,
            ListColumn::Overdue,
        ]);
    }
    // Only when a displayed row is archived: the marker column is noise on a
    // board that has opted into `--with-archived` but archived nothing, and its
    // absence keeps the default table byte-identical (issue #1492).
    if issues.iter().any(|issue| issue.archived) {
        columns.push(ListColumn::Archived);
    }
    columns
}

/// The columns `--show relationships` appends, in order.
///
/// Appended rather than interleaved so an existing `--columns` list keeps its
/// meaning, and so the two relationship facts land together where a reader
/// comparing two issues sees them side by side.
const RELATIONSHIP_COLUMNS: [ListColumn; 2] = [ListColumn::Blocked, ListColumn::Relations];

#[allow(clippy::too_many_arguments)]
pub fn run(
    store: &Store,
    status: Option<&str>,
    filter: Option<&str>,
    sort: Option<&str>,
    group: Option<&str>,
    columns: Option<&str>,
    show: Option<&str>,
    with_archived: bool,
) -> Result<()> {
    // `list` understands two `--show` values, not one. `link::wants_relationships`
    // rejects anything that is not `relationships`, so a shared validator that
    // rejected `progress` would make the documented flag (cli-surface.md ยง2)
    // unusable. Validated here, before anything is printed, for the same stdout
    // reason `view` validates early.
    // One parse, one call: this used to call `wants_show` twice, and while the two
    // answers cannot disagree today, a validator that ran twice is a validator whose
    // cost and behaviour scale with the number of callers rather than with the input.
    let shows = wants_show(show)?;
    let show_relationships = shows.contains(&"relationships");
    let show_progress = shows.contains(&"progress");
    let show_category = shows.contains(&"category");
    let mut issues = query(store, status, filter, with_archived)?;
    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());
    // WP04 T019 (C-004): completion comes from the service, not from a column name
    // resolved in the command with a literal `"done"` fallback.
    //
    // The `unwrap_or("done")` was the defect, and it was a **behaviour** defect
    // rather than a tidiness one. A board that configures no `done_column` fell
    // back to the literal string, so `tix list --show progress` counted an issue in
    // a column actually named `done` as complete on a board that had declared no
    // completion column at all โ€” while `tix mv` into that same column, going
    // through the seam, recorded no decision as reaching completion. Two surfaces
    // answering "is this done?" differently is precisely what this mission exists
    // to end.
    let (_, resolution) = crate::workflow::active_resolution(&store.config);
    // Still needed, and still a *column name*: the relationship graph and the
    // hierarchy rollup are existing services that take the board's completion
    // column as a parameter. Re-deriving it here is what they already did; changing
    // their signatures is outside this WP's map and is recorded rather than done
    // half-way.
    // WP09: the **service's** completion column. The column is only a *parameter*
    // for `hierarchy_cells` and the `RelationshipGraph` โ€” both are existing services
    // that take a completion column name, and changing their signatures is outside
    // this mission. But supplying that name from `done_column` meant the blocked
    // marker and the progress rollup were computed against the wrong column on a
    // board whose `category_map` puts `completed` elsewhere. The meaning is now
    // resolved once, here, from the service.
    let done_column =
        crate::workflow::completion_column_or_default(store.config.default_config(), &store.config);
    let mut columns = columns
        .map(parse_columns)
        .transpose()?
        .unwrap_or_else(|| default_columns(&issues));
    let mut derived: Option<BTreeMap<u32, RelationshipCells>> = None;
    // Populated when the caller asked for a relationship column **or** passed
    // `--show relationships`.
    //
    // It used to be gated on `show_relationships` alone, which meant
    // `tix list --columns num,title,status,blocked` accepted `blocked`, built a
    // table with the column in it, and then rendered `-` for every row โ€” because
    // `derived` was `None` and `render_table_with` falls through to the
    // empty-cell placeholder. A column that is accepted and always empty reads as
    // "nothing is blocked" rather than "ask for the detail", which is a worse lie
    // than not offering the column.
    //
    // Asking for `blocked` or `relations` by name is a request for the data, not
    // only for the heading.
    let wants_relationship_column = RELATIONSHIP_COLUMNS.iter().any(|c| columns.contains(c));
    if show_relationships || wants_relationship_column {
        for column in RELATIONSHIP_COLUMNS {
            // `--columns blocked` already asked for it; appending a second copy
            // would make the two columns indistinguishable.
            if !columns.contains(&column) {
                columns.push(column);
            }
        }
        derived = Some(relationship_cells(store)?);
    }
    let mut hierarchy: Option<BTreeMap<u32, String>> = None;
    // Asking for `progress` **by name** is a request for the data, not only for the
    // heading โ€” the same rule the relationship columns follow, for the same reason:
    // a column that is accepted and always `-` reads as "nothing is a parent" rather
    // than "ask for the detail".
    if show_progress || columns.contains(&ListColumn::Progress) {
        if !columns.contains(&ListColumn::Progress) {
            columns.push(ListColumn::Progress);
        }
        hierarchy = Some(hierarchy_cells(store, &done_column)?);
    }
    // WP04 T019: `--show category` adds the category column. Requesting
    // `category` by name in `--columns` is already a request for the data โ€” the
    // same rule the relationship and progress columns follow โ€” so this only has to
    // add the column when it was asked for via `--show`.
    if show_category && !columns.contains(&ListColumn::Category) {
        columns.push(ListColumn::Category);
    }
    let group_key = group
        .map(str::to_string)
        .or_else(|| filter.and_then(|q| control_token(q, "group")));
    let width = terminal_width();
    print!(
        "{}",
        render_table_with(
            &issues,
            &columns,
            group_key.as_deref(),
            &resolution,
            width,
            derived.as_ref(),
            hierarchy.as_ref(),
        )
    );
    Ok(())
}

/// The `--show` values `tix list` understands.
///
/// Returns them **deduplicated and in the order given**, so `--show progress
/// relationships` and `--show relationships,progress` are the same request.
fn wants_show(show: Option<&str>) -> Result<Vec<&'static str>> {
    let mut out: Vec<&'static str> = Vec::new();
    for token in show.unwrap_or("").split(',').map(str::trim) {
        if token.is_empty() {
            continue;
        }
        let known = match token {
            "relationships" => "relationships",
            "progress" => "progress",
            // WP04 T019, per `contracts/cli-surface.md` ยง3.
            "category" => "category",
            other => {
                return Err(TixError::InvalidInput(format!(
                    "unknown --show value `{other}`; this surface understands \
                     `relationships`, `progress` and `category`"
                )));
            }
        };
        if !out.contains(&known) {
            out.push(known);
        }
    }
    Ok(out)
}

/// Every issue's hierarchy cell, read from the service in one pass.
///
/// The cell text is produced by the **same** [`crate::commands::parent::HierarchyFacts`]
/// that `tix parent show` and the `tix show` block use, so the three surfaces
/// cannot report different figures for one issue (parity contract ยง2). T017 step 3
/// forbids computing a progress number here, and this is how that is honoured: this
/// function reads and formats, and computes nothing.
///
/// Empty for a leaf, which the cell renders as `-`.
fn hierarchy_cells(store: &Store, done_column: &str) -> Result<BTreeMap<u32, String>> {
    let (index, issues, _) = crate::commands::parent::source(store)?;
    let mut out = BTreeMap::new();
    for issue in &issues {
        let facts = crate::commands::parent::facts_for(&index, &issues, issue.number, done_column);
        if !facts.has_children() {
            continue;
        }
        out.insert(
            issue.number,
            format!(
                "{}  {}/{}",
                facts.rollup.direct_children,
                facts.rollup.completed_children,
                facts.rollup.progress.total
            ),
        );
    }
    Ok(out)
}

/// Every issue's relationship facts, read from the service in one pass.
///
/// One graph for the whole board: deriving blocked state per row would mean
/// re-reading every file per row, and โ€” worse โ€” could let two rows in the same
/// table describe different snapshots.
fn relationship_cells(store: &Store) -> Result<BTreeMap<u32, RelationshipCells>> {
    let (issues, done_column) = store.graph_source()?;
    let views: Vec<crate::relationships::IssueView<'_>> =
        issues.iter().map(Issue::issue_view).collect();
    let graph = crate::relationships::RelationshipGraph::new(&views, &done_column);
    let mut out = BTreeMap::new();
    for issue in &issues {
        let state = graph.blocked_state(issue.number);
        let relationships = graph
            .relationships_for(issue.number)
            .into_iter()
            .map(|rel| format!("{} -> #{}", rel.kind, rel.to))
            .collect::<Vec<_>>()
            .join(", ");
        out.insert(
            issue.number,
            RelationshipCells {
                blocked: state.reason,
                relationships,
            },
        );
    }
    Ok(out)
}

fn terminal_width() -> usize {
    if std::io::stdout().is_terminal() {
        crossterm::terminal::size()
            .ok()
            .map(|(width, _)| width as usize)
            .filter(|width| *width > 0)
            .unwrap_or(FALLBACK_WIDTH)
    } else {
        FALLBACK_WIDTH
    }
}

pub fn render_table(
    issues: &[Issue],
    columns: &[ListColumn],
    group: Option<&str>,
    resolution: &crate::workflow::CategoryResolution,
    width: usize,
) -> String {
    render_table_with(issues, columns, group, resolution, width, None, None)
}

/// [`render_table`], with the service-derived relationship facts the
/// `--show relationships` columns render.
///
/// `derived` is keyed by issue number and only consulted for
/// [`ListColumn::Blocked`] and [`ListColumn::Relations`]; passing `None` makes
/// this identical to [`render_table`], which is what keeps the default listing
/// and MCP's `render_default_table` unchanged.
/// `hierarchy` carries the [`ListColumn::Progress`] cell, keyed by issue number,
/// and is consulted only for that column. It is a **separate** map from `derived`
/// rather than a new field on [`RelationshipCells`], because a child count is not a
/// relationship fact and putting it there would make the type's name lie about its
/// contents โ€” the same mistake a second rollup implementation would be.
pub fn render_table_with(
    issues: &[Issue],
    columns: &[ListColumn],
    group: Option<&str>,
    resolution: &crate::workflow::CategoryResolution,
    width: usize,
    derived: Option<&BTreeMap<u32, RelationshipCells>>,
    hierarchy: Option<&BTreeMap<u32, String>>,
) -> String {
    let today = crate::model::today();
    let rows: Vec<Vec<String>> = issues
        .iter()
        .map(|issue| {
            let cells = derived.and_then(|map| map.get(&issue.number));
            columns
                .iter()
                .map(|column| cell(*column, issue, resolution, &today, cells, hierarchy))
                .collect()
        })
        .collect();
    let natural: Vec<usize> = columns
        .iter()
        .enumerate()
        .map(|(index, column)| {
            rows.iter()
                .map(|row| display_width(&row[index]))
                .chain(std::iter::once(display_width(column.header())))
                .max()
                .unwrap_or(1)
                .min(column.cap())
                .max(1)
        })
        .collect();
    let separator_width = columns.len().saturating_sub(1) * 2;
    let natural_width = separator_width + natural.iter().sum::<usize>();
    let width = if width == 0 { natural_width } else { width };
    let available = width.saturating_sub(separator_width).max(columns.len());
    let mut widths = vec![1; columns.len()];
    let mut remaining = available;
    for (index, column) in columns.iter().enumerate() {
        if *column == ListColumn::Title {
            continue;
        }
        let take = natural[index].min(remaining.saturating_sub(1));
        widths[index] = take.max(1);
        remaining = remaining.saturating_sub(widths[index]);
    }
    if let Some(title) = columns
        .iter()
        .position(|column| *column == ListColumn::Title)
    {
        widths[title] = remaining;
    }
    let line_width = width;
    let mut out = String::new();
    let header: Vec<String> = columns
        .iter()
        .map(|column| column.header().to_string())
        .collect();
    render_row(&mut out, &header, &widths, line_width);
    if let Some(group) = group.filter(|group| *group == "cycle" || *group == "milestone") {
        let mut progress: BTreeMap<String, (usize, usize)> = BTreeMap::new();
        for issue in issues {
            let key = group_value(issue, group);
            let entry = progress.entry(key).or_insert((0, 0));
            entry.1 += 1;
            // WP04 T019: the service's completion decision (C-004), for the same
            // reason the `Overdue` cell uses it. A group header that counts a
            // differently-spelled completion column would contradict the board's
            // own category map in the same table.
            if crate::workflow::is_completed(issue, resolution) {
                entry.0 += 1;
            }
        }
        let mut current = String::new();
        for issue in issues {
            let key = group_value(issue, group);
            if current != key {
                current = key.clone();
                let (done, total) = progress.get(&key).copied().unwrap_or((0, 0));
                let pct = if total == 0 { 0 } else { done * 100 / total };
                out.push_str(&format!(
                    "-- {group}: {key} ({done}/{total} done, {pct}%) --\n"
                ));
            }
            let index = issues
                .iter()
                .position(|candidate| std::ptr::eq(candidate, issue))
                .unwrap();
            render_row(&mut out, &rows[index], &widths, line_width);
        }
    } else {
        for row in &rows {
            render_row(&mut out, row, &widths, line_width);
        }
    }
    out
}

fn render_row(out: &mut String, cells: &[String], widths: &[usize], line_width: usize) {
    let wrapped: Vec<Vec<String>> = cells
        .iter()
        .zip(widths)
        .map(|(cell, width)| wrap_cell(cell, *width))
        .collect();
    let height = wrapped.iter().map(Vec::len).max().unwrap_or(1);
    for row in 0..height {
        for (index, cell) in wrapped.iter().enumerate() {
            if index > 0 {
                out.push_str("  ");
            }
            let value = cell.get(row).map(String::as_str).unwrap_or("");
            out.push_str(value);
            out.push_str(&" ".repeat(widths[index].saturating_sub(display_width(value))));
        }
        let padding = line_width
            .saturating_sub(separator_width(wrapped.len()))
            .saturating_sub(widths.iter().sum::<usize>());
        out.push_str(&" ".repeat(padding));
        out.push('\n');
    }
}

fn separator_width(count: usize) -> usize {
    count.saturating_sub(1) * 2
}

/// One table cell.
///
/// `derived` is `Some` only when the caller asked for relationship
/// information; the two relationship columns render a `-` placeholder without
/// it, so the default table is byte-identical to what it was before WP03.
#[allow(clippy::too_many_arguments)]
fn cell(
    column: ListColumn,
    issue: &Issue,
    resolution: &crate::workflow::CategoryResolution,
    today: &str,
    derived: Option<&RelationshipCells>,
    hierarchy: Option<&BTreeMap<u32, String>>,
) -> String {
    match column {
        ListColumn::Num => issue.number.to_string(),
        ListColumn::Title => issue.title.clone(),
        ListColumn::Status => issue.status.display().to_string(),
        ListColumn::Priority => issue.priority.to_string(),
        ListColumn::Cycle => issue
            .cycles
            .as_ref()
            .map(|v| v.join(","))
            .unwrap_or_default(),
        ListColumn::Milestone => issue
            .milestones
            .as_ref()
            .map(|v| v.join(","))
            .unwrap_or_default(),
        ListColumn::Reviewer => issue.reviewer.clone().unwrap_or_default(),
        ListColumn::Start => issue.start_date.clone().unwrap_or_default(),
        ListColumn::Due => issue.due_date.clone().unwrap_or_default(),
        ListColumn::Overdue => {
            // WP04 T019: `is_completed`, not a column comparison (C-004). An issue
            // that is past due but complete is not overdue, and that is a category
            // decision โ€” a board mapping its last column to `completed` must not
            // depend on that column being spelled `done`.
            if issue.due_date.as_deref().is_some_and(|due| due < today)
                && !crate::workflow::is_completed(issue, resolution)
            {
                "yes".to_string()
            } else {
                String::new()
            }
        }
        // WP04 T019: the category label, from the service's own `label()` so the CLI
        // and the TUI cannot spell the same category differently (WP08 asserts the
        // detail view agrees with this column).
        //
        // An issue in a column the board does not configure resolves to `None`.
        // That is a configuration error the user should be able to *see* in the
        // listing rather than have it silently become the safe default here โ€” the
        // safe default governs transition policy, and applying it to a display would
        // report a category the board never assigned. Shown as `(unmapped)`, which
        // is a statement about the file rather than an error the command refuses to
        // print (T019 step 4 asks for a label, not a failure).
        ListColumn::Category => crate::workflow::category_of(issue, resolution)
            .map(|c| c.label())
            .unwrap_or("(unmapped)")
            .to_string(),
        // A `-` rather than an empty cell, because an empty column next to
        // other empty columns is indistinguishable from a column that was not
        // rendered at all.
        ListColumn::Blocked => match derived {
            Some(cells) if !cells.blocked.is_empty() => cells.blocked.clone(),
            _ => "-".to_string(),
        },
        ListColumn::Relations => match derived {
            Some(cells) if !cells.relationships.is_empty() => cells.relationships.clone(),
            _ => "-".to_string(),
        },
        // A `-` for a leaf, not `0`. A leaf genuinely has no children, and a `0`
        // reads as "measured, and there are none" โ€” which is the same sentence as
        // what a parent with no completed children would say. `-` says "not a
        // parent", which is the fact the column is for.
        //
        // Looked up per issue rather than guarded on the map being non-empty. A leaf
        // has **no entry at all** โ€” `hierarchy_cells` skips it โ€” so "the map is not
        // empty" is true on a board where every issue but one is a leaf, and
        // `cells[&issue.number]` then panicked. Found by running `tix list --show
        // progress`.
        ListColumn::Progress => match hierarchy.and_then(|cells| cells.get(&issue.number)) {
            Some(text) if !text.is_empty() => text.clone(),
            _ => "-".to_string(),
        },
        ListColumn::Archived => {
            if issue.archived {
                "ARCHIVED".to_string()
            } else {
                "-".to_string()
            }
        }
    }
}

fn group_value(issue: &Issue, group: &str) -> String {
    let values = match group {
        "cycle" => issue.cycles.as_ref(),
        "milestone" => issue.milestones.as_ref(),
        _ => None,
    };
    values
        .and_then(|values| values.first().cloned())
        .unwrap_or_else(|| "(none)".to_string())
}

fn wrap_cell(value: &str, width: usize) -> Vec<String> {
    if value.is_empty() || width == 0 {
        return vec![String::new()];
    }
    let mut lines = Vec::new();
    let mut line = String::new();
    for word in value.split_whitespace() {
        let word_width = display_width(word);
        let candidate_width = display_width(&line) + usize::from(!line.is_empty()) + word_width;
        if !line.is_empty() && candidate_width > width {
            lines.push(std::mem::take(&mut line));
        }
        if word_width <= width {
            if !line.is_empty() {
                line.push(' ');
            }
            line.push_str(word);
        } else {
            let mut chunk = String::new();
            for character in word.chars() {
                let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
                if !chunk.is_empty() && display_width(&chunk) + character_width > width {
                    lines.push(std::mem::take(&mut chunk));
                }
                chunk.push(character);
            }
            line = chunk;
        }
    }
    if !line.is_empty() || lines.is_empty() {
        lines.push(line);
    }
    lines
}

fn display_width(value: &str) -> usize {
    UnicodeWidthStr::width(value)
}

/// WP04: takes the service's [`CategoryResolution`](crate::workflow::CategoryResolution)
/// rather than a completion column name.
///
/// MCP's `list_issues` called this with `done_column`, which is where the
/// "100% of surfaces agree" claim would have quietly stopped: the CLI would render
/// `Overdue` and the group rollup through the service while MCP rendered them
/// through a string. One parameter, both surfaces.
pub fn render_default_table(
    issues: &[Issue],
    group: Option<&str>,
    resolution: &crate::workflow::CategoryResolution,
    width: usize,
) -> String {
    render_table(issues, &default_columns(issues), group, resolution, width)
}

pub fn query(
    store: &Store,
    status: Option<&str>,
    filter: Option<&str>,
    with_archived: bool,
) -> Result<Vec<Issue>> {
    // `--with-archived` opts into the exhaustive walk; the default reads the
    // active set, whose dot-prefixed files are never opened (issue #1492).
    let mut issues = if with_archived {
        store.list_all()?
    } else {
        store.list()?
    };
    if let Some(col) = status {
        issues.retain(|i| i.status.is(col));
    }
    if let Some(filter) = filter {
        // `parent:<sel>` names an issue by selector; matching happens against
        // rendered frontmatter, which carries a number. Resolved here so `tix list
        // parent:<sel>` behaves exactly as `tix search "parent:<sel>"` does, and so
        // an unresolvable selector is the same error on both.
        // `parent:` is a selector and `category:` is derived, so neither can be
        // matched from the file's bytes. Both are resolved once here โ€” the one layer
        // with a store and a config โ€” into the pair `matches_issue` needs (WP08
        // T035). One call, so a site cannot validate the token and then forget to
        // hand the criterion on: that mistake returns an empty board with exit 0.
        let (filter, criteria) = crate::search::resolve_filter_criteria(store, filter)?;
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        issues.retain(|i| {
            crate::search::matches_issue(&filter, &criteria, i, &i.to_file_contents(), &resolution)
        });
    }
    Ok(issues)
}

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 {
    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) -> Issue {
        let mut issue = Issue {
            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,
            parent: 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();
        issue
    }

    #[test]
    fn columns_are_case_insensitive_and_ordered() {
        let parsed = parse_columns("PrIoRiTy,TITLE,num").unwrap();
        assert_eq!(
            parsed,
            vec![ListColumn::Priority, ListColumn::Title, ListColumn::Num]
        );
    }

    #[test]
    fn invalid_columns_are_rejected() {
        for value in ["", "title,", "title,title", "unknown"] {
            assert!(parse_columns(value).is_err(), "{value:?} should fail");
        }
    }

    #[test]
    fn selected_order_and_empty_output() {
        let _store = make_store().1;
        let columns = parse_columns("status,title").unwrap();
        let store = make_store().1;
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let output = render_table(&[], &columns, None, &resolution, 40);
        let header = output.lines().next().unwrap();
        assert!(header.starts_with("STATUS  TITLE"));
        assert_eq!(UnicodeWidthStr::width(header), 40);
        assert_eq!(output.lines().count(), 1);
    }

    #[test]
    fn title_receives_space_and_secondary_cells_wrap() {
        let store = make_store().1;
        let issue = seed(&store, 1, "A long title that wraps", "in progress");
        let mut issue = issue;
        issue.reviewer = Some("reviewer with a long name".to_string());
        let columns = parse_columns("num,title,status,priority,reviewer").unwrap();
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let output = render_table(&[issue], &columns, None, &resolution, 45);
        assert!(output.lines().count() > 2);
        assert!(
            output
                .lines()
                .all(|line| UnicodeWidthStr::width(line) == 45)
        );
    }

    #[test]
    fn query_without_filter_returns_every_issue() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "First", "todo");
        seed(&store, 2, "Second", "done");
        assert_eq!(query(&store, None, None, false).unwrap().len(), 2);
    }

    #[test]
    fn with_archived_shows_the_row_marked_and_composes_with_the_filter() {
        let (_tmp, store) = make_store();
        seed(&store, 1, "Keep", "todo");
        seed(&store, 2, "Old", "todo");
        store.archive("2").unwrap();

        // Default: the archived row is hidden (and never read).
        let visible = query(&store, None, None, false).unwrap();
        assert_eq!(visible.len(), 1);
        assert_eq!(visible[0].number, 1);

        // `--with-archived`: both, the archived one flagged.
        let all = query(&store, None, None, true).unwrap();
        assert_eq!(all.len(), 2);
        assert!(all.iter().any(|issue| issue.number == 2 && issue.archived));

        // The derived `archived:` criterion composes with `--with-archived`.
        let archived_only = query(&store, None, Some("archived:true"), true).unwrap();
        assert_eq!(numbers(&archived_only), vec![2]);
        let active_only = query(&store, None, Some("archived:false"), true).unwrap();
        assert_eq!(numbers(&active_only), vec![1]);

        // The default table marks the archived row with the ARCHIVED column.
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let table = render_default_table(&all, None, &resolution, 0);
        assert!(table.contains("ARCHIVED"), "marker column missing: {table}");
    }

    fn numbers(issues: &[Issue]) -> Vec<u32> {
        issues.iter().map(|issue| issue.number).collect()
    }
}