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
//! WP02 (`triage-inbox-review-flow-01M3C600`) — T007–T011: inbox scope, one-pass
//! entries/age, counts/order, list+search integration, and the performance and
//! no-write tests.
//!
//! Every test is named `triage_queue_*`, so `cargo test triage_queue` selects
//! this file *and* the unit tests in `src/triage/inbox.rs` — one command for the
//! whole work package, the same property WP01's `triage_config_*` prefix gives.
//!
//! | Test | Subtask |
//! |---|---|
//! | `triage_queue_scope_*` | T007 resolve inbox scope |
//! | `triage_queue_*_age_*`, `*_entries_*` | T008 one-pass entries and age |
//! | `triage_queue_*_counts_*`, `*_order*` | T009 counts and stable order |
//! | `triage_queue_scope_filter_*` | T010 list/search integration |
//! | `triage_queue_nfr001_*`, `triage_queue_query_writes_nothing*` | T011 |
//!
//! No TTY, no network, deterministic. Ages are computed against a **supplied**
//! `today`, never against the wall clock, so this file does not rot when the
//! date does.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use assert_cmd::Command;
use tempfile::TempDir;
use tix::config::Config;
use tix::model::Issue;
use tix::search::Corpus;
use tix::storage::Store;
use tix::triage;

/// A board that declares every category, so `[triage]` can name a `canceled`
/// column (WP01 T004) and a `completed` one — the same fixture shape WP01's
/// `src/triage/config.rs` tests use, so a scope built here and a section
/// validated there agree about what the board is.
const BOARD: &str = r#"
[kanban.default]
columns = ["triage", "todo", "in progress", "in review", "done", "wontfix"]
done_column = "done"
category_map = { triage = "backlog", todo = "unstarted", "in progress" = "active", "in review" = "active", done = "completed", wontfix = "canceled" }
"#;

const TRIAGE: &str = "\n[triage]\nentry_status = \"triage\"\ndeclined_status = \"wontfix\"\n";

/// The fixed date every age in this file is computed against.
const TODAY: &str = "2026-09-30";

// ---------------------------------------------------------------------------
// Fixtures
// ---------------------------------------------------------------------------

/// A repo with an absolute `issues_dir` and a board that declares every
/// category, plus whatever `[triage]` section the caller asks for.
///
/// `section` may be empty — a project with no inbox is a first-class fixture,
/// not an error case, and T010's "preserve default operational views" claim is
/// about exactly that repo.
fn repo(section: &str) -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    let text = format!("issues_dir = \"{}\"{}{}", dir.display(), BOARD, section);
    fs::write(tmp.path().join("tix.toml"), text).unwrap();
    (tmp, dir)
}

fn load(tmp: &TempDir) -> Config {
    Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {})
        .expect("the fixture tix.toml loads")
}

/// Write one issue file. `entered_at` is written only when asked for, so a
/// legacy issue (no entry stamp) is one argument away from a stamped one.
fn write_issue(
    dir: &Path,
    file: &str,
    number: u32,
    title: &str,
    status: &str,
    entered_at: Option<&str>,
) {
    let mut text = format!(
        "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{status}\"\nlabels: []\n\
         priority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n"
    );
    if let Some(at) = entered_at {
        text.push_str(&format!("entered_at: {at}\nsource: test\n"));
    }
    text.push_str("---\n\nBody text.");
    fs::write(dir.join(file), text).unwrap();
}

fn tix() -> Command {
    let mut c = Command::cargo_bin("tix").expect("the tix binary must build");
    c.env("NO_COLOR", "1").env("TERM", "dumb");
    c
}

/// Every byte under a directory, for the byte-identical no-write comparison.
fn snapshot(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    let mut out = BTreeMap::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(cur) = stack.pop() {
        for entry in fs::read_dir(&cur).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                out.insert(path.clone(), fs::read(&path).unwrap());
            }
        }
    }
    out
}

/// The scope of the fixture repo, or `None` when it has no `[triage]` section.
fn scope_of(tmp: &TempDir) -> Option<triage::inbox::InboxScope> {
    triage::inbox::scope(&load(tmp)).expect("the fixture validates")
}

/// The queue over an already-loaded corpus: `scope` then `collect`, which is the
/// two-step call every production surface uses. The old `inbox::query` wrapper
/// had no production caller and was removed (tix #1495); this keeps the tests
/// reading the same way without resurrecting it.
fn collect_inbox<'a>(
    config: &Config,
    corpus: &'a Corpus,
    today: &str,
) -> Result<Option<triage::inbox::QueueMetrics<'a>>, tix::error::TixError> {
    let Some(scope) = triage::inbox::scope(config)? else {
        return Ok(None);
    };
    Ok(Some(triage::inbox::collect(&corpus.issues, &scope, today)))
}

// ---------------------------------------------------------------------------
// T007 — resolve inbox scope
// ---------------------------------------------------------------------------

#[test]
fn triage_queue_scope_is_none_for_a_project_that_configures_no_inbox() {
    let (tmp, _dir) = repo("");
    assert_eq!(load(&tmp).triage, None, "the fixture has no `[triage]`");
    assert_eq!(scope_of(&tmp), None, "so it has no scope either");
}

#[test]
fn triage_queue_scope_names_the_configured_entry_and_deferred_columns() {
    let (tmp, _dir) = repo(&format!("{TRIAGE}deferred_status = \"todo\"\n"));
    let scope = scope_of(&tmp).expect("the fixture configures an inbox");

    assert_eq!(scope.board, "default");
    assert_eq!(scope.entry_status, "triage");
    assert_eq!(scope.deferred_status, "todo");
    assert_eq!(
        scope.columns,
        vec!["triage".to_string(), "todo".to_string()],
        "both inbox columns, deduplicated, in board order"
    );
    assert_eq!(
        scope.resolution.resolve("triage"),
        Some(triage_scope_backlog()),
        "#183's answer, carried rather than re-derived"
    );
}

/// `WorkflowCategory::Backlog`, spelled through the type so this file cannot
/// drift from it if the vocabulary ever moves.
fn triage_scope_backlog() -> tix::workflow::WorkflowCategory {
    tix::workflow::WorkflowCategory::from_key("backlog").expect("`backlog` is in the vocabulary")
}

// ---------------------------------------------------------------------------
// T008 — one-pass entries and age
// ---------------------------------------------------------------------------

#[test]
fn triage_queue_single_entry_reports_the_age_of_the_supplied_date() {
    let (tmp, dir) = repo(TRIAGE);
    write_issue(
        &dir,
        "2026-01-01-waiting.md",
        1,
        "Waiting",
        "triage",
        Some("2026-09-20T09:12:44Z"),
    );
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();
    let corpus = Corpus::build(&store).unwrap();

    let metrics = collect_inbox(&config, &corpus, TODAY)
        .unwrap()
        .expect("the fixture configures an inbox");

    assert_eq!(metrics.total, 1);
    assert_eq!(metrics.entries[0].age_days, Some(10), "ten days, not nine");
    assert_eq!(metrics.unknown_age, 0);
    assert_eq!(metrics.entries[0].issue.number, 1);
}

#[test]
fn triage_queue_legacy_entry_is_in_the_inbox_with_an_unknown_age() {
    // The whole point of research R4: this issue's `created` and `updated` are
    // both 2026-01-01 — 272 days before `TODAY` — and neither was ever the day
    // it entered triage. Reporting either as an age would be a confident,
    // wrong number.
    let (tmp, dir) = repo(TRIAGE);
    write_issue(&dir, "2026-01-01-legacy.md", 1, "Legacy", "triage", None);
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();
    let corpus = Corpus::build(&store).unwrap();

    let metrics = collect_inbox(&config, &corpus, TODAY).unwrap().unwrap();

    assert_eq!(metrics.total, 1, "a legacy issue is still in the inbox");
    assert_eq!(metrics.entries[0].age_days, None, "and has no honest age");
    assert_eq!(metrics.unknown_age, 1);
    assert_eq!(metrics.entries[0].entered_at, triage::EntryTime::Unknown);
}

#[test]
fn triage_queue_a_move_into_the_inbox_records_the_moved_origin() {
    // tix #1489: a status change into an inbox column is an **entry**, and the
    // fourth one. The vocabulary's `new` would be false for an issue that has
    // existed for a year, so the origin word is `moved` — and the stamp is what
    // the age column measures from, which is the one figure the queue exists to
    // report.
    let (tmp, _dir) = repo(TRIAGE);
    let config = load(&tmp);

    let mut moved = Issue::parse(
        "---\nnumber: 2\ntitle: \"Moved\"\nstatus: \"triage\"\nlabels: []\n\
         priority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.",
    )
    .expect("the fixture parses");
    assert!(
        triage::record_move_entry(&config, &mut moved).expect("the fixture validates"),
        "landing in the entry column stamps the entry"
    );
    assert_eq!(moved.source.as_deref(), Some("moved"));
    assert!(moved.entered_at.is_some(), "and records when it entered");

    // The queue now has an age for it rather than `unknown`.
    let scope = triage::inbox::scope(&config)
        .expect("the fixture validates")
        .expect("the fixture configures an inbox");
    let metrics = triage::inbox::collect(std::slice::from_ref(&moved), &scope, TODAY);
    assert_eq!(metrics.unknown_age, 0, "a moved entry has an age");
    assert_eq!(
        metrics.entries[0].entered_at,
        triage::EntryTime::Recorded(moved.entered_at.as_deref().unwrap())
    );

    // A status change that does **not** land in the inbox stamps nothing: the
    // existing rule for every non-inside landing column.
    let mut outside = Issue::parse(
        "---\nnumber: 3\ntitle: \"Outside\"\nstatus: \"todo\"\nlabels: []\n\
         priority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.",
    )
    .expect("the fixture parses");
    assert!(
        !triage::record_move_entry(&config, &mut outside).expect("the fixture validates"),
        "an ordinary column is not an entry"
    );
    assert!(outside.entered_at.is_none() && outside.source.is_none());
}

#[test]
fn triage_queue_empty_repo_has_an_empty_inbox() {
    let (tmp, _dir) = repo(TRIAGE);
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();
    let corpus = Corpus::build(&store).unwrap();

    let metrics = collect_inbox(&config, &corpus, TODAY).unwrap().unwrap();

    assert_eq!(metrics.total, 0);
    assert_eq!(metrics.entries.len(), 0);
    assert!(
        metrics.age_distribution.iter().all(|b| b.count == 0),
        "and no phantom buckets"
    );
}

// ---------------------------------------------------------------------------
// T009 — counts and stable order
// ---------------------------------------------------------------------------

/// Three inbox members and one outsider, each distinguishable by title: `alpha`
/// awaits a decision in the entry column, `bravo` is deferred, and `charlie`
/// sits in `in review` — outside the inbox entirely.
fn mixed_repo() -> (TempDir, PathBuf) {
    let (tmp, dir) = repo(&format!("{TRIAGE}deferred_status = \"todo\"\n"));
    write_issue(
        &dir,
        "2026-01-01-alpha.md",
        1,
        "Alpha waits",
        "triage",
        Some("2026-09-28T00:00:00Z"),
    );
    write_issue(
        &dir,
        "2026-01-01-bravo.md",
        2,
        "Bravo deferred",
        "todo",
        None,
    );
    write_issue(
        &dir,
        "2026-01-01-charlie.md",
        3,
        "Charlie outside",
        "in review",
        Some("2026-09-28T00:00:00Z"),
    );
    (tmp, dir)
}

#[test]
fn triage_queue_counts_split_the_mixed_board_and_drop_the_outsider() {
    let (tmp, _dir) = mixed_repo();
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();
    let corpus = Corpus::build(&store).unwrap();

    let metrics = collect_inbox(&config, &corpus, TODAY).unwrap().unwrap();

    assert_eq!(
        metrics.total, 2,
        "the entry column and the deferred column; `in review` is not in the inbox"
    );
    assert_eq!(metrics.awaiting, 1, "Alpha awaits");
    assert_eq!(metrics.deferred, 1, "Bravo is deferred");
    assert_eq!(metrics.accepted, 0, "nobody has been decided");
    assert_eq!(metrics.declined, 0);
    assert_eq!(metrics.duplicated, 0);
    assert_eq!(metrics.unknown_age, 1, "Bravo carries no entry stamp");

    let sum: usize = metrics.age_distribution.iter().map(|b| b.count).sum();
    assert_eq!(
        sum, metrics.total,
        "every entry lands in exactly one bucket"
    );
}

#[test]
fn triage_queue_entries_keep_the_store_order() {
    // `Store::list` sorts by relative filename; the inbox must not re-sort, or
    // it would disagree with `tix list` about which row is first.
    let (tmp, _dir) = mixed_repo();
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();
    let corpus = Corpus::build(&store).unwrap();

    let metrics = collect_inbox(&config, &corpus, TODAY).unwrap().unwrap();
    let listed: Vec<String> = store
        .list()
        .unwrap()
        .into_iter()
        .filter(|i| metrics.entries.iter().any(|e| e.issue.number == i.number))
        .map(|i| i.filename)
        .collect();
    let in_box: Vec<String> = metrics
        .entries
        .iter()
        .map(|e| e.issue.filename.clone())
        .collect();

    assert_eq!(in_box, listed, "same rows, same order, no second sort");
}

// ---------------------------------------------------------------------------
// T010 — read-only triage scope through the list/search seams
// ---------------------------------------------------------------------------

#[test]
fn triage_queue_scope_filter_selects_the_inbox_through_tix_list() {
    let (tmp, _dir) = mixed_repo();

    let out = tix()
        .current_dir(tmp.path())
        .args(["list", "--filter", "scope:triage"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(out.status.success(), "a valid scope is not an error");
    assert!(text.contains("Alpha waits"), "an entry member:\n{text}");
    assert!(
        text.contains("Bravo deferred"),
        "a deferred member:\n{text}"
    );
    assert!(
        !text.contains("Charlie outside"),
        "and nothing outside the inbox:\n{text}"
    );
}

#[test]
fn triage_queue_scope_filter_selects_the_inbox_through_tix_search() {
    let (tmp, _dir) = mixed_repo();

    let out = tix()
        .current_dir(tmp.path())
        .args(["search", "scope:triage"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(out.status.success(), "{text}");
    assert!(text.contains("Alpha waits"), "{text}");
    assert!(text.contains("Bravo deferred"), "{text}");
    assert!(!text.contains("Charlie outside"), "{text}");
}

#[test]
fn triage_queue_scope_combines_with_an_existing_criterion() {
    // The scope is a criterion, not a mode: it ANDs with the text layer the way
    // `category:` does, rather than replacing the query.
    let (tmp, _dir) = mixed_repo();

    let out = tix()
        .current_dir(tmp.path())
        .args(["list", "--filter", "scope:triage Alpha"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(out.status.success(), "{text}");
    assert!(text.contains("Alpha waits"), "{text}");
    assert!(!text.contains("Bravo deferred"), "AND, not OR:\n{text}");
}

#[test]
fn triage_queue_default_operational_views_are_untouched() {
    // T010's other half: adding a scope must not make the *absence* of one
    // select the inbox. `tix list` with no filter still shows the whole board.
    let (tmp, _dir) = mixed_repo();

    let out = tix()
        .current_dir(tmp.path())
        // `--all`: the default listing is scoped to your issues in the board's entry
        // column (#1711), and these fixtures are hand-written.
        .args(["list", "--all"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(out.status.success(), "{text}");
    assert!(text.contains("Alpha waits"), "{text}");
    assert!(text.contains("Bravo deferred"), "{text}");
    assert!(
        text.contains("Charlie outside"),
        "the default view must keep showing what the scope filters out:\n{text}"
    );
}

#[test]
fn triage_queue_an_unscoped_criterion_still_selects() {
    // The other side of the same rule, through a path that can actually see it.
    // Neither obvious default can: `tix list` with no `--filter` never enters the
    // filtering block, and `tix search Alpha` with no `:` in the query falls
    // through to substring search. Neither calls `matches_issue` at all, so an
    // absent scope flipping to "no scope, no match" would empty both and this
    // rule would have no witness. A criterion-only `tix list` filter reaches it
    // with `scope` absent, and must come back as one row rather than none.
    let (tmp, _dir) = mixed_repo();

    let out = tix()
        .current_dir(tmp.path())
        .args(["list", "--filter", "Alpha"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(out.status.success(), "{text}");
    assert!(text.contains("Alpha waits"), "{text}");
    assert!(
        !text.contains("Charlie outside"),
        "a filter with no scope must still be a filter:\n{text}"
    );
}

#[test]
fn triage_queue_unknown_scope_is_a_named_error_not_an_empty_board() {
    let (tmp, _dir) = mixed_repo();

    let out = tix()
        .current_dir(tmp.path())
        .args(["list", "--filter", "scope:backlog"])
        .output()
        .unwrap();
    let err = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(
        !out.status.success(),
        "a typo must not read as 'no matches'"
    );
    assert!(err.contains("unknown scope `backlog`"), "{err}");
    assert!(err.contains("triage"), "and name what would work: {err}");
}

#[test]
fn triage_queue_scope_on_a_repo_without_a_triage_section_is_an_error() {
    // The other half of "error, not empty result": a user who typed
    // `scope:triage` on a project with no inbox is told so, rather than being
    // handed the same empty board a typo would produce.
    let (tmp, _dir) = repo("");

    let out = tix()
        .current_dir(tmp.path())
        .args(["list", "--filter", "scope:triage"])
        .output()
        .unwrap();
    let err = String::from_utf8_lossy(&out.stderr).to_string();
    assert!(!out.status.success(), "{err}");
    assert!(err.contains("scope:triage"), "{err}");
    assert!(err.contains("[triage]"), "{err}");
}

// ---------------------------------------------------------------------------
// T011 — performance and no-write
// ---------------------------------------------------------------------------

#[test]
fn triage_queue_query_writes_nothing_to_the_tree() {
    let (tmp, _dir) = mixed_repo();
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();

    let before = snapshot(tmp.path());
    assert!(
        !before.is_empty(),
        "the fixture has files, or this assertion compares nothing with nothing"
    );

    let corpus = Corpus::build(&store).unwrap();
    let metrics = collect_inbox(&config, &corpus, TODAY).unwrap().unwrap();
    assert_eq!(metrics.total, 2, "and the query actually ran");

    let after = snapshot(tmp.path());
    assert_eq!(
        before, after,
        "a queue query reads a snapshot; it must leave every byte where it found it"
    );
}

/// The other half of T011's risks: "repeated filesystem work → one snapshot".
///
/// The test above proves the query does not *write*; it says nothing about how
/// many times it *reads*. So the tree is deleted between the build and the
/// query. `Corpus` owns its `Vec<Issue>`s, so a query that needs only the
/// snapshot still answers here; one that went back for a second pass — a
/// per-entry `Store::get`, a re-walk to assemble the counts, a second corpus
/// for the entries to borrow — has nothing left to read and fails.
#[test]
fn triage_queue_query_needs_no_second_pass_over_the_tree() {
    let (tmp, dir) = repo(TRIAGE);
    write_issue(
        &dir,
        "2026-01-01-waiting.md",
        1,
        "Waiting",
        "triage",
        Some("2026-09-20T09:12:44Z"),
    );
    let config = load(&tmp);
    let store = Store::open(&config).unwrap();
    let corpus = Corpus::build(&store).unwrap();

    drop(store);
    std::fs::remove_dir_all(&dir).expect("the tree goes away before the query runs");

    let metrics = collect_inbox(&config, &corpus, TODAY)
        .unwrap()
        .expect("the fixture configures an inbox");

    assert_eq!(
        metrics.total, 1,
        "the snapshot came from the build, not from a second trip to disk"
    );
    assert_eq!(metrics.entries[0].age_days, Some(10));
    assert_eq!(
        metrics
            .age_distribution
            .iter()
            .map(|b| b.count)
            .sum::<usize>(),
        1
    );
}

/// NFR-001 / SC-002: 10,000 in-memory entries, one pass, under 500 ms, file I/O
/// excluded (it is excluded by the requirement itself).
///
/// The anti-vacuity half matters as much as the timing: a `collect` that
/// returned an empty `QueueMetrics` is instantaneous, so every count is pinned
/// too. A timing assertion over a query that did nothing would be green for the
/// wrong reason — which is the failure mode this mission keeps finding.
#[test]
fn triage_queue_nfr001_ten_thousand_entries_derive_in_one_pass_under_500ms() {
    const TOTAL: u32 = 10_000;
    const ENTRY: u32 = 7_000;
    const DEFERRED: u32 = 2_000;

    let (tmp, _dir) = repo(&format!("{TRIAGE}deferred_status = \"todo\"\n"));
    let scope = scope_of(&tmp).expect("the fixture configures an inbox");

    // Built outside the measurement: NFR-001 excludes file I/O *and* fixture
    // construction, both of which are the test's cost rather than the query's.
    let issues: Vec<Issue> = (0..TOTAL)
        .map(|i| {
            let status = if i < ENTRY {
                "triage"
            } else if i < ENTRY + DEFERRED {
                "todo"
            } else {
                "in review"
            };
            // Half the members carry a stamp, so `unknown_age` is a real number
            // and not a zero the assertion would wave through.
            let entered_at = if i % 2 == 0 {
                Some("2026-09-20T00:00:00Z")
            } else {
                None
            };
            let mut issue = Issue::parse(&format!(
                "---\nnumber: {}\ntitle: \"Issue {i}\"\nstatus: \"{status}\"\nlabels: []\n\
                 priority: medium\ncreated: 2026-01-01\nupdated: 2026-01-01\n\
                 {}---\n\nBody.",
                i + 1,
                entered_at.map_or(String::new(), |at| format!("entered_at: {at}\n")),
            ))
            .expect("the generated fixture parses");
            issue.filename = format!("issue-{i:05}.md");
            issue
        })
        .collect();

    // Median of five, so one scheduling hiccup does not decide the verdict —
    // the same shape `tests/relationship_parity.rs` uses for its own tripwire.
    let mut samples = Vec::new();
    let mut metrics = None;
    for _ in 0..5 {
        let started = Instant::now();
        let derived = triage::inbox::collect(&issues, &scope, TODAY);
        samples.push(started.elapsed());
        metrics = Some(derived);
    }
    samples.sort();
    let median = samples[samples.len() / 2];

    let metrics = metrics.expect("the loop ran at least once");
    let expected_members = (ENTRY + DEFERRED) as usize;
    assert_eq!(
        metrics.total, expected_members,
        "the 1,000 outsiders are out"
    );
    assert_eq!(metrics.awaiting, ENTRY as usize);
    assert_eq!(metrics.deferred, DEFERRED as usize);
    assert_eq!(
        metrics.accepted, 0,
        "nothing in this fixture has been decided"
    );
    assert_eq!(metrics.declined, 0);
    assert_eq!(metrics.duplicated, 0);
    assert_eq!(
        metrics.unknown_age,
        expected_members / 2,
        "the odd-numbered members carry no stamp"
    );
    assert_eq!(metrics.entries.len(), expected_members);
    let sum: usize = metrics.age_distribution.iter().map(|b| b.count).sum();
    assert_eq!(
        sum, expected_members,
        "the histogram accounts for every row"
    );
    assert_eq!(
        metrics.age_distribution[3].count,
        expected_members / 2,
        "the stamped half is ten days old, in the `7-13` bucket"
    );
    assert_eq!(
        metrics.age_distribution[6].count,
        expected_members / 2,
        "and the unstamped half is unknown"
    );

    assert!(
        median < Duration::from_millis(500),
        "NFR-001: 10,000 entries must derive in under 500 ms, took {median:?}"
    );
}