tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
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
#[allow(clippy::wildcard_imports)]
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\nid: A1B2C3D4\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 **canonical id** 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:A1B2C3D4|1",
        "parent stays as canonical identity, 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"
            );
        }
    }
}