tix-tracker 0.11.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
#[allow(clippy::wildcard_imports)]
use super::*;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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