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
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
//! Shared search corpus and matchers for `tix search` (CLI, WP04) and the
//! `/` search (TUI, WP05).
//!
//! Both consumers search **exactly the same corpus**: the complete serialized
//! markdown of every issue (`Issue::to_file_contents()`, i.e. frontmatter +
//! body + comments). A single engine here keeps the CLI and TUI behavior from
//! drifting (C-005, FR-012):
//!
//! - [`Corpus::build`] snapshots every issue's full file text.
//! - [`search_substring`] is the case-insensitive single-occurrence matcher
//!   the CLI uses, returning matched-line context.
//! - [`query_matches`] is the grammar-aware matcher (`key:value` tokens plus
//!   case-insensitive **substring** bare terms) the board's `/` search uses.
//! - [`fuzzy_score`] is the deterministic subsequence scorer, now used only as
//!   the help overlay's fallback when a literal substring finds no row (tix
//!   #1496); the board's `/` search no longer uses it (tix #1498).
//!
//! Nothing here touches the `-assets/` directories (C-005): binary contents
//! are never indexed, and [`Corpus::build`] inherits that from
//! [`Store::list`], which already excludes non-`.md` files and `-assets` dirs.

use serde::{Deserialize, Serialize};

use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::storage::Store;
use crate::watcher::FsDelta;
use std::collections::HashSet;
use std::path::{Path, PathBuf};

/// The corpus: one `Issue` per file (in [`Store::list`] order) and the
/// byte-for-byte serialized file text matching it.
pub struct Corpus {
    pub issues: Vec<Issue>,
    /// Serialized file text per issue, built on first use (tix #1520).
    ///
    /// `texts()[i]` is exactly `issues[i].to_file_contents()` — the same
    /// invariant [`Corpus::build`] has always upheld — but *when* it is
    /// computed is now deferred: a startup that never searches should not pay
    /// to serialize every issue. Access through [`Corpus::texts`].
    texts: std::cell::OnceCell<Vec<String>>,
}

impl Corpus {
    /// Snapshot the full serialized text of every issue under `store`.
    ///
    /// `texts[i]` is exactly `issues[i].to_file_contents()`, so the corpus is
    /// byte-identical to the on-disk files (modulo whatever the serializer
    /// itself produces). Files are read once here, through [`Store::list`];
    /// consumers never re-read them (C-005/NFR-007 keep the corpus a single,
    /// stable source).
    pub fn build(store: &Store) -> Result<Corpus> {
        Self::build_with(store, false)
    }

    /// Snapshot the corpus, optionally including archived issues (issue #1492).
    ///
    /// `with_archived == false` is the default path and reads
    /// [`Store::list`], which never opens an archived file. `true` reads
    /// [`Store::list_all`] so `tix search --with-archived` can match the archived
    /// set; the archived issues carry `archived == true`.
    pub fn build_with(store: &Store, with_archived: bool) -> Result<Corpus> {
        let issues = if with_archived {
            store.list_all()?
        } else {
            store.list()?
        };
        Ok(Self::from_issues(issues))
    }

    /// Snapshot a corpus from an **already-read** issue set (tix #1518).
    ///
    /// The TUI's startup reads the tree exactly once and shares that single
    /// enumeration between the board, the rollover plan and this corpus; this
    /// constructor is that sharing point. It upholds the same invariant
    /// [`Corpus::build`] does — `texts[i] == issues[i].to_file_contents()` — so a
    /// corpus built here is byte-identical to one built by a fresh walk.
    pub fn from_issues(issues: Vec<Issue>) -> Corpus {
        // No serialization here: `texts()` builds the cached snapshot on first
        // use (tix #1520). Startup that never searches pays nothing.
        Corpus {
            issues,
            texts: std::cell::OnceCell::new(),
        }
    }

    /// The serialized file text of every issue, built on first use and cached
    /// thereafter (tix #1520).
    ///
    /// `texts()[i]` is exactly `issues[i].to_file_contents()`, so a caller
    /// cannot tell whether the corpus was built by a full walk or shared from an
    /// already-read issue set — only that it is not paying to serialize issues
    /// no search will ever look at.
    pub fn texts(&self) -> &[String] {
        self.texts.get_or_init(|| {
            self.issues
                .iter()
                .map(|issue| issue.to_file_contents())
                .collect()
        })
    }

    /// Build a corpus with a fixed serialized-text snapshot (tests only).
    ///
    /// Production always goes through [`Corpus::from_issues`], which defers
    /// serialization; a test that wants to pin the matcher's input without a
    /// store uses this instead of reaching into the private cache.
    #[cfg(test)]
    pub fn with_texts(issues: Vec<Issue>, texts: Vec<String>) -> Corpus {
        Corpus {
            issues,
            texts: std::cell::OnceCell::from(texts),
        }
    }

    /// Whether the serialized snapshot has been built yet (tests only).
    #[cfg(test)]
    pub fn texts_initialized(&self) -> bool {
        self.texts.get().is_some()
    }

    /// Index of the issue with `number` `n`, if present (stable, linear scan).
    pub fn by_number(&self, n: u32) -> Option<usize> {
        self.issues.iter().position(|issue| issue.number == n)
    }

    /// Apply a filesystem delta to the corpus without re-reading the tree
    /// (issue #10 follow-up).
    ///
    /// Re-reads only the paths the watcher reported changed, drops the removed
    /// ones, and keeps `texts[i] == issues[i].to_file_contents()` and the
    /// corpus ordered by `filename` exactly as [`Store::scan`] returns it — so
    /// an incrementally updated corpus is byte-identical to a full
    /// [`Corpus::build_with`] over the same files.
    ///
    /// Paths [`Store::scan`] would not index are ignored: non-`.md` files,
    /// files in a `.tix-tmp-*`/`*-assets/` segment, and anything nested deeper
    /// than one segment (see [`crate::storage::is_issue_rel_path`]). A file
    /// that vanished or cannot be read since the watcher saw it counts as
    /// removed. A **parse** failure is returned as an error with the corpus
    /// left untouched — all-or-nothing — so a half-written file cannot replace
    /// the last good corpus, and so the caller's board stays as it was.
    ///
    /// The delta is applied as given: the archived-view policy lives in the
    /// caller (`App::refresh_from_disk` strips archived paths when the archived
    /// toggle is off).
    pub fn apply(&mut self, store: &Store, delta: &FsDelta) -> Result<()> {
        if !delta
            .changed
            .iter()
            .any(|p| crate::storage::is_issue_rel_path(p))
            && !delta
                .removed
                .iter()
                .any(|p| crate::storage::is_issue_rel_path(p))
        {
            return Ok(());
        }
        // Read every changed file first: a parse error must leave `self` as it
        // was, which is only possible if nothing is mutated before all reads
        // succeed.
        let mut updates: Vec<Issue> = Vec::new();
        for path in &delta.changed {
            if !crate::storage::is_issue_rel_path(path) {
                continue;
            }
            match store.read_issue_at(path) {
                Ok(issue) => updates.push(issue),
                // Gone or unreadable since the walk: a removal, not an error.
                Err(TixError::NotFound(_) | TixError::Io(_)) => {}
                Err(e) => return Err(e),
            }
        }
        // Every indexable changed path replaces its corpus entry, and every
        // indexable removed path drops one.
        let dropped: HashSet<&Path> = delta
            .changed
            .iter()
            .chain(delta.removed.iter())
            .filter(|path| crate::storage::is_issue_rel_path(path))
            .map(PathBuf::as_path)
            .collect();
        let mut combined: Vec<Issue> = Vec::with_capacity(self.issues.len() + updates.len());
        let issues = std::mem::take(&mut self.issues);
        for issue in issues {
            if !dropped.contains(Path::new(&issue.filename)) {
                combined.push(issue);
            }
        }
        combined.extend(updates);
        // `scan` sorts by filename; matching it keeps an incremental corpus
        // byte-identical to a rebuild.
        combined.sort_by(|a, b| a.filename.cmp(&b.filename));
        self.issues = combined;
        // The serialized snapshot is stale now (tix #1520). Dropping the cache
        // rather than rebuilding it keeps the deferral: the next reader
        // re-serializes from the updated issue set, and `texts()` still upholds
        // `texts[i] == issues[i].to_file_contents()`.
        self.texts = std::cell::OnceCell::new();
        Ok(())
    }
}

/// One substring search hit: the issue and every corpus line that contains
/// the matched query (context for the CLI result block, NFR-007).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchHit {
    pub issue: Issue,
    pub matched_lines: Vec<String>,
}

/// Case-insensitive substring search over the corpus.
///
/// For each corpus text containing `query` (case-insensitive), every line
/// containing the match is collected verbatim as matched-line context. Hits
/// are ordered by issue `number` ascending (stable, NFR-007).
///
/// An empty query matches **nothing** by contract: the CLI refuses it via
/// clap, and the TUI treats an empty filter as "no filter" — callers decide,
/// this function returns an empty vec so they never see a surprise.
pub fn search_substring(corpus: &Corpus, query: &str) -> Vec<SearchHit> {
    if query.is_empty() {
        return Vec::new();
    }
    let needle = query.to_lowercase();
    let mut hits: Vec<SearchHit> = Vec::new();
    for (issue, text) in corpus.issues.iter().zip(corpus.texts().iter()) {
        let hay = text.to_lowercase();
        if !hay.contains(&needle) {
            continue;
        }
        let matched_lines: Vec<String> = text
            .lines()
            .filter(|line| line.to_lowercase().contains(&needle))
            .map(str::to_string)
            .collect();
        hits.push(SearchHit {
            issue: issue.clone(),
            matched_lines,
        });
    }
    hits.sort_by_key(|hit| hit.issue.number);
    hits
}

/// Deterministic fuzzy subsequence score: higher is a better match, `None`
/// when `query` is not a subsequence of `haystack` (case-insensitive).
///
/// The scorer is the fzf/vim-style "fast substring" heuristic, kept simple
/// and pure (no normalization, no unicode tables, no dependencies):
///
/// - every matched character contributes a presence bonus plus an
///   earlier-position bonus (`1000 - position`), so matches near the start of
///   the text outrank those buried deep in it;
/// - adjacent matched characters (contiguous runs) get a run bonus;
/// - a match that starts at the very beginning gets a prefix bonus;
/// - an exact match (equal strings, case-insensitive) dominates.
///
/// An empty query is an implicit match with score `Some(0)` — the TUI treats
/// it as "no filter". Deterministic and fast enough for > 500 issues per
/// keystroke (verified by the perf tripwire test).
pub fn fuzzy_score(query: &str, haystack: &str) -> Option<u32> {
    let q = query.to_lowercase();
    let h = haystack.to_lowercase();
    if q.is_empty() {
        return Some(0);
    }
    if q == h {
        return Some(EXACT_MATCH_SCORE);
    }
    let positions = greedy_subsequence_positions(&q, &h)?;
    let mut score = 0u32;
    let mut prev: Option<usize> = None;
    for pos in &positions {
        score += 100;
        score += (1000 - (*pos).min(1000)) as u32;
        if prev.is_some_and(|p| *pos == p + 1) {
            score += RUN_BONUS;
        }
        prev = Some(*pos);
    }
    if positions.first() == Some(&0) {
        score += PREFIX_BONUS;
    }
    Some(score)
}

/// Bonus for a contiguous pair of matched characters.
const RUN_BONUS: u32 = 150;
/// Bonus when the first matched character is the first character of the text.
const PREFIX_BONUS: u32 = 500;
/// Score for an exact (case-insensitive) equality — dominates any partial.
const EXACT_MATCH_SCORE: u32 = 50_000;

/// Greedy leftmost subsequence match, case-insensitive. Returns the haystack
/// positions of `query`'s characters in order, or `None` when `query` is not
/// a subsequence of `haystack`.
fn greedy_subsequence_positions(query: &str, haystack: &str) -> Option<Vec<usize>> {
    let q: Vec<char> = query.chars().collect();
    if q.is_empty() {
        return Some(Vec::new());
    }
    let h: Vec<char> = haystack.chars().collect();
    let mut positions = Vec::with_capacity(q.len());
    let mut hi = 0usize;
    /* tolerate differing-cased surrogates the same way the lowercase scan does */
    for qc in &q {
        let found = h[hi..]
            .iter()
            .position(|hc| *hc == *qc)
            .map(|off| off + hi)?;
        positions.push(found);
        hi = found + 1;
    }
    Some(positions)
}

// ---------------------------------------------------------------------------
// Structured filtering (FR-007..FR-013)
// ---------------------------------------------------------------------------

/// A selectable structured-filter criterion.
///
/// [`FilterField::ALL`] is the single ordered field list the filter modal
/// renders its rows from (risk: field/modal drift) and [`StructuredFilter`]
/// evaluates over — adding a criterion (FR-011) is one more `Option<String>`
/// field on [`StructuredFilter`] plus one variant / match arm here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterField {
    Assignee,
    Label,
    Status,
    Priority,
    Cycle,
    Milestone,
    Reviewer,
    StartDate,
    DueDate,
    /// An issue's **direct** parent, by selector (WP06 T024).
    Parent,
    /// An issue's resolved workflow category, by category key (WP08 T034).
    ///
    /// **Derived, not stored.** Unlike the nine above, this criterion matches
    /// nothing an issue's file contains: there is no `category` frontmatter key
    /// (research R2), and the value comes from the issue's `status` resolved
    /// through the board's `category_map`. See [`FilterField::key`] for what
    /// that means for diagnostics.
    Category,
    /// An issue's **project membership**, by resolved project id (WP06 T026).
    ///
    /// A **membership** criterion, not a text one. `project:<id>` asks whether the
    /// issue's association list — `Issue::projects`, read through the shared
    /// [`crate::projects::ProjectNode::project_ids`] accessor that
    /// `ProjectIndex::build` itself reads — contains the referenced project. It is
    /// deliberately **not** a substring test on the rendered frontmatter: that
    /// would call an issue whose body mentions an id a member, and would match
    /// `project:p-1` against an issue associated with `p-12`.
    ///
    /// An issue in two projects matches `project:A` **and** `project:B`
    /// (recorded in `contracts/cli-surface.md` §3); an unassociated issue matches
    /// no project criterion, and an id no association carries matches nothing.
    Project,
    /// An issue's **epic membership**, by resolved epic id (WP06 T028).
    ///
    /// A **membership** criterion, not a text one, and the exact analogue of
    /// [`FilterField::Project`] for the epic registry. `epic:<id>` asks whether the
    /// issue's reference list — `Issue::epics`, read through the shared
    /// [`crate::epics::EpicNode::epic_ids`] accessor that
    /// [`crate::epics::EpicIndex::build`] itself reads — contains the referenced
    /// epic. It is deliberately **not** a substring test on the rendered
    /// frontmatter: that would call an issue whose body mentions an id a member, and
    /// would match `epic:e-1` against an issue referencing `e-12`.
    ///
    /// An issue in two epics matches `epic:A` **and** `epic:B` (recorded in
    /// `contracts/cli-surface.md` §3); an unreferenced issue matches no epic
    /// criterion, and an id no reference carries matches nothing.
    ///
    /// The **token** is the singular `epic:` while [`Self::key`] is the plural
    /// `epics` the model serializes — the same split [`FilterField::Project`]
    /// records, and for the same reason.
    Epic,
}

impl FilterField {
    /// The criteria in modal row order (research D-05).
    ///
    /// `Parent` is **appended** rather than interleaved: a row's position is a
    /// user's muscle memory and a TUI test's golden index, and moving eight
    /// existing rows to make room for a ninth helps nobody (T024 step 2).
    ///
    /// `Category` is **appended** after `Parent`, for the same reason T024 step 2
    /// gave: a row's position is a user's muscle memory and the TUI's golden
    /// index, and it is also the position a user reaches last. A category is the
    /// one criterion a user cannot reach from the file itself, so it is the one
    /// they will look up last.
    ///
    /// `Project` is **appended** after `Category` for the same reason T024 step 2
    /// gave: a row's position is a user's muscle memory and the TUI's golden index.
    /// Appending is also what keeps `next()`/`prev()` wrapping correct without
    /// touching a single existing index — the arithmetic is a modulus of the
    /// extended length, and the wrapping test asserts both ends.
    ///
    /// `Epic` is **appended** after `Project` (WP06 T028) for exactly the same
    /// reason: a row's position is a user's muscle memory and the TUI's golden
    /// index, and appending keeps `next()`/`prev()` correct as a modulus of the
    /// extended length without moving a single existing row.
    pub const ALL: [FilterField; 13] = [
        FilterField::Assignee,
        FilterField::Label,
        FilterField::Status,
        FilterField::Priority,
        FilterField::Cycle,
        FilterField::Milestone,
        FilterField::Reviewer,
        FilterField::StartDate,
        FilterField::DueDate,
        FilterField::Parent,
        FilterField::Category,
        FilterField::Project,
        FilterField::Epic,
    ];

    pub fn label(self) -> &'static str {
        match self {
            FilterField::Assignee => "Assignee",
            FilterField::Label => "Label",
            FilterField::Status => "Status",
            FilterField::Priority => "Priority",
            FilterField::Cycle => "Cycle",
            FilterField::Milestone => "Milestone",
            FilterField::Reviewer => "Reviewer",
            FilterField::StartDate => "Start date",
            FilterField::DueDate => "Due date",
            FilterField::Parent => "Parent",
            FilterField::Category => "Category",
            FilterField::Project => "Project",
            FilterField::Epic => "Epic",
        }
    }

    /// The serialized frontmatter key each criterion matches against
    /// (`Issue::to_file_contents` emits these). Used by diagnostics.
    ///
    /// **For [`FilterField::Category`] this is the token name, not a frontmatter
    /// key**, because there is no `category` key: the criterion is derived from the
    /// issue's `status` through the board's `category_map` (research R2). T034
    /// step 4 asked what to report here and warned that leaving a nonexistent key
    /// in the diagnostics would be a quiet lie, so the honest spelling is
    /// `category` — which is exactly what the user types, and what the grammar
    /// parses — plus [`FilterField::is_derived`] for any surface that has to
    /// *explain* the criterion rather than merely echo it.
    ///
    /// The distinction is not cosmetic. `key()` feeds two things that read very
    /// differently: a hint bar, where `category:completed` is exactly right, and
    /// an error, where "no issue has `category:completed`" would send a user
    /// looking for a field that does not exist. [`is_derived`] is what keeps the
    /// second from happening.
    pub fn key(self) -> &'static str {
        match self {
            FilterField::Assignee => "assignee",
            FilterField::Label => "labels",
            FilterField::Status => "status",
            FilterField::Priority => "priority",
            FilterField::Cycle => "cycle",
            FilterField::Milestone => "milestone",
            FilterField::Reviewer => "reviewer",
            FilterField::StartDate => "start_date",
            FilterField::DueDate => "due_date",
            // The exact key `Issue` serializes. T024 step 4 asks for a test that
            // fails if this drifts from the model, because `key()` feeds the
            // diagnostics: a mismatch makes `tix lint` point at a field that does
            // not exist, with no error anywhere.
            FilterField::Parent => "parent",
            // The **token** name, and the only correct spelling here: the grammar
            // parses `category:` and the hint bar echoes it. Not a frontmatter key,
            // and `is_derived` is what stops it being read as one.
            FilterField::Category => "category",
            // The exact frontmatter key WP03's model serializes (`Issue::to_file_contents`
            // emits `projects:` via `PROJECTS_KEY`). Unlike `category`, this **is** a
            // real frontmatter key, so the diagnostics may name it honestly — and a
            // test asserts the string equals the model's constant, so a rename on
            // there breaks a test rather than silently breaking the filter.
            FilterField::Project => "projects",
            // The exact frontmatter key WP03's model serializes (`Issue::to_file_contents`
            // emits `epics:` via [`crate::epics::EPICS_KEY`]). Named through the
            // service constant rather than a second literal so the filter table and
            // the file format cannot drift: a rename on the service side fails a test
            // (and this arm) rather than silently breaking the filter.
            FilterField::Epic => crate::epics::EPICS_KEY,
        }
    }

    /// Whether this criterion is **derived** from other data rather than read off
    /// a frontmatter field (WP08 T034 step 4).
    ///
    /// `Category` is the only one. It is derived from `status` through the board's
    /// `category_map`, so a diagnostic that names it as a field points at a field
    /// that does not exist. Any surface printing *why* a criterion matched, or why
    /// it found nothing, must say so through this.
    pub fn is_derived(self) -> bool {
        matches!(self, FilterField::Category)
    }

    /// The criterion as a user should read it in an explanation: `category` on its
    /// own, or `category (derived from status)` where the extra clause matters.
    ///
    /// Split from [`key`] so a caller has to choose. A hint bar that appends
    /// "(derived from status)" on every keystroke is noise, and an error that
    /// omits it sends the user hunting for a field; this hands each surface the
    /// short form and lets the ones that explain pick the long one.
    pub fn describe(self) -> String {
        if self.is_derived() {
            format!("{} (derived from status)", self.key())
        } else {
            self.key().to_string()
        }
    }

    /// Row index of this criterion in [`FilterField::ALL`].
    pub fn row(self) -> usize {
        FilterField::ALL
            .iter()
            .position(|field| *field == self)
            .expect("FilterField variants are all in ALL")
    }

    pub fn next(self) -> Self {
        let all = FilterField::ALL;
        all[(self.row() + 1) % all.len()]
    }

    pub fn prev(self) -> Self {
        let all = FilterField::ALL;
        all[(self.row() + all.len() - 1) % all.len()]
    }

    /// The criterion value when set *and* non-empty. An empty string is
    /// treated as "no criterion" everywhere (canonical invariant), so the
    /// filter modal can edit a slot without a live-match surprise.
    pub fn value(self, filter: &StructuredFilter) -> Option<&str> {
        let value = match self {
            FilterField::Assignee => filter.assignee.as_deref(),
            FilterField::Label => filter.label.as_deref(),
            FilterField::Status => filter.status.as_deref(),
            FilterField::Priority => filter.priority.as_deref(),
            FilterField::Cycle => filter.cycle.as_deref(),
            FilterField::Milestone => filter.milestone.as_deref(),
            FilterField::Reviewer => filter.reviewer.as_deref(),
            FilterField::StartDate => filter.start_date.as_deref(),
            FilterField::DueDate => filter.due_date.as_deref(),
            FilterField::Parent => filter.parent.as_deref(),
            FilterField::Category => filter.category.as_deref(),
            FilterField::Project => filter.project.as_deref(),
            FilterField::Epic => filter.epic.as_deref(),
        };
        value.filter(|s| !s.is_empty())
    }

    /// Mutable access to the criterion buffer, materializing an empty one
    /// when the criterion is unset (the filter modal types into it and
    /// `StructuredFilter::normalize` promotes empty back to `None`).
    pub fn value_mut(self, filter: &mut StructuredFilter) -> &mut String {
        match self {
            FilterField::Assignee => filter.assignee.get_or_insert_default(),
            FilterField::Label => filter.label.get_or_insert_default(),
            FilterField::Status => filter.status.get_or_insert_default(),
            FilterField::Priority => filter.priority.get_or_insert_default(),
            FilterField::Cycle => filter.cycle.get_or_insert_default(),
            FilterField::Milestone => filter.milestone.get_or_insert_default(),
            FilterField::Reviewer => filter.reviewer.get_or_insert_default(),
            FilterField::StartDate => filter.start_date.get_or_insert_default(),
            FilterField::DueDate => filter.due_date.get_or_insert_default(),
            FilterField::Parent => filter.parent.get_or_insert_default(),
            // The criterion is typed into the modal and validated when the query is
            // **run** (see `resolve_category_criterion`), not per keystroke: the
            // modal edits a buffer, and rejecting a half-typed `comp` because it is
            // not yet a category would make the row unusable. The service has no
            // business being called from a text field.
            FilterField::Category => filter.category.get_or_insert_default(),
            // Same reasoning as `Category` above: the modal edits a buffer, and the
            // criterion is judged when the query **runs** (see `project_matches`),
            // not per keystroke. A half-typed project id is not a project, and the
            // service has no business being called from a text field.
            FilterField::Project => filter.project.get_or_insert_default(),
            // Same reasoning as `Project` above: the modal edits a buffer, and the
            // criterion is judged when the query **runs** (see `epic_matches`), not
            // per keystroke. A half-typed epic id is not an epic, and the service
            // has no business being called from a text field.
            FilterField::Epic => filter.epic.get_or_insert_default(),
        }
    }

    /// Clear the criterion back to `None`.
    pub fn unset(self, filter: &mut StructuredFilter) {
        match self {
            FilterField::Assignee => filter.assignee = None,
            FilterField::Label => filter.label = None,
            FilterField::Status => filter.status = None,
            FilterField::Priority => filter.priority = None,
            FilterField::Cycle => filter.cycle = None,
            FilterField::Milestone => filter.milestone = None,
            FilterField::Reviewer => filter.reviewer = None,
            FilterField::StartDate => filter.start_date = None,
            FilterField::DueDate => filter.due_date = None,
            FilterField::Parent => filter.parent = None,
            FilterField::Category => filter.category = None,
            FilterField::Project => filter.project = None,
            FilterField::Epic => filter.epic = None,
        }
    }

    /// Whether this criterion is a **parent reference** rather than a text field.
    ///
    /// The distinction drives two things: the free-typing path is bypassed in
    /// favour of the issue picker (WP06 T026), and `evaluate` compares exactly
    /// rather than by substring, because a number must not match a longer number
    /// that merely contains it.
    pub fn is_reference(self) -> bool {
        matches!(self, FilterField::Parent)
    }

    /// The criterion's **query token**, as the grammar parses it and the hint bar
    /// should echo it.
    ///
    /// For every criterion but [`FilterField::Project`] and
    /// [`FilterField::Epic`] this is [`Self::key`] — the two spellings coincide
    /// (`status:`, `labels:`, `parent:` the token and the frontmatter key alike).
    /// Those two are the places they differ, and deliberately: the **token** is the
    /// singular `project:`/`epic:` the parser accepts and the modal's help
    /// advertises, while the **key** is the plural `projects`/`epics` WP03's model
    /// serializes. A hint bar echoing `projects:p-1` would advertise a token
    /// [`query_matches`] does not parse, which is a key that looks usable and does
    /// nothing — the exact failure `key()`'s own doc warns about for diagnosis.
    pub fn token(self) -> &'static str {
        match self {
            FilterField::Project => "project",
            FilterField::Epic => "epic",
            _ => self.key(),
        }
    }

    /// Whether this criterion is a **project membership** test rather than a text
    /// field (WP06 T026).
    ///
    /// Kept separate from [`Self::is_reference`] even though both compare exactly:
    /// a parent is a *number* on the issue's own frontmatter and can be rewritten
    /// into the query, while a project is a *membership* the file's bytes answer
    /// only indirectly (the association list is a YAML block, not a scalar), so the
    /// criterion travels in the [`StructuredFilter`] and is judged by
    /// [`StructuredFilter::project_matches`]. The surfaces use this predicate to
    /// route the row to the project picker rather than the issue picker.
    pub fn is_project(self) -> bool {
        matches!(self, FilterField::Project)
    }

    /// Whether this criterion is an **epic membership** test rather than a text
    /// field (WP06 T028).
    ///
    /// The exact analogue of [`Self::is_project`]: a reference list is a YAML block
    /// the rendered bytes answer only indirectly, so the criterion travels in the
    /// [`StructuredFilter`] and is judged by [`StructuredFilter::epic_matches`]. Kept
    /// a separate predicate from `is_project` because the two name different
    /// registries and different pickers — collapsing them would make the surfaces
    /// offer a project picker for an epic row.
    pub fn is_epic(self) -> bool {
        matches!(self, FilterField::Epic)
    }

    /// Whether this criterion holds a date (picker-only, no free typing).
    pub fn is_date(self) -> bool {
        matches!(self, FilterField::StartDate | FilterField::DueDate)
    }
}

/// Typed, extensible structured filter (FR-007..FR-010, FR-011).
///
/// Every criterion is optional; an `None`/empty criterion narrows nothing.
/// Criteria match **case-insensitively** against the serialized corpus text
/// (the same haystack [`fuzzy_score`] runs over), following the existing
/// fuzzy matcher's `to_lowercase()` behavior — this keeps the predicate a
/// pure, config-independent function of the corpus (WP02 runs in parallel
/// with WP01 for exactly that reason).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StructuredFilter {
    pub assignee: Option<String>,
    pub label: Option<String>,
    pub status: Option<String>,
    pub priority: Option<String>,
    pub cycle: Option<String>,
    pub milestone: Option<String>,
    pub reviewer: Option<String>,
    pub start_date: Option<String>,
    pub due_date: Option<String>,
    pub overdue: Option<bool>,
    /// The referenced parent, as a **resolved issue number** (WP06 T025).
    ///
    /// A number, not the selector the user typed, because matching happens against
    /// an issue's rendered frontmatter and that carries `parent: 7`. Resolution
    /// happens once, at the command layer, where the store is available; matching
    /// then stays a pure string comparison and `query_matches` keeps its
    /// store-free signature.
    ///
    /// Direct children only, and by construction: an issue's `parent:` field *is*
    /// its direct parent, so a grandchild's file says `parent: 2` and never matches
    /// a criterion of `parent: 1`. A transitive implementation would have to walk
    /// the chain explicitly, and this way there is nothing to get wrong.
    pub parent: Option<String>,
    /// A workflow **category key** (WP08 T035), never a column name.
    ///
    /// A category key rather than a column, because several columns can share one
    /// category and the whole point of the criterion is to select across that
    /// boundary: `category:completed` on a board with `shipped`, `done` and
    /// `released` all complete returns every one of them, where `status:done`
    /// returns one.
    ///
    /// Validated through the service's `from_key` when the query runs
    /// ([`resolve_category_criterion`]), so this never holds a value the
    /// vocabulary does not contain. The TUI modal types into it unchecked — see
    /// [`FilterField::value_mut`] for why that is the right layer to do it at.
    pub category: Option<String>,
    /// A resolved **project id** (WP06 T026/T027), or a reference no project
    /// resolves to.
    ///
    /// Judged by [`Self::project_matches`] against the issue's association list —
    /// never by [`Self::evaluate`]'s substring loop, because the association list
    /// is a YAML block rather than a scalar line and a substring would match an id
    /// mentioned in a body.
    ///
    /// [`resolve_filter_criteria`] canonicalizes a `project:<selector>` token into
    /// this field, resolving an id or a name through the project service. A
    /// reference the registry does not know is kept **verbatim** rather than
    /// refused: the documented behaviour is that an unknown project id matches
    /// nothing (T027 step 6), and `tix search` must not turn a typo into a hard
    /// error where the filter grammar accepts every other unknown value. Matching
    /// then simply finds no member, which is the empty result the user can see.
    ///
    /// An issue in two projects matches `project:A` and `project:B`; the criterion
    /// narrows to the union of one project's members per query token, exactly like
    /// every other single-valued criterion.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub project: Option<String>,
    /// A resolved **epic id** (WP06 T028/T029), or a reference no epic resolves
    /// to.
    ///
    /// The epic analogue of [`Self::project`], judged by [`Self::epic_matches`]
    /// against the issue's `epics` reference list — never by [`Self::evaluate`]'s
    /// substring loop, because the list is a YAML block rather than a scalar line
    /// and a substring would match an id mentioned in a body.
    ///
    /// [`resolve_filter_criteria`] canonicalizes an `epic:<selector>` token into
    /// this field, resolving an id or a name through the epic service
    /// ([`crate::epics::resolve_epic_id`]). A reference the registry does not know is
    /// kept **verbatim** rather than refused: the documented behaviour is that an
    /// unknown epic id matches nothing (T029 step 6), mirroring `project:`.
    ///
    /// An issue in two epics matches `epic:A` and `epic:B`; the criterion narrows to
    /// the union of one epic's members per query token, exactly like every other
    /// single-valued criterion.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub epic: Option<String>,
    /// The columns a `scope:` token selected (WP02 T010).
    ///
    /// A set of **column names**, not a name, because the columns are not
    /// knowable from the query: `scope:triage` means "the columns `[triage]`
    /// names", and only the config can answer that — the same reason `parent:`
    /// and `category:` are resolved rather than matched from bytes. Filled by
    /// [`resolve_filter_criteria`] through
    /// [`crate::triage::inbox::scope_columns`], and judged by
    /// [`Self::scope_matches`], which needs the issue the way `category` does.
    ///
    /// Deliberately **not** a [`FilterField`]: the filter modal has no row for
    /// it and no user can type a scope into it, and appending a variant would
    /// change `FilterField::ALL`'s length — which the modal's row layout, its
    /// click mapping and its own tests all count. The extensibility promise on
    /// [`FilterField`] is about criteria a user can enter; this is a resolved
    /// selection a *token* produces, and `overdue` already shows a
    /// `StructuredFilter` field that is not a modal row.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scope: Option<Vec<String>>,
    /// Whether the issue is **archived** (issue #1492), from an
    /// `archived:true|false` token.
    ///
    /// A **derived** criterion, like `overdue` and `scope`, and for the same
    /// reason: `archived` is not a frontmatter key. The marker is the leading dot
    /// of the issue's filename, mirrored onto [`Issue::archived`], so nothing in
    /// the serialized bytes can answer the question and the token is lifted out
    /// by [`resolve_filter_criteria`] into this field, then judged by
    /// [`Self::archived_matches`], which has the issue.
    ///
    /// `None` (no token) narrows nothing.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub archived: Option<bool>,
}

impl StructuredFilter {
    /// The active (set, non-empty) criteria, in [`FilterField::ALL`] order.
    pub fn criteria(&self) -> impl Iterator<Item = (FilterField, &str)> {
        FilterField::ALL
            .into_iter()
            .filter_map(move |field| field.value(self).map(|value| (field, value)))
    }

    /// True when at least one criterion is active. When false the board must
    /// render unchanged (no criteria → pass-through).
    ///
    /// The `scope` criterion is counted here even though it is not a
    /// [`FilterField`] and so never appears in [`Self::criteria`]: a query that
    /// selected rows is active however it selected them, and omitting it would
    /// make `has_active_criteria` disagree with [`Self::evaluate_issue`] about
    /// whether the same filter narrowed anything.
    pub fn has_active_criteria(&self) -> bool {
        self.criteria().next().is_some() || self.scope.is_some() || self.archived.is_some()
    }

    /// AND predicate over the serialized corpus text (FR-012, C-002).
    ///
    /// Applies *every* active criterion; the first miss short-circuits the
    /// entry to `false`. The caller (WP03's `build_filtered`) invokes this
    /// once per corpus entry, giving **one linear O(entries) pass** (NFR-001)
    /// — `haystack` is lowercased once and each active criterion is a single
    /// substring `contains` on that pre-lowered text, with no nested
    /// field×corpus loops.
    ///
    /// Matching is case-insensitive and substring-based, consistently across
    /// assignee/label/status/priority, exactly as WP02's prompt specifies
    /// (T009). The stricter per-criterion "equals"/"contains-in-labels" rules
    /// in `contracts/filtering.md` would require re-parsing the issue; on the
    /// serialized corpus the substring rule is the single consistent gate.
    pub fn evaluate(&self, haystack: &str) -> bool {
        let hay = haystack.to_lowercase();
        // The parent criterion is **not** a substring test, and is handled before
        // the generic loop rather than inside it.
        //
        // Two reasons. First, a substring test over the whole haystack would match
        // an issue whose *body* mentions the number, or whose `parent: 17` contains
        // `1` — so `parent:1` would return the children of #17 as well. Second, the
        // generic loop would also be reached for an issue with **no** `parent:` key
        // at all, where `hay.contains("1")` is true for any issue whose text
        // mentions 1. Every other criterion is a text field where substring is the
        // right semantic; a reference is a value.
        if let Some(number) = &self.parent
            && field_value(haystack, "parent") != Some(number.as_str())
        {
            return false;
        }
        for (field, value) in self.criteria() {
            // `parent` was already compared exactly above, and `category` cannot be
            // compared here at all — see `evaluate_issue`. `project` is the same: a
            // membership the rendered bytes answer only as a YAML block, judged by
            // `project_matches` where the issue is in hand.
            if field.is_reference() || field.is_derived() || field.is_project() || field.is_epic() {
                continue;
            }
            if !hay.contains(&value.to_lowercase()) {
                return false;
            }
        }
        if let Some(cycle) = &self.cycle
            && !hay.contains(&cycle.to_lowercase())
        {
            return false;
        }
        if let Some(milestone) = &self.milestone
            && !hay.contains(&milestone.to_lowercase())
        {
            return false;
        }
        if let Some(reviewer) = &self.reviewer
            && !hay.contains(&reviewer.to_lowercase())
        {
            return false;
        }
        if let Some(start_date) = &self.start_date
            && !hay.contains(start_date)
        {
            return false;
        }
        if let Some(due_date) = &self.due_date
            && !hay.contains(due_date)
        {
            return false;
        }
        if self.overdue == Some(true) && !is_overdue_haystack(haystack) {
            return false;
        }
        true
    }

    /// The full structured predicate for an issue, including the criteria
    /// [`Self::evaluate`] structurally cannot judge.
    ///
    /// WP08 T035. [`evaluate`] takes a haystack and is therefore store-free; the
    /// category criterion needs the issue's `status` **and** the board's
    /// `category_map`, so it is judged here instead, where both are available.
    /// The two halves AND together, exactly as `evaluate` ANDs its own criteria.
    ///
    /// `text` is passed in rather than re-serialized from `issue`, because
    /// `Corpus` already holds the exact bytes every issue was matched against and
    /// a second `to_file_contents()` per issue per keystroke is measurable work
    /// for an identical string.
    pub fn evaluate_issue(
        &self,
        issue: &Issue,
        text: &str,
        resolution: &crate::workflow::CategoryResolution,
    ) -> bool {
        self.evaluate(text)
            && self.category_matches(issue, resolution)
            && self.scope_matches(issue)
            && self.archived_matches(issue)
            && self.project_matches(issue)
            && self.epic_matches(issue)
    }

    /// Whether `issue`'s association list contains the referenced project
    /// (WP06 T027).
    ///
    /// The membership predicate, and the **only** place a `project:` criterion is
    /// judged. It reads the issue's association list through
    /// [`crate::projects::ProjectNode::project_ids`] — the same accessor
    /// `ProjectIndex::build` reads — so the two rules cannot drift at the accessor
    /// level: there is one definition of "what the issue stores", and this reads it
    /// rather than re-deriving it (C-006). Nothing here resolves a name, validates an
    /// id, or crawls the registry; [`resolve_filter_criteria`] did that once, through
    /// the service.
    ///
    /// **Raw-string match, deliberately, and it is the repair affordance.** A stored
    /// association whose project the registry no longer holds (a `tix project delete`
    /// left the reference behind — C-005 retains it) **still matches** here: the user
    /// must be able to *find* the issues carrying the deleted id, because
    /// `tix project remove <stale-id>` (and `tix edit --remove-project`) is how the
    /// reference is repaired, and it takes the id as stored. The board's **partition**
    /// deliberately differs: an unresolved id is not a project, so such an issue is
    /// bucketed `(no project)` (see `ProjectPartition`). The two are a chosen
    /// asymmetry, not a drift: the filter answers "which issues carry this string?",
    /// the partition answers "which project owns this issue?" — and the second has no
    /// answer for an id nothing resolves to. `tix lint` names the same references.
    ///
    /// **Exact**, not substring: `p-1` must not match an association with `p-12`,
    /// and an issue whose *body* mentions an id is not a member. Case-sensitive
    /// too — a resolved id is a canonical registry key, and a raw one is compared as
    /// the file spells it, which is what a repair has to match.
    ///
    /// The multi-membership rule (T027 step 3, recorded in
    /// `contracts/cli-surface.md` §3): an issue associated with two projects
    /// matches either criterion, because the check is a membership test, not a
    /// first-value read. An unassociated issue matches nothing, and an id no
    /// association carries — including one the registry does not know — matches
    /// nothing.
    pub fn project_matches(&self, issue: &Issue) -> bool {
        let Some(want) = self.project.as_deref().filter(|s| !s.is_empty()) else {
            return true;
        };
        crate::projects::ProjectNode::project_ids(issue)
            .iter()
            .any(|id| id == want)
    }

    /// Whether `issue`'s epic reference list contains the referenced epic
    /// (WP06 T029).
    ///
    /// The membership predicate, and the **only** place an `epic:` criterion is
    /// judged. It reads the issue's references through [`crate::epics::EpicNode::epic_ids`]
    /// — the same accessor [`crate::epics::EpicIndex::build`] reads, so the filter
    /// and the service's membership index cannot drift at the accessor level: there
    /// is one definition of "what the issue stores" (C-002), and this reads it
    /// rather than re-deriving it. Nothing here resolves a name, validates an id, or
    /// crawls the registry; [`resolve_filter_criteria`] did that once, through the
    /// service.
    ///
    /// **Raw-string match, deliberately, and it is the repair affordance.** A stored
    /// reference whose epic the registry no longer holds (a `tix epic delete` left
    /// the reference behind — C-005 retains it) **still matches** here: the user must
    /// be able to *find* the issues carrying the deleted id, because
    /// `tix epic remove <stale-id>` (and `tix edit --remove-epic`) is how the
    /// reference is repaired, and it takes the id as stored. The board's **partition**
    /// deliberately differs: an unresolved id is not an epic, so such an issue is
    /// bucketed `(no epic)` (see `crate::search::epic_bucket_label`). The two are a
    /// chosen asymmetry, not a drift, exactly as `project_matches` records.
    ///
    /// **Exact**, not substring: `e-1` must not match a reference to `e-12`, and an
    /// issue whose *body* mentions an id is not a member. Case-sensitive too — a
    /// resolved id is a canonical registry key, and a raw one is compared as the
    /// file spells it, which is what a repair has to match.
    ///
    /// The multi-membership rule (T029 step 3, recorded in
    /// `contracts/cli-surface.md` §3): an issue referencing two epics matches either
    /// criterion, because the check is a membership test, not a first-value read. An
    /// unreferenced issue matches nothing, and an id no reference carries —
    /// including one the registry does not know — matches nothing.
    pub fn epic_matches(&self, issue: &Issue) -> bool {
        let Some(want) = self.epic.as_deref().filter(|s| !s.is_empty()) else {
            return true;
        };
        crate::epics::EpicNode::epic_ids(issue)
            .iter()
            .any(|id| id == want)
    }

    /// Whether `issue`'s archived state matches the `archived:` criterion
    /// (issue #1492).
    ///
    /// Judged here rather than in [`Self::evaluate`] because the archived flag is
    /// derived from the *filename* and never appears in the haystack; `None`
    /// narrows nothing, and a set value is an exact `bool` comparison —
    /// `archived:false` selects the active issues, `archived:true` the archived
    /// ones.
    pub fn archived_matches(&self, issue: &Issue) -> bool {
        match self.archived {
            None => true,
            Some(want) => issue.archived == want,
        }
    }

    /// Whether `issue` is in one of the columns the `scope:` token selected.
    ///
    /// WP02 T010. The same three-way reasoning as [`Self::category_matches`],
    /// in reverse: a scope is a **membership set**, so an issue either has a
    /// status in it or does not, and there is no category to default. `None` (no
    /// token) passes everything — an unset criterion narrows nothing — and a set
    /// that fails to contain `issue.status` fails closed, because a scope the
    /// issue is not in is precisely what was asked for.
    ///
    /// Judged here rather than in [`Self::evaluate`] for the reason that
    /// function gives: `evaluate` has a haystack and no issue, and the issue's
    /// status is not reliably *in* the haystack in a form this can compare —
    /// `status: triage` is a line of frontmatter, but a scope is a set of
    /// columns and substring-matching the set against the file would call an
    /// issue whose title contains `todo` a member of the `todo` column.
    pub fn scope_matches(&self, issue: &Issue) -> bool {
        match &self.scope {
            None => true,
            Some(columns) => columns.iter().any(|c| issue.status.is(c)),
        }
    }

    /// Whether `issue` is in the requested category (WP08 T035).
    ///
    /// Three cases, and the third is the one the surfaces already distinguish:
    ///
    /// 1. **A mapped column** → its category, from the service's resolution.
    /// 2. **A configured but unmapped column** → the **safe default**, because
    ///    that is what it resolves to. T035 step 3 asks for this explicitly, and it
    ///    is what keeps the criterion consistent with `tix workflow show`, which
    ///    reports the same default for the same column.
    /// 3. **A column the board does not configure** → matches **nothing**. There
    ///    is no category to report: `resolve` is `None`, `tix list --show category`
    ///    prints `(unmapped)`, and MCP returns `category: null` (WP07). A criterion
    ///    has to agree with the surfaces that show the same fact, and silently
    ///    folding this into the safe default would make `category:unstarted` return
    ///    issues every other surface call unmapped.
    ///
    /// The unknown-category case is *not* handled here and cannot be: a value the
    /// vocabulary does not contain is an error at the command layer
    /// ([`resolve_category_criterion`]), not a match decision here. A criterion
    /// that reached this function unchecked compares against a key nothing
    /// resolves to and therefore matches nothing — the same empty result an
    /// unknown `status:` gives, which is the established behaviour for a bad value
    /// in a haystack criterion.
    pub fn category_matches(
        &self,
        issue: &Issue,
        resolution: &crate::workflow::CategoryResolution,
    ) -> bool {
        let Some(want) = self.category.as_deref().filter(|s| !s.is_empty()) else {
            return true;
        };
        match resolution.resolve(issue.status.display()) {
            Some(actual) => actual.key() == want,
            // Case 3. `None` only for a column this board does not configure.
            None => false,
        }
    }

    /// Trim every criterion; values that trim to empty become `None` (the
    /// canonical "unset" state). Used by the filter modal's commit path.
    pub fn normalize(&mut self) {
        for field in FilterField::ALL {
            let empty = field.value_mut(self).trim().is_empty();
            if empty {
                field.unset(self);
            } else {
                let value = field.value_mut(self);
                let trimmed = value.trim().to_string();
                *value = trimmed;
            }
        }
    }
}

impl std::fmt::Display for StructuredFilter {
    /// Diagnostics for the hint bar: `assignee:alice, status:todo`, or
    /// `(no active criteria)`.
    ///
    /// Built as a list rather than written field by field, because there are
    /// now three sources of a part — the [`FilterField`] criteria, an active
    /// `scope`, and `overdue` — and the first version returned early when the
    /// *criteria* were empty. A scope-only filter would then have printed
    /// `(no active criteria)` while actively filtering, which is the hint bar
    /// telling the user the opposite of what the board is doing.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut parts: Vec<String> = self
            .criteria()
            .map(|(field, value)| format!("{}:{value}", field.token()))
            .collect();
        if let Some(columns) = &self.scope {
            parts.push(format!("scope:{}", columns.join(",")));
        }
        if let Some(archived) = self.archived {
            parts.push(format!("archived:{archived}"));
        }
        if self.overdue == Some(true) {
            parts.push("overdue:true".to_string());
        }
        if parts.is_empty() {
            return write!(f, "(no active criteria)");
        }
        write!(f, "{}", parts.join(", "))
    }
}

/// Composite predicate: the `/` fuzzy text layer **and** the structured
/// filter both apply (FR-013).
///
/// - empty `query` → structured filter only;
/// - empty structured filter → text query only;
/// - both active → an entry must satisfy **both** layers.
///
/// Zero matches is a valid board, never an error (consumers render empty
/// columns).
pub fn matches(query: &str, filter: &StructuredFilter, haystack: &str) -> bool {
    let text_matches = query_matches(query, haystack);
    text_matches && filter.evaluate(haystack)
}

/// The full predicate for one corpus entry, including the derived criteria
/// (WP08 T035, WP02 T010).
///
/// **Every** consumer should call this rather than [`matches`]. `matches` cannot
/// judge a `category:` or `scope:` criterion — both need the issue (and the
/// board's map, for `category`), and it has neither — and a consumer that calls
/// it directly would therefore **silently ignore** an active category or scope
/// criterion: the query would return the unfiltered set and read as "every issue
/// is in that category/scope". One composition point is what keeps the CLI, the
/// TUI board, and `tix search` from disagreeing, which is the property the
/// module header exists to protect (C-005).
///
/// `text` is the corpus's own bytes for this entry, so no caller re-serializes.
pub fn matches_issue(
    query: &str,
    filter: &StructuredFilter,
    issue: &Issue,
    text: &str,
    resolution: &crate::workflow::CategoryResolution,
) -> bool {
    query_matches(query, text) && filter.evaluate_issue(issue, text, resolution)
}

/// Resolve a `parent:<selector>` query token to the **number** it names.
///
/// Matching happens against an issue's rendered frontmatter, and that carries
/// `parent: 7` — a number. The user types a *selector*, so something has to close
/// that gap, and the only place with a store is the command layer. Doing it here,
/// once, keeps `query_matches` and `evaluate` pure string comparisons and
/// store-free, which is the property every other criterion already has.
///
/// The substitution is textual on the **query**, not on the results: `parent:5` in,
/// `parent:5` out, with the selector replaced by the number it resolves to. That
/// means no new plumbing in the matchers, and no second code path for a criterion
/// that only needs one comparison.
///
/// A selector that resolves to nothing is an **error**, not an empty result: a user
/// who typed `parent:Epicc` has made a typo, and "no issues found" is a different
/// answer from "there is no such issue". Every other command's selector handling
/// errors the same way.
///
/// Returns the query unchanged when it carries no `parent:` token, so a caller can
/// use the result unconditionally.
pub fn resolve_parent_criterion(store: &crate::storage::Store, query: &str) -> Result<String> {
    let mut out: Vec<String> = Vec::with_capacity(8);
    let mut touched = false;
    for token in query.split_whitespace() {
        let Some((key, value)) = parse_token(token) else {
            out.push(token.to_string());
            continue;
        };
        if !key.eq_ignore_ascii_case("parent") {
            out.push(token.to_string());
            continue;
        }
        let target = crate::commands::parse_selector(store, value)?;
        // The store's own message, propagated as-is. The first version wrapped it in
        // a fresh `NotFound`, and the user saw `not found: not found: issue matching
        // …` — the same class of doubled prefix the relationship renderer fixed in
        // WP03. One message, from one place.
        let number = store
            .get(target)
            .map_err(|_| {
                crate::error::TixError::NotFound(format!(
                    "issue matching '{value}' by number, filename or title"
                ))
            })?
            .number;
        out.push(format!("parent:{number}"));
        touched = true;
    }
    if !touched {
        return Ok(query.to_string());
    }
    Ok(out.join(" "))
}

/// **Lift** the `category:<value>` criterion out of `query`, validating the value
/// against the project's closed vocabulary (WP08 T035).
///
/// Returns `(query-without-the-token, Some(canonical_key))`. "Lift", not "rewrite":
/// the token is **removed** and the criterion travels in the
/// [`StructuredFilter`] instead, because that is the only shape that works. The
/// first version rewrote `category:Completed` to `category:completed` and left the
/// token in the string, so [`query_matches`] still met a `category` key, still
/// refused it, and the filter matched **nothing** — while the canonicalization test
/// beside it passed. Two green results and an empty board.
///
/// The validation this closes is the one a substring matcher cannot do. A bad
/// `status:` value is a legitimate test that matches nothing; a bad *category* is a
/// typo in a closed set of at most six words, and "0 issues found" is a silent dead
/// end where one line names the words that would have worked.
///
/// Checked against the **project's** `[categories] order` rather than
/// [`crate::config::CATEGORY_KEYS`] because `order` may be a **subset**: a project
/// declaring `["backlog", "active", "completed", "canceled"]` has said its
/// vocabulary is four words, and accepting `unstarted` would return results from a
/// category it never declared. The error names that project's list.
///
/// `None` when the query carries no `category:` token, so a caller can use the
/// result unconditionally. Same shape and same reason as
/// [`resolve_parent_criterion`]: the matchers are pure string comparisons over a
/// store-free haystack, so anything needing the config is resolved once, in the one
/// layer that has it.
fn lift_category_criterion(
    config: &crate::config::Config,
    query: &str,
) -> crate::error::Result<(String, Option<String>)> {
    let mut out: Vec<String> = Vec::with_capacity(8);
    let mut category = None;
    for token in query.split_whitespace() {
        let Some((key, value)) = parse_token(token) else {
            out.push(token.to_string());
            continue;
        };
        if !key.eq_ignore_ascii_case("category") {
            out.push(token.to_string());
            continue;
        }
        let lowered = value.to_lowercase();
        if !config.categories.contains(&lowered) {
            return Err(crate::error::TixError::InvalidInput(format!(
                "unknown category '{value}' — this project's categories are: {}",
                config.categories.order.join(", ")
            )));
        }
        // `contains` and `from_key` read the same six words, so this cannot fail
        // after the check above. `from_key` is still what produces the canonical
        // spelling rather than trusting the user's casing, and it is the same
        // function `WorkflowCategory::key` is compared against when matching.
        category = Some(
            crate::workflow::WorkflowCategory::from_key(&lowered)
                .expect("categories.order is validated against the global vocabulary at load")
                .key()
                .to_string(),
        );
        // Dropped, not pushed: `out` is the query the store-free matcher will see.
    }
    Ok((out.join(" "), category))
}

/// Resolve a `project:<selector>` query token to a canonical project id
/// (WP06 T027).
///
/// Same shape as [`lift_category_criterion`], and for the same reason: the
/// association list is a YAML block, so a store-free matcher has no scalar to
/// compare and leaving the token in the string would have [`query_matches`]
/// refuse it and return an empty result that reads as "no matches".
///
/// Resolution goes through the **service** ([`crate::projects::resolve_project_id`]),
/// so a name resolves to the same id `tix project show <name>` names and the id
/// grammar is the registry's, not this function's. The canonical id is what
/// travels in [`StructuredFilter::project`].
///
/// A selector the registry does not know is kept **verbatim** rather than
/// refused. Every other command errors on an unknown selector, but the contract
/// for this criterion is that an unknown project id matches **nothing**
/// (T027 step 6) — so a typo yields the visible empty result rather than a hard
/// error, and matching finds no member because no association can carry a
/// reference the registry never issued. The typed reference is retained as the
/// needle (not lowercased, not trimmed beyond what `parse_token` did) so the
/// comparison stays an exact one against the stored ids.
///
/// Returns the query with every `project:` token removed, so a caller can use the
/// result unconditionally. The last token wins when several are present, exactly
/// as `category:` behaves.
fn lift_project_criterion(config: &crate::config::Config, query: &str) -> (String, Option<String>) {
    let mut out: Vec<String> = Vec::with_capacity(8);
    let mut project = None;
    for token in query.split_whitespace() {
        let Some((key, value)) = parse_token(token) else {
            out.push(token.to_string());
            continue;
        };
        if !key.eq_ignore_ascii_case("project") {
            out.push(token.to_string());
            continue;
        }
        project = Some(
            crate::projects::resolve_project_id(config, value)
                .map(|id| id.to_string())
                .unwrap_or_else(|_| value.to_string()),
        );
        // Dropped, not pushed: `out` is the query the store-free matcher will see.
    }
    (out.join(" "), project)
}

/// Resolve an `epic:<selector>` query token to a canonical epic id (WP06 T029).
///
/// The epic twin of [`lift_project_criterion`], and the same shape for the same
/// reason: the reference list is a YAML block, so a store-free matcher has no
/// scalar to compare and leaving the token in the string would have
/// [`query_matches`] refuse it and return an empty result that reads as "no
/// matches".
///
/// Resolution goes through the **service** ([`crate::epics::resolve_epic_id`]), so a
/// name resolves to the same id `tix epic show <name>` names and the id grammar is
/// the registry's, not this function's. The canonical id is what travels in
/// [`StructuredFilter::epic`].
///
/// A selector the registry does not know is kept **verbatim** rather than refused,
/// exactly as `project:` does: an unknown epic id matches **nothing** (T029 step 6)
/// — so a typo yields the visible empty result rather than a hard error, and
/// matching finds no member because no reference can carry an id the registry never
/// issued. The typed reference is retained as the needle so the comparison stays an
/// exact one against the stored ids.
///
/// Returns the query with every `epic:` token removed, so a caller can use the
/// result unconditionally. The last token wins when several are present, exactly as
/// `project:` behaves.
fn lift_epic_criterion(config: &crate::config::Config, query: &str) -> (String, Option<String>) {
    let mut out: Vec<String> = Vec::with_capacity(8);
    let mut epic = None;
    for token in query.split_whitespace() {
        let Some((key, value)) = parse_token(token) else {
            out.push(token.to_string());
            continue;
        };
        if !key.eq_ignore_ascii_case("epic") {
            out.push(token.to_string());
            continue;
        }
        // The resolve-or-keep-verbatim classification is the service's one owner
        // (`epics::dereference_needle`), not a fourth spelling of it (WP09 item B).
        epic = Some(crate::epics::dereference_needle(&config.epics, value));
        // Dropped, not pushed: `out` is the query the store-free matcher will see.
    }
    (out.join(" "), epic)
}

/// The group-section label for one issue's epic membership (WP06 T029).
///
/// The epic analogue of [`crate::projects::project_bucket_label`], and the recorded
/// partition decision (T029 step 4, `contracts/cli-surface.md` §3): one bucket per
/// issue — the single epic **id** when the issue references exactly one resolved
/// epic, `(multiple epics)` when it references several, and `(no epic)` when it
/// references none (including a reference no registry entry resolves).
///
/// Duplication is the road not taken, for the reason the project partition records:
/// one issue would become two rows, and the board's cursor, hit-testing and
/// per-column counts are all index-into-one-list arithmetic, so a card that appeared
/// twice would need a second identity the renderer does not have. The **filter**
/// still matches an issue in two epics under either id
/// ([`StructuredFilter::epic_matches`]), so the union semantics are not lost where
/// they matter.
pub fn epic_bucket_label(ids: &[String]) -> String {
    match ids {
        [] => NO_EPIC_BUCKET.to_string(),
        [only] => only.clone(),
        _ => MULTIPLE_EPICS_BUCKET.to_string(),
    }
}

/// The labelled bucket for an issue in no epic (WP06 T029, WP09 item C).
///
/// A constant rather than a literal so the board, `tix list --group epic`/
/// `--sort epic` and `tix status --group epic` cannot spell the empty bucket two
/// ways; the project partition has the same pair.
pub const NO_EPIC_BUCKET: &str = "(no epic)";

/// The labelled bucket for an issue resolved into several epics (WP06 T029, WP09
/// item C).
///
/// One bucket rather than a duplicate per epic, for the reason
/// [`crate::projects::MULTIPLE_PROJECTS_BUCKET`] records: a listing's cursor,
/// hit-testing and per-column counts are index-into-one-list arithmetic.
pub const MULTIPLE_EPICS_BUCKET: &str = "(multiple epics)";

/// Resolve a `scope:<name>` query token to the columns it selects (WP02 T010).
///
/// Same shape as [`lift_category_criterion`], and for the same reason: the
/// columns a scope names are a **config** fact, so a store-free matcher cannot
/// reach them, and leaving the token in the string would have [`query_matches`]
/// refuse it and return an empty result that reads as "no matches".
///
/// One token rather than a new grammar. `scope:` is the `key:value` shape every
/// other criterion already uses, resolved through the same entry point, with no
/// new operator, no list syntax and no precedence — the module's own extension
/// promise ("adding a criterion is one more field on `StructuredFilter` plus one
/// match arm"), minus the `FilterField` variant, which would change the modal's
/// row count (see [`StructuredFilter::scope`]).
///
/// A token the project cannot honour is an **error**, not an empty selection:
/// see [`crate::triage::inbox::scope_columns`].
///
/// Returns the query with every `scope:` token removed, so a caller can use the
/// result unconditionally.
fn lift_scope_criterion(
    config: &crate::config::Config,
    query: &str,
) -> crate::error::Result<(String, Option<Vec<String>>)> {
    let mut out: Vec<String> = Vec::with_capacity(8);
    let mut scope = None;
    for token in query.split_whitespace() {
        let Some((key, value)) = parse_token(token) else {
            out.push(token.to_string());
            continue;
        };
        if !key.eq_ignore_ascii_case("scope") {
            out.push(token.to_string());
            continue;
        }
        // Validated *and* resolved in one call, so a caller cannot keep a token
        // it failed to check. The last one wins, as `category:` does.
        scope = Some(crate::triage::inbox::scope_columns(config, value)?);
        // Dropped, not pushed: `out` is the query the store-free matcher will see.
    }
    Ok((out.join(" "), scope))
}

/// Resolve a `--filter` / query string into the **pair** a match needs: the
/// canonicalized query, and the criteria the store-free matchers cannot judge
/// (WP08 T035).
///
/// Every consumer that takes a filter string should call this and hand both parts
/// to [`matches_issue`]. One function rather than two calls, because the failure
/// mode of getting it half-right is silent: a query whose `category:` token was
/// validated but not canonicalized into the structured criterion still matches
/// **nothing** (the token matcher refuses it), and a query that was canonicalized
/// but never validated accepts a category this project did not declare. Neither
/// error is visible in a return value.
///
/// `parent:` is resolved here too. It was always resolved at the command layer —
/// it is the same shape of problem — but in four separate call sites, and the
/// `category:` work would have made that four more. One entry point means a fifth
/// surface gets both.
///
/// Returns the query unchanged when it carries neither token, so a caller can use
/// the result unconditionally.
pub fn resolve_filter_criteria(
    store: &crate::storage::Store,
    query: &str,
) -> Result<(String, StructuredFilter)> {
    let query = resolve_parent_criterion(store, query)?;
    // `parent:`'s resolver **rewrites** its token — a selector becomes a number, and
    // the haystack holds the number. `category:`'s **lifts** its token out. The
    // asymmetry is not an oversight: the parent criterion is compared against a
    // rendered frontmatter field, so it can stay in the string, while the category
    // criterion has no field to compare against and must arrive as a structured
    // value. Both are resolved here so no call site has to know which is which.
    // `scope:` is a `category:` in kind — a selection nothing in the file bytes
    // can answer — and is lifted the same way (WP02 T010).
    let (query, category) = lift_category_criterion(&store.config, &query)?;
    let (query, scope) = lift_scope_criterion(&store.config, &query)?;
    let (query, archived) = lift_archived_criterion(&query)?;
    // `project:` is lifted rather than rewritten, unlike `parent:`: the association
    // list is a YAML block, so there is no scalar in the haystack to rewrite the
    // token **into**. Resolution is best-effort (see `lift_project_criterion`) and
    // infallible here, so it needs no `?`.
    let (query, project) = lift_project_criterion(&store.config, &query);
    // `epic:` is the second lifted membership criterion, exactly as `project:` is
    // (WP06 T029): the reference list is a YAML block, so it needs the same
    // best-effort service resolution and infallible lift.
    let (query, epic) = lift_epic_criterion(&store.config, &query);
    Ok((
        query,
        StructuredFilter {
            category,
            project,
            epic,
            scope,
            archived,
            ..StructuredFilter::default()
        },
    ))
}

/// Lift an `archived:true|false` token out of the query into the
/// [`StructuredFilter::archived`] field (issue #1492).
///
/// The archived state is derived from the filename, so it cannot be judged from
/// the serialized bytes and the token has to arrive as a structured value — the
/// same shape as `scope:` and `category:`. The last token wins, as both of those
/// do. A value that is neither `true` nor `false` is refused by name, because
/// `archived:1` matching nothing would be indistinguishable from a correct filter
/// with no matches.
fn lift_archived_criterion(query: &str) -> crate::error::Result<(String, Option<bool>)> {
    let mut out: Vec<String> = Vec::with_capacity(8);
    let mut archived = None;
    for token in query.split_whitespace() {
        let Some((key, value)) = parse_token(token) else {
            out.push(token.to_string());
            continue;
        };
        if !key.eq_ignore_ascii_case("archived") {
            out.push(token.to_string());
            continue;
        }
        archived = match value.to_ascii_lowercase().as_str() {
            "true" => Some(true),
            "false" => Some(false),
            other => {
                return Err(crate::error::TixError::InvalidInput(format!(
                    "invalid archived value '{other}' — use archived:true or archived:false"
                )));
            }
        };
        // Dropped, not pushed: `out` is the query the store-free matcher will see.
    }
    Ok((out.join(" "), archived))
}

/// Parse a structured query token of the form `key:value`.
fn parse_token(token: &str) -> Option<(&str, &str)> {
    let (key, value) = token.split_once(':')?;
    let value = value.trim();
    if key.is_empty() || value.is_empty() {
        return None;
    }
    Some((key, value))
}

pub fn control_token(query: &str, key: &str) -> Option<String> {
    query.split_whitespace().find_map(|token| {
        let (k, v) = token.split_once(':')?;
        if k.eq_ignore_ascii_case(key) {
            Some(v.to_ascii_lowercase())
        } else {
            None
        }
    })
}

/// Apply the query grammar to a haystack.
///
/// Bare terms (anything that is not a `key:value` token or the bare `overdue`
/// keyword) must appear in the haystack as a **case-insensitive substring** —
/// the same literal rule [`tix search`](crate::commands::search) uses over the
/// same corpus, so the board's `/` search and the CLI agree on what "matches".
///
/// This replaced the old subsequence (`fuzzy_score`) rule for bare terms (tix
/// #1498): a subsequence is far too permissive over a whole issue file, where
/// `greedy` is a subsequence of nearly every issue because `g`, `r`, `e`, `e`,
/// `d`, `y` all occur in order somewhere. Substring matching keeps a query
/// about a word about that word. `fuzzy_score` remains the help overlay's
/// fallback, where the rows are short and a literal miss is worth a second pass.
pub fn query_matches(query: &str, haystack: &str) -> bool {
    let mut bare_terms = Vec::new();
    let hay = haystack.to_lowercase();
    for token in query.split_whitespace() {
        if token.eq_ignore_ascii_case("overdue") {
            if !is_overdue_haystack(haystack) {
                return false;
            }
            continue;
        }
        if let Some((key, value)) = parse_token(token) {
            let value = value.to_lowercase();
            let ok = match key.to_lowercase().as_str() {
                // A **pre-existing defect, found while adding `category`** (WP08).
                //
                // `StructuredFilter` has carried `assignee`, `label`, `status` and
                // `priority` since the filter grammar landed, and `evaluate` matches
                // all four — so the TUI's filter modal has always filtered on them.
                // The **token** grammar had no arm for any of them, and the `_ => false`
                // below turned each into a filter that matched nothing:
                //
                //     tix list --filter status:shipped    # → empty table, exit 0
                //     tix list --filter assignee:alice     # → empty table, exit 0
                //
                // Silent, total, and on the four most obvious criteria. A user typing
                // the documented `--filter` had no way to tell a filter from a typo, and
                // the empty table is indistinguishable from a correct filter with no
                // matches.
                //
                // Substring, and lowercased, because that is exactly what `evaluate`
                // does for these four — the module's stated rule, and the one
                // `StructuredFilter`'s own tests pin. The two grammars now agree
                // criterion for criterion instead of the token grammar silently
                // supporting less than the modal does.
                //
                // `label` matches the rendered `labels: [a, b]` list by substring,
                // which is also `evaluate`'s rule, and the one `contracts/filtering.md`
                // §3's stricter "contains-in-labels" spelling would need a re-parse to
                // improve on. Not changed here: one behaviour, two grammars.
                "assignee" | "label" | "status" | "priority" | "cycle" | "milestone"
                | "reviewer" => hay.contains(&value),
                "start" | "due" => hay.contains(&value),
                // Exact, for the same reason `evaluate` is: a number must not
                // match a longer number that contains it. The value here is already
                // a **resolved** number — see `resolve_parent_criterion`.
                "parent" => field_value(haystack, "parent") == Some(value.as_str()),
                // A **category key**, not a field value: an issue's file contains no
                // `category` line, so a substring test here would match the word
                // "category" wherever it appears in a title or body, and would
                // match `completed` against any issue that happens to use the word.
                // This arm exists only to make the refusal **explicit and total**
                // rather than accidental: a store-free matcher cannot judge it, and
                // [`matches_issue`] is the entry point that does, with the
                // criterion carried in the [`StructuredFilter`] that
                // [`resolve_filter_criteria`] fills. Reaching this arm with a real
                // `category:` token therefore means a caller skipped one of those
                // two — and returning `false` for every issue turns that mistake into
                // an empty result a user can see, instead of an unfiltered result
                // they cannot.
                "category" => false,
                // The `scope:` twin of the `category` refusal above, and the
                // same contract: the columns a scope selects are a config fact
                // this store-free matcher does not have, and
                // [`resolve_filter_criteria`] is what lifts the token out before
                // it ever gets here. Reaching this arm with a real `scope:` token
                // means a caller skipped that step — see [`matches_issue`] — and
                // returning `false` for every issue turns the mistake into an
                // empty result a user can see instead of an unfiltered one they
                // cannot. (WP02 T010.)
                "scope" => false,
                // The `archived:` twin of the `category`/`scope` refusals above
                // (issue #1492): the archived flag lives on the filename, not in
                // the bytes, so this store-free matcher cannot judge it and
                // `resolve_filter_criteria` lifts the token into the structured
                // filter instead. A caller that skipped that step gets an empty
                // result rather than an unfiltered one.
                "archived" => false,
                // The `project:` twin of the refusals above (WP06 T026/T027). The
                // association list is a YAML **block** in the frontmatter, so this
                // store-free matcher has no scalar to compare: a substring test
                // would match an id the body merely mentions, and `p-1` against
                // `p-12`. The criterion travels in the [`StructuredFilter`] that
                // [`resolve_filter_criteria`] fills, and is judged by
                // [`StructuredFilter::project_matches`], which has the issue.
                // Reaching this arm with a real `project:` token means a caller
                // skipped that step, and returning `false` turns the mistake into
                // an empty result a user can see rather than an unfiltered one they
                // cannot.
                "project" => false,
                // The `epic:` twin of the `project:` refusal above (WP06 T029). The
                // reference list is a YAML **block** in the frontmatter, so this
                // store-free matcher has no scalar to compare: a substring test would
                // match an id the body merely mentions, and `e-1` against `e-12`. The
                // criterion travels in the [`StructuredFilter`] that
                // [`resolve_filter_criteria`] fills, and is judged by
                // [`StructuredFilter::epic_matches`], which has the issue. Reaching
                // this arm with a real `epic:` token means a caller skipped that step,
                // and returning `false` turns the mistake into an empty result a user
                // can see rather than an unfiltered one they cannot.
                "epic" => false,
                "sort" => matches!(
                    value.as_str(),
                    "created"
                        | "priority"
                        | "status"
                        | "cycle"
                        | "milestone"
                        | "due"
                        | "start"
                        | "reviewer"
                        // WP06 T028: sorting by project is what makes the project
                        // partition contiguous and in declaration order. A control
                        // token this grammar did not list would veto **every** issue
                        // and the board would render empty rather than sorted.
                        //
                        // WP09 INTEGRATION ITEM: the token grammar accepting a key
                        // is not the same as a consumer implementing it. Only the
                        // TUI board honours `project` here. `src/commands/list.rs`
                        // (its sort table, and the group whitelist at
                        // src/commands/list.rs:557) and `src/commands/status.rs`
                        // (its group whitelist at src/commands/status.rs:171) still
                        // filter on `cycle | milestone` and ignore `project`
                        // silently, where an unknown token used to be refused by
                        // this arm. Both are WP04's files and are not edited here.
                        | "project"
                        // WP06 T029: the epic partition's sort key, the exact
                        // analogue of `project` above.
                        | "epic"
                ),
                // The same WP09 integration item as the `sort` arm above:
                // `src/commands/list.rs:557` and `src/commands/status.rs:171`
                // whitelist the group key to `cycle | milestone`.
                "group" => matches!(value.as_str(), "cycle" | "milestone" | "project" | "epic"),
                "overdue" if value == "true" => is_overdue_haystack(haystack),
                _ => false,
            };
            if !ok {
                return false;
            }
        } else {
            bare_terms.push(token);
        }
    }
    let bare = bare_terms.join(" ").to_lowercase();
    bare.is_empty() || hay.contains(&bare)
}

fn field_value<'a>(haystack: &'a str, key: &str) -> Option<&'a str> {
    for line in haystack.lines() {
        let prefix = format!("{key}:");
        if let Some(rest) = line.strip_prefix(&prefix) {
            return Some(rest.trim().trim_matches('"'));
        }
    }
    None
}

fn is_overdue_haystack(haystack: &str) -> bool {
    let status = field_value(haystack, "status").unwrap_or_default();
    let due = field_value(haystack, "due_date").unwrap_or_default();
    !due.is_empty() && due < crate::model::today().as_str() && status != "done"
}

/// Classify a bare-number `/` query: `Some(n)` iff `raw` trims to a
/// non-empty run of ASCII digits that fits `u32`. Any other input — empty,
/// whitespace-only, non-digit characters, mixed (`55bug`), or overflowing
/// `u32` — returns `None`, signalling "not a number query" so the caller
/// falls back to fuzzy-text behavior (board-filtering FR-02). Leading zeros
/// parse normally (`"055"` → `55`); `"0"` is a valid (if typically
/// matchless) number query.
pub fn number_query(raw: &str) -> Option<u32> {
    let trimmed = raw.trim();
    if trimmed.is_empty() || !trimmed.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    trimmed.parse::<u32>().ok()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Issue, Priority, Status};
    use std::fs;

    // ----------------------------------------------------------------------
    // T007 — corpus builder
    // ----------------------------------------------------------------------

    fn make_store() -> (tempfile::TempDir, Store) {
        let tmp = tempfile::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();
        let store = Store {
            issues_dir: dir,
            config,
        };
        (tmp, store)
    }

    fn sample_issue(number: u32, title: &str, extra_body: &str) -> Issue {
        let mut issue = Issue {
            projects: None,
            id: None,
            number,
            title: title.to_string(),
            status: Status::default(),
            labels: vec!["urgent".to_string()],
            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: extra_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,
        };
        // Serialized frontmatter carries the title; `filename` is memory-only
        // and never written to disk, so it only needs to be non-empty here.
        issue.filename = format!("alice/{}-{}.md", "2026-01-01", crate::slug::slugify(title));
        issue
    }

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

    #[test]
    fn corpus_texts_match_issue_to_file_contents_byte_for_byte() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        let a = sample_issue(1, "Login bug", "Need to reproduce the redirect loop.");
        write_issue(&store, "alice/2026-01-01-login-bug.md", &a);
        let b = sample_issue(
            2,
            "Export csv",
            "## Comments\n\n### alice (2026-01-01)\n\nSort order is wrong.\n",
        );
        write_issue(&store, "alice/2026-01-01-export-csv.md", &b);

        let corpus = Corpus::build(&store).unwrap();
        assert_eq!(corpus.issues.len(), 2);
        // Corpus texts are byte-for-byte the serialized issues, matched by
        // stable number lookup regardless of store order.
        let idx_a = corpus.by_number(1).unwrap();
        let idx_b = corpus.by_number(2).unwrap();
        assert_eq!(corpus.texts()[idx_a], a.to_file_contents());
        assert_eq!(corpus.texts()[idx_b], b.to_file_contents());
        assert_eq!(corpus.by_number(99), None);
    }

    #[test]
    fn corpus_never_indexes_asset_dirs() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        let a = sample_issue(1, "Login bug", "body");
        write_issue(&store, "alice/2026-01-01-login-bug.md", &a);
        // A `.md` straggler inside an `-assets` dir and a real binary asset.
        let assets = store.issues_dir.join("alice/login-bug-assets");
        fs::create_dir_all(&assets).unwrap();
        fs::write(assets.join("notes.md"), "# not an issue\n").unwrap();
        fs::write(assets.join("diagram.png"), b"\x89PNG").unwrap();

        let corpus = Corpus::build(&store).unwrap();
        assert_eq!(corpus.issues.len(), 1);
        let evil_found = corpus.texts().iter().any(|t| t.contains("not an issue"));
        assert!(
            !evil_found,
            "asset-dir markdown must not leak into the corpus"
        );
    }

    // ----------------------------------------------------------------------
    // Issue #10 follow-up — incremental corpus updates
    // ----------------------------------------------------------------------

    fn fs_delta(changed: &[&str], removed: &[&str]) -> FsDelta {
        FsDelta {
            changed: changed.iter().map(PathBuf::from).collect(),
            removed: removed.iter().map(PathBuf::from).collect(),
        }
    }

    fn shape(corpus: &Corpus) -> Vec<(u32, String, String)> {
        corpus
            .issues
            .iter()
            .map(|i| (i.number, i.title.clone(), i.filename.clone()))
            .collect()
    }

    #[test]
    fn apply_matches_a_full_rebuild_after_edits() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        write_issue(
            &store,
            "alice/2026-01-01-login-bug.md",
            &sample_issue(1, "Login bug", "one"),
        );
        write_issue(
            &store,
            "alice/2026-01-02-export-csv.md",
            &sample_issue(2, "Export csv", "two"),
        );
        write_issue(
            &store,
            "2026-01-03-flat.md",
            &sample_issue(3, "Flat", "three"),
        );
        let mut corpus = Corpus::build(&store).unwrap();

        // One delta carrying an edit, an addition, a deletion and non-issue
        // churn — exactly what a settled watcher burst hands over.
        write_issue(
            &store,
            "alice/2026-01-01-login-bug.md",
            &sample_issue(1, "Login bug fixed", "one v2"),
        );
        write_issue(
            &store,
            "alice/2026-01-04-new.md",
            &sample_issue(4, "New", "four"),
        );
        fs::remove_file(store.issues_dir.join("2026-01-03-flat.md")).unwrap();
        fs::write(store.issues_dir.join("notes.txt"), "not an issue").unwrap();
        corpus
            .apply(
                &store,
                &fs_delta(
                    &[
                        "alice/2026-01-01-login-bug.md",
                        "alice/2026-01-04-new.md",
                        "notes.txt",
                    ],
                    &["2026-01-03-flat.md"],
                ),
            )
            .unwrap();

        let rebuilt = Corpus::build(&store).unwrap();
        assert_eq!(
            shape(&corpus),
            shape(&rebuilt),
            "the incremental corpus is exactly a rebuild, in scan order"
        );
        assert_eq!(
            corpus.texts(),
            rebuilt.texts(),
            "texts stay byte-identical to `to_file_contents`"
        );
    }

    #[test]
    fn apply_ignores_paths_scan_would_skip() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        write_issue(
            &store,
            "alice/2026-01-01-a.md",
            &sample_issue(1, "A", "body"),
        );
        let mut corpus = Corpus::build(&store).unwrap();
        let before = shape(&corpus);

        // A temp marker segment, an assets segment, and a non-`.md` file.
        for (path, contents) in [
            (".tix-tmp-x/a.md", "temp"),
            ("foo-assets/a.md", "asset"),
            ("notes.txt", "not an issue"),
        ] {
            let full = store.issues_dir.join(path);
            fs::create_dir_all(full.parent().unwrap()).unwrap();
            fs::write(&full, contents).unwrap();
        }
        corpus
            .apply(
                &store,
                &fs_delta(&["notes.txt", ".tix-tmp-x/a.md", "foo-assets/a.md"], &[]),
            )
            .unwrap();

        assert_eq!(shape(&corpus), before, "nothing `scan` skips is indexed");
        assert_eq!(corpus.texts(), Corpus::build(&store).unwrap().texts());
    }

    #[test]
    fn from_issues_matches_a_fresh_walk() {
        // tix #1518: the TUI builds its corpus from the same enumeration it built
        // the board and rollover plan from. That shared corpus must be identical to
        // one that walked the store itself, or the single-scan startup silently
        // changes what search sees.
        let (_tmp, store) = make_store();
        write_issue(&store, "2026-01-01-a.md", &sample_issue(1, "A", "body"));
        write_issue(
            &store,
            "2026-01-02-b.md",
            &sample_issue(2, "B", "more body"),
        );

        let shared = Corpus::from_issues(store.list().unwrap());
        let walked = Corpus::build(&store).unwrap();
        assert_eq!(shared.issues.len(), walked.issues.len());
        assert_eq!(
            shared.texts(),
            walked.texts(),
            "same files, same serialized text"
        );
    }

    #[test]
    fn texts_are_serialized_lazily() {
        // tix #1520: building a corpus must not serialize every issue, because a
        // startup that never searches would pay for text it never reads. The
        // snapshot is materialized on first access.
        let (_tmp, store) = make_store();
        write_issue(&store, "2026-01-01-a.md", &sample_issue(1, "A", "body"));

        let corpus = Corpus::build(&store).unwrap();
        assert!(
            !corpus.texts_initialized(),
            "the walk must not serialize issues it may never search"
        );
        let texts = corpus.texts();
        assert!(corpus.texts_initialized(), "first read builds the snapshot");
        assert_eq!(texts.len(), 1);
    }

    #[test]
    fn apply_treats_a_vanished_changed_file_as_removed() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        write_issue(
            &store,
            "alice/2026-01-01-a.md",
            &sample_issue(1, "A", "body"),
        );
        let mut corpus = Corpus::build(&store).unwrap();
        fs::remove_file(store.issues_dir.join("alice/2026-01-01-a.md")).unwrap();

        // The watcher saw it change; by the time the delta is applied it is gone.
        corpus
            .apply(&store, &fs_delta(&["alice/2026-01-01-a.md"], &[]))
            .unwrap();

        assert_eq!(corpus.issues, [] as [crate::model::Issue; 0]);
        assert_eq!(corpus.texts(), [] as [String; 0]);
    }

    #[test]
    fn apply_keeps_the_corpus_on_a_parse_error() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        write_issue(
            &store,
            "alice/2026-01-01-a.md",
            &sample_issue(1, "A", "body"),
        );
        let mut corpus = Corpus::build(&store).unwrap();
        let before = shape(&corpus);
        let texts_before = corpus.texts().to_vec();

        fs::write(
            store.issues_dir.join("alice/2026-01-01-bad.md"),
            "not frontmatter",
        )
        .unwrap();
        let result = corpus.apply(&store, &fs_delta(&["alice/2026-01-01-bad.md"], &[]));

        assert!(result.is_err(), "a malformed file is reported, not ignored");
        assert_eq!(
            shape(&corpus),
            before,
            "all-or-nothing: nothing was applied"
        );
        assert_eq!(corpus.texts(), texts_before);
    }

    #[test]
    fn apply_indexes_an_archived_file_the_caller_passes() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        let mut corpus = Corpus::build(&store).unwrap();
        assert_eq!(corpus.issues, [] as [crate::model::Issue; 0]);

        write_issue(
            &store,
            "alice/.2026-01-01-a.md",
            &sample_issue(1, "Archived", "body"),
        );
        corpus
            .apply(&store, &fs_delta(&["alice/.2026-01-01-a.md"], &[]))
            .unwrap();

        // The archived-view policy is the caller's; `apply` reads what it is
        // handed and marks the dot-prefixed file the way `scan` does.
        assert_eq!(corpus.issues.len(), 1);
        assert!(corpus.issues[0].archived);
        assert_eq!(
            corpus.texts(),
            Corpus::build_with(&store, true).unwrap().texts()
        );
    }

    // ----------------------------------------------------------------------
    // T008 — substring matcher + matched context
    // ----------------------------------------------------------------------

    fn two_issue_corpus() -> Corpus {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        let a = sample_issue(1, "Login bug", "The redirect URL is broken.");
        write_issue(&store, "alice/2026-01-01-login-bug.md", &a);
        let b = sample_issue(
            2,
            "Export csv",
            "## Comments\n\n### alice (2026-01-01)\n\nHandle empty rows.\n",
        );
        write_issue(&store, "alice/2026-01-01-export-csv.md", &b);
        Corpus::build(&store).unwrap()
    }

    #[test]
    fn substring_matches_frontmatter() {
        let corpus = two_issue_corpus();
        let hits = search_substring(&corpus, "Login bug");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].issue.number, 1);
        assert!(
            hits[0]
                .matched_lines
                .iter()
                .any(|l| l.contains("Login bug")),
            "frontmatter title line must appear as context: {hits:?}"
        );
    }

    #[test]
    fn substring_matches_comment_text_only() {
        let corpus = two_issue_corpus();
        let hits = search_substring(&corpus, "empty rows");
        assert_eq!(hits.len(), 1);
        assert_eq!(hits[0].issue.number, 2);
        assert!(
            hits[0]
                .matched_lines
                .iter()
                .any(|l| l.contains("empty rows")),
            "comment line must appear as context: {hits:?}"
        );
    }

    #[test]
    fn substring_matches_label() {
        let corpus = two_issue_corpus();
        let hits = search_substring(&corpus, "urgent");
        assert_eq!(hits.len(), 2, "both issues carry the `urgent` label");
        assert_eq!(
            hits.iter().map(|h| h.issue.number).collect::<Vec<_>>(),
            vec![1, 2],
            "stable number-ascending order (NFR-007)"
        );
    }

    #[test]
    fn substring_is_case_insensitive() {
        let corpus = two_issue_corpus();
        assert_eq!(search_substring(&corpus, "LOGIN BUG").len(), 1);
        assert_eq!(search_substring(&corpus, "login bug").len(), 1);
    }

    #[test]
    fn substring_orders_by_number_ascending() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        let hi = sample_issue(9, "Zed bug", "The redirect loop");
        let lo = sample_issue(3, "Alpha", "The redirect loop, too");
        write_issue(&store, "alice/2026-01-01-zed-bug.md", &hi);
        write_issue(&store, "alice/2026-01-01-alpha.md", &lo);
        let corpus = Corpus::build(&store).unwrap();
        let hits = search_substring(&corpus, "redirect loop");
        assert_eq!(
            hits.iter().map(|h| h.issue.number).collect::<Vec<_>>(),
            vec![3, 9],
            "hits sorted by number regardless of file order"
        );
    }

    #[test]
    fn substring_zero_matches_is_empty() {
        let corpus = two_issue_corpus();
        assert_eq!(
            search_substring(&corpus, "nope-nothing-here"),
            [] as [crate::search::SearchHit; 0]
        );
    }

    #[test]
    fn substring_empty_query_is_empty() {
        let corpus = two_issue_corpus();
        assert_eq!(
            search_substring(&corpus, ""),
            [] as [crate::search::SearchHit; 0]
        );
    }

    // ----------------------------------------------------------------------
    // T009 — fuzzy subsequence scorer
    // ----------------------------------------------------------------------

    #[test]
    fn fuzzy_exact_match_scores_higher_than_partial() {
        let exact = fuzzy_score("login bug", "login bug").unwrap();
        let partial = fuzzy_score("login bug", "debug the login bug report").unwrap();
        assert!(exact > partial);
    }

    #[test]
    fn fuzzy_contiguous_beats_spread() {
        let contiguous = fuzzy_score("ab", "xyab").unwrap();
        let spread = fuzzy_score("ab", "xayb").unwrap();
        assert!(contiguous > spread);
    }

    #[test]
    fn fuzzy_prefix_beats_mid_string() {
        let prefix = fuzzy_score("ab", "abxy").unwrap();
        let mid = fuzzy_score("ab", "xaby").unwrap();
        assert!(prefix > mid);
    }

    #[test]
    fn fuzzy_non_subsequence_is_none() {
        assert_eq!(fuzzy_score("abc", "aac"), None);
        assert_eq!(fuzzy_score("zzz", "haystack"), None);
    }

    #[test]
    fn fuzzy_is_case_insensitive() {
        assert_eq!(
            fuzzy_score("LOGIN", "login").unwrap(),
            fuzzy_score("login", "login").unwrap()
        );
        assert_eq!(
            fuzzy_score("aBc", "xAbC").unwrap(),
            fuzzy_score("abc", "xabc").unwrap()
        );
    }

    #[test]
    fn fuzzy_empty_query_scores_zero() {
        assert_eq!(fuzzy_score("", "anything"), Some(0));
    }

    #[test]
    fn fuzzy_earlier_positions_beat_later() {
        let early = fuzzy_score("ab", "abcxyz").unwrap();
        let late = fuzzy_score("ab", "xyzabc").unwrap();
        assert!(early > late);
    }

    #[test]
    fn fuzzy_perf_tripwire_500_issue_sweep_stays_fast() {
        // Synthetic 500-issue corpus, each ~1KB of prose — modelled on what
        // a `to_file_contents()` body actually looks like. The scorer runs
        // against each issue's text once per keystroke, so this is the real
        // hot path (C-005: no asset-dir binary reads).
        let issues: Vec<String> = (0..500u32)
            .map(|i| {
                format!(
                    "---\nnumber: {i}\ntitle: \"synthetic issue {i}\"\npriority: medium\n---\n\n\
                     A long body about feature {i} that mentions refunds, retries, idempotency keys, \
                     and a blocking redirect loop. The assigned developer needs to investigate the \
                     flaky test and prepare a hotfix for the staging deploy.\n\n\
                     ## Comments\n\n### alice (2026-01-01)\n\nNotes for issue {i}.\n"
                )
            })
            .collect();
        // Score 10 representative queries against the full corpus (each call
        // = one issue text per keystroke).
        let queries = [
            "issue",
            "transient race",
            "payment",
            "hotfix 3",
            "aAa",
            "zzz",
            "issue 499",
            "staging",
            "deploy",
            "ref",
        ];
        let start = std::time::Instant::now();
        for q in &queries {
            for issue in &issues {
                let _ = fuzzy_score(q, issue);
            }
        }
        let elapsed = start.elapsed();
        // 5000 fuzzy_score calls (10 queries × 500 issues); generous 500ms
        // bound. On modern hardware this runs in < 10ms.
        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "500-issue corpus re-filter must stay under 500ms, took {elapsed:?}"
        );
    }

    // ----------------------------------------------------------------------
    // WP02 phase 0 — T008/T009/T010: StructuredFilter, evaluate, matches
    // ----------------------------------------------------------------------

    #[test]
    fn filter_default_has_no_active_criteria() {
        let filter = StructuredFilter::default();
        assert!(!filter.has_active_criteria());
        assert_eq!(filter.criteria().count(), 0);
        assert_eq!(filter.to_string(), "(no active criteria)");
    }

    #[test]
    fn filter_criteria_lists_only_active_in_all_order() {
        let filter = StructuredFilter {
            label: Some("urgent".to_string()),
            assignee: Some(String::new()),
            status: Some("todo".to_string()),
            priority: None,
            cycle: None,
            milestone: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            overdue: None,
            parent: None,
            category: None,
            scope: None,
            archived: None,
            project: None,
            epic: None,
        };
        let criteria: Vec<(FilterField, &str)> = filter.criteria().collect();
        assert_eq!(
            criteria,
            vec![
                (FilterField::Label, "urgent"),
                (FilterField::Status, "todo")
            ]
        );
    }

    // Issue #1492 — the `archived:true|false` criterion and the
    // `--with-archived` corpus. The criterion is derived (the filename is the
    // marker), so it is lifted into the filter and judged against the issue.

    #[test]
    fn archived_criterion_matches_the_issue_state() {
        let mut archived = sample_issue(1, "Old", "");
        archived.archived = true;
        let active = sample_issue(2, "New", "");

        let want_true = StructuredFilter {
            archived: Some(true),
            ..Default::default()
        };
        assert!(want_true.archived_matches(&archived));
        assert!(!want_true.archived_matches(&active));

        let want_false = StructuredFilter {
            archived: Some(false),
            ..Default::default()
        };
        assert!(want_false.archived_matches(&active));
        assert!(!want_false.archived_matches(&archived));

        // Unset narrows nothing.
        assert!(StructuredFilter::default().archived_matches(&archived));
    }

    #[test]
    fn archived_token_is_lifted_out_of_the_query() {
        let (_tmp, store) = make_store();
        let (query, filter) = resolve_filter_criteria(&store, "archived:true status:todo").unwrap();
        assert_eq!(filter.archived, Some(true));
        assert!(
            !query.contains("archived"),
            "the token is lifted, not left for the store-free matcher: {query:?}"
        );
        assert!(filter.has_active_criteria());
        assert_eq!(filter.to_string(), "archived:true");

        let (_query, filter) = resolve_filter_criteria(&store, "archived:false").unwrap();
        assert_eq!(filter.archived, Some(false));
    }

    #[test]
    fn an_invalid_archived_value_is_refused_by_name() {
        let (_tmp, store) = make_store();
        let err = resolve_filter_criteria(&store, "archived:1").unwrap_err();
        assert!(
            err.to_string().contains("archived:true"),
            "the diagnostic names the accepted spellings: {err}"
        );
        // And a caller that skips the lift gets an empty result rather than a
        // silently-unfiltered one.
        assert!(!query_matches("archived:true", "---\nstatus: todo\n---\n"));
    }

    #[test]
    fn corpus_build_with_includes_archived_issues() {
        let (_tmp, store) = make_store();
        fs::create_dir_all(store.issues_dir.join("alice")).unwrap();
        let active = sample_issue(1, "Active", "body");
        write_issue(&store, "alice/2026-01-01-active.md", &active);
        let mut old = sample_issue(2, "Old", "body");
        old.archived = true;
        fs::write(
            store.issues_dir.join("alice/.2026-01-01-old.md"),
            old.to_file_contents(),
        )
        .unwrap();

        assert_eq!(
            Corpus::build(&store).unwrap().issues.len(),
            1,
            "the default corpus never reads the archived file"
        );
        let all = Corpus::build_with(&store, true).unwrap();
        assert_eq!(all.issues.len(), 2);
        assert!(all.issues.iter().any(|issue| issue.archived));
    }

    #[test]
    fn filter_evaluate_is_case_insensitive_substring() {
        let filter = StructuredFilter {
            status: Some("TODO".to_string()),
            ..Default::default()
        };
        assert!(filter.evaluate("---\nstatus: todo\n---\n"));
        assert!(filter.evaluate("---\nstatus: Todo\n---\n"));
        assert!(!filter.evaluate("---\nstatus: done\n---\n"));
        // Substring semantics on the serialized text (T009): a status token
        // must appear anywhere in the haystack, not only as a standalone field.
        assert!(filter.evaluate("todo"));
    }

    #[test]
    fn filter_evaluate_requires_all_active_criteria_and() {
        let haystack = "---\nstatus: todo\nlabels: [urgent]\npriority: high\nassignee: alice\n/**/";
        let all = StructuredFilter {
            assignee: Some("alice".to_string()),
            label: Some("urgent".to_string()),
            status: Some("todo".to_string()),
            priority: Some("high".to_string()),
            cycle: None,
            milestone: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            overdue: None,
            parent: None,
            category: None,
            scope: None,
            archived: None,
            project: None,
            epic: None,
        };
        assert!(all.evaluate(haystack), "all four present => match");
        // Same filter, haystack missing one criterion => no match (AND).
        assert!(!all.evaluate("status: todo labels: [urgent] priority: high"));
        assert!(
            !all.evaluate(
                "---\nstatus: todo\nlabels: [urgent]\npriority: medium\nassignee: alice\n"
            )
        );
        assert!(
            !all.evaluate("---\nstatus: todo\nlabels: [other]\npriority: high\nassignee: alice\n")
        );
    }

    #[test]
    fn filter_empty_string_criterion_counts_as_unset() {
        let filter = StructuredFilter {
            assignee: Some(String::new()),
            label: Some("urgent".to_string()),
            ..Default::default()
        };
        assert!(
            filter.evaluate("labels: [urgent]"),
            "empty assignee excluded"
        );
        assert!(filter.has_active_criteria());
    }

    #[test]
    fn filter_no_criteria_matches_everything() {
        let filter = StructuredFilter::default();
        assert!(filter.evaluate("anything at all"));
        assert!(filter.evaluate(""));
    }

    #[test]
    fn filter_display_renders_key_value_pairs() {
        let filter = StructuredFilter {
            assignee: Some("alice".to_string()),
            status: Some("todo".to_string()),
            ..Default::default()
        };
        assert_eq!(filter.to_string(), "assignee:alice, status:todo");
    }

    // ----------------------------------------------------------------------
    // WP02 T010 — the `scope:` criterion
    // ----------------------------------------------------------------------

    #[test]
    fn filter_scope_is_active_even_though_it_is_not_a_modal_row() {
        // A scope is a `StructuredFilter` field but not a `FilterField`, so
        // `criteria()` — which walks `FilterField::ALL` — cannot see it. Both
        // of the things that report "is this filter doing something" have to
        // agree that it is, or the hint bar says `(no active criteria)` while
        // the board is narrowed.
        let filter = StructuredFilter {
            scope: Some(vec!["triage".to_string(), "todo".to_string()]),
            ..Default::default()
        };

        assert!(
            filter.has_active_criteria(),
            "a filter that selects rows is active however it selects them"
        );
        assert_eq!(
            filter.criteria().count(),
            0,
            "and it still is not a modal row — the TUI's row count is unchanged"
        );
        assert_eq!(
            filter.to_string(),
            "scope:triage,todo",
            "the hint bar shows the columns it resolved to, not (no active criteria)"
        );
    }

    #[test]
    fn filter_display_keeps_criteria_overdue_and_scope_together() {
        let filter = StructuredFilter {
            assignee: Some("alice".to_string()),
            status: Some("todo".to_string()),
            overdue: Some(true),
            scope: Some(vec!["triage".to_string()]),
            ..Default::default()
        };
        assert_eq!(
            filter.to_string(),
            "assignee:alice, status:todo, scope:triage, overdue:true",
            "all three sources of a part, in the order they have always printed"
        );
    }

    #[test]
    fn filter_scope_round_trips_through_toml() {
        // `skip_serializing_if` keeps a scope-less filter byte-identical to what
        // it was before WP02, and a set one survives the round trip.
        let plain = StructuredFilter::default();
        assert!(
            !toml::to_string(&plain).unwrap().contains("scope"),
            "an unset scope writes no key at all"
        );

        let filter = StructuredFilter {
            scope: Some(vec!["triage".to_string()]),
            ..Default::default()
        };
        let back: StructuredFilter = toml::from_str(&toml::to_string(&filter).unwrap()).unwrap();
        assert_eq!(back, filter);
    }

    #[test]
    fn filter_scope_criterion_narrows_evaluate_issue_but_its_absence_does_not() {
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let in_box = issue_in(1, "Alpha", "triage");
        let outside = issue_in(2, "Bravo", "wip");
        let in_text = in_box.to_file_contents();
        let out_text = outside.to_file_contents();

        let scoped = StructuredFilter {
            scope: Some(vec!["triage".to_string()]),
            ..Default::default()
        };
        assert!(
            scoped.evaluate_issue(&in_box, &in_text, &resolution),
            "a member of the scope passes"
        );
        assert!(
            !scoped.evaluate_issue(&outside, &out_text, &resolution),
            "and a non-member fails — the scope is what was asked for"
        );

        let unset = StructuredFilter::default();
        assert!(
            unset.evaluate_issue(&outside, &out_text, &resolution),
            "an unset criterion narrows nothing (WP02 T010: a default view is untouched)"
        );
    }

    #[test]
    fn filter_normalize_trims_and_drops_empty() {
        let mut filter = StructuredFilter {
            assignee: Some("  ".to_string()),
            label: Some(" urgent ".to_string()),
            ..Default::default()
        };
        filter.normalize();
        assert_eq!(
            filter,
            StructuredFilter {
                assignee: None,
                label: Some("urgent".to_string()),
                ..Default::default()
            }
        );
    }

    #[test]
    fn filter_round_trips_through_toml() {
        let filter = StructuredFilter {
            assignee: Some("alice".to_string()),
            label: Some("urgent".to_string()),
            status: Some("todo".to_string()),
            priority: Some("high".to_string()),
            cycle: None,
            milestone: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            overdue: None,
            parent: None,
            category: None,
            scope: None,
            archived: None,
            project: None,
            epic: None,
        };
        let text = toml::to_string(&filter).unwrap();
        let back: StructuredFilter = toml::from_str(&text).unwrap();
        assert_eq!(back, filter);
    }

    #[test]
    fn number_query_classifies_bare_numbers() {
        assert_eq!(number_query("55"), Some(55));
        assert_eq!(number_query(" 55 "), Some(55), "whitespace-padded trims");
        assert_eq!(number_query("055"), Some(55), "leading zeros parse");
        assert_eq!(number_query("0"), Some(0));
    }

    #[test]
    fn number_query_rejects_non_number_inputs() {
        assert_eq!(number_query(""), None, "empty");
        assert_eq!(number_query("   "), None, "whitespace-only");
        assert_eq!(number_query("login"), None, "non-digit");
        assert_eq!(number_query("55bug"), None, "mixed digits + letters");
        assert_eq!(
            number_query("99999999999999999999"),
            None,
            "overflows u32 -> falls back to fuzzy"
        );
        assert_eq!(number_query("-55"), None, "sign not a bare number");
    }

    #[test]
    fn number_query_accepts_u32_max() {
        assert_eq!(number_query(&u32::MAX.to_string()), Some(u32::MAX));
    }

    #[test]
    fn matches_composes_fuzzy_and_structured() {
        let filter = StructuredFilter {
            label: Some("urgent".to_string()),
            ..Default::default()
        };
        let haystack_1 = "---\ntitle: \"Login bug\"\nlabels: [urgent]\n---\n";
        let haystack_2 = "---\ntitle: \"Export csv\"\nlabels: [urgent]\n---\n";

        // Both layers must hold when both are active (FR-013).
        assert!(matches("Login", &filter, haystack_1));
        assert!(
            !matches("Login", &filter, haystack_2),
            "label matches but text does not"
        );
        assert!(
            !matches("zzz", &filter, haystack_1),
            "text matches but label does not"
        );

        // Empty query => structured filter only.
        assert!(matches("", &filter, haystack_1));
        assert!(!matches("", &filter, "labels: [critical]\n"));

        // Default filter => fuzzy text only.
        let default = StructuredFilter::default();
        assert!(matches("Login", &default, haystack_1));
        assert!(!matches("zzz", &default, haystack_1));

        // Empty layers both => always true.
        assert!(matches("", &default, "anything"));
    }

    #[test]
    fn matches_against_real_corpus() {
        let corpus = two_issue_corpus();
        let filter = StructuredFilter {
            label: Some("urgent".to_string()),
            status: Some("todo".to_string()),
            ..Default::default()
        };
        let matches_by = |query: &str| {
            corpus
                .issues
                .iter()
                .zip(corpus.texts())
                .filter(|(_, text)| matches(query, &filter, text))
                .map(|(issue, _)| issue.number)
                .collect::<std::collections::BTreeSet<u32>>()
                .into_iter()
                .collect::<Vec<_>>()
        };
        // Both issues carry `urgent` label + todo status: filter-only
        // returns both; fuzzy text narrows: "Login bug" -> issue 1 only,
        // "empty rows" -> issue 2 only, miss -> empty.
        assert_eq!(matches_by(""), vec![1, 2]);
        assert_eq!(matches_by("Login bug"), vec![1]);
        assert_eq!(matches_by("empty rows"), vec![2]);
        assert_eq!(matches_by("zzz-no-hit"), Vec::<u32>::new());
    }

    #[test]
    fn query_matches_supports_token_grammar_and_bare_terms() {
        let haystack = "---\ncycle: Cycle 1\nmilestone: Backlog\nreviewer: alice\nstatus: todo\nstart_date: 2026-09-01\ndue_date: 2000-09-10\n---\nlogin bug\n";
        assert!(query_matches("cycle:Cycle", haystack));
        assert!(query_matches("milestone:Backlog reviewer:alice", haystack));
        assert!(query_matches("overdue:true", haystack));
        assert!(query_matches("overdue", haystack));
        assert!(query_matches("group:cycle sort:due", haystack));
        assert!(!query_matches("group:assignee", haystack));
        assert!(query_matches("login bug", haystack));
        assert!(!query_matches("cycle:Other", haystack));
        assert!(!query_matches("missing term", haystack));
    }

    #[test]
    fn t1498_a_bare_term_is_a_substring_not_a_subsequence() {
        // The board `/` search used to end at `fuzzy_score`, a subsequence
        // match: `greedy` is `g`,`r`,`e`,`e`,`d`,`y` in order across nearly
        // any prose, so it matched almost every issue. It is now the same
        // case-insensitive **substring** rule the CLI search uses (tix #1498).
        let hit = "---\nstatus: todo\n---\nthe greedy matcher\n";
        let scattered = "---\nstatus: todo\n---\ngreat red dye\n";
        // A subsequence would match `scattered` (g,r,e,e,d,y in order); a
        // substring must not.
        assert!(fuzzy_score("greedy", scattered).is_some());
        assert!(query_matches("greedy", hit));
        assert!(
            !query_matches("greedy", scattered),
            "characters in order are not a substring match"
        );
        assert!(query_matches("GREEDY", hit), "case-insensitive");
        // A bare term still ANDs with the structured tokens beside it.
        assert!(query_matches("status:todo greedy", hit));
        assert!(!query_matches("status:todo greedy", scattered));
    }

    #[test]
    fn matches_uses_query_tokens_for_board_paths() {
        let filter = StructuredFilter::default();
        let haystack = "---\nstatus: todo\ndue_date: 2000-01-01\ncycle: Cycle 1\n---\nbody\n";
        assert!(matches("overdue cycle:Cycle", &filter, haystack));
        assert!(!matches("overdue cycle:Other", &filter, haystack));
    }

    #[test]
    fn structured_filter_overdue_uses_due_date_and_status() {
        let filter = StructuredFilter {
            overdue: Some(true),
            ..Default::default()
        };
        let overdue_haystack = "---\nstatus: todo\ndue_date: 2000-01-01\n---\nbody\n";
        let done_haystack = "---\nstatus: done\ndue_date: 2000-01-01\n---\nbody\n";
        assert!(filter.evaluate(overdue_haystack));
        assert!(!filter.evaluate(done_haystack));
    }

    #[test]
    fn structured_filter_display_includes_new_fields() {
        let filter = StructuredFilter {
            cycle: Some("Cycle 1".to_string()),
            milestone: Some("Backlog".to_string()),
            reviewer: Some("alice".to_string()),
            start_date: Some("2026-09-01".to_string()),
            due_date: Some("2026-09-10".to_string()),
            overdue: Some(true),
            ..Default::default()
        };
        assert!(filter.to_string().contains("cycle:Cycle 1"));
        assert!(filter.to_string().contains("overdue:true"));
    }

    #[test]
    fn filter_evaluate_perf_tripwire_500_issue_sweep_stays_fast() {
        // Same synthetic corpus as the fuzzy tripwire; `evaluate` runs once
        // per entry per re-filter (NFR-001, C-002). With 4 active criteria
        // each evaluate is a handful of lowercases + contains calls.
        let filter = StructuredFilter {
            assignee: Some("alice".to_string()),
            label: Some("urgent".to_string()),
            status: Some("todo".to_string()),
            priority: Some("medium".to_string()),
            cycle: None,
            milestone: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            overdue: None,
            parent: None,
            category: None,
            scope: None,
            archived: None,
            project: None,
            epic: None,
        };
        let issues: Vec<String> = (0..500u32)
            .map(|i| {
                format!(
                    "---\nnumber: {i}\ntitle: \"synthetic issue {i}\"\nstatus: todo\nlabels: [urgent]\npriority: medium\nassignee: alice\n---\n\n\
                     A long body about feature {i}.\n"
                )
            })
            .collect();
        let start = std::time::Instant::now();
        for haystack in &issues {
            assert!(filter.evaluate(haystack));
        }
        let elapsed = start.elapsed();
        assert!(
            elapsed < std::time::Duration::from_millis(500),
            "500-issue structured re-filter must stay under 500ms, took {elapsed:?}"
        );
    }

    // -----------------------------------------------------------------------
    // WP06 / T024 + T025 — the `parent` criterion
    // -----------------------------------------------------------------------

    #[test]
    fn t024_the_parent_key_is_the_key_the_model_serialises() {
        // T024 step 4, the guard against the table and the file format drifting
        // apart. `key()` feeds the diagnostics, so a mismatch would make `tix
        // lint` point at a field that does not exist, with no error anywhere.
        let issue = Issue::parse(
            "---\nnumber: 1\ntitle: T\nstatus: todo\nlabels: []\npriority: medium\nparent: 7\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nB.",
        )
        .unwrap();
        let fm = issue.frontmatter();
        assert!(
            fm.contains(&format!("\n{}:", FilterField::Parent.key())),
            "`key()` ({}) must be a key the renderer emits:\n{fm}",
            FilterField::Parent.key()
        );
        // And the reverse direction: every criterion's key is a real field, so the
        // guard above is not a one-way check that happens to pass.
        for field in FilterField::ALL {
            let key = field.key();
            if key == "cycle" || key == "milestone" {
                // These two are **not** the frontmatter keys: the model writes
                // `cycles` and `milestones`, and the query grammar uses the
                // singular. Pre-existing, and the reason this assertion is scoped
                // to `parent` rather than generalised.
                continue;
            }
            let mut probe = issue.clone();
            probe.parent = None;
            let rendered = probe.frontmatter();
            assert!(
                rendered.contains(&format!("\n{key}:")) || rendered.contains("\nlabels:"),
                "`{key}` is not a key the model emits"
            );
        }
    }

    #[test]
    fn t024_all_label_and_key_are_consistent_and_the_nine_keep_their_order() {
        // `Parent` is **appended**, so the nine existing criteria keep their
        // relative order (T024 step 2) and any user's muscle memory, or any golden
        // index, still holds.
        let expected: [FilterField; 9] = [
            FilterField::Assignee,
            FilterField::Label,
            FilterField::Status,
            FilterField::Priority,
            FilterField::Cycle,
            FilterField::Milestone,
            FilterField::Reviewer,
            FilterField::StartDate,
            FilterField::DueDate,
        ];
        assert_eq!(
            FilterField::ALL[..9],
            expected,
            "the existing nine criteria must keep their relative order"
        );
        assert_eq!(FilterField::ALL[9], FilterField::Parent, "appended tenth");
        // WP08 T034 step 2: `Category` is appended for the same reason, so `Parent`
        // is no longer last. Both are asserted rather than derived, because a test
        // that computed the expectation from `ALL` would agree with any order.
        assert_eq!(
            FilterField::ALL[10],
            FilterField::Category,
            "and Category is appended eleventh"
        );
        // WP06 T026: `Project` is appended twelfth, for the same reason — and
        // appending is what keeps every index above stable, so no golden row moved.
        assert_eq!(
            FilterField::ALL[11],
            FilterField::Project,
            "and Project is appended twelfth"
        );
        // WP06 T028: `Epic` is appended thirteenth, for the same reason.
        assert_eq!(
            FilterField::ALL[12],
            FilterField::Epic,
            "and Epic is appended thirteenth"
        );
        assert_eq!(FilterField::ALL.len(), 13, "and ALL must be complete");

        // Every variant is in ALL exactly once, so `row()` cannot panic and `next()`
        // cannot skip one.
        for field in FilterField::ALL {
            let row = field.row();
            assert_eq!(
                FilterField::ALL[row],
                field,
                "{field:?} is not at its own row"
            );
            assert_eq!(
                FilterField::ALL.iter().filter(|f| **f == field).count(),
                1,
                "{field:?} appears more than once in ALL"
            );
            assert!(!field.label().is_empty(), "{field:?} has an empty label");
            assert!(!field.key().is_empty(), "{field:?} has an empty key");
        }
    }

    #[test]
    fn t024_row_navigation_wraps_at_the_new_bounds() {
        // The first version of the table wrapped correctly by accident of the
        // bounds; with a tenth row the arithmetic is different, so both ends are
        // asserted — and WP08 added an eleventh and WP06 a twelfth, so the bound
        // moved again each time.
        assert_eq!(FilterField::Assignee.row(), 0, "the first row");
        assert_eq!(FilterField::Parent.row(), 9, "not last any more");
        assert_eq!(FilterField::Category.row(), 10, "not last any more");
        assert_eq!(FilterField::Project.row(), 11, "not last any more");
        assert_eq!(FilterField::Epic.row(), 12, "the new last row");
        assert_eq!(
            FilterField::Epic.next(),
            FilterField::Assignee,
            "the last row wraps to the first"
        );
        assert_eq!(
            FilterField::Assignee.prev(),
            FilterField::Epic,
            "and the first row's predecessor is the new last"
        );
        // The boundary is `ALL.len()` in both directions, so a fourteenth row would
        // wrap correctly without either of the assertions above being edited.
        assert_eq!(
            FilterField::ALL[FilterField::Assignee.row() + FilterField::ALL.len() - 1],
            FilterField::Epic,
            "prev is a mod of len, not of a hard-coded index"
        );
        // A full lap visits all thirteen, once each.
        let mut field = FilterField::Assignee;
        let mut seen = Vec::new();
        for _ in 0..FilterField::ALL.len() {
            seen.push(field);
            field = field.next();
        }
        assert_eq!(field, FilterField::Assignee, "a full lap returns home");
        seen.sort_by_key(|f| f.row());
        assert_eq!(seen, FilterField::ALL.to_vec(), "visiting each once");
    }

    // -----------------------------------------------------------------------
    // WP06 / T026 + T027 — the `project` criterion and the `group:project` key
    // -----------------------------------------------------------------------

    /// An issue carrying an association list, for the membership tests.
    fn project_issue(number: u32, title: &str, projects: &[&str]) -> Issue {
        let mut issue = sample_issue(number, title, "");
        issue.projects = if projects.is_empty() {
            None
        } else {
            Some(projects.iter().map(|p| (*p).to_string()).collect())
        };
        issue
    }

    #[test]
    fn t026_the_project_key_is_the_key_the_model_serialises() {
        // T026 step 3, the guard against the filter table and the file format
        // drifting apart — the same guard T024 placed on `parent`. `key()` feeds the
        // diagnostics, so a mismatch would name a field the model never writes.
        let mut probe = sample_issue(1, "T", "");
        probe.projects = Some(vec!["p-1".to_string()]);
        let rendered = probe.frontmatter();
        assert!(
            rendered.contains(&format!("\n{}:\n- p-1", FilterField::Project.key())),
            "`key()` ({}) must be the key the model serialises the association list under:\n{rendered}",
            FilterField::Project.key()
        );
        // The model's own registered-key table agrees, so a rename on either side
        // of the boundary fails a test rather than the filter.
        assert!(
            crate::model::KNOWN_FRONTMATTER_KEYS.contains(&FilterField::Project.key()),
            "{} must be a registered frontmatter key",
            FilterField::Project.key()
        );
    }

    #[test]
    fn t027_the_project_criterion_matches_by_membership_not_by_substring() {
        let filter = |id: &str| StructuredFilter {
            project: Some(id.to_string()),
            ..StructuredFilter::default()
        };
        let member = project_issue(1, "Member", &["p-1"]);
        let other = project_issue(2, "Other", &["p-2"]);
        let unassociated = project_issue(3, "None", &[]);
        assert!(filter("p-1").project_matches(&member), "a member matches");
        assert!(
            !filter("p-1").project_matches(&other),
            "a non-member does not"
        );
        assert!(
            !filter("p-1").project_matches(&unassociated),
            "an unassociated issue matches no project"
        );
        // Exact, not substring: `p-1` must not match an association with `p-12`.
        let longer = project_issue(4, "Longer", &["p-12"]);
        assert!(
            !filter("p-1").project_matches(&longer),
            "p-1 must not match p-12"
        );
        // A body that merely mentions the id is not a membership either.
        let mut mentions = sample_issue(5, "mentions p-1", "this body says p-1");
        mentions.projects = None;
        assert!(!filter("p-1").project_matches(&mentions));
        // An unset criterion narrows nothing, like every other criterion.
        assert!(StructuredFilter::default().project_matches(&unassociated));
    }

    #[test]
    fn t027_a_stored_but_unresolved_id_still_matches_the_criterion() {
        // The repair affordance, pinned (WP06 review item 4): a `tix project delete`
        // leaves the reference behind (C-005 retains it), and the filter must still
        // find the issues carrying it — `tix project remove <stale-id>` takes the id
        // **as stored**. This matches the raw string; the board's partition
        // deliberately buckets such an issue `(no project)`, and both are asserted so
        // the asymmetry is a decision rather than a drift.
        let stale = project_issue(1, "Stale", &["p-gone"]);
        let filter = StructuredFilter {
            project: Some("p-gone".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            filter.project_matches(&stale),
            "a stored reference to a deleted project must still be findable"
        );
        // And a different stale reference does not match it.
        assert!(
            !StructuredFilter {
                project: Some("p-other".to_string()),
                ..StructuredFilter::default()
            }
            .project_matches(&stale)
        );
    }

    #[test]
    fn t027_an_issue_in_two_projects_matches_both_and_an_unknown_id_matches_nothing() {
        // T027 step 3: multi-membership is a union — the criterion is a membership
        // test, not a first-value read.
        let both = project_issue(1, "Both", &["p-1", "p-2"]);
        let only = |id: &str| StructuredFilter {
            project: Some(id.to_string()),
            ..StructuredFilter::default()
        };
        assert!(only("p-1").project_matches(&both));
        assert!(only("p-2").project_matches(&both));
        assert!(!only("p-3").project_matches(&both));
        // T027 step 6: an id no association carries — including one the registry
        // does not know — matches nothing rather than erroring.
        let unknown = only("p-does-not-exist");
        assert!(!unknown.project_matches(&both));
        assert!(!unknown.project_matches(&project_issue(2, "Plain", &[])));
    }

    #[test]
    fn t027_the_project_criterion_joins_the_full_predicate_and_the_hint_bar() {
        // `evaluate_issue` ANDs the membership with the rest, and the criterion is
        // visible in `Display` through `criteria()` — a criterion the hint bar did
        // not print would be a filter the user cannot see.
        let config = crate::config::Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let issue = project_issue(1, "Member", &["p-1"]);
        let text = issue.frontmatter();
        let filter = StructuredFilter {
            project: Some("p-1".to_string()),
            status: Some("todo".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            filter.evaluate_issue(&issue, &text, &resolution),
            "both active criteria hold"
        );
        let missed = StructuredFilter {
            project: Some("p-1".to_string()),
            status: Some("shipped".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            !missed.evaluate_issue(&issue, &text, &resolution),
            "the two layers AND together"
        );
        assert!(filter.has_active_criteria());
        assert_eq!(filter.to_string(), "status:todo, project:p-1");
        assert_eq!(
            FilterField::Project.describe(),
            "projects",
            "a real frontmatter key is named honestly, unlike the derived category"
        );
        assert!(FilterField::Project.is_project());
        assert!(
            !FilterField::Project.is_derived() && !FilterField::Project.is_reference(),
            "membership is its own kind, not a derived value or a parent reference"
        );
    }

    // -----------------------------------------------------------------------
    // WP06 / T028 + T029 — the `epic` criterion and the `group:epic` key
    // -----------------------------------------------------------------------

    /// An issue carrying an epic reference list, for the membership tests.
    fn epic_issue(number: u32, title: &str, epics: &[&str]) -> Issue {
        let mut issue = sample_issue(number, title, "");
        issue.epics = if epics.is_empty() {
            None
        } else {
            Some(epics.iter().map(|e| (*e).to_string()).collect())
        };
        issue
    }

    /// The config with the named epics registered.
    fn epic_registry(epics: &[(&str, &str)]) -> crate::config::Config {
        let mut config = crate::config::Config::default();
        for (id, name) in epics {
            config.epics.insert(
                (*id).to_string(),
                crate::config::EpicConfiguration {
                    name: (*name).to_string(),
                    ..Default::default()
                },
            );
        }
        config
    }

    #[test]
    fn t028_the_epic_key_is_the_exact_frontmatter_key_the_model_serialises() {
        // T028 step 3: the guard against the filter table and the file format
        // drifting apart. `key()` feeds the diagnostics, so a mismatch would name a
        // field the model never writes — and a service-side rename has no other
        // alarm.
        assert_eq!(
            FilterField::Epic.key(),
            crate::epics::EPICS_KEY,
            "key() must be the service's own constant, not a second literal"
        );
        let mut probe = epic_issue(1, "T", &["e-aaa111"]);
        probe.epics = Some(vec!["e-aaa111".to_string()]);
        let rendered = probe.frontmatter();
        assert!(
            rendered.contains(&format!("\n{}:\n- e-aaa111", FilterField::Epic.key())),
            "`key()` ({}) must be the key the model serialises the reference list under:\n{rendered}",
            FilterField::Epic.key()
        );
        assert!(
            crate::model::KNOWN_FRONTMATTER_KEYS.contains(&FilterField::Epic.key()),
            "{} must be a registered frontmatter key",
            FilterField::Epic.key()
        );
        // The **token** is the singular `epic:` — the split Project records.
        assert_eq!(FilterField::Epic.token(), "epic");
        assert_eq!(FilterField::Epic.describe(), "epics");
    }

    #[test]
    fn t029_the_epic_criterion_matches_by_membership_not_by_substring() {
        let filter = |id: &str| StructuredFilter {
            epic: Some(id.to_string()),
            ..StructuredFilter::default()
        };
        let member = epic_issue(1, "Member", &["e-aaa111"]);
        let other = epic_issue(2, "Other", &["e-bbb222"]);
        let unassociated = epic_issue(3, "None", &[]);
        assert!(filter("e-aaa111").epic_matches(&member), "a member matches");
        assert!(
            !filter("e-aaa111").epic_matches(&other),
            "a non-member does not"
        );
        assert!(
            !filter("e-aaa111").epic_matches(&unassociated),
            "an unreferenced issue matches no epic"
        );
        // Exact, not substring: `e-1` must not match a reference to `e-12`.
        let longer = epic_issue(4, "Longer", &["e-12"]);
        assert!(
            !filter("e-1").epic_matches(&longer),
            "e-1 must not match e-12"
        );
        // A body that merely mentions the id is not a membership either.
        let mut mentions = sample_issue(5, "mentions e-aaa111", "this body says e-aaa111");
        mentions.epics = None;
        assert!(!filter("e-aaa111").epic_matches(&mentions));
        // An unset criterion narrows nothing, like every other criterion.
        assert!(StructuredFilter::default().epic_matches(&unassociated));
    }

    #[test]
    fn t029_a_stored_but_unresolved_epic_still_matches_the_criterion() {
        // The repair affordance, pinned: a `tix epic delete` leaves the reference
        // behind (C-005 retains it), and the filter must still find the issues
        // carrying it — `tix epic remove <stale-id>` takes the id as stored.
        let stale = epic_issue(1, "Stale", &["e-gone"]);
        let filter = StructuredFilter {
            epic: Some("e-gone".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            filter.epic_matches(&stale),
            "a stored reference to a deleted epic must still be findable"
        );
        assert!(
            !StructuredFilter {
                epic: Some("e-other".to_string()),
                ..StructuredFilter::default()
            }
            .epic_matches(&stale)
        );
    }

    #[test]
    fn t029_an_issue_in_two_epics_matches_both_and_an_unknown_id_matches_nothing() {
        // T029 step 3: multi-membership is a union — the criterion is a membership
        // test, not a first-value read.
        let both = epic_issue(1, "Both", &["e-aaa111", "e-bbb222"]);
        let only = |id: &str| StructuredFilter {
            epic: Some(id.to_string()),
            ..StructuredFilter::default()
        };
        assert!(only("e-aaa111").epic_matches(&both));
        assert!(only("e-bbb222").epic_matches(&both));
        assert!(!only("e-ccc333").epic_matches(&both));
        // T029 step 6: an id no reference carries — including one the registry does
        // not know — matches nothing rather than erroring.
        let unknown = only("e-does-not-exist");
        assert!(!unknown.epic_matches(&both));
        assert!(!unknown.epic_matches(&epic_issue(2, "Plain", &[])));
    }

    #[test]
    fn t029_the_epic_bucket_label_partitions_with_a_labelled_no_epic_bucket() {
        // T029 step 4, the recorded partition decision: one bucket per issue — the
        // single epic id, `(multiple epics)`, or a labelled `(no epic)`.
        assert_eq!(epic_bucket_label(&[]), "(no epic)");
        assert_eq!(epic_bucket_label(&["e-aaa111".to_string()]), "e-aaa111");
        assert_eq!(
            epic_bucket_label(&["e-aaa111".to_string(), "e-bbb222".to_string()]),
            "(multiple epics)"
        );
    }

    #[test]
    fn t028_group_and_sort_accept_epic_and_still_reject_unknown_keys() {
        // The `epic` grouping/sort key rides the **existing** control-token
        // machinery: a key this grammar did not list would veto every issue and the
        // board would render empty rather than grouped.
        assert!(query_matches("group:epic sort:epic", "status: todo"));
        assert!(query_matches("group:epic", "status: todo"));
        assert!(query_matches("sort:epic", "status: todo"));
        // An unknown key is rejected the way other unknown keys are.
        assert!(!query_matches("group:assignee", "status: todo"));
        assert!(!query_matches("sort:magic", "status: todo"));
        assert!(!query_matches("group:magic sort:magic", "status: todo"));
    }

    #[test]
    fn t029_a_name_resolves_to_its_id_and_an_unknown_reference_is_kept_verbatim() {
        let config = epic_registry(&[("e-aaa111", "Alpha")]);
        // By name, through the service's own resolver — the same id
        // `tix epic show Alpha` names.
        let (query, epic) = lift_epic_criterion(&config, "epic:Alpha status:todo");
        assert_eq!(query, "status:todo", "the token is lifted out of the query");
        assert_eq!(epic.as_deref(), Some("e-aaa111"));
        // By id, unchanged.
        let (_, epic) = lift_epic_criterion(&config, "epic:e-aaa111");
        assert_eq!(epic.as_deref(), Some("e-aaa111"));
        // A reference the registry does not know is kept **verbatim** rather than
        // refused, so a typo is the visible empty result an unknown `project:` gives.
        let (_, unknown) = lift_epic_criterion(&config, "epic:e-nope");
        assert_eq!(unknown.as_deref(), Some("e-nope"));
        // Last token wins, as `project:` behaves.
        let (_, last) = lift_epic_criterion(&config, "epic:Alpha epic:e-bbb222");
        assert_eq!(last.as_deref(), Some("e-bbb222"));
    }

    #[test]
    fn t029_the_epic_criterion_joins_the_full_predicate_and_the_hint_bar() {
        // `evaluate_issue` ANDs the membership with the rest, and the criterion is
        // visible in `Display` through `criteria()` — a criterion the hint bar did
        // not print would be a filter the user cannot see.
        let config = crate::config::Config::default();
        let (_, resolution) = crate::workflow::active_resolution(&config);
        let issue = epic_issue(1, "Member", &["e-aaa111"]);
        let text = issue.frontmatter();
        let filter = StructuredFilter {
            epic: Some("e-aaa111".to_string()),
            status: Some("todo".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            filter.evaluate_issue(&issue, &text, &resolution),
            "both active criteria hold"
        );
        let missed = StructuredFilter {
            epic: Some("e-aaa111".to_string()),
            status: Some("shipped".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            !missed.evaluate_issue(&issue, &text, &resolution),
            "the two layers AND together"
        );
        assert!(filter.has_active_criteria());
        assert_eq!(
            filter.to_string(),
            "status:todo, epic:e-aaa111",
            "the hint bar echoes the **token**, so the row is usable"
        );
        assert!(FilterField::Epic.is_epic());
        assert!(
            !FilterField::Epic.is_derived()
                && !FilterField::Epic.is_reference()
                && !FilterField::Epic.is_project(),
            "membership is its own kind, and epic ≠ project"
        );
        // `is_derived` matched nothing new: only Category is derived.
        for field in FilterField::ALL {
            assert_eq!(
                field.is_derived(),
                field == FilterField::Category,
                "{field:?} derived-flag is wrong"
            );
        }
    }

    #[test]
    fn t027_the_store_free_matcher_refuses_a_project_token_rather_than_matching_everything() {
        // A caller that skipped `resolve_filter_criteria` gets an empty result it
        // can see, not an unfiltered one it cannot — the same refusal `category:`,
        // `scope:` and `archived:` carry.
        assert!(!query_matches(
            "project:p-1",
            "projects:\n- p-1\nstatus: todo"
        ));
        assert!(!query_matches("project:p-1", "status: todo"));
    }

    #[test]
    fn t026_group_and_sort_accept_project_and_reject_unknown_keys() {
        // A control token the grammar does not list vetoes **every** issue, so
        // `sort:project` (which makes the partition contiguous) and `group:project`
        // must be accepted exactly as `cycle`/`milestone` are.
        assert!(query_matches("group:project sort:project", "status: todo"));
        assert!(query_matches(
            "group:project sort:project",
            "projects:\n- p-1"
        ));
        // An unknown key is rejected the way other unknown keys are: the criterion
        // matches nothing.
        assert!(!query_matches("group:assignee", "status: todo"));
        assert!(!query_matches("sort:magic", "status: todo"));
        assert!(!query_matches("group:project sort:magic", "status: todo"));
    }

    fn child_file(number: u32, title: &str, parent: Option<u32>) -> String {
        let parent_line = parent.map(|p| format!("parent: {p}\n")).unwrap_or_default();
        format!(
            "---\nnumber: {number}\ntitle: {title}\nstatus: todo\nlabels: []\npriority: medium\n{parent_line}files: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody text.\n"
        )
    }

    #[test]
    fn t025_a_parent_criterion_matches_exactly_its_direct_children() {
        // #1 has children #2 and #3; #4 is #2's child, and #5 is unrelated.
        let files = [
            child_file(1, "Parent", None),
            child_file(2, "Child A", Some(1)),
            child_file(3, "Child B", Some(1)),
            child_file(4, "Grandchild", Some(2)),
            child_file(5, "Unrelated", None),
        ];
        let filter = StructuredFilter {
            parent: Some("1".to_string()),
            ..StructuredFilter::default()
        };
        let matched: Vec<u32> = files
            .iter()
            .filter(|f| filter.evaluate(f))
            .map(|f| {
                f.lines()
                    .find_map(|l| l.strip_prefix("number: "))
                    .and_then(|n| n.parse().ok())
                    .unwrap()
            })
            .collect();
        assert_eq!(
            matched,
            vec![2, 3],
            "direct children only — a grandchild must not match its grandparent"
        );
    }

    #[test]
    fn t025_the_criterion_compares_the_number_exactly_not_as_a_substring() {
        // The hazard a substring implementation walks into: `parent: 1` would also
        // match `parent: 11`, and `parent: 1` would match any issue whose *body*
        // mentions 1.
        let filter = StructuredFilter {
            parent: Some("1".to_string()),
            ..StructuredFilter::default()
        };
        assert!(filter.evaluate(&child_file(2, "A", Some(1))), "exactly 1");
        assert!(
            !filter.evaluate(&child_file(2, "A", Some(11))),
            "11 must not match a criterion of 1"
        );
        assert!(!filter.evaluate(&child_file(2, "A", Some(10))), "nor 10");
        // An issue with no `parent:` key at all must not match, even though its
        // number is 1 and its body mentions 1.
        let no_parent = "---\nnumber: 1\ntitle: mentions 1\nstatus: todo\nlabels: []\npriority: medium\nfiles: []\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody with 1 in it.\n";
        assert!(
            !filter.evaluate(no_parent),
            "an issue with no parent key must not match a parent criterion"
        );
    }

    #[test]
    fn t025_a_child_of_a_deleted_parent_matches_nothing() {
        // T025 step 4. The recorded reference is retained, so the child still says
        // `parent: 1`; but a criterion can only be *set* to a number a user named,
        // and once #1 is gone no selector resolves to it — so nothing is reachable
        // through the query path, which is the outcome the subtask asks for.
        let filter = StructuredFilter {
            parent: Some("1".to_string()),
            ..StructuredFilter::default()
        };
        let orphan = child_file(2, "Orphan", Some(1));
        // The service reports it unresolved, which is the state that matters.
        let parsed = Issue::parse(&orphan).unwrap();
        let index = crate::hierarchy::HierarchyIndex::build(std::slice::from_ref(&parsed));
        assert_eq!(index.unresolved().len(), 1, "the reference is diagnosed");
        // And a criterion naming a *different, live* parent does not match it.
        let other = StructuredFilter {
            parent: Some("7".to_string()),
            ..StructuredFilter::default()
        };
        assert!(
            !other.evaluate(&orphan),
            "a live, different parent does not match"
        );
        // The retained reference still matches its own number, which is the honest
        // answer: the field says 1, so a filter saying 1 selects it. Documented in
        // contracts/cli-surface.md §4 rather than papered over.
        assert!(
            filter.evaluate(&orphan),
            "the recorded reference is retained, so it still matches its own number"
        );
    }

    #[test]
    fn t025_the_query_grammar_matches_parent_exactly_too() {
        // The `query_matches` path, which is what `tix list --filter` and the TUI's
        // text field use — a different entry point from `StructuredFilter::evaluate`.
        let child = child_file(2, "A", Some(1));
        assert!(query_matches("parent:1", &child), "exactly 1");
        // The negative case has to be a fixture whose **other text** contains `11`,
        // or a substring implementation is not actually exercised. The first version
        // of this test used a plain fixture whose remaining text happens not to
        // contain "11" — so reverting the exact comparison to a substring left the
        // test green.
        let decoy = child_file(2, "Issue 11 notes", Some(1))
            .replace("Body text.\n", "Body text. See issue 11 for context.\n");
        assert!(
            !query_matches("parent:11", &decoy),
            "a body mentioning 11 must not match a criterion of 11"
        );
        assert!(
            query_matches("parent:1", &decoy),
            "while the real parent still matches"
        );
        assert!(
            query_matches("parent:11", &child_file(2, "A", Some(11))),
            "and 11 matches when it is the real parent"
        );
        // An empty value is **not** a criterion: `parse_token` rejects a token with
        // an empty value, so `parent:` falls through to the bare-term path and is
        // fuzzy-matched like any other word — which is what every other key does
        // too, and is why `parent` needed no special case here.
        //
        // The first version of this test asserted `!query_matches("parent:", ..)`,
        // reading "not a criterion" as "matches nothing". Measured, it matches — as
        // `status:` and `due:` do. An intermediate attempt asserted consistency by
        // comparing the same query against two different haystacks, which is not a
        // consistency property at all and failed for the right reason: the keys are
        // not interchangeable on one haystack, because `parent:` and `status:` are
        // literally different strings.
        //
        // Measured, an empty `parent:` **does** correlate with "has a parent",
        // because the bare term happens to be the literal string `parent:` and the
        // haystack contains it. That is an accident of the fuzzy path, not a
        // criterion: the *values* are ignored entirely, so two issues with
        // completely different parents both match.
        //
        // Asserted as a pair, because the first half alone is a misleading
        // statement and the second alone is trivially true. Two earlier versions of
        // this test asserted the narrowing property above, which is simply not how
        // it behaves.
        assert!(
            query_matches("parent:", &child_file(2, "A", Some(1)))
                && query_matches("parent:", &child_file(3, "B", Some(7))),
            "an empty value ignores the parent, so any two parents both match"
        );
        assert!(
            !query_matches("parent:", &child_file(4, "C", None)),
            "and an issue with no `parent:` key has no literal to match"
        );
        // And the substring and fuzzy semantics are untouched when a criterion is
        // combined with a bare term.
        assert!(
            query_matches("parent:1 Body", &child),
            "a bare term still applies alongside the criterion"
        );
        assert!(
            !query_matches("parent:1 nonsense", &child),
            "and can still exclude"
        );
    }

    #[test]
    fn t025_an_empty_criterion_behaves_like_the_others() {
        // The canonical invariant: an empty string is "no criterion" everywhere, so
        // the filter modal can edit a slot without a live-match surprise.
        let mut filter = StructuredFilter::default();
        assert_eq!(filter.parent, None);
        // The mutable accessor is what the filter modal types into, and what
        // creates the empty slot (there is no `set()`; `value_mut` is the path).
        assert_eq!(
            FilterField::Parent.value_mut(&mut filter),
            "",
            "value_mut() creates the slot empty"
        );
        assert_eq!(
            FilterField::Parent.value(&filter),
            None,
            "and value() reports no criterion"
        );
        assert!(
            !filter.has_active_criteria(),
            "an empty slot is not an active criterion"
        );
        // Any other active criterion still counts.
        filter.assignee = Some("alice".into());
        assert!(filter.has_active_criteria());
        FilterField::Parent.unset(&mut filter);
        assert_eq!(filter.parent, None, "unset clears the slot");
    }
    // ----------------------------------------------------------------------
    // WP08 T034/T035 — the category criterion
    // ----------------------------------------------------------------------

    /// A board that **declares a `category_map`**, so the criterion has something
    /// to resolve against.
    ///
    /// `triage=backlog, wip=active, review=active, shipped=completed,
    /// abandoned=canceled`. Two properties this fixture is chosen for:
    ///
    /// - `shipped` is complete and `done_column` is `shipped`, so a column
    ///   comparison and a category decision *agree* here — which is why a second
    ///   fixture below inverts them.
    /// - Three columns share `active`, so `category:active` returning three issues
    ///   is a claim a `status:` criterion could not make.
    fn mapped_config() -> crate::config::Config {
        crate::config::Config {
            issues_dir: std::path::PathBuf::from("/nonexistent"),
            kanban: crate::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    crate::config::BoardConfiguration {
                        columns: vec![
                            "triage".into(),
                            "wip".into(),
                            "review".into(),
                            "shipped".into(),
                            "abandoned".into(),
                        ],
                        done_column: Some("shipped".to_string()),
                        category_map: indexmap::IndexMap::from([
                            ("triage".to_string(), "backlog".to_string()),
                            ("wip".to_string(), "active".to_string()),
                            ("review".to_string(), "active".to_string()),
                            ("shipped".to_string(), "completed".to_string()),
                            ("abandoned".to_string(), "canceled".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..crate::config::Config::default()
        }
    }

    fn issue_in(number: u32, title: &str, column: &str) -> Issue {
        let mut issue = sample_issue(number, title, "");
        issue.status = Status::new(column);
        issue
    }

    fn filter_for(category: Option<&str>) -> StructuredFilter {
        StructuredFilter {
            category: category.map(str::to_string),
            ..StructuredFilter::default()
        }
    }

    fn resolution_for(config: &crate::config::Config) -> crate::workflow::CategoryResolution {
        let (_, resolution) = crate::workflow::active_resolution(config);
        resolution
    }

    #[test]
    fn t034_key_reports_the_token_and_is_derived() {
        // T034 step 4, the design question. `key()` says `category` because that
        // is what the grammar parses and what a hint bar should echo; `is_derived`
        // is what stops a surface from reading it as a frontmatter key.
        assert_eq!(FilterField::Category.key(), "category");
        assert!(FilterField::Category.is_derived());
        assert_eq!(
            FilterField::Category.label(),
            "Category",
            "in the existing style"
        );
        // Every other criterion is a real field, so the derived flag singles out
        // exactly one — a test that only checked `Category` would pass if
        // `is_derived` matched everything.
        for field in FilterField::ALL {
            assert_eq!(
                field.is_derived(),
                field == FilterField::Category,
                "{field:?} derived-flag is wrong"
            );
        }
        // The two spellings differ **only** for the derived one.
        assert_eq!(FilterField::Assignee.describe(), "assignee");
        assert_eq!(
            FilterField::Category.describe(),
            "category (derived from status)",
            "an explanation must not send a user looking for a field that does not exist"
        );
    }

    #[test]
    fn t035_a_mapped_completed_column_matches_category_completed() {
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let shipped = issue_in(1, "Shipped", "shipped");
        let wip = issue_in(2, "Wip", "wip");
        let filter = filter_for(Some("completed"));
        assert!(
            filter.category_matches(&shipped, &resolution),
            "a completed column is in the completed category"
        );
        assert!(
            !filter.category_matches(&wip, &resolution),
            "and nothing else is"
        );
    }

    #[test]
    fn t035_one_category_spans_every_column_mapped_to_it() {
        // The reason the criterion is a category and not a column: three columns
        // resolve to `active`, and all three must match.
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let filter = filter_for(Some("active"));
        for column in ["wip", "review"] {
            assert!(
                filter.category_matches(&issue_in(1, "A", column), &resolution),
                "{column} is active"
            );
        }
        assert!(
            !filter.category_matches(&issue_in(1, "A", "triage"), &resolution),
            "and triage is not"
        );
    }

    #[test]
    fn t035_an_unconfigured_column_matches_no_category() {
        // The third case T035 step 3 does not name, and the one the other two
        // surfaces already distinguish: `tix list --show category` prints
        // `(unmapped)` and MCP returns `category: null` (WP07) for a column the
        // board does not configure. Folding it into the safe default would make
        // `category:unstarted` return issues every other surface call unmapped.
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let orphan = issue_in(1, "Orphan", "not-a-column");
        for category in ["unstarted", "backlog", "active", "completed", "canceled"] {
            assert!(
                !filter_for(Some(category)).category_matches(&orphan, &resolution),
                "an unconfigured column has no category, so `category:{category}` \\
                 must not match it"
            );
        }
    }

    #[test]
    fn t035_a_canceled_column_is_in_canceled_and_not_in_completed() {
        // The C-004 rule, made visible at the criterion: a canceled issue is
        // terminal and **not** complete, and a criterion that conflated the two
        // would put abandoned work in a "done" search.
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let canceled = issue_in(1, "Abandoned", "abandoned");
        assert!(filter_for(Some("canceled")).category_matches(&canceled, &resolution));
        assert!(!filter_for(Some("completed")).category_matches(&canceled, &resolution));
    }

    #[test]
    fn t035_evaluate_ignores_the_category_criterion_but_evaluate_issue_does_not() {
        // `evaluate` is store-free and therefore cannot judge a derived criterion.
        // If it *tried*, `hay.contains("completed")` would match an issue whose
        // **body** mentions the word — so the test pins both halves: `evaluate`
        // does not apply it, and `evaluate_issue` does.
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let filter = filter_for(Some("completed"));
        let in_wip = issue_in(1, "Mentioning shipped work", "wip");
        let text = format!(
            "{}\n\nwe shipped this last quarter\n",
            in_wip.to_file_contents()
        );
        assert!(
            filter.evaluate(&text),
            "a substring test would wrongly match the body"
        );
        assert!(
            !filter.evaluate_issue(&in_wip, &text, &resolution),
            "the real criterion says no"
        );
        let done = issue_in(2, "Done", "shipped");
        let text = done.to_file_contents();
        assert!(filter.evaluate_issue(&done, &text, &resolution));
    }

    #[test]
    fn t035_an_unknown_category_is_an_error_not_an_empty_result() {
        // T037 step 5, at the layer that can produce the error. Through the
        // composed entry point, because that is what every surface calls — a test of
        // the inner function would not show that the *surface* rejects.
        let (_tmp, store) = store_with(mapped_config());
        let err = crate::search::resolve_filter_criteria(&store, "category:finished")
            .unwrap_err()
            .to_string();
        assert!(err.contains("unknown category 'finished'"), "{err}");
        // The message names what *would* have worked — from this project's own
        // vocabulary, not the global six.
        for key in crate::config::CATEGORY_KEYS {
            assert!(err.contains(key), "'{key}' missing from: {err}");
        }
    }

    /// A store over an arbitrary `Config`, holding one issue (`Alpha`, in `triage`),
    /// for the command-layer resolvers.
    ///
    /// The issue is there because `resolve_filter_criteria` resolves a
    /// `parent:<selector>` token through the store, and a fixture with no issues
    /// would fail every query carrying one — so the composed function could not be
    /// exercised on the half of its job that is not about categories.
    fn store_with(config: crate::config::Config) -> (tempfile::TempDir, Store) {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(dir.join("alice")).unwrap();
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            ..config
        };
        config.save(&tmp.path().join("tix.toml")).unwrap();
        let config =
            crate::config::Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {}).unwrap();
        fs::write(
            dir.join("alice/2026-01-01-alpha.md"),
            "---\nnumber: 1\ntitle: Alpha\nstatus: triage\nlabels: []\n\
             priority: medium\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n\
             ---\n\nbody\n",
        )
        .unwrap();
        let store = Store {
            issues_dir: dir,
            config,
        };
        (tmp, store)
    }

    #[test]
    fn t035_a_reduced_project_vocabulary_rejects_a_key_it_did_not_declare() {
        // The project's `order` may be a subset of the global six. `unstarted` is
        // in the global set but not in this project, so accepting it would return
        // results from a category the project never declared.
        let mut config = mapped_config();
        config.categories.order = vec![
            "backlog".to_string(),
            "active".to_string(),
            "completed".to_string(),
        ];
        config.categories.default = "active".to_string();
        // The board's own map has to fit inside the reduced vocabulary or the config
        // is refused at load. That refusal is the **right** behaviour and a
        // constraint the fixture has to honour rather than work around: the first
        // version kept `abandoned -> canceled`, so the fixture never reached the
        // code under test and the failure it reported was about the board, not
        // about the criterion.
        let board = config.kanban.configurations.get_mut("default").unwrap();
        board.category_map.shift_remove("abandoned");
        board.columns.retain(|c| c != "abandoned");
        let (_tmp, store) = store_with(config);
        let err = crate::search::resolve_filter_criteria(&store, "category:unstarted")
            .unwrap_err()
            .to_string();
        assert!(err.contains("unstarted"), "{err}");
        assert!(
            !err.contains("canceled"),
            "a key the project did not declare must not be offered: {err}"
        );
        assert!(err.contains("backlog, active, completed"), "{err}");
        // A declared key still resolves, and is canonicalized.
        let (query, criteria) =
            crate::search::resolve_filter_criteria(&store, "category:Completed").unwrap();
        assert_eq!(criteria.category.as_deref(), Some("completed"));
        assert_eq!(query, "", "and the token is lifted out of the query");
    }

    #[test]
    fn t035_a_query_without_a_category_token_is_unchanged() {
        let (_tmp, store) = store_with(mapped_config());
        for query in ["", "alice", "assignee:alice", "overdue"] {
            let (resolved, criteria) =
                crate::search::resolve_filter_criteria(&store, query).unwrap();
            assert_eq!(resolved, query, "{query:?} must round-trip");
            assert_eq!(criteria.category, None, "{query:?} gained a criterion");
        }
    }

    #[test]
    fn t035_a_category_token_is_lifted_out_and_canonicalized() {
        // The shape that actually works, and the one the first version got wrong.
        // It rewrote the token in place, so `query_matches` still met a `category`
        // key, still refused it, and every filter came back empty — while this
        // test's own assertion (that the value was canonicalized) passed.
        let (_tmp, store) = store_with(mapped_config());
        let (query, criteria) =
            crate::search::resolve_filter_criteria(&store, "category:COMPLETED alpha").unwrap();
        assert_eq!(
            criteria.category.as_deref(),
            Some("completed"),
            "canonical, and carried structurally"
        );
        assert_eq!(
            query, "alpha",
            "the token is **removed**: a token left in the string meets a key \
             `query_matches` refuses, which is an empty result with no error"
        );
    }

    #[test]
    fn t035_the_parent_and_category_resolvers_compose() {
        // One entry point, so a call site cannot resolve one and forget the other.
        // A `parent:` selector becomes a **number** in the query (a rewrite); a
        // `category:` value leaves the query entirely (a lift).
        let (_tmp, store) = store_with(mapped_config());
        let (query, criteria) =
            crate::search::resolve_filter_criteria(&store, "category:completed parent:1").unwrap();
        assert_eq!(query, "parent:1", "parent stays, category is lifted");
        assert_eq!(criteria.category.as_deref(), Some("completed"));
    }

    #[test]
    fn t035_a_query_with_no_criterion_is_unaffected() {
        // T035 step 4: existing substring and fuzzy behaviour must not change.
        let config = mapped_config();
        let resolution = resolution_for(&config);
        let issue = issue_in(1, "Alpha", "wip");
        let text = issue.to_file_contents();
        let empty = StructuredFilter::default();
        assert!(crate::search::matches_issue(
            "alpha",
            &empty,
            &issue,
            &text,
            &resolution
        ));
        assert!(crate::search::matches_issue(
            "",
            &empty,
            &issue,
            &text,
            &resolution
        ));
        assert!(!crate::search::matches_issue(
            "zzz",
            &empty,
            &issue,
            &text,
            &resolution
        ));
    }

    #[test]
    fn t035_matching_reads_the_service_and_never_the_column_name() {
        // A board whose `category_map` puts `completed` on `shipped` while
        // `done_column` is `done` — so the two disagree. Second time this
        // programme has needed such a board: on `mapped_config` they agree, so a
        // column comparison and a category decision cannot tell each other apart.
        let config = crate::config::Config {
            kanban: crate::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    crate::config::BoardConfiguration {
                        columns: vec!["todo".into(), "shipped".into(), "done".into()],
                        done_column: Some("done".to_string()),
                        category_map: indexmap::IndexMap::from([
                            ("todo".to_string(), "unstarted".to_string()),
                            ("shipped".to_string(), "completed".to_string()),
                            ("done".to_string(), "active".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..crate::config::Config::default()
        };
        let resolution = resolution_for(&config);
        let shipped = issue_in(1, "Shipped", "shipped");
        let done = issue_in(2, "Done column", "done");
        assert!(
            filter_for(Some("completed")).category_matches(&shipped, &resolution),
            "the service says shipped is complete"
        );
        assert!(
            !filter_for(Some("completed")).category_matches(&done, &resolution),
            "and `done` is not, even though it is the done_column"
        );
        // The derived criterion still finds `todo` under the safe default.
        assert!(
            filter_for(Some("unstarted"))
                .category_matches(&issue_in(3, "Todo", "todo"), &resolution)
        );
    }

    #[test]
    fn t035_the_query_token_matcher_refuses_rather_than_guessing() {
        // `query_matches` cannot judge the criterion, so its `category` arm is an
        // explicit total refusal. This pins the *consequence*: a caller that
        // skipped `matches_issue` gets an empty result a user can see, not an
        // unfiltered one they cannot.
        let issue = issue_in(1, "Shipped", "shipped");
        let text = issue.to_file_contents();
        assert!(!query_matches("category:completed", &text));
        // And it does not fall through to a substring test on the word.
        let mention = issue_in(2, "Mentions completed", "triage");
        assert!(
            !query_matches("category:completed", &mention.to_file_contents()),
            "and never matches the word in a title"
        );
    }

    #[test]
    fn t035_two_boards_with_different_column_names_agree() {
        // T037 step 4, the intake's first acceptance scenario at the criterion
        // layer. Same mapping, different column names: the criterion is about the
        // category, so both boards must return the same answer.
        let a = mapped_config();
        let b = crate::config::Config {
            kanban: crate::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    crate::config::BoardConfiguration {
                        columns: vec![
                            "icebox".into(),
                            "doing".into(),
                            "verifying".into(),
                            "released".into(),
                            "dropped".into(),
                        ],
                        done_column: Some("released".to_string()),
                        category_map: indexmap::IndexMap::from([
                            ("icebox".to_string(), "backlog".to_string()),
                            ("doing".to_string(), "active".to_string()),
                            ("verifying".to_string(), "active".to_string()),
                            ("released".to_string(), "completed".to_string()),
                            ("dropped".to_string(), "canceled".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..crate::config::Config::default()
        };
        for (column_a, column_b) in [
            ("triage", "icebox"),
            ("wip", "doing"),
            ("shipped", "released"),
            ("abandoned", "dropped"),
        ] {
            for key in crate::config::CATEGORY_KEYS {
                let want = filter_for(Some(key))
                    .category_matches(&issue_in(1, "X", column_a), &resolution_for(&a));
                let got = filter_for(Some(key))
                    .category_matches(&issue_in(1, "X", column_b), &resolution_for(&b));
                assert_eq!(
                    want, got,
                    "{column_a} ({key}) and {column_b} ({key}) disagree"
                );
            }
        }
    }
}