tix-tracker 0.8.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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
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 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 {
    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 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,title,status,priority,cycle,milestone,reviewer,start,due,overdue,blocked,relations,progress,projects,epics,category,archived,wip,health"
            ))),
        }
    }

    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",
            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",
        }
    }

    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,
            // `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)
}

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>,
    project: Option<&str>,
    epic: 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 mut issues = query(store, status, filter, with_archived)?;
    // `--project <reference>` is applied with the **same** membership predicate
    // `tix search "project:<id>"` uses ([`crate::search::StructuredFilter::project_matches`]),
    // but the reference is resolved to its stable id **here** rather than spliced
    // into the `--filter` string. An id never contains whitespace, so resolution
    // keeps a multi-word display name (`--project "Platform hardening"`) from being
    // split into `project:Platform` plus a stray haystack term — which silently
    // returned an empty listing with no diagnostic. An unknown reference is kept
    // verbatim and matches nothing, exactly as the criterion documents (WP09 item D).
    if let Some(project) = project {
        let reference = crate::projects::resolve_project_id(&store.config, project)
            .map_or_else(|_| project.to_string(), |id| id.to_string());
        let criterion = crate::search::StructuredFilter {
            project: Some(reference),
            ..crate::search::StructuredFilter::default()
        };
        issues.retain(|issue| criterion.project_matches(issue));
    }
    // `--epic <reference>` is the epic twin of `--project`: the **same** membership
    // predicate `tix search "epic:<id>"` uses ([`crate::search::StructuredFilter::epic_matches`]),
    // resolved to its stable id here so a multi-word display name is not split into
    // `epic:Platform` plus a stray haystack term (which silently returned an empty
    // listing). An unknown reference is kept verbatim and matches nothing, so a typo
    // yields a visible empty listing rather than a silent unfiltered one (T029 step
    // 6, WP09 item C).
    if let Some(epic) = epic {
        let reference = crate::epics::dereference_needle(&store.config.epics, epic);
        let criterion = crate::search::StructuredFilter {
            epic: Some(reference),
            ..crate::search::StructuredFilter::default()
        };
        issues.retain(|issue| criterion.epic_matches(issue));
    }
    let sort_key = sort
        .map(str::to_string)
        .or_else(|| filter.and_then(|q| control_token(q, "sort")));
    let group_key = group
        .map(str::to_string)
        .or_else(|| filter.and_then(|q| control_token(q, "group")));
    // Project grouping and sorting need each issue's resolved memberships, read once
    // from the shared index and labelled by the service, so the CLI cannot bucket a
    // project differently from the board (WP09 item D).
    let by_project =
        sort_key.as_deref() == Some("project") || group_key.as_deref() == Some("project");
    let project_groups = if by_project {
        Some(project_group_labels(store, &issues))
    } else {
        None
    };
    // Epic grouping and sorting are the same shape: one shared inverse-membership
    // read from the epic service, labelled by the service's own
    // [`crate::search::epic_bucket_label`], so `tix list --group epic` and the
    // board's `EpicPartition` cannot spell a bucket two ways (WP09 item C).
    let by_epic = sort_key.as_deref() == Some("epic") || group_key.as_deref() == Some("epic");
    let epic_groups = if by_epic {
        Some(epic_group_labels(store, &issues))
    } else {
        None
    };
    if by_project {
        // Grouping must see a project's rows contiguously, so a project partition is
        // applied before (and instead of) a secondary sort when the caller asked to
        // group or sort by project.
        sort_by_project(store, &mut issues, project_groups.as_ref().unwrap());
    } else if by_epic {
        // The epic partition ranks by the same declaration order the board uses.
        sort_by_epic(store, &mut issues, epic_groups.as_ref().unwrap());
    } else {
        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));
    // The `--show`-driven columns are appended in one pure step, so the column-set
    // shape (`--show progress` => CHILDREN then PROJECTS, while `--columns progress`
    // is CHILDREN alone) is pinned by a unit test rather than by a TTY-bound
    // whole-`run` test.
    append_show_columns(&mut columns, &shows);
    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 {
        // `--show relationships` already appended them in `append_show_columns`;
        // naming one by hand (`--columns blocked`) appends its sibling here, so
        // the two relationship facts always travel together.
        for column in RELATIONSHIP_COLUMNS {
            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 wants_progress_data(show_progress, &columns) {
        hierarchy = Some(hierarchy_cells(store, &done_column)?);
    }
    // WP04 T018 (`contracts/cli-surface.md` §3): `--show progress` also carries the
    // project progress/health column (appended by `append_show_columns`, after
    // `CHILDREN`, so the pre-existing column keeps its meaning and position).
    let mut projects: Option<BTreeMap<u32, String>> = None;
    if columns.contains(&ListColumn::Projects) {
        projects = Some(project_cells(store, &issues)?);
    }
    // WP04 T018 (`contracts/cli-surface.md` §3): `--show progress` also carries the
    // epic progress/weight column, from the same one-pass service read `tix show`
    // uses for one issue.
    let mut epics: Option<BTreeMap<u32, String>> = None;
    if columns.contains(&ListColumn::Epics) {
        epics = Some(crate::commands::view::epic_cells(store, &issues)?);
    }
    // WP02 T010: `--show wip` adds the column, and building the snapshot is what
    // makes it show data rather than a column of `-` (the rule `blocked`,
    // `relations` and `progress` already follow).
    let mut wip: Option<crate::wip::WipSnapshot> = None;
    if columns.contains(&ListColumn::Wip) {
        wip = Some(crate::wip::WipSnapshot::build(
            store.config.default_config(),
            &issues,
        ));
    }
    // The health document, built only when the column (or `--show health`) asks for
    // it: asking for the column by name is a request for the data, the rule the
    // relationship, hierarchy and WIP columns already follow.
    let mut health: Option<crate::health::PortableHealth> = None;
    if columns.contains(&ListColumn::Health) {
        health = Some(crate::commands::export::run_health_core(&store.config)?);
    }
    let width = terminal_width();
    print!(
        "{}",
        render_table_with(
            &issues,
            &columns,
            group_key.as_deref(),
            &resolution,
            width,
            derived.as_ref(),
            hierarchy.as_ref(),
            wip.as_ref(),
            health.as_ref(),
            projects.as_ref(),
            epics.as_ref(),
            project_groups.as_ref(),
            epic_groups.as_ref(),
        )
    );
    Ok(())
}

/// 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.
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);
    }
}

/// Whether the caller asked for the progress **data**: `--show progress`, or a
/// `progress` column named in `--columns`.
///
/// Asking for the column by name is a request for the data, not only for the
/// heading — the rule the relationship columns already follow. Without it
/// `--columns progress` was accepted, built the column, and rendered `-` for
/// every row, which reads as "nothing is a parent" rather than "ask for the
/// detail". Extracted so the branch has a unit test of its own (#1380), since a
/// whole-`run` test needs a TTY-bound stdout.
fn wants_progress_data(show_progress: bool, columns: &[ListColumn]) -> bool {
    show_progress || columns.contains(&ListColumn::Progress)
}

/// 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",
            // 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)
}

/// 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 project/health cell, read from the service in one pass (WP04
/// T018, FR-003).
///
/// The text is built from the service's typed values — one health read per project
/// for the whole listing — so a row can never report a figure that disagrees with
/// `tix show` for the same snapshot (C-006). An issue in no project has no entry
/// (rendered `-`), and a reference that no longer resolves renders its recorded id
/// and `(missing reference)`, so the two empty-looking cases stay distinguishable.
pub(crate) fn project_cells(store: &Store, issues: &[Issue]) -> Result<BTreeMap<u32, String>> {
    // The figures are read from the **full** snapshot, not from the listed slice:
    // a progress total is a property of the project, and a `--status`/`--filter`
    // narrowing must not silently reduce it. `issues` is only the set of rows to
    // render. This is the same snapshot source `projects_block` reads (contract
    // §5: the two surfaces must report the same values), so a filtered listing and
    // `tix show` cannot disagree.
    let snapshot = store.list()?;
    let (_index, reports) = crate::commands::view::project_reports(store, &snapshot)?;
    let mut out = BTreeMap::new();
    for issue in issues {
        let Some(ids) = issue.projects.as_ref().filter(|ids| !ids.is_empty()) else {
            continue;
        };
        let mut rendered: Vec<String> = Vec::new();
        let mut seen: Vec<&str> = Vec::new();
        for raw in ids {
            if seen.contains(&raw.as_str()) {
                continue;
            }
            seen.push(raw.as_str());
            match crate::config::ProjectId::new(raw)
                .ok()
                .and_then(|id| reports.get(&id))
            {
                Some(report) => rendered.push(format!(
                    "{} {}/{}{}",
                    crate::projects::project_display(&report.project_id, &report.name),
                    report.progress.done,
                    report.progress.total,
                    crate::commands::view::health_suffix(report),
                )),
                None => rendered.push(format!("{raw} (missing reference)")),
            }
        }
        out.insert(issue.number, rendered.join("; "));
    }
    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, 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 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 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"
            || (*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();
        for issue in issues {
            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"
                ));
            }
            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>>,
    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(),
        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),
    }
}

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

/// The group-section label for one issue.
///
/// `project` reads the **resolved** memberships the caller built from the shared
/// index, so its labels are the service's ([`crate::projects::project_bucket_label`])
/// and cannot differ from the board's — an issue in no project is the clearly
/// labelled bucket, an issue in several collapses to one bucket, and a single
/// membership is labelled with the project **id** (WP09 item D). Every other key is
/// read straight off the issue.
fn group_key(
    issue: &Issue,
    group: &str,
    project_groups: Option<&BTreeMap<u32, String>>,
    epic_groups: Option<&BTreeMap<u32, String>>,
) -> String {
    match group {
        "project" => project_groups
            .and_then(|groups| groups.get(&issue.number).cloned())
            .unwrap_or_else(|| crate::projects::NO_PROJECT_BUCKET.to_string()),
        "epic" => epic_groups
            .and_then(|groups| groups.get(&issue.number).cloned())
            .unwrap_or_else(|| crate::search::NO_EPIC_BUCKET.to_string()),
        _ => group_value(issue, group),
    }
}

/// Issue number -> its project bucket label, from the shared membership index.
///
/// One [`crate::projects::ProjectIndex`] build for the whole listing, so the labels
/// are derived from the same buckets `tix project list` counts and the board
/// partitions (C-006, WP09 item D).
fn project_group_labels(store: &Store, issues: &[Issue]) -> BTreeMap<u32, String> {
    let index = crate::projects::ProjectIndex::build(&store.config, issues);
    let memberships = index.resolved_memberships();
    issues
        .iter()
        .map(|issue| {
            let ids = memberships.get(&issue.number).cloned().unwrap_or_default();
            (issue.number, crate::projects::project_bucket_label(&ids))
        })
        .collect()
}

/// Issue number -> its epic bucket label, from the shared membership helper.
///
/// One [`crate::epics::memberships_by_issue`] read for the whole listing, so the
/// labels are derived from the same resolved memberships the board's epic partition
/// and `tix status --group epic` use, and labelled by the service's own
/// [`crate::search::epic_bucket_label`] (WP09 item C).
fn epic_group_labels(store: &Store, issues: &[Issue]) -> BTreeMap<u32, String> {
    let memberships = crate::epics::memberships_by_issue(&store.config, issues);
    issues
        .iter()
        .map(|issue| {
            let ids = memberships.get(&issue.number).cloned().unwrap_or_default();
            (issue.number, crate::search::epic_bucket_label(&ids))
        })
        .collect()
}

/// Sort issues by the project partition, the board's own rank.
///
/// A single membership ranks by its project's **declaration index**, several rank
/// after every declared project (`(multiple projects)`), and none sorts **last** so
/// `(no project)` is the final section — the same order
/// [`crate::ui::board`]'s partition uses.
fn sort_by_project(store: &Store, issues: &mut [Issue], groups: &BTreeMap<u32, String>) {
    let declaration: Vec<&str> = store.config.projects.keys().map(String::as_str).collect();
    let rank = |issue: &Issue| -> usize {
        match groups.get(&issue.number).map(String::as_str) {
            Some(crate::projects::MULTIPLE_PROJECTS_BUCKET) => usize::MAX - 1,
            Some(crate::projects::NO_PROJECT_BUCKET) | None => usize::MAX,
            Some(id) => declaration
                .iter()
                .position(|candidate| *candidate == id)
                .unwrap_or(usize::MAX),
        }
    };
    issues.sort_by(|a, b| rank(a).cmp(&rank(b)).then(a.number.cmp(&b.number)));
}

/// Sort issues by the epic partition, the board's own rank.
///
/// The epic twin of [`sort_by_project`]: a single membership ranks by its epic's
/// **declaration index**, several rank after every declared epic
/// ([`crate::search::MULTIPLE_EPICS_BUCKET`]), and none sorts **last** so
/// [`crate::search::NO_EPIC_BUCKET`] is the final section — the same order the
/// board's [`crate::ui::board`] partition uses (WP09 item C).
fn sort_by_epic(store: &Store, issues: &mut [Issue], groups: &BTreeMap<u32, String>) {
    let declaration: Vec<&str> = store.config.epics.keys().map(String::as_str).collect();
    let rank = |issue: &Issue| -> usize {
        match groups.get(&issue.number).map(String::as_str) {
            Some(crate::search::MULTIPLE_EPICS_BUCKET) => usize::MAX - 1,
            Some(crate::search::NO_EPIC_BUCKET) | None => usize::MAX,
            Some(id) => declaration
                .iter()
                .position(|candidate| *candidate == id)
                .unwrap_or(usize::MAX),
        }
    };
    issues.sort_by(|a, b| rank(a).cmp(&rank(b)).then(a.number.cmp(&b.number)));
}

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

    #[test]
    fn progress_renders_the_count_and_rollup_for_a_parent_and_a_dash_for_a_leaf() {
        let store = make_store().1;
        // #1 is a parent with one completed child (#2); #3 is a leaf.
        let parent = seed(&store, 1, "Epic", "todo");
        let mut child = seed(&store, 2, "Child", "done");
        child.parent = Some(1);
        fs::write(
            store.issues_dir.join(&child.filename),
            child.to_file_contents(),
        )
        .unwrap();
        let leaf = seed(&store, 3, "Leaf", "todo");

        let done_column = crate::workflow::completion_column_or_default(
            store.config.default_config(),
            &store.config,
        );
        let cells = hierarchy_cells(&store, &done_column).unwrap();
        assert_eq!(
            cells.get(&1).map(String::as_str),
            Some("1  1/1"),
            "a parent renders its completed/total rollup"
        );
        assert_eq!(cells.get(&3), None, "a leaf has no hierarchy cell");

        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let columns = parse_columns("num,progress").unwrap();
        let output = render_table_with(
            &[parent, leaf],
            &columns,
            None,
            &resolution,
            40,
            None,
            Some(&cells),
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let parent_row = output
            .lines()
            .find(|l| l.trim_start().starts_with('1'))
            .unwrap();
        let leaf_row = output
            .lines()
            .find(|l| l.trim_start().starts_with('3'))
            .unwrap();
        assert!(
            parent_row.contains("1/1"),
            "parent row shows the rollup: {output:?}"
        );
        assert!(
            leaf_row.trim_end().ends_with('-'),
            "a leaf renders `-`, not `0`: {output:?}"
        );
    }

    #[test]
    fn a_progress_column_requested_by_name_renders_data_rather_than_a_placeholder() {
        // The branch `run` gates the hierarchy fetch on: `--columns progress` is a
        // request for the data, not only the heading, so a fast-path that only
        // fetched cells for `--show progress` would render every row as `-`.
        let by_name = parse_columns("num,progress").unwrap();
        assert!(
            wants_progress_data(false, &by_name),
            "a progress column named in --columns fetches the data"
        );
        let plain = parse_columns("num,title").unwrap();
        assert!(
            wants_progress_data(true, &plain),
            "--show progress fetches the data"
        );
        assert!(
            !wants_progress_data(false, &plain),
            "neither spelling: no hierarchy fetch"
        );
    }

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

    // ---- WP04 T018: the project/health column -------------------------------

    /// The `make_store` store with a `(id, name)` registry, so the project service
    /// resolves associations.
    fn store_with_projects(projects: &[(&str, &str)]) -> (TempDir, Store) {
        let (tmp, mut store) = make_store();
        for (id, name) in projects {
            store.config.projects.insert(
                (*id).to_string(),
                crate::config::ProjectConfiguration {
                    name: (*name).to_string(),
                    ..crate::config::ProjectConfiguration::default()
                },
            );
        }
        (tmp, store)
    }

    /// Write `issue` back with its associations set.
    fn rewrite(store: &Store, mut issue: Issue, projects: &[&str]) {
        issue.projects = Some(projects.iter().map(|p| (*p).to_string()).collect());
        write_back(store, &issue);
    }

    fn write_back(store: &Store, issue: &Issue) {
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();
    }

    #[test]
    fn t018_the_project_column_shows_both_projects_and_a_dash_when_none() {
        let (_tmp, store) = store_with_projects(&[("p-a", "Platform"), ("p-b", "Docs")]);
        rewrite(&store, seed(&store, 1, "Shared", "todo"), &["p-a", "p-b"]);
        seed(&store, 2, "None", "todo");
        let issues = query(&store, None, None, false).unwrap();
        let cells = project_cells(&store, &issues).unwrap();

        let cell = cells.get(&1).expect("issue #1 belongs to two projects");
        assert!(cell.contains("Platform (p-a)"), "{cell}");
        assert!(cell.contains("Docs (p-b)"), "{cell}");
        assert!(
            cell.contains("done, overdue 0, blocked 0, unassigned 0"),
            "the health context is rendered: {cell}"
        );
        assert_eq!(cells.get(&2), None, "an unassociated issue has no cell");

        // The rendered table shows the PROJECTS column and the `-` placeholder for
        // the unassociated issue — the two states stay distinguishable.
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let columns = parse_columns("num,projects").unwrap();
        let table = render_table_with(
            &issues,
            &columns,
            None,
            &resolution,
            0,
            None,
            None,
            None,
            None,
            Some(&cells),
            None,
            None,
            None,
        );
        assert!(table.contains("PROJECTS"), "{table}");
        assert!(
            table
                .lines()
                .any(|l| l.trim_start().starts_with('2') && l.trim_end().ends_with('-')),
            "an unassociated issue renders `-`: {table}"
        );
    }

    #[test]
    fn t018_a_missing_reference_is_visible_in_the_project_cell() {
        let (_tmp, store) = store_with_projects(&[("p-a", "Platform")]);
        rewrite(
            &store,
            seed(&store, 1, "Dangling", "todo"),
            &["p-a", "p-gone"],
        );
        let issues = query(&store, None, None, false).unwrap();
        let cells = project_cells(&store, &issues).unwrap();
        let cell = cells.get(&1).unwrap();
        assert!(
            cell.contains("p-gone (missing reference)"),
            "a dangling association is named: {cell}"
        );
        assert!(cell.contains("Platform (p-a)"), "{cell}");
    }

    #[test]
    fn t018_the_project_cells_are_deterministic() {
        let (_tmp, store) = store_with_projects(&[("p-a", "Platform"), ("p-b", "Docs")]);
        rewrite(&store, seed(&store, 1, "Shared", "todo"), &["p-b", "p-a"]);
        rewrite(&store, seed(&store, 2, "One", "todo"), &["p-a"]);
        let issues = query(&store, None, None, false).unwrap();
        let first = project_cells(&store, &issues).unwrap();
        assert_eq!(
            first.get(&1).map(String::as_str),
            Some(
                "Docs (p-b) 0/1 done, overdue 0, blocked 0, unassigned 0; Platform (p-a) 0/2 done, overdue 0, blocked 0, unassigned 0"
            ),
            "associations keep the issue's own order, projects in declaration order"
        );
        for _ in 0..3 {
            assert_eq!(
                project_cells(&store, &issues).unwrap(),
                first,
                "repeated reads are identical"
            );
        }
    }

    #[test]
    fn t018_the_show_progress_column_set_is_pinned() {
        // The shape of `--show progress` is deliberate (`contracts/cli-surface.md`
        // §3): `progress` appends the hierarchy CHILDREN column **and** the project
        // PROJECTS column after it, while naming `progress` in `--columns` requests
        // the CHILDREN data alone. Pinned here so a future change cannot alter the
        // shape silently.
        let (_tmp, store) = make_store();
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        // The exact headers, in order, read from the column's own `header()`
        // accessor rather than from a rendered line (whose padding the width
        // allocator would make brittle).
        let headers = |columns: &[ListColumn]| -> Vec<&'static str> {
            columns.iter().map(|column| column.header()).collect()
        };

        let by_name = parse_columns("num,progress").unwrap();
        assert_eq!(
            headers(&by_name),
            ["NUM", "CHILDREN"],
            "`--columns progress` is the CHILDREN data only"
        );

        let mut via_show = default_columns(&[]);
        append_show_columns(&mut via_show, &["progress"]);
        assert_eq!(
            headers(&via_show),
            [
                "NUM", "TITLE", "STATUS", "PRIORITY", "CHILDREN", "PROJECTS", "EPICS"
            ],
            "`--show progress` is CHILDREN then PROJECTS then EPICS (WP04 T018)"
        );

        // A project-free repository still emits the PROJECTS column, rendered `-`
        // for every row: the column is a statement about the listing, not about
        // whether the registry happens to hold anything.
        let issue = seed(&store, 1, "Plain", "todo");
        let mut project_free = default_columns(&[]);
        append_show_columns(&mut project_free, &["progress"]);
        let table = render_table_with(
            &[issue],
            &project_free,
            None,
            &resolution,
            0,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let row = table.lines().nth(1).unwrap();
        assert!(table.contains("PROJECTS"), "{table}");
        assert!(
            row.trim_end().ends_with('-'),
            "a project-free row renders `-` in PROJECTS: {table}"
        );
    }

    #[test]
    fn t018_a_filtered_listing_reports_the_same_project_figures_as_tix_show() {
        // The parity defect this pins (contract §5): `project_cells` used to build
        // the index from the query-filtered slice, so `tix list --status todo
        // --show progress` reported a smaller denominator than `tix show` for the
        // same snapshot. A project's figures are a property of the project, not of
        // the listed rows.
        let (_tmp, store) = store_with_projects(&[("p-a", "Platform")]);
        let mut done = seed(&store, 1, "Done", "done");
        done.projects = Some(vec!["p-a".into()]);
        write_back(&store, &done);
        rewrite(&store, seed(&store, 2, "Open", "todo"), &["p-a"]);
        let mut unassigned = seed(&store, 3, "Unassigned", "todo");
        unassigned.assignee = None;
        unassigned.projects = Some(vec!["p-a".into()]);
        write_back(&store, &unassigned);

        let filtered = query(&store, Some("todo"), None, false).unwrap();
        assert_eq!(
            numbers(&filtered),
            vec![2, 3],
            "precondition: only the open rows are listed"
        );
        let cells = project_cells(&store, &filtered).unwrap();
        let figure = "1/3 done, overdue 0, blocked 0, unassigned 1";
        let cell = cells.get(&2).expect("a listed row in the project");
        assert!(
            cell.contains(figure),
            "the filtered listing reports the **full** project: {cell}"
        );

        // `tix show` reads the whole snapshot and must agree for the same project.
        let loaded = crate::commands::view::get(&store, "2").unwrap();
        let block = crate::commands::view::projects_block(&store, &loaded).unwrap();
        assert!(block.contains(figure), "`tix show` must agree: {block}");
    }

    // ---- WP04 T018: the epic column ----------------------------------------

    /// The `make_store` store with an epic registry `(id, name, weight, parent)`.
    fn store_with_epics(epics: &[(&str, &str, Option<i64>, Option<&str>)]) -> (TempDir, Store) {
        let (tmp, mut store) = make_store();
        for (id, name, weight, parent) in epics {
            store.config.epics.insert(
                (*id).to_string(),
                crate::config::EpicConfiguration {
                    name: (*name).to_string(),
                    weight: *weight,
                    parent: parent.map(str::to_string),
                    ..crate::config::EpicConfiguration::default()
                },
            );
        }
        (tmp, store)
    }

    /// Write `issue` back with its epic references set.
    fn set_epics(store: &Store, mut issue: Issue, epics: &[&str]) -> Issue {
        issue.epics = Some(epics.iter().map(|id| (*id).to_string()).collect());
        write_back(store, &issue);
        issue
    }

    #[test]
    fn t018_the_epic_column_shows_every_reference_and_a_dash_when_none() {
        let (_tmp, store) = store_with_epics(&[
            ("e-aaa111", "Alpha", None, None),
            ("e-bbb222", "Beta", None, None),
        ]);
        set_epics(
            &store,
            seed(&store, 1, "Shared", "todo"),
            &["e-aaa111", "e-bbb222"],
        );
        seed(&store, 2, "None", "todo");
        let issues = query(&store, None, None, false).unwrap();
        let cells = crate::commands::view::epic_cells(&store, &issues).unwrap();
        let cell = cells.get(&1).expect("#1 references two epics");
        assert!(cell.contains("Alpha (e-aaa111)"), "{cell}");
        assert!(cell.contains("Beta (e-bbb222)"), "{cell}");
        assert!(
            cell.contains("Alpha (e-aaa111) 0/1 done"),
            "the figures are read from the service: {cell}"
        );
        assert_eq!(cells.get(&2), None, "an unreferenced issue has no cell");

        // The rendered table shows the EPICS column and the `-` placeholder, so the
        // two empty-looking cases stay distinguishable.
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let columns = parse_columns("num,epics").unwrap();
        let table = render_table_with(
            &issues,
            &columns,
            None,
            &resolution,
            0,
            None,
            None,
            None,
            None,
            None,
            Some(&cells),
            None,
            None,
        );
        assert!(table.contains("EPICS"), "{table}");
        assert!(
            table
                .lines()
                .any(|l| l.trim_start().starts_with('2') && l.trim_end().ends_with('-')),
            "an unreferenced issue renders `-`: {table}"
        );
    }

    #[test]
    fn t018_a_missing_epic_reference_is_visible_in_the_cell() {
        let (_tmp, store) = store_with_epics(&[("e-aaa111", "Alpha", None, None)]);
        set_epics(
            &store,
            seed(&store, 1, "Dangling", "todo"),
            &["e-aaa111", "e-gone1"],
        );
        let issues = query(&store, None, None, false).unwrap();
        let cells = crate::commands::view::epic_cells(&store, &issues).unwrap();
        let cell = cells.get(&1).unwrap();
        assert!(
            cell.contains("e-gone1 (missing reference)"),
            "a dangling reference is named: {cell}"
        );
        assert!(cell.contains("Alpha (e-aaa111)"), "{cell}");
    }

    #[test]
    fn t018_the_epic_cells_are_deterministic() {
        let (_tmp, store) = store_with_epics(&[
            ("e-aaa111", "Alpha", None, None),
            ("e-bbb222", "Beta", None, None),
        ]);
        set_epics(
            &store,
            seed(&store, 1, "Shared", "todo"),
            &["e-bbb222", "e-aaa111"],
        );
        let issues = query(&store, None, None, false).unwrap();
        let first = crate::commands::view::epic_cells(&store, &issues).unwrap();
        let cell = first.get(&1).unwrap();
        assert!(
            cell.starts_with("Beta (e-bbb222)"),
            "the issue's own reference order is kept: {cell}"
        );
        assert!(cell.ends_with("blocked 0"), "{cell}");
        for _ in 0..3 {
            assert_eq!(
                crate::commands::view::epic_cells(&store, &issues).unwrap(),
                first,
                "repeated reads are identical"
            );
        }
    }

    #[test]
    fn t018_epic_is_a_recognised_column_spelling() {
        assert_eq!(
            parse_columns("epics").unwrap(),
            vec![ListColumn::Epics],
            "the plural is the column name"
        );
        assert_eq!(
            parse_columns("epic").unwrap(),
            vec![ListColumn::Epics],
            "the singular parses to the same column"
        );
    }
}