tix-tracker 0.3.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
//! Shared search corpus and matchers for `tix search` (CLI, WP04) and the
//! `/` fuzzy filter (TUI, WP05).
//!
//! Both consumers search **exactly the same corpus**: the complete serialized
//! markdown of every issue (`Issue::to_file_contents()`, i.e. frontmatter +
//! body + comments). A single engine here keeps the CLI and TUI behavior from
//! drifting (C-005, FR-012):
//!
//! - [`Corpus::build`] snapshots every issue's full file text.
//! - [`search_substring`] is the case-insensitive single-occurrence matcher
//!   the CLI uses, returning matched-line context.
//! - [`fuzzy_score`] is the deterministic subsequence scorer the TUI uses to
//!   rank filter results on each keystroke.
//!
//! Nothing here touches the `-assets/` directories (C-005): binary contents
//! are never indexed, and [`Corpus::build`] inherits that from
//! [`Store::list`], which already excludes non-`.md` files and `-assets` dirs.

use serde::{Deserialize, Serialize};

use crate::error::Result;
use crate::model::Issue;
use crate::storage::Store;

/// The corpus: one `Issue` per file (in [`Store::list`] order) and the
/// byte-for-byte serialized file text matching it.
pub struct Corpus {
    pub issues: Vec<Issue>,
    pub texts: Vec<String>,
}

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

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

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

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

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

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

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

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

/// A selectable structured-filter criterion.
///
/// [`FilterField::ALL`] is the single ordered field list the filter modal
/// renders its rows from (risk: field/modal drift) and [`StructuredFilter`]
/// evaluates over — adding a criterion (FR-011) is one more `Option<String>`
/// field on [`StructuredFilter`] plus one variant / match arm here.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FilterField {
    Assignee,
    Label,
    Status,
    Priority,
}

impl FilterField {
    /// The criteria in modal row order (research D-05).
    pub const ALL: [FilterField; 4] = [
        FilterField::Assignee,
        FilterField::Label,
        FilterField::Status,
        FilterField::Priority,
    ];

    pub fn label(self) -> &'static str {
        match self {
            FilterField::Assignee => "Assignee",
            FilterField::Label => "Label",
            FilterField::Status => "Status",
            FilterField::Priority => "Priority",
        }
    }

    /// The serialized frontmatter key each criterion matches against
    /// (`Issue::to_file_contents` emits these). Used by diagnostics.
    pub fn key(self) -> &'static str {
        match self {
            FilterField::Assignee => "assignee",
            FilterField::Label => "labels",
            FilterField::Status => "status",
            FilterField::Priority => "priority",
        }
    }

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

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

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

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).
    pub fn has_active_criteria(&self) -> bool {
        self.criteria().next().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();
        for (_, value) in self.criteria() {
            if !hay.contains(&value.to_lowercase()) {
                return false;
            }
        }
        true
    }

    /// 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)`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut criteria = self.criteria();
        let Some((field, value)) = criteria.next() else {
            return write!(f, "(no active criteria)");
        };
        write!(f, "{}:{value}", field.key())?;
        for (field, value) in criteria {
            write!(f, ", {}:{value}", field.key())?;
        }
        Ok(())
    }
}

/// 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.is_empty() || fuzzy_score(query, haystack).is_some();
    text_matches && filter.evaluate(haystack)
}

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

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

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

    fn make_store() -> (tempfile::TempDir, Store) {
        let tmp = tempfile::TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        let store = Store {
            issues_dir: dir,
            config,
        };
        (tmp, store)
    }

    fn sample_issue(number: u32, title: &str, extra_body: &str) -> Issue {
        let mut issue = Issue {
            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,
            links: vec![],
            files: vec![],
            created: "2026-01-01".to_string(),
            updated: "2026-01-01".to_string(),
            filename: String::new(),
            body: extra_body.to_string(),
        };
        // 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"
        );
    }

    // ----------------------------------------------------------------------
    // 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!(search_substring(&corpus, "nope-nothing-here").is_empty());
    }

    #[test]
    fn substring_empty_query_is_empty() {
        let corpus = two_issue_corpus();
        assert!(search_substring(&corpus, "").is_empty());
    }

    // ----------------------------------------------------------------------
    // 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,
        };
        let criteria: Vec<(FilterField, &str)> = filter.criteria().collect();
        assert_eq!(
            criteria,
            vec![
                (FilterField::Label, "urgent"),
                (FilterField::Status, "todo")
            ]
        );
    }

    #[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()),
        };
        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");
    }

    #[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()),
        };
        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 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()),
        };
        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:?}"
        );
    }
}