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
#[allow(clippy::wildcard_imports)]
use super::*;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListColumn {
    Num,
    /// The issue's canonical 8-character id (the identity `crate::id` mints, not
    /// the colliding-per-checkout `number`). A default column: the compact listing
    /// is `number`, `id`, `title`, so a reader can copy the token that is stable
    /// across clones and branches (#1711).
    Id,
    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 project associations with each project's progress and health,
    /// from the project service (WP04 T018, FR-003). Requested by `--show progress`
    /// (or by the `projects` column name), never emitted by default.
    Projects,
    /// The issue's epic references with each epic's progress, weight-aware figure
    /// and blocked count, from the epic service (WP04 T018, FR-003). Requested by
    /// `--show progress` (or by the `epics` column name), never emitted by default.
    Epics,
    /// The issue's resolved category label, from the service (WP04 T019).
    Category,
    /// The issue's **column** usage against its WIP limit, from the shared snapshot
    /// (mission `configurable-wip-limits-01M3C6WX`, WP02). The cell is the column's
    /// count/limit, repeated on each of its rows — a per-row copy is what a table
    /// column is, exactly as `Category` repeats a per-column fact.
    Wip,
    /// 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 issue's health: its own value, with the derived rollup beside it when
    /// its children say something different (`at_risk→unknown`). Read from the one
    /// portable health document (mission `project-issue-health-status-01M3C8HX`,
    /// WP05 T028), so the CLI, the TUI and MCP cannot disagree about a state.
    Health,
}

/// 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 {
    pub(super) fn parse(value: &str) -> Result<Self> {
        match value.to_ascii_lowercase().as_str() {
            "num" => Ok(Self::Num),
            // `hash` is the word the issue that asked for this column used; `id` is
            // the field's own name in the model. Both spellings reach the same
            // column, so neither has to be guessed at.
            "id" | "hash" => Ok(Self::Id),
            "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 T018: the project/health column, per `contracts/cli-surface.md` §3.
            "projects" | "project" => Ok(Self::Projects),
            // WP04 T018: the epic/progress column, per `contracts/cli-surface.md` §3.
            "epics" | "epic" => Ok(Self::Epics),
            // WP04 T019: `--show category`, per `contracts/cli-surface.md` §3.
            "category" => Ok(Self::Category),
            "archived" => Ok(Self::Archived),
            "health" => Ok(Self::Health),
            // WP02 of `configurable-wip-limits-01M3C6WX`.
            "wip" => Ok(Self::Wip),
            _ => Err(TixError::InvalidInput(format!(
                "unknown list column `{value}`; expected one of num,id,title,status,priority,cycle,milestone,reviewer,start,due,overdue,blocked,relations,progress,projects,epics,category,archived,wip,health"
            ))),
        }
    }

    pub(super) fn header(self) -> &'static str {
        match self {
            Self::Num => "NUM",
            Self::Id => "ID",
            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",
            Self::Projects => "PROJECTS",
            Self::Epics => "EPICS",
            // 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",
            Self::Wip => "WIP",
            Self::Health => "HEALTH",
        }
    }

    pub(super) fn cap(self) -> usize {
        match self {
            Self::Num => 6,
            // The canonical id is exactly 8 Crockford base32 characters, so the cap
            // is its width and the column never eats the title's room (#1711).
            Self::Id => 8,
            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,
            // `Platform hardening (p-3f9a2c) 1/4 done, overdue 1, blocked 0, unassigned 2`
            // — one association, so the cell is the visible unit of the column.
            Self::Projects => 60,
            // `Sync hardening (e-3f9a2c) 1/4 done, weighted 3/5 (60%), blocked 1`
            // — one reference, so the cell is the visible unit of the column.
            Self::Epics => 60,
            // 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,
            // `4/5 12/20d!` — the item pair, the estimate pair and the marker.
            Self::Wip => 20,
            // `needs_attention→at_risk` — the two layers, when they disagree.
            Self::Health => 22,
        }
    }
}

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)
}

/// The default column set: `NUM`, `ID`, `TITLE` — one identity pair and the
/// title, nothing else (#1711).
///
/// It used to grow to ten columns as soon as any listed issue carried a cycle,
/// milestone, reviewer or date, which meant the listing's *shape* depended on the
/// data rather than on the request: the same command printed four columns on
/// Monday and ten on Tuesday. The full board is `tix render`, and every column
/// this set dropped is one `--columns` away.
///
/// The archived marker stays conditional for the reason it always was: it is
/// noise on a board that has opted into `--with-archived` but archived nothing.
pub(super) fn default_columns(issues: &[Issue]) -> Vec<ListColumn> {
    let mut columns = vec![ListColumn::Num, ListColumn::Id, ListColumn::Title];
    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.
pub(super) const RELATIONSHIP_COLUMNS: [ListColumn; 2] =
    [ListColumn::Blocked, ListColumn::Relations];

/// Append the columns a `--show` value asks for, in the established order.
///
/// Pure, and separate from `run`, so the column-set shape is pinned by a unit test
/// rather than by a TTY-bound whole-`run` test. `progress` appends the
/// [`ListColumn::Progress`] (`CHILDREN`) column **and** the
/// [`ListColumn::Projects`] column after it (WP04 T018), while naming `progress` in
/// `--columns` requests the `CHILDREN` data alone.
///
/// A column already requested by name is not duplicated, which is why each push
/// checks membership first.
pub(super) fn append_show_columns(columns: &mut Vec<ListColumn>, shows: &[&str]) {
    let mut push = |column: ListColumn| {
        if !columns.contains(&column) {
            columns.push(column);
        }
    };
    if shows.contains(&"relationships") {
        for column in RELATIONSHIP_COLUMNS {
            push(column);
        }
    }
    if shows.contains(&"progress") {
        push(ListColumn::Progress);
        push(ListColumn::Projects);
        // WP04 T018: `--show progress` also carries the epic progress/weight column
        // (`contracts/cli-surface.md` §3), after PROJECTS so both pre-existing columns
        // keep their meaning and position.
        push(ListColumn::Epics);
    }
    if shows.contains(&"category") {
        push(ListColumn::Category);
    }
    if shows.contains(&"wip") {
        push(ListColumn::Wip);
    }
    if shows.contains(&"health") {
        push(ListColumn::Health);
    }
}

/// 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.
pub(super) 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",
            // WP02 of `configurable-wip-limits-01M3C6WX`.
            "wip" => "wip",
            // WP05 T028 of `project-issue-health-status-01M3C8HX`.
            "health" => "health",
            other => {
                return Err(TixError::InvalidInput(format!(
                    "unknown --show value `{other}`; this surface understands \
                     `relationships`, `progress`, `category`, `wip` and `health`"
                )));
            }
        };
        if !out.contains(&known) {
            out.push(known);
        }
    }
    Ok(out)
}

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, None, None, None, None, 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.
// The three derived facts (relationships, hierarchy, WIP) are separate optional maps
// rather than one struct because each is built by a different service and requested
// by a different flag; `run` above carries the same allow for the same reason.
#[allow(clippy::too_many_arguments)]
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>>,
    wip: Option<&crate::wip::WipSnapshot>,
    health: Option<&crate::health::PortableHealth>,
    projects: Option<&BTreeMap<u32, String>>,
    epics: Option<&BTreeMap<u32, String>>,
    project_groups: Option<&BTreeMap<u32, String>>,
    epic_groups: Option<&BTreeMap<u32, String>>,
) -> String {
    let (header, rows) = table_rows(
        issues, columns, resolution, derived, hierarchy, wip, health, projects, epics,
    );
    render_table_from(
        issues,
        columns,
        group,
        resolution,
        width,
        &header,
        &rows,
        project_groups,
        epic_groups,
        false,
    )
}

/// The table's header row and one cell row per issue, in issue order.
///
/// Split out of [`render_table_with`] so `--format` serializes **exactly the cells
/// the table would have shown** rather than a second reading of the same listing:
/// one place builds the cells, so a structured record and a table row cannot
/// disagree about what a column holds (#1711).
#[allow(clippy::too_many_arguments)]
pub(super) fn table_rows(
    issues: &[Issue],
    columns: &[ListColumn],
    resolution: &crate::workflow::CategoryResolution,
    derived: Option<&BTreeMap<u32, RelationshipCells>>,
    hierarchy: Option<&BTreeMap<u32, String>>,
    wip: Option<&crate::wip::WipSnapshot>,
    health: Option<&crate::health::PortableHealth>,
    projects: Option<&BTreeMap<u32, String>>,
    epics: Option<&BTreeMap<u32, String>>,
) -> (Vec<String>, Vec<Vec<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, wip, health,
                        projects, epics,
                    )
                })
                .collect()
        })
        .collect();
    let header = columns
        .iter()
        .map(|column| column.header().to_string())
        .collect();
    (header, rows)
}

/// Render [`table_rows`] output: column widths, the group sections, and the
/// padding that lands every line exactly on `width`.
///
/// `truncate` is the **compact** mode `tix list` renders in — one physical line per
/// issue, a cell that does not fit cropped rather than wrapped (#1711). Wrapping
/// stays the default for a caller that named eight columns by hand, which is not
/// the caller who asked for one line per issue.
#[allow(clippy::too_many_arguments)]
pub(super) fn render_table_from(
    issues: &[Issue],
    columns: &[ListColumn],
    group: Option<&str>,
    resolution: &crate::workflow::CategoryResolution,
    width: usize,
    header: &[String],
    rows: &[Vec<String>],
    project_groups: Option<&BTreeMap<u32, String>>,
    epic_groups: Option<&BTreeMap<u32, String>>,
    truncate: bool,
) -> String {
    let natural: Vec<usize> = columns
        .iter()
        .enumerate()
        .map(|(index, column)| {
            // A crop needs a width to crop *to*. With no terminal, the compact
            // listing prints the whole title on one line rather than cutting it at
            // the column's cap, so `tix list | grep` keeps every word (#1711).
            let cap = if truncate && width == 0 && *column == ListColumn::Title {
                usize::MAX
            } else {
                column.cap()
            };
            rows.iter()
                .map(|row| display_width(&row[index]))
                .chain(std::iter::once(display_width(column.header())))
                .max()
                .unwrap_or(1)
                .min(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());
    // The title column takes whatever is left, so every other column leaves it room
    // for at least one column — but only when there **is** a title to leave room
    // for. The reservation used to be unconditional, which cost the last column a
    // character on a table with no title at all (`--columns num,id`), and in the
    // compact mode that character is a cropped cell rather than padding (#1711).
    let title = columns
        .iter()
        .position(|column| *column == ListColumn::Title);
    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(usize::from(title.is_some())));
        widths[index] = take.max(1);
        remaining = remaining.saturating_sub(widths[index]);
    }
    if let Some(title) = title {
        widths[title] = remaining;
    }
    let line_width = width;
    let mut out = String::new();
    render_row(&mut out, header, &widths, line_width, truncate);
    if let Some(group) = group.filter(|group| {
        *group == "cycle"
            || *group == "milestone"
            || (*group == "project" && project_groups.is_some())
            || (*group == "epic" && epic_groups.is_some())
    }) {
        let mut progress: BTreeMap<String, (usize, usize)> = BTreeMap::new();
        for issue in issues {
            let key = group_key(issue, group, project_groups, epic_groups);
            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();
        // `rows` is `issues`'s own cell row, index for index (both come from
        // [`table_rows`]), so walking them together is what keeps a group heading
        // attached to the rows under it. This used to re-find each row with a
        // pointer-equality scan, which is quadratic on a board of a thousand
        // issues and said nothing a zip does not.
        for (issue, row) in issues.iter().zip(rows) {
            let key = group_key(issue, group, project_groups, epic_groups);
            if current != key {
                current = key.clone();
                let (done, total) = progress.get(&key).copied().unwrap_or((0, 0));
                let pct = (done * 100).checked_div(total).unwrap_or(0);
                out.push_str(&format!(
                    "-- {group}: {key} ({done}/{total} done, {pct}%) --\n"
                ));
            }
            render_row(&mut out, row, &widths, line_width, truncate);
        }
    } else {
        for row in rows {
            render_row(&mut out, row, &widths, line_width, truncate);
        }
    }
    out
}

pub(super) fn render_row(
    out: &mut String,
    cells: &[String],
    widths: &[usize],
    line_width: usize,
    truncate: bool,
) {
    if truncate {
        // The compact mode: every cell cut to its column, so the row is exactly one
        // physical line and the issue below it starts on the next one (#1711).
        let values: Vec<String> = cells
            .iter()
            .zip(widths)
            .map(|(cell, width)| truncate_cell(cell, *width))
            .collect();
        for (index, value) in values.iter().enumerate() {
            if index > 0 {
                out.push_str("  ");
            }
            out.push_str(value);
            out.push_str(&" ".repeat(widths[index].saturating_sub(display_width(value))));
        }
        let padding = line_width
            .saturating_sub(separator_width(values.len()))
            .saturating_sub(widths.iter().sum::<usize>());
        out.push_str(&" ".repeat(padding));
        out.push('\n');
        return;
    }
    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');
    }
}

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

/// [`wrap_cell`]'s single-line twin: the value cut to `width`, with an ellipsis
/// when anything was dropped.
///
/// The ellipsis is the point. A silently cut title reads as the issue's real title,
/// and the truncation marker is the only thing that says otherwise without spending
/// a second line on it.
pub(super) fn truncate_cell(value: &str, width: usize) -> String {
    if width == 0 {
        return String::new();
    }
    if display_width(value) <= width {
        return value.to_string();
    }
    let mut out = String::new();
    let mut used = 0usize;
    for character in value.chars() {
        let character_width = UnicodeWidthChar::width(character).unwrap_or(0);
        // One column is held back for the ellipsis, so the result fits `width`
        // exactly rather than `width + 1`.
        if used + character_width + 1 > width {
            break;
        }
        out.push(character);
        used += character_width;
    }
    // A cut that landed just after a space would otherwise print `word …`.
    let trimmed = out.trim_end().len();
    out.truncate(trimmed);
    out.push('…');
    out
}

/// 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)]
pub(super) fn cell(
    column: ListColumn,
    issue: &Issue,
    resolution: &crate::workflow::CategoryResolution,
    today: &str,
    derived: Option<&RelationshipCells>,
    hierarchy: Option<&BTreeMap<u32, String>>,
    wip: Option<&crate::wip::WipSnapshot>,
    health: Option<&crate::health::PortableHealth>,
    projects: Option<&BTreeMap<u32, String>>,
    epics: Option<&BTreeMap<u32, String>>,
) -> String {
    match column {
        ListColumn::Num => issue.number.to_string(),
        // `-` for an issue written before the id schema (the field is optional so
        // those files keep parsing), never a blank cell: beside other blank cells it
        // would read as a rendering gap rather than as "this issue has no id yet".
        ListColumn::Id => issue.id.clone().unwrap_or_else(|| "-".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(),
        },
        // A `-` for an issue in no project, matching the `CHILDREN` placeholder: an
        // empty cell beside other empty cells reads as a rendering gap rather than
        // as "this issue is in no project". A reference that no longer resolves is
        // **not** blanked — `project_cells` renders its recorded id — so the two
        // states stay distinguishable (T018 step 5).
        ListColumn::Projects => match projects.and_then(|cells| cells.get(&issue.number)) {
            Some(text) if !text.is_empty() => text.clone(),
            _ => "-".to_string(),
        },
        // A `-` for an issue in no epic, matching the PROJECTS/CHILDREN placeholder.
        // The cell text is built by the shared service read (`view::epic_cells`), so a
        // row can never report a figure that disagrees with `tix show` (C-008). A
        // reference that no longer resolves renders its recorded id, so the two
        // empty-looking cases stay distinguishable (T018 step 5).
        ListColumn::Epics => match epics.and_then(|cells| cells.get(&issue.number)) {
            Some(text) if !text.is_empty() => text.clone(),
            _ => "-".to_string(),
        },
        // The issue's own value, and the derived rollup beside it when the two
        // differ: a parent whose children are at risk reads `unknown→at_risk`, so the
        // cell never hides a derived layer that says something the current one does
        // not. Both values come from the document, never from a local formula.
        ListColumn::Health => health
            .and_then(|document| {
                document.scope(&crate::health::HealthScope::of_issue(issue.number))
            })
            .map(|entry| match entry.rollup.as_ref() {
                Some(derived) if entry.state != derived.state => {
                    format!("{}→{}", entry.state, derived.state)
                }
                _ => entry.state.clone(),
            })
            .unwrap_or_else(|| "-".to_string()),
        ListColumn::Archived => {
            if issue.archived {
                "ARCHIVED".to_string()
            } else {
                "-".to_string()
            }
        }
        // WP02 of `configurable-wip-limits-01M3C6WX`: the **column's** usage against
        // its limit, from the one shared snapshot. A column with no limit is `-`
        // rather than an empty cell, for the reason `Blocked` gives: an empty cell
        // beside other empty cells reads as a rendering gap, not as "no limit here".
        //
        // The snapshot is the one the surface was built from, so a row can never
        // report figures that disagree with the column's own heading count.
        ListColumn::Wip => wip
            .and_then(|snapshot| snapshot.column(issue.status.display()))
            .filter(|usage| usage.limit.is_some())
            .map_or_else(|| "-".to_string(), crate::wip::ColumnUsage::cell),
    }
}

pub(super) 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
}

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

/// The structured formats `tix list --format` writes (#1711).
///
/// Deliberately without JSON. The listing's JSON spelling is its own piece of work,
/// and a `--format` that quietly grew a fourth arm would be a machine contract
/// nobody reviewed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ListFormat {
    Xml,
    Yaml,
    Toml,
}

impl ListFormat {
    pub(super) fn parse(value: &str) -> Result<Self> {
        match value.to_ascii_lowercase().as_str() {
            "xml" => Ok(Self::Xml),
            "yml" | "yaml" => Ok(Self::Yaml),
            "toml" => Ok(Self::Toml),
            other => Err(TixError::InvalidInput(format!(
                "unknown list format `{other}`; this surface understands `xml`, `yml` and `toml`"
            ))),
        }
    }
}

/// Serialize a listing as records: one record per issue, keyed by the **displayed
/// columns** (#1711).
///
/// The input is [`table_rows`]' own output, so `--format` and the table are two
/// renderings of one listing — `--columns` selects a column once, for both, and a
/// derived column (`blocked`, `children`, `health`) carries the service's value into
/// the structured form rather than a `-`.
///
/// Group sections are a plain-text affordance and are **not** part of a record, so
/// `--format` renders a flat sequence however `--group` was spelled.
pub(super) fn render_records(
    header: &[String],
    rows: &[Vec<String>],
    format: ListFormat,
) -> Result<String> {
    let records: Vec<IndexMap<String, String>> = rows
        .iter()
        .map(|row| {
            header
                .iter()
                .zip(row)
                .map(|(column, value)| (column.to_ascii_lowercase(), value.clone()))
                .collect()
        })
        .collect();
    // `issues` is the document's one root key, so the three formats agree about the
    // shape a consumer parses: a list of records under one name.
    let document = IndexMap::from([("issues".to_string(), records)]);
    match format {
        ListFormat::Xml => Ok(render_xml(&document["issues"])),
        ListFormat::Yaml => serde_yaml::to_string(&document)
            .map_err(|error| TixError::InvalidInput(format!("could not render yaml: {error}"))),
        ListFormat::Toml => toml::to_string(&document)
            .map_err(|error| TixError::InvalidInput(format!("could not render toml: {error}"))),
    }
}

/// The XML spelling: `<issues><issue><column>value</column>…</issue></issues>`.
///
/// Hand-written because the document is flat and its keys are the column headers —
/// bringing in a serializer for five element kinds would buy nothing but a
/// dependency. Values are escaped, so a title containing `<` cannot produce a
/// document that no parser will read.
pub(super) fn render_xml(records: &[IndexMap<String, String>]) -> String {
    let mut out = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<issues>\n");
    for record in records {
        out.push_str("  <issue>\n");
        for (column, value) in record {
            out.push_str("    <");
            out.push_str(column);
            out.push('>');
            out.push_str(&escape_xml(value));
            out.push_str("</");
            out.push_str(column);
            out.push_str(">\n");
        }
        out.push_str("  </issue>\n");
    }
    out.push_str("</issues>\n");
    out
}

pub(super) fn escape_xml(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for character in value.chars() {
        match character {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            _ => out.push(character),
        }
    }
    out
}

/// 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.
///
/// It renders in the CLI's **compact** mode, for the same reason: `list_issues`
/// carries `tix list`'s text, so it has to be the same text — including the crop
/// rule, which is a no-op at the zero width a caller passes when there is no
/// terminal to crop to (#1711).
pub fn render_default_table(
    issues: &[Issue],
    group: Option<&str>,
    resolution: &crate::workflow::CategoryResolution,
    width: usize,
) -> String {
    let columns = default_columns(issues);
    let (header, rows) = table_rows(
        issues, &columns, resolution, None, None, None, None, None, None,
    );
    render_table_from(
        issues, &columns, group, resolution, width, &header, &rows, None, None, true,
    )
}