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
//! `tix parent show|children|list`: the CLI hierarchy reports.
//!
//! Every figure here comes from [`crate::hierarchy`]'s typed values. Nothing here
//! recomputes a count, a percentage, or a completion figure — a surface that
//! derives its own numbers is how `tix parent show`, the TUI detail block (WP04) and
//! the MCP read tools (WP07) end up disagreeing about the same issue, which is the
//! divergence `contracts/surface-parity.md` §3 exists to prevent.
//!
//! The rendering is factored as pure `*_text` functions beside the `println!`
//! loops, for the same reason `link::listing_text` is: WP07 needs these exact
//! strings in a protocol response, and two renderers would be two formats. One
//! renderer, two callers.

use crate::cli::ParentAction;
use crate::commands::parse_selector;
use crate::error::{Result, TixError};
use crate::hierarchy::{self, HierarchyIndex, ParentRollup};
use crate::model::Issue;
use crate::relationships::IssueView;
use crate::storage::Store;

/// `tix parent <action>`.
pub fn run(store: &Store, action: &ParentAction) -> Result<()> {
    match action {
        ParentAction::Show { issue } => show(store, issue),
        ParentAction::Children { issue } => children(store, issue),
        ParentAction::List => list(store),
    }
}

/// The snapshot both reports read: the issue set plus the board's configured
/// completion column, which the rollup needs and which is a parameter rather than
/// a literal `"done"` so a renamed completion column still reports correctly.
pub fn source(store: &Store) -> Result<(HierarchyIndex, Vec<Issue>, String)> {
    let (issues, done_column) = store.graph_source()?;
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    Ok((HierarchyIndex::build(&views), issues, done_column))
}

/// The display label for an issue, or a clear stand-in when the number resolves to
/// nothing in the snapshot.
fn label(issues: &[Issue], number: u32) -> String {
    match issues.iter().find(|i| i.number == number) {
        Some(issue) => hierarchy::display_label(issue.number, &issue.title),
        None => format!("#{number}"),
    }
}

// ---------------------------------------------------------------------------
// The shared hierarchy read, for the surfaces that are not `tix parent`
// ---------------------------------------------------------------------------

/// The hierarchy facts every surface renders, as **typed values**.
///
/// One producer for `tix show` (T016), `tix list --show progress` (T017) and the
/// TUI (T018), so the three cannot describe different snapshots of the same issue.
/// A surface that recomputes a child count or a rollup here is exactly the boundary
/// breach `contracts/surface-parity.md` §3 forbids.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HierarchyFacts {
    /// The issue these facts describe.
    pub number: u32,
    /// The recorded parent, or `None`. A parent that is recorded but absent from
    /// the snapshot is still `Some` — the reference is kept for repair, so hiding
    /// it would destroy the only record that the decomposition existed.
    pub parent: Option<u32>,
    /// The canonical parent reference as stored.
    pub parent_ref: Option<crate::id::IssueRef>,
    /// Why that reference cannot be resolved, when it cannot be.
    pub unresolved_reason: Option<String>,
    /// The parent line, already resolved to a display label.
    pub parent_label: String,
    /// Direct children, ordered by issue number.
    pub children: Vec<hierarchy::ChildRef>,
    /// The rollup, from the service.
    pub rollup: ParentRollup,
}

impl HierarchyFacts {
    /// Whether the recorded parent is not in the snapshot.
    pub fn is_unresolved(&self) -> bool {
        self.unresolved_reason.is_some()
    }

    /// Whether the issue has any direct children.
    pub fn has_children(&self) -> bool {
        !self.children.is_empty()
    }

    /// The `children: N` line, in the service's own singular/plural wording.
    pub fn child_count_line(&self) -> String {
        match self.rollup.direct_children {
            1 => "children: 1".to_string(),
            n => format!("children: {n}"),
        }
    }

    /// The rollup line, naming the basis so the figure cannot be misread.
    ///
    /// The `only` is load-bearing: `CompletionBasis::as_str()` is `"direct
    /// children"`, which describes the population but not the **exclusivity**, and
    /// the exclusivity is the whole point of the basis (data-model.md §3.1). A
    /// reader who sees `completed: 12/40 (direct children)` has to know the reading
    /// rules; one who sees `(direct children only)` does not.
    pub fn completion_line(&self) -> String {
        format!(
            "completed: {}/{} ({} only)",
            self.rollup.completed_children,
            self.rollup.progress.total,
            self.rollup.completion_basis.as_str()
        )
    }
}

/// Build the facts for `number` from an issue set and a completion column.
///
/// The same shape as `commands::graph_over`, which the TUI already calls for the
/// relationship graph: a caller that already has the issue set and the configured
/// column gets the hierarchy facts without re-reading the store. Used by the TUI's
/// two detail-opening paths, which build the relationship graph the same way.
pub fn facts_over(issues: &[Issue], done_column: &str, number: u32) -> HierarchyFacts {
    let index = index_over(issues);
    facts_for(&index, issues, number, done_column)
}

/// The hierarchy index over an issue set.
pub fn index_over(issues: &[Issue]) -> HierarchyIndex {
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    HierarchyIndex::build(&views)
}

/// Read the hierarchy facts for `number` from one snapshot.
pub fn facts_for(
    index: &HierarchyIndex,
    issues: &[Issue],
    number: u32,
    done_column: &str,
) -> HierarchyFacts {
    let parent = index.parent_of(number);
    let parent_ref = index.parent_ref_of(number).copied();
    // The unresolved reason comes from the service, verbatim, so a surface cannot
    // invent its own wording for a condition two other surfaces describe.
    let unresolved_reason = parent_ref
        .filter(|reference| !index.contains_ref(reference))
        .map(|reference| hierarchy::unresolved_reason(number, reference));
    let parent_label = match (parent_ref, parent) {
        (Some(_reference), Some(p)) if index.contains(p) => label(issues, p),
        (Some(reference), _) if index.contains_ref(&reference) => reference.to_string(),
        (Some(reference), _) => format!("{reference} (missing)"),
        (None, _) => "none".to_string(),
    };
    let children = index.children_of(number).children;
    let rollup = hierarchy::rollup(index, number, done_column);
    HierarchyFacts {
        number,
        parent,
        parent_ref,
        unresolved_reason,
        parent_label,
        children,
        rollup,
    }
}

// ---------------------------------------------------------------------------
// `tix parent show <selector>`
// ---------------------------------------------------------------------------

fn show(store: &Store, raw: &str) -> Result<()> {
    let (index, issues, done_column) = source(store)?;
    let number = store.get(parse_selector(store, raw)?)?.number;
    println!("{}", show_text(&index, &issues, number, &done_column)?);
    Ok(())
}

/// The `parent show` report, as one string.
///
/// Errors when the selector names an issue absent from the snapshot, which is a
/// genuine inconsistency rather than an empty hierarchy: the store resolved it, so
/// it was in the file set a moment ago.
pub fn show_text(
    index: &HierarchyIndex,
    issues: &[Issue],
    number: u32,
    done_column: &str,
) -> Result<String> {
    if !index.contains(number) {
        return Err(TixError::NotFound(format!(
            "issue #{number} is not in the current snapshot"
        )));
    }
    Ok(render_show(&facts_for(index, issues, number, done_column)))
}

/// The report body. Pure, so a test can compare it without a store.
fn render_show(facts: &HierarchyFacts) -> String {
    let mut out = String::new();
    out.push_str(&format!("Parent of #{}\n", facts.number));
    out.push_str(&format!("  parent: {}\n", parent_line(facts)));
    out.push_str(&format!("  {}\n", facts.child_count_line()));
    out.push_str(&format!("  {}\n", facts.completion_line()));
    out.push_str("Children\n");
    if facts.children.is_empty() {
        out.push_str(&format!("  {}\n", empty_children_text(facts.number)));
    } else {
        for child in &facts.children {
            out.push_str(&format!("  {}\n", child.display));
        }
    }
    out.trim_end_matches('\n').to_string()
}

/// The parent line, as one string, for surfaces that are not `tix parent show`.
///
/// `pub` so the TUI detail pane and the `tix show` block cannot word the same
/// condition differently — particularly the unresolved case, where the service's
/// `reason` is the authority (T016 step 3).
pub fn parent_text(facts: &HierarchyFacts) -> String {
    parent_line(facts)
}

/// The parent line, naming the shape of the answer and the issue.
///
/// A reference to an issue that is gone is reported as such rather than as "no
/// parent": the two are different states, and only one of them is a problem
/// (data-model.md §5). The reason is the service's own text, verbatim.
fn parent_line(facts: &HierarchyFacts) -> String {
    match &facts.unresolved_reason {
        Some(reason) => format!("{} — {}", facts.parent_label, reason),
        None if facts.parent_ref.is_some() => facts.parent_label.clone(),
        None => "none".to_string(),
    }
}

/// The one wording for "this issue has no children", shared by every surface.
///
/// `pub` because the TUI detail pane needs the same sentence as the two CLI
/// reports, and a second wording for one condition is a divergence the mission
/// escalates.
pub fn no_children_text(number: u32) -> String {
    empty_children_text(number)
}

fn empty_children_text(number: u32) -> String {
    format!("No children for #{number}")
}

// ---------------------------------------------------------------------------
// `tix parent children <selector>`
// ---------------------------------------------------------------------------

fn children(store: &Store, raw: &str) -> Result<()> {
    let (index, _, _) = source(store)?;
    let number = store.get(parse_selector(store, raw)?)?.number;
    println!("{}", children_text(&index, number)?);
    Ok(())
}

/// The `parent children` report, as one string. Direct children only, ordered by
/// issue number — the ordering the index guarantees, not a re-sort here.
pub fn children_text(index: &HierarchyIndex, number: u32) -> Result<String> {
    if !index.contains(number) {
        return Err(TixError::NotFound(format!(
            "issue #{number} is not in the current snapshot"
        )));
    }
    let membership = index.children_of(number);
    // The child rows come from `ChildRef::display`, which the index already
    // derived from the same snapshot. Re-deriving them here from `issues` would be
    // a second renderer for the same label.
    Ok(render_children(number, &membership.children))
}

fn render_children(number: u32, children: &[hierarchy::ChildRef]) -> String {
    if children.is_empty() {
        return empty_children_text(number);
    }
    children
        .iter()
        .map(|c| c.display.clone())
        .collect::<Vec<_>>()
        .join("\n")
        + &format!("\n{}", count_suffix(children.len()))
}

fn count_suffix(n: usize) -> String {
    match n {
        1 => "1 child".to_string(),
        k => format!("{k} children"),
    }
}

// ---------------------------------------------------------------------------
// The `tix show` block (WP04 / T016)
// ---------------------------------------------------------------------------

/// The hierarchy block appended to `tix show`'s output.
///
/// Markdown, matching the `--show relationships` block beside it: both are
/// appended to the issue file, so both are markdown rather than a column layout.
///
/// **The same facts in the same order as `tix parent show`**, which is the parity
/// contract. The figures are not recomputed here — they arrive in the
/// [`HierarchyFacts`] — so the two reports cannot disagree about a snapshot.
pub fn detail_block(facts: &HierarchyFacts) -> String {
    let mut out = String::new();
    out.push_str("\n## Hierarchy\n\n");
    out.push_str(&format!("- parent: {}\n", parent_line(facts)));
    out.push_str(&format!("- {}\n", facts.child_count_line()));
    out.push_str(&format!("- {}\n", facts.completion_line()));
    out.push_str("children:\n");
    if facts.children.is_empty() {
        // An explicit empty state, not an empty heading — T016 step 5.
        out.push_str(&format!("  - {}\n", empty_children_text(facts.number)));
    } else {
        for child in &facts.children {
            out.push_str(&format!("  - {}\n", child.display));
        }
    }
    out
}

// ---------------------------------------------------------------------------
// `tix parent list`
// ---------------------------------------------------------------------------

fn list(store: &Store) -> Result<()> {
    let (index, issues, done_column) = source(store)?;
    println!("{}", list_text(&index, &issues, &done_column));
    Ok(())
}

/// The `parent list` report, as one string: one line per issue that **has**
/// children. An issue with none is not reported, because the report is "the
/// hierarchy", and a board where every leaf is listed as a parent is a list
/// nobody reads.
///
/// Columns are padded to the widest cell, matching `tix list` and `tix link list`:
/// a hierarchy list is read by scanning, and ragged columns are what make scanning
/// slow.
pub fn list_text(index: &HierarchyIndex, issues: &[Issue], done_column: &str) -> String {
    // Sorted by issue number, and sorted on the **numbers** rather than on the
    // rendered rows. Sorting the formatted string would mean re-parsing a number
    // back out of `#<n> <title>`, which breaks the moment a title contains a `#`.
    let mut rows: Vec<(u32, String, String, String)> = Vec::new();
    for issue in issues {
        let membership = index.children_of(issue.number);
        if membership.child_count == 0 {
            continue;
        }
        let rollup = hierarchy::rollup(index, issue.number, done_column);
        rows.push((
            issue.number,
            label(issues, issue.number),
            count_suffix(membership.child_count),
            format!("{}/{}", rollup.completed_children, rollup.progress.total),
        ));
    }
    if rows.is_empty() {
        return "No issues have children".to_string();
    }
    rows.sort_by_key(|(number, ..)| *number);
    let headers = ["ISSUE", "CHILDREN", "COMPLETED"];
    let body: Vec<[String; 3]> = rows
        .iter()
        .map(|(_, label, children, completed)| [label.clone(), children.clone(), completed.clone()])
        .collect();
    aligned_table(&headers, &body)
}

/// Lay out a header and rows in aligned columns, two spaces between columns and
/// no trailing whitespace — the shape `tix list` and `tix link list` already use.
///
/// Two spaces rather than one because a one-space gutter is ambiguous when a column
/// is empty; trailing spaces are trimmed so a line's content is what `wc -l` and a
/// test comparison see.
fn aligned_table(headers: &[&str], rows: &[[String; 3]]) -> String {
    let mut widths = [0usize; 3];
    for (i, header) in headers.iter().enumerate() {
        widths[i] = widths[i].max(header.chars().count());
    }
    for row in rows {
        for (i, cell) in row.iter().enumerate() {
            widths[i] = widths[i].max(cell.chars().count());
        }
    }
    let render = |cells: [&str; 3]| {
        let mut parts: Vec<String> = Vec::with_capacity(3);
        for (i, cell) in cells.iter().enumerate() {
            // The last column is not padded, so nothing trails whitespace.
            if i == 2 {
                parts.push((*cell).to_string());
            } else {
                parts.push(format!("{cell:<width$}", width = widths[i]));
            }
        }
        parts.join("  ")
    };
    let mut out = render([headers[0], headers[1], headers[2]]);
    for row in rows {
        out.push('\n');
        out.push_str(&render([&row[0], &row[1], &row[2]]));
    }
    out
}

#[cfg(test)]
mod tests {
    // T013 — the hierarchy reports, at the renderer level so no store is needed,
    // plus a store-backed test for the selector path.
    //
    // The pure `*_text` functions are what these exercise, which is the point of
    // having them: a report's exact bytes are assertable without a temp directory,
    // and WP07 will consume the same functions for its protocol responses, so a
    // change to the format is a change to both surfaces at once.

    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::{Priority, Status};

    fn issue(number: u32, title: &str, status: &str, parent: Option<u32>) -> Issue {
        Issue {
            number,
            title: title.into(),
            status: Status::new(status),
            labels: vec![],
            priority: Priority::Medium,
            files: vec![],
            parent: parent.map(crate::id::IssueRef::Number),
            epics: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            ..make_issue(title)
        }
    }

    /// A minimal `Issue` with the required non-default fields, so the tests above
    /// can state only what they are about.
    fn make_issue(title: &str) -> Issue {
        Issue {
            number: 0,
            title: title.into(),
            status: Status::new("todo"),
            labels: vec![],
            priority: Priority::Medium,
            created: "2026-01-01".into(),
            updated: "2026-01-01".into(),
            ..Issue::parse(
                "---\nnumber: 0\ntitle: t\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nB.",
            )
            .unwrap()
        }
    }

    fn index(issues: &[Issue]) -> HierarchyIndex {
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        HierarchyIndex::build(&views)
    }

    #[test]
    fn t013_show_reports_parent_children_count_and_rollup() {
        let issues = vec![
            issue(1, "Epic", "todo", None),
            issue(2, "Task A", "done", Some(1)),
            issue(3, "Task B", "todo", Some(1)),
        ];
        let index = index(&issues);
        let text = show_text(&index, &issues, 1, "done").unwrap();
        assert_eq!(
            text,
            "Parent of #1\n  parent: none\n  children: 2\n  completed: 1/2 (direct children only)\nChildren\n  #2 Task A\n  #3 Task B",
        );
    }

    #[test]
    fn t013_show_handles_an_issue_with_neither_parent_nor_children() {
        let issues = vec![issue(1, "Alone", "todo", None)];
        let index = index(&issues);
        let text = show_text(&index, &issues, 1, "done").unwrap();
        assert!(text.contains("parent: none"), "{text}");
        assert!(text.contains("children: 0"), "{text}");
        assert!(text.contains("completed: 0/0"), "{text}");
        // The empty case is named, not printed as nothing.
        assert!(text.contains("No children for #1"), "{text}");
    }

    #[test]
    fn t013_show_reports_a_leaf_that_has_a_parent() {
        let issues = vec![
            issue(1, "Epic", "todo", None),
            issue(2, "Leaf", "todo", Some(1)),
        ];
        let index = index(&issues);
        let text = show_text(&index, &issues, 2, "done").unwrap();
        assert!(text.contains("parent: #1 Epic"), "{text}");
        assert!(text.contains("children: 0"), "{text}");
        assert!(text.contains("No children for #2"), "{text}");
    }

    #[test]
    fn t013_show_marks_a_dangling_parent_as_missing_rather_than_as_none() {
        // A reference to an issue that is gone is a *different state* from having
        // no parent, and only one of them is a problem (data-model.md §5).
        let issues = vec![issue(1, "Orphan", "todo", Some(999))];
        let index = index(&issues);
        let text = show_text(&index, &issues, 1, "done").unwrap();
        // The service's own reason, verbatim — T016 step 3 requires it, and two
        // surfaces inventing their own wording for one condition is the
        // divergence the mission exists to prevent. Asserted against
        // `unresolved_reason`'s output rather than a hand-copied sentence.
        let expected = crate::hierarchy::unresolved_reason(1, 999);
        assert!(
            text.contains(&expected),
            "expected {expected:?} in:\n{text}"
        );
        assert!(
            text.contains("#999"),
            "the recorded reference must stay visible so it can be repaired: {text}"
        );
        assert!(
            !text.contains("parent: none"),
            "a dangling reference must not read as no parent: {text}"
        );
    }

    #[test]
    fn t013_children_lists_direct_children_ordered_by_issue_number() {
        // Deliberately seeded out of order, and with a grandchild present, so the
        // ordering guarantee and the direct-only scope are both load-bearing.
        let issues = vec![
            issue(3, "Third", "todo", Some(1)),
            issue(1, "Epic", "todo", None),
            issue(4, "Grandchild", "todo", Some(3)),
            issue(2, "Second", "todo", Some(1)),
        ];
        let index = index(&issues);
        assert_eq!(
            children_text(&index, 1).unwrap(),
            "#2 Second\n#3 Third\n2 children",
            "ordered by issue number, and the grandchild is not listed"
        );
    }

    #[test]
    fn t013_children_names_the_empty_case() {
        let issues = vec![issue(1, "Alone", "todo", None)];
        let index = index(&issues);
        assert_eq!(children_text(&index, 1).unwrap(), "No children for #1");
    }

    #[test]
    fn t013_children_singular_wording_for_exactly_one() {
        let issues = vec![issue(1, "P", "todo", None), issue(2, "C", "todo", Some(1))];
        let index = index(&issues);
        let text = children_text(&index, 1).unwrap();
        assert!(text.ends_with("1 child"), "{text}");
        assert!(!text.contains("1 children"), "{text}");
    }

    #[test]
    fn t013_list_reports_only_issues_that_have_children() {
        let issues = vec![
            issue(1, "Epic", "todo", None),
            issue(2, "Child", "done", Some(1)),
            issue(3, "Lonely", "todo", None),
        ];
        let index = index(&issues);
        let text = list_text(&index, &issues, "done");
        assert!(text.starts_with("ISSUE"), "{text}");
        assert!(text.contains("#1 Epic"), "{text}");
        assert!(
            !text.contains("Lonely"),
            "an issue with no children is not a parent: {text}"
        );
        // #2 is `done`, so the service's rollup is 1/1. Asserting `0/1` here —
        // which the first version of this test did — would have passed for a
        // service that reported nothing as complete.
        assert!(
            text.contains("1/1"),
            "the rollup comes from the service: {text}"
        );
    }

    #[test]
    fn t013_list_names_the_empty_board() {
        let issues = vec![issue(1, "Alone", "todo", None)];
        let index = index(&issues);
        assert_eq!(
            list_text(&index, &issues, "done"),
            "No issues have children"
        );
    }

    #[test]
    fn t013_list_columns_are_aligned_and_never_trailing_space() {
        let issues = vec![
            issue(1, "A very long epic title indeed", "todo", None),
            issue(2, "x", "todo", Some(1)),
            issue(3, "A middling one", "done", Some(1)),
        ];
        let index = index(&issues);
        let text = list_text(&index, &issues, "done");
        for line in text.lines() {
            assert_eq!(line, line.trim_end(), "trailing whitespace: {line:?}");
        }
        // Alignment is asserted on the **cell text**, located at its own offset in
        // each row. The first version sliced every row at the header's `CHILDREN`
        // offset and asserted the result began with a letter — which fails on a
        // correctly aligned table whose cell starts with a digit, and would have
        // passed on a misaligned one whose cell happened to start with a letter.
        let header = text.lines().next().unwrap();
        let header_at = header.find("CHILDREN").unwrap();
        let expected: [(&str, &str); 3] = [
            ("2 children", "#1 A very long epic title indeed"),
            ("1 child", "#2 x"),
            ("1 child", "#3 A middling one"),
        ];
        for (line, (children, label)) in text.lines().skip(1).zip(expected) {
            assert!(line.starts_with(label), "row lost its label: {line:?}");
            let at = line
                .find(children)
                .unwrap_or_else(|| panic!("row {line:?} has no children cell {children:?}"));
            assert_eq!(
                at, header_at,
                "the CHILDREN cell starts at {at} in {line:?} but at {header_at} in the header"
            );
        }
    }

    #[test]
    fn t013_list_is_ordered_by_issue_number_even_when_titles_contain_a_hash() {
        // The earlier implementation sorted the *rendered* rows, which meant
        // re-parsing a number out of `#<n> <title>`. A title with a `#` in it
        // broke that. Sorted on the numbers instead.
        let issues = vec![
            issue(3, "release #7 notes", "todo", Some(1)),
            issue(1, "root", "todo", None),
            issue(2, "#99 decoy", "todo", Some(1)),
        ];
        let index = index(&issues);
        let text = list_text(&index, &issues, "done");
        let order: Vec<&str> = text.lines().skip(1).collect();
        assert_eq!(order.len(), 1, "only the root is a parent: {text}");
        assert!(order[0].starts_with("#1 root"), "{text}");
    }

    #[test]
    fn t013_show_and_children_error_on_an_issue_absent_from_the_snapshot() {
        let issues = vec![issue(1, "Present", "todo", None)];
        let index = index(&issues);
        assert!(show_text(&index, &issues, 404, "done").is_err());
        assert!(children_text(&index, 404).is_err());
    }
}