tix-tracker 0.10.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
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::search::control_token;
use crate::storage::Store;
use indexmap::IndexMap;
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,
    /// The issue's canonical 8-character id (the identity `crate::id` mints, not
    /// the colliding-per-checkout `number`). A default column: the compact listing
    /// is `number`, `id`, `title`, so a reader can copy the token that is stable
    /// across clones and branches (#1711).
    Id,
    Title,
    Status,
    Priority,
    Cycle,
    Milestone,
    Reviewer,
    Start,
    Due,
    Overdue,
    /// The service-derived blocked reason. Empty when the issue is not blocked.
    Blocked,
    /// The issue's relationships as `kind -> #target`, in the service's order.
    Relations,
    /// The child count, and the rollup for a parent, from the hierarchy service.
    Progress,
    /// The issue's project associations with each project's progress and health,
    /// from the project service (WP04 T018, FR-003). Requested by `--show progress`
    /// (or by the `projects` column name), never emitted by default.
    Projects,
    /// The issue's epic references with each epic's progress, weight-aware figure
    /// and blocked count, from the epic service (WP04 T018, FR-003). Requested by
    /// `--show progress` (or by the `epics` column name), never emitted by default.
    Epics,
    /// The issue's resolved category label, from the service (WP04 T019).
    Category,
    /// The issue's **column** usage against its WIP limit, from the shared snapshot
    /// (mission `configurable-wip-limits-01M3C6WX`, WP02). The cell is the column's
    /// count/limit, repeated on each of its rows — a per-row copy is what a table
    /// column is, exactly as `Category` repeats a per-column fact.
    Wip,
    /// Whether the issue is archived (issue #1492). Derived from the filename,
    /// never stored; appended to the default columns only when at least one row
    /// is archived.
    Archived,
    /// The issue's health: its own value, with the derived rollup beside it when
    /// its children say something different (`at_risk→unknown`). Read from the one
    /// portable health document (mission `project-issue-health-status-01M3C8HX`,
    /// WP05 T028), so the CLI, the TUI and MCP cannot disagree about a state.
    Health,
}

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

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

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

    fn cap(self) -> usize {
        match self {
            Self::Num => 6,
            // The canonical id is exactly 8 Crockford base32 characters, so the cap
            // is its width and the column never eats the title's room (#1711).
            Self::Id => 8,
            Self::Title => 40,
            Self::Status => 16,
            Self::Priority => 12,
            Self::Cycle | Self::Milestone | Self::Reviewer => 20,
            Self::Start | Self::Due => 10,
            Self::Overdue => 7,
            Self::Blocked | Self::Relations => 40,
            // `3  1/3` — the count and the rollup, side by side.
            Self::Progress => 16,
            // `Platform hardening (p-3f9a2c) 1/4 done, overdue 1, blocked 0, unassigned 2`
            // — one association, so the cell is the visible unit of the column.
            Self::Projects => 60,
            // `Sync hardening (e-3f9a2c) 1/4 done, weighted 3/5 (60%), blocked 1`
            // — one reference, so the cell is the visible unit of the column.
            Self::Epics => 60,
            // The longest current label is "Not started" (12); 14 leaves a little
            // room so a future label does not silently truncate into a lie.
            Self::Category => 14,
            // "ARCHIVED" is the whole cell value, so the cap is its width.
            Self::Archived => 8,
            // `4/5 12/20d!` — the item pair, the estimate pair and the marker.
            Self::Wip => 20,
            // `needs_attention→at_risk` — the two layers, when they disagree.
            Self::Health => 22,
        }
    }
}

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

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

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

/// The board's **entry column**: the first configured column that is not the
/// triage inbox (#1711).
///
/// Not simply the first column. A board whose columns start with the inbox —
/// `tix init`'s own board does — would otherwise scope the default listing to
/// **unaccepted candidates**, and this repository's recorded workflow reads
/// `tix list --status todo`. The inbox has its own surface (`tix triage list`), and
/// `tix create` still files into the board's first column, because deciding a new
/// issue is exactly what the inbox is for.
///
/// With no `[triage]` section, or one that names no `entry_status`, the first
/// configured column *is* the entry column, and a board whose only column is the
/// inbox falls back to it rather than to nothing.
pub fn entry_column(config: &crate::config::Config) -> Option<String> {
    let inbox = config
        .triage
        .as_ref()
        .and_then(|triage| triage.entry_status.as_deref());
    let columns = &config.default_config().columns;
    columns
        .iter()
        .find(|column| Some(column.as_str()) != inbox)
        .or_else(|| columns.first())
        .cloned()
}

/// The scope a listing uses when the caller asked for no other (#1711).
///
/// `status` is the board's entry column and `me` is the git author identity, each
/// `None` when it cannot be derived: a board with no configured columns scopes
/// nothing, and so does a checkout with no git identity — the listing then falls
/// back to every issue rather than to an empty table that would read as "you have
/// no work".
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ListScope {
    pub status: Option<String>,
    pub me: Option<crate::assignee::AuthorIdentity>,
}

/// The default scope: my issues in the board's entry column, or nothing at all
/// under `--all`.
pub fn default_scope(config: &crate::config::Config, all: bool) -> ListScope {
    if all {
        return ListScope::default();
    }
    ListScope {
        status: entry_column(config),
        me: crate::assignee::git_identity(),
    }
}

/// Whether an issue is assigned to `me`.
///
/// The exact rendering is the case that matters: `tix create` without `--assignee`
/// stores precisely [`AuthorIdentity`](crate::assignee::AuthorIdentity)'s
/// `Display`. The tolerant forms cover what a human types by hand — the bare name,
/// the email address, and its local part — so an issue assigned `@thyseus` is not
/// silently "not mine" while an issue assigned to somebody else never matches.
fn is_mine(issue: &Issue, me: &crate::assignee::AuthorIdentity) -> bool {
    let Some(assignee) = issue.assignee.as_deref() else {
        return false;
    };
    if assignee == me.to_string() {
        return true;
    }
    let handle = assignee.strip_prefix('@').unwrap_or(assignee);
    if handle.eq_ignore_ascii_case(&me.name) {
        return true;
    }
    me.email.as_deref().is_some_and(|email| {
        handle.eq_ignore_ascii_case(email)
            || handle.eq_ignore_ascii_case(email.split('@').next().unwrap_or_default())
    })
}

/// One listing request's **selection**: the flags that choose which issues are
/// asked for, as opposed to the ones that choose how they are shown.
///
/// Grouped into a type because the default scope's rule is about the *set* of
/// them, not about any one: [`ListSelection::names_a_selection`] is the sentence
/// the whole feature turns on, and four separate booleans at a call site is how
/// that sentence gets written four times and drifts.
#[derive(Debug, Clone, Copy, Default)]
pub struct ListSelection<'a> {
    pub status: Option<&'a str>,
    pub filter: Option<&'a str>,
    pub project: Option<&'a str>,
    pub epic: Option<&'a str>,
    /// `--all`: the wide board, stated without naming anything.
    pub all: bool,
}

impl ListSelection<'_> {
    /// Whether the request names a selection of its own.
    ///
    /// The default scope is what a listing means with **no arguments**. The moment
    /// the caller names a column, a query, a project or an epic, that is the
    /// request — and composing it with an unstated default is how
    /// `tix list --filter 'scope:triage'` returns an empty table: two scopes, one
    /// of them never asked for. `--sort`, `--group`, `--columns`, `--show` and
    /// `--format` order and print the listing rather than choosing it, so they
    /// leave the scope alone.
    fn names_a_selection(&self) -> bool {
        self.all
            || self.status.is_some()
            || self.filter.is_some()
            || self.project.is_some()
            || self.epic.is_some()
    }
}

/// [`query`], with the default scope applied (#1711).
///
/// The one seam the CLI and MCP share, so `tix list` and MCP's `list_issues` with
/// no arguments are the same listing rather than two readings of "the default".
pub fn scoped_query(
    store: &Store,
    selection: &ListSelection<'_>,
    with_archived: bool,
) -> Result<Vec<Issue>> {
    let scope = default_scope(&store.config, selection.names_a_selection());
    let effective = selection.status.map(str::to_string).or(scope.status);
    let mut issues = query(store, effective.as_deref(), selection.filter, with_archived)?;
    if let Some(me) = scope.me.as_ref() {
        issues.retain(|issue| is_mine(issue, me));
    }
    Ok(issues)
}

/// `tix ready`'s preset: the listing that answers "what do I pick up next".
///
/// It rides [`run`]'s one pipeline rather than duplicating the query, the column
/// resolution, the derived reads and the rendering — `tix ready` is a *scope* on
/// the listing, and a second implementation of the listing is how the two would
/// start disagreeing about what an issue's blocked state is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReadyOptions {
    /// Cap the listing after it is ordered, so `--limit 1` is the single next
    /// issue rather than "the first one in file order".
    pub limit: Option<usize>,
}

/// Whether `tix ready` should treat `issue` as work that has not begun.
///
/// Two halves, because a board can answer the question either way:
///
/// * the **category** the board maps the column to. `backlog` and `unstarted` are
///   the two that mean "not begun"; an active column is already under way and a
///   terminal one is out of the running.
/// * the **board order**, bounded by the entry column. `tix init`'s board leaves
///   its working columns unmapped *deliberately* — an explicit map turns on
///   adjacency enforcement, which would refuse the daily `in progress -> todo`
///   move — so on such a board every non-terminal column reads as `unstarted` and
///   the category alone cannot tell work under way from work not started. The
///   order can: nothing is "next" after the column new work arrives in.
///
/// A column the board does not configure has no category, so it is not work this
/// listing can place. `tix lint` is where that misconfiguration is reported.
fn is_startable(
    issue: &Issue,
    resolution: &crate::workflow::CategoryResolution,
    board: &[String],
    entry: Option<&str>,
) -> bool {
    let Some(category) = crate::workflow::category_of(issue, resolution) else {
        return false;
    };
    if !matches!(
        category,
        crate::workflow::WorkflowCategory::Backlog | crate::workflow::WorkflowCategory::Unstarted
    ) {
        return false;
    }
    // No entry column (an empty board, or one whose entry is not in its own order)
    // leaves the category as the whole answer.
    let Some(entry_index) = entry.and_then(|entry| board.iter().position(|column| column == entry))
    else {
        return true;
    };
    board
        .iter()
        .position(|column| column == issue.status.display())
        .is_none_or(|index| index <= entry_index)
}

/// The columns `tix ready` shows: the identity pair, the priority it is ordered
/// by, and the title (#1711).
///
/// Priority is in the set because a ready list is *about* priority — dropping the
/// column the rows were just sorted on would hide the reason for the order.
fn ready_columns(issues: &[Issue]) -> Vec<ListColumn> {
    let mut columns = vec![
        ListColumn::Num,
        ListColumn::Id,
        ListColumn::Priority,
        ListColumn::Title,
    ];
    if issues.iter().any(|issue| issue.archived) {
        columns.push(ListColumn::Archived);
    }
    columns
}

/// `tix ready`'s order: highest priority first, then oldest, then by number.
///
/// The tie-breaks matter more than the first key does. A repository where every
/// ready issue is `medium` would otherwise list in file order, which changes when a
/// file is renamed; `created` is stable and answers "what has been waiting longest".
fn sort_ready(issues: &mut [Issue]) {
    issues.sort_by(|a, b| {
        priority_rank(&a.priority)
            .cmp(&priority_rank(&b.priority))
            .then(a.created.cmp(&b.created))
            .then(a.number.cmp(&b.number))
    });
}

/// Where a priority sits in [`sort_ready`]'s order: lower is picked up sooner.
///
/// Priority is free-form on purpose (`urgent`, `blocker`, a project's own word), so
/// the rank is a **documented policy**, not a comparison of the stored strings. The
/// words this project's own surfaces write come first, then the built-ins, then an
/// unset priority, then anything unrecognized — last, never guessed at. A `ready`
/// list that silently promoted `P0` to the top would be inventing an order the
/// repository never stated, and every unrecognized word would compete to be first.
fn priority_rank(priority: &crate::model::Priority) -> u8 {
    match priority.to_string().to_ascii_lowercase().as_str() {
        "critical" | "urgent" | "blocker" | "blocking" => 0,
        "high" => 1,
        "medium" => 2,
        "low" => 3,
        // Written `priority: ''` — explicitly no priority, which is not the same as
        // the `medium` default and not high enough to pick up first either.
        "" => 4,
        _ => 5,
    }
}

/// `tix ready`: the unblocked, unstarted work, ordered so the next issue is first.
///
/// A thin wrapper over [`run`] with the preset below — the flags it takes are the
/// ones that still make sense on a ready list (which columns, how many, one
/// project's or one epic's slice, and the structured formats).
pub fn ready(
    store: &Store,
    columns: Option<&str>,
    limit: Option<usize>,
    project: Option<&str>,
    epic: Option<&str>,
    format: Option<&str>,
) -> Result<()> {
    run(
        store,
        None,
        None,
        project,
        epic,
        None,
        None,
        columns,
        None,
        false,
        true,
        format,
        Some(ReadyOptions { limit }),
    )
}

#[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,
    all: bool,
    format: Option<&str>,
    ready: Option<ReadyOptions>,
) -> 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");
    // The format is validated before anything is read, so a typo cannot print half
    // a listing and then fail (`--format json` is a refusal, not a table).
    let format = format.map(ListFormat::parse).transpose()?;
    // The default scope (#1711): my issues in the board's entry column, applied
    // only when this request names no selection of its own. Resolved through the one
    // seam MCP shares, so the two surfaces cannot disagree about what "no arguments"
    // means.
    let mut issues = scoped_query(
        store,
        &ListSelection {
            status,
            filter,
            project,
            epic,
            all,
        },
        with_archived,
    )?;
    // The service's completion decision, read once and reused by the ready filter,
    // the group rollup and the `Overdue` cell (WP04 T019, C-004). It is computed
    // here because `tix ready` needs it before the ordering, not because the
    // listing changed its mind about who decides completion.
    let (_, resolution) = crate::workflow::active_resolution(&store.config);
    if let Some(options) = ready {
        // "Unblocked" comes from the one graph the `blocked` column reads, so this
        // list cannot call an issue ready while `tix list --show relationships`
        // calls it blocked. An issue with no graph entry is unblocked: nothing
        // points at it.
        let cells = relationship_cells(store)?;
        issues.retain(|issue| {
            cells
                .get(&issue.number)
                .is_none_or(|entry| entry.blocked.is_empty())
        });
        // Startable work: not under way, not finished, and not canceled — see
        // [`is_startable`] for why the board's categories *and* the board's order
        // both have a say. The inbox is deliberately **included**: it is before the
        // entry column, and a freshly filed issue nothing blocks is work that can be
        // picked up, which is the same answer `bd ready` gives.
        let board = &store.config.default_config().columns;
        let entry = entry_column(&store.config);
        issues.retain(|issue| is_startable(issue, &resolution, board, entry.as_deref()));
        sort_ready(&mut issues);
        // Capped **after** ordering, so `--limit 1` is the single next issue rather
        // than the first one in file order.
        if let Some(limit) = options.limit {
            issues.truncate(limit);
        }
    }
    // `--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 if ready.is_none() {
        // `tix ready` ordered the listing already, and that order *is* the command:
        // sorting again here would put the issues back in file order and make the
        // priority the list was built around disappear.
        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.
    // 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(|| {
        if ready.is_some() {
            ready_columns(&issues)
        } 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();
    let (header, rows) = table_rows(
        &issues,
        &columns,
        &resolution,
        derived.as_ref(),
        hierarchy.as_ref(),
        wip.as_ref(),
        health.as_ref(),
        projects.as_ref(),
        epics.as_ref(),
    );
    let text = match format {
        // A structured format carries the displayed columns, one record per issue,
        // in the order they were asked for — so `--columns` and `--format` are one
        // feature rather than two (#1711).
        Some(format) => render_records(&header, &rows, format)?,
        // `true`: the compact listing is one physical line per issue, with the title
        // cropped to the terminal rather than wrapped onto the next line (#1711).
        None => render_table_from(
            &issues,
            &columns,
            group_key.as_deref(),
            &resolution,
            width,
            &header,
            &rows,
            project_groups.as_ref(),
            epic_groups.as_ref(),
            true,
        ),
    };
    print!("{text}");
    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 (header, rows) = table_rows(
        issues, columns, resolution, derived, hierarchy, wip, health, projects, epics,
    );
    render_table_from(
        issues,
        columns,
        group,
        resolution,
        width,
        &header,
        &rows,
        project_groups,
        epic_groups,
        false,
    )
}

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

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

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

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

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

/// One table cell.
///
/// `derived` is `Some` only when the caller asked for relationship
/// information; the two relationship columns render a `-` placeholder without
/// it, so the default table is byte-identical to what it was before WP03.
#[allow(clippy::too_many_arguments)]
fn cell(
    column: ListColumn,
    issue: &Issue,
    resolution: &crate::workflow::CategoryResolution,
    today: &str,
    derived: Option<&RelationshipCells>,
    hierarchy: Option<&BTreeMap<u32, String>>,
    wip: Option<&crate::wip::WipSnapshot>,
    health: Option<&crate::health::PortableHealth>,
    projects: Option<&BTreeMap<u32, String>>,
    epics: Option<&BTreeMap<u32, String>>,
) -> String {
    match column {
        ListColumn::Num => issue.number.to_string(),
        // `-` for an issue written before the id schema (the field is optional so
        // those files keep parsing), never a blank cell: beside other blank cells it
        // would read as a rendering gap rather than as "this issue has no id yet".
        ListColumn::Id => issue.id.clone().unwrap_or_else(|| "-".to_string()),
        ListColumn::Title => issue.title.clone(),
        ListColumn::Status => issue.status.display().to_string(),
        ListColumn::Priority => issue.priority.to_string(),
        ListColumn::Cycle => issue
            .cycles
            .as_ref()
            .map(|v| v.join(","))
            .unwrap_or_default(),
        ListColumn::Milestone => issue
            .milestones
            .as_ref()
            .map(|v| v.join(","))
            .unwrap_or_default(),
        ListColumn::Reviewer => issue.reviewer.clone().unwrap_or_default(),
        ListColumn::Start => issue.start_date.clone().unwrap_or_default(),
        ListColumn::Due => issue.due_date.clone().unwrap_or_default(),
        ListColumn::Overdue => {
            // WP04 T019: `is_completed`, not a column comparison (C-004). An issue
            // that is past due but complete is not overdue, and that is a category
            // decision — a board mapping its last column to `completed` must not
            // depend on that column being spelled `done`.
            if issue.due_date.as_deref().is_some_and(|due| due < today)
                && !crate::workflow::is_completed(issue, resolution)
            {
                "yes".to_string()
            } else {
                String::new()
            }
        }
        // WP04 T019: the category label, from the service's own `label()` so the CLI
        // and the TUI cannot spell the same category differently (WP08 asserts the
        // detail view agrees with this column).
        //
        // An issue in a column the board does not configure resolves to `None`.
        // That is a configuration error the user should be able to *see* in the
        // listing rather than have it silently become the safe default here — the
        // safe default governs transition policy, and applying it to a display would
        // report a category the board never assigned. Shown as `(unmapped)`, which
        // is a statement about the file rather than an error the command refuses to
        // print (T019 step 4 asks for a label, not a failure).
        ListColumn::Category => crate::workflow::category_of(issue, resolution)
            .map(|c| c.label())
            .unwrap_or("(unmapped)")
            .to_string(),
        // A `-` rather than an empty cell, because an empty column next to
        // other empty columns is indistinguishable from a column that was not
        // rendered at all.
        ListColumn::Blocked => match derived {
            Some(cells) if !cells.blocked.is_empty() => cells.blocked.clone(),
            _ => "-".to_string(),
        },
        ListColumn::Relations => match derived {
            Some(cells) if !cells.relationships.is_empty() => cells.relationships.clone(),
            _ => "-".to_string(),
        },
        // A `-` for a leaf, not `0`. A leaf genuinely has no children, and a `0`
        // reads as "measured, and there are none" — which is the same sentence as
        // what a parent with no completed children would say. `-` says "not a
        // parent", which is the fact the column is for.
        //
        // Looked up per issue rather than guarded on the map being non-empty. A leaf
        // has **no entry at all** — `hierarchy_cells` skips it — so "the map is not
        // empty" is true on a board where every issue but one is a leaf, and
        // `cells[&issue.number]` then panicked. Found by running `tix list --show
        // progress`.
        ListColumn::Progress => match hierarchy.and_then(|cells| cells.get(&issue.number)) {
            Some(text) if !text.is_empty() => text.clone(),
            _ => "-".to_string(),
        },
        // A `-` for an issue in no project, matching the `CHILDREN` placeholder: an
        // empty cell beside other empty cells reads as a rendering gap rather than
        // as "this issue is in no project". A reference that no longer resolves is
        // **not** blanked — `project_cells` renders its recorded id — so the two
        // states stay distinguishable (T018 step 5).
        ListColumn::Projects => match projects.and_then(|cells| cells.get(&issue.number)) {
            Some(text) if !text.is_empty() => text.clone(),
            _ => "-".to_string(),
        },
        // A `-` for an issue in no epic, matching the PROJECTS/CHILDREN placeholder.
        // The cell text is built by the shared service read (`view::epic_cells`), so a
        // row can never report a figure that disagrees with `tix show` (C-008). A
        // reference that no longer resolves renders its recorded id, so the two
        // empty-looking cases stay distinguishable (T018 step 5).
        ListColumn::Epics => match epics.and_then(|cells| cells.get(&issue.number)) {
            Some(text) if !text.is_empty() => text.clone(),
            _ => "-".to_string(),
        },
        // The issue's own value, and the derived rollup beside it when the two
        // differ: a parent whose children are at risk reads `unknown→at_risk`, so the
        // cell never hides a derived layer that says something the current one does
        // not. Both values come from the document, never from a local formula.
        ListColumn::Health => health
            .and_then(|document| {
                document.scope(&crate::health::HealthScope::of_issue(issue.number))
            })
            .map(|entry| match entry.rollup.as_ref() {
                Some(derived) if entry.state != derived.state => {
                    format!("{}→{}", entry.state, derived.state)
                }
                _ => entry.state.clone(),
            })
            .unwrap_or_else(|| "-".to_string()),
        ListColumn::Archived => {
            if issue.archived {
                "ARCHIVED".to_string()
            } else {
                "-".to_string()
            }
        }
        // WP02 of `configurable-wip-limits-01M3C6WX`: the **column's** usage against
        // its limit, from the one shared snapshot. A column with no limit is `-`
        // rather than an empty cell, for the reason `Blocked` gives: an empty cell
        // beside other empty cells reads as a rendering gap, not as "no limit here".
        //
        // The snapshot is the one the surface was built from, so a row can never
        // report figures that disagree with the column's own heading count.
        ListColumn::Wip => wip
            .and_then(|snapshot| snapshot.column(issue.status.display()))
            .filter(|usage| usage.limit.is_some())
            .map_or_else(|| "-".to_string(), crate::wip::ColumnUsage::cell),
    }
}

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

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

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

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

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

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

/// WP04: takes the service's [`CategoryResolution`](crate::workflow::CategoryResolution)
/// rather than a completion column name.
///
/// MCP's `list_issues` called this with `done_column`, which is where the
/// "100% of surfaces agree" claim would have quietly stopped: the CLI would render
/// `Overdue` and the group rollup through the service while MCP rendered them
/// through a string. One parameter, both surfaces.
///
/// It renders in the CLI's **compact** mode, for the same reason: `list_issues`
/// carries `tix list`'s text, so it has to be the same text — including the crop
/// rule, which is a no-op at the zero width a caller passes when there is no
/// terminal to crop to (#1711).
pub fn render_default_table(
    issues: &[Issue],
    group: Option<&str>,
    resolution: &crate::workflow::CategoryResolution,
    width: usize,
) -> String {
    let columns = default_columns(issues);
    let (header, rows) = table_rows(
        issues, &columns, resolution, None, None, None, None, None, None,
    );
    render_table_from(
        issues, &columns, group, resolution, width, &header, &rows, None, None, true,
    )
}

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", "ID", "TITLE", "CHILDREN", "PROJECTS", "EPICS"],
            "`--show progress` is CHILDREN then PROJECTS then EPICS (WP04 T018), \
             appended to the compact default set (#1711)"
        );

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

    // -----------------------------------------------------------------------
    // #1711: the compact listing, the default scope and `tix ready`
    // -----------------------------------------------------------------------

    #[test]
    fn the_canonical_id_is_a_column_and_a_default_one() {
        assert_eq!(parse_columns("id").unwrap(), vec![ListColumn::Id]);
        assert_eq!(
            parse_columns("hash").unwrap(),
            vec![ListColumn::Id],
            "the word the request used reaches the same column"
        );
        assert_eq!(
            default_columns(&[]),
            vec![ListColumn::Num, ListColumn::Id, ListColumn::Title],
            "the identity pair and the title, nothing else"
        );
    }

    #[test]
    fn truncate_cell_fits_the_width_and_marks_what_it_dropped() {
        assert_eq!(truncate_cell("short", 10), "short");
        assert_eq!(truncate_cell("exactly-10", 10), "exactly-10");
        assert_eq!(truncate_cell("anything", 0), "", "no width, no cell");

        let cut = truncate_cell("a very long title indeed", 8);
        assert!(cut.ends_with('…'), "a cut is visible: {cut:?}");
        assert!(
            display_width(&cut) <= 8,
            "and fits its column: {cut:?} is {} wide",
            display_width(&cut)
        );
        assert!(
            !cut.trim_end().ends_with(' '),
            "a cut that landed after a space does not print `word …`: {cut:?}"
        );

        // A wide character is never split, and the ellipsis still fits.
        let wide = truncate_cell("日本語のタイトル", 4);
        assert!(display_width(&wide) <= 4, "{wide:?}");
    }

    /// The compact mode is one physical line per issue, and every line lands exactly
    /// on the width it was given — which is the whole point of cropping rather than
    /// wrapping (#1711).
    #[test]
    fn the_compact_table_is_one_line_per_issue_at_the_given_width() {
        let store = make_store().1;
        let issue = seed(
            &store,
            1,
            "A title long enough that it cannot possibly fit in one row",
            "todo",
        );
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let columns = default_columns(std::slice::from_ref(&issue));
        let (header, rows) = table_rows(
            std::slice::from_ref(&issue),
            &columns,
            &resolution,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let rendered = render_table_from(
            std::slice::from_ref(&issue),
            &columns,
            None,
            &resolution,
            40,
            &header,
            &rows,
            None,
            None,
            true,
        );
        assert_eq!(
            rendered.lines().count(),
            2,
            "a header and one row: {rendered}"
        );
        for line in rendered.lines() {
            assert_eq!(UnicodeWidthStr::width(line), 40, "{line:?}");
        }
    }

    /// With no terminal there is no width to crop to, so the compact listing prints
    /// the whole title: a pipe must not silently lose words.
    #[test]
    fn the_compact_table_keeps_the_whole_title_when_no_width_is_known() {
        let store = make_store().1;
        let title = "A title long enough that no forty column cap could ever hold it";
        let issue = seed(&store, 1, title, "todo");
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let columns = default_columns(std::slice::from_ref(&issue));
        let (header, rows) = table_rows(
            std::slice::from_ref(&issue),
            &columns,
            &resolution,
            None,
            None,
            None,
            None,
            None,
            None,
        );
        let rendered = render_table_from(
            std::slice::from_ref(&issue),
            &columns,
            None,
            &resolution,
            0,
            &header,
            &rows,
            None,
            None,
            true,
        );
        assert!(rendered.contains(title), "{rendered}");
        assert_eq!(rendered.lines().count(), 2, "{rendered}");
    }

    #[test]
    fn the_entry_column_skips_the_triage_inbox() {
        // A board whose first column is the inbox: the listing's scope starts at the
        // column an *accepted* issue lands in (#1711).
        let starter = crate::config::Config::starter();
        assert_eq!(entry_column(&starter).as_deref(), Some("todo"));

        // No `[triage]` section: the first column is the entry column.
        let bare = crate::config::Config::default();
        assert_eq!(bare.triage, None);
        assert_eq!(entry_column(&bare).as_deref(), Some("todo"));

        // A board whose *only* column is the inbox falls back to it rather than to
        // nothing.
        let mut inbox_only = crate::config::Config::starter();
        inbox_only.kanban.configurations.insert(
            "default".to_string(),
            crate::config::BoardConfiguration {
                columns: vec!["triage".to_string()],
                ..crate::config::BoardConfiguration::default()
            },
        );
        assert_eq!(entry_column(&inbox_only).as_deref(), Some("triage"));
    }

    #[test]
    fn the_default_scope_is_dropped_by_any_selection_of_your_own() {
        assert!(!ListSelection::default().names_a_selection());
        for selection in [
            ListSelection {
                all: true,
                ..ListSelection::default()
            },
            ListSelection {
                status: Some("doing"),
                ..ListSelection::default()
            },
            ListSelection {
                filter: Some("label:bug"),
                ..ListSelection::default()
            },
            ListSelection {
                project: Some("p-1"),
                ..ListSelection::default()
            },
            ListSelection {
                epic: Some("e-1"),
                ..ListSelection::default()
            },
        ] {
            assert!(
                selection.names_a_selection(),
                "a named selection replaces the scope: {selection:?}"
            );
        }
    }

    /// "Mine" is the git identity as `tix create` stores it, plus the spellings a
    /// human types by hand. Somebody else's issue and an unassigned one never match.
    #[test]
    fn is_mine_matches_the_stored_identity_and_its_handles() {
        let me = crate::assignee::AuthorIdentity {
            name: "Herbert Maschke".to_string(),
            email: Some("thyseus@pm.me".to_string()),
        };
        let assigned = |value: Option<&str>| {
            let mut issue = seed(&make_store().1, 1, "T", "todo");
            issue.assignee = value.map(str::to_string);
            issue
        };

        for stored in [
            "Herbert Maschke <thyseus@pm.me>",
            "Herbert Maschke",
            "@Herbert Maschke",
            "thyseus@pm.me",
            "thyseus",
        ] {
            assert!(is_mine(&assigned(Some(stored)), &me), "{stored:?}");
        }
        for stored in [None, Some("alice"), Some("alice@example.com")] {
            assert!(!is_mine(&assigned(stored), &me), "{stored:?}");
        }
    }

    /// The order `tix ready` prints: highest priority first, then oldest, then by
    /// number — and an unrecognized priority word sorts last rather than being
    /// guessed at.
    #[test]
    fn ready_orders_by_priority_then_age_then_number() {
        let store = make_store().1;
        let with = |number: u32, priority: &str, created: &str| {
            let mut issue = seed(&store, number, "T", "todo");
            issue.priority = priority.parse().unwrap();
            issue.created = created.to_string();
            issue
        };
        let mut issues = vec![
            with(1, "low", "2026-01-01"),
            with(2, "", "2026-01-01"),
            with(3, "high", "2026-02-01"),
            with(4, "high", "2026-01-01"),
            with(5, "someday", "2026-01-01"),
            with(6, "medium", "2026-01-01"),
        ];
        sort_ready(&mut issues);
        assert_eq!(
            issues.iter().map(|issue| issue.number).collect::<Vec<_>>(),
            vec![4, 3, 6, 1, 2, 5],
            "high (oldest first), medium, low, unset, then the unknown word"
        );
    }

    /// The structure of a `--format` record: the displayed columns, in order, under
    /// one root — and the same cells the table would have printed.
    #[test]
    fn records_carry_the_displayed_columns_in_every_format() {
        let header = vec!["NUM".to_string(), "TITLE".to_string()];
        let rows = vec![
            vec!["1".to_string(), "Alpha & <Beta>".to_string()],
            vec!["2".to_string(), String::new()],
        ];

        let toml = render_records(&header, &rows, ListFormat::Toml).unwrap();
        assert!(toml.contains("[[issues]]"), "{toml}");
        assert!(toml.contains(r#"title = "Alpha & <Beta>""#), "{toml}");
        assert_eq!(
            toml.matches("[[issues]]").count(),
            2,
            "one record per issue: {toml}"
        );

        let yaml = render_records(&header, &rows, ListFormat::Yaml).unwrap();
        assert!(yaml.starts_with("issues:\n"), "{yaml}");
        assert!(
            yaml.contains("  title: ''"),
            "an empty cell is present and empty: {yaml}"
        );

        let xml = render_records(&header, &rows, ListFormat::Xml).unwrap();
        assert!(xml.contains("<num>1</num>"), "{xml}");
        assert!(
            xml.contains("<title>Alpha &amp; &lt;Beta&gt;</title>"),
            "values are escaped, so the document parses: {xml}"
        );

        assert!(ListFormat::parse("YAML").is_ok(), "case-insensitive");
        for value in ["json", "csv", ""] {
            let error = ListFormat::parse(value).unwrap_err().to_string();
            assert!(error.contains("unknown list format"), "{value}: {error}");
        }
    }
}