tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
//! WP03 acceptance tests: the shared filters, the one-pass integer-minute totals
//! and the findings beside them (mission `per-issue-time-tracking-01M3C9A4`,
//! subtasks T013–T018).
//!
//! Every test names the requirement ids it exercises. The properties this file
//! exists for are the mission's own:
//!
//! * **A malformed value is never zero.** It is excluded from the sum, counted, and
//!   reported with a reason and a remedy; a scope whose every entry is malformed has
//!   **no** total rather than a zero one.
//! * **Nothing is not zero.** An empty scope and a recorded `0m` are different
//!   facts, and the total's explicit state says which one a reader is in.
//! * **Determinism.** The same issues produce the same bytes twice, so CLI, TUI, MCP
//!   and portable output cannot disagree (NFR-003).
//! * **Read-only.** The aggregation is handed an `&[Issue]` and writes nothing; the
//!   slice's render and the store's files are compared byte for byte around it.
//!
//! Each negative claim carries its positive control: a scope that *does* sum, a
//! filter that *is* refused, an entry that *is* a recorded zero.

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

use tempfile::TempDir;
use tix::config::Config;
use tix::model::Issue;
use tix::storage::{IssueSelector, Store};
use tix::time_tracking::aggregate::{TimeGroup, TimeSnapshot, TimeTotal, TimeTotalState};
use tix::time_tracking::diagnostics::TimeDiagnostic;
use tix::time_tracking::entry::{TimeEntry, TimeEntryExtensions};
use tix::time_tracking::filters::{PeriodPlacement, TimeFilter, TimeFilterError, identity_cmp};
use tix::time_tracking::service::{NewTimeEntry, TimeEntryEdit, TimeMutationRequest, apply};

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

/// A project with a real `tix.toml` and an `issues/` directory.
fn repo() -> (TempDir, PathBuf) {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("issues");
    fs::create_dir_all(&dir).unwrap();
    fs::write(
        tmp.path().join("tix.toml"),
        format!(
            "issues_dir = {issues:?}\n\
             [kanban.default]\ncolumns = [\"todo\", \"in progress\", \"done\"]\n\
             done_column = \"done\"\n[layout]\nmove_on_change = false\n",
            issues = dir.to_string_lossy(),
        ),
    )
    .unwrap();
    (tmp, dir)
}

fn store_of(tmp: &TempDir) -> Store {
    let config = Config::load(tmp.path()).expect("the fixture loads");
    Store::open(&config).expect("the store opens")
}

fn issue_filename(number: u32) -> String {
    format!("2026-01-01-issue-{number}.md")
}

/// The markdown of one issue file, by hand.
///
/// Written as bytes rather than assembled from the writer, so the fixture is what a
/// hand-edited file can be — including a negative duration, a date that is not a
/// calendar date, and a blank author, all of which WP01's model deliberately keeps
/// readable so they can be *reported* rather than fail the whole parse.
fn issue_markdown(number: u32, entries: &str, history: &[String]) -> String {
    let mut markdown = format!(
        "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"in progress\"\n\
         labels: []\npriority: \"medium\"\nassignee: \"bob\"\ncreated: \"2026-01-01\"\n\
         updated: \"2026-01-01\"\n{entries}---\n\n"
    );
    if !history.is_empty() {
        markdown.push_str("## History\n\n");
        for line in history {
            markdown.push_str(line);
            markdown.push('\n');
        }
        markdown.push('\n');
    }
    markdown.push_str("Body prose that must survive.\n");
    markdown
}

/// Write one issue into the store's directory.
fn write_issue(dir: &Path, number: u32, entries: &str, history: &[String]) {
    fs::write(
        dir.join(issue_filename(number)),
        issue_markdown(number, entries, history),
    )
    .unwrap();
}

fn issue_of(store: &Store, number: u32) -> Issue {
    store
        .get(IssueSelector::Number(number))
        .expect("the issue reads")
}

/// A `time_entries:` block line for one entry, with the date omitted when undated.
fn entry_line(id: &str, minutes: i64, date: Option<&str>, author: &str) -> String {
    let mut out = format!("- id: {id}\n  duration_minutes: {minutes}\n");
    if let Some(date) = date {
        out.push_str(&format!("  date: {date:?}\n"));
    }
    out.push_str(&format!("  author: {author:?}\n"));
    out
}

/// An issue parsed straight from markdown: the cheap fixture for the unit-shaped
/// tests, which need no store.
fn parsed_issue(number: u32, entries: &str, history: &[String]) -> Issue {
    Issue::parse(&issue_markdown(number, entries, history)).expect("the fixture parses")
}

fn entry(id: &str, minutes: i64, date: Option<&str>, author: &str) -> TimeEntry {
    TimeEntry::new(id, minutes, date.map(str::to_string), author, None)
        .expect("the fixture entry is valid")
}

/// An entry a test varies exactly one field of, so a malformed value stays
/// constructible without going through validation.
fn hand_made(
    id: &str,
    minutes: Option<i64>,
    date: Option<&str>,
    author: &str,
    note: Option<&str>,
) -> TimeEntry {
    TimeEntry {
        id: id.into(),
        duration_minutes: minutes,
        date: date.map(str::to_string),
        author: author.into(),
        note: note.map(str::to_string),
        extensions: TimeEntryExtensions::default(),
    }
}

/// An issue built in memory from entries, for the malformed shapes a one-line YAML
/// scalar cannot express.
fn memory_issue(number: u32, entries: Vec<TimeEntry>) -> Issue {
    let mut issue = parsed_issue(number, "time_entries: []\n", &[]);
    issue.time_entries = entries;
    issue
}

/// The `(kind, field)` of every finding, in order.
fn findings(total: &TimeTotal) -> Vec<(&'static str, Option<&'static str>)> {
    total
        .diagnostics
        .iter()
        .map(|finding| (finding.kind.as_str(), finding.field))
        .collect()
}

/// The deterministic bytes a surface would see: the value plus its rendered
/// findings.
fn bytes(total: &TimeTotal) -> String {
    let rendered: Vec<String> = total
        .diagnostics
        .iter()
        .map(TimeDiagnostic::render)
        .collect();
    format!("{total:?}\n{}", rendered.join("\n"))
}

// ---------------------------------------------------------------------------
// C-005 / FR-002: a malformed value is excluded, counted and reported
// ---------------------------------------------------------------------------

#[test]
fn c005_fr002_a_malformed_entry_is_excluded_counted_and_reported_never_zero() {
    let issue = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}{}{}",
            entry_line("e-ok", 90, Some("2026-03-01"), "alice"),
            entry_line("e-bad", -5, Some("2026-03-02"), "alice"),
            entry_line("e-ok2", 30, Some("2026-03-03"), "@alice"),
        ),
        &[],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));
    let total = snapshot.total(&TimeFilter::new());

    assert_eq!(
        total.total_minutes,
        Some(120),
        "the valid entries sum, and the malformed one contributes no number"
    );
    assert_ne!(
        total.total_minutes,
        Some(115),
        "a `-5` duration must never be added as `-5`"
    );
    assert_eq!(total.entry_count, 2);
    assert_eq!(total.malformed_count, 1);
    assert!(
        total.is_partial(),
        "a total that dropped an entry must say so"
    );
    assert_eq!(total.state(), TimeTotalState::Recorded);
    assert_eq!(
        findings(&total),
        vec![("invalid_duration", Some("duration_minutes"))],
        "the excluded entry is reported, with its field"
    );
    let finding = &total.diagnostics[0];
    assert_eq!(finding.issue, Some(3));
    assert_eq!(finding.entry_id.as_deref(), Some("e-bad"));
    assert_eq!(
        finding.reason,
        "duration_minutes -5 is negative; write a non-negative number of whole minutes"
    );
    assert!(
        !finding.remedy.is_empty(),
        "a finding carries what to do about it"
    );
    assert!(
        finding.render().contains("help:"),
        "the rendered finding carries the remedy: {}",
        finding.render()
    );
}

#[test]
fn c005_a_scope_whose_every_entry_is_malformed_reports_unknown_not_zero() {
    let issue = memory_issue(
        3,
        vec![
            hand_made("e-1", Some(-5), Some("2026-03-01"), "alice", None),
            hand_made("e-2", None, Some("2026-03-02"), "alice", None),
        ],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));
    let total = snapshot.total(&TimeFilter::new());

    assert_eq!(
        total.total_minutes, None,
        "nothing usable was counted, so there is no total — not a zero one"
    );
    assert_eq!(total.entry_count, 0);
    assert_eq!(total.malformed_count, 2);
    assert_eq!(total.state(), TimeTotalState::Unknown);
    assert_eq!(
        findings(&total),
        vec![
            ("invalid_duration", Some("duration_minutes")),
            ("invalid_duration", Some("duration_minutes")),
        ]
    );
}

// ---------------------------------------------------------------------------
// C-005: nothing is not zero
// ---------------------------------------------------------------------------

#[test]
fn c005_an_empty_scope_says_nothing_where_a_recorded_zero_says_zero() {
    let with_zero = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}",
            entry_line("e-zero", 0, Some("2026-03-01"), "alice")
        ),
        &[],
    );
    let with_nothing = parsed_issue(4, "time_entries: []\n", &[]);
    let snapshot = TimeSnapshot::of(&[with_zero, with_nothing]);

    let recorded_zero = snapshot.total(&TimeFilter::new().for_issue(3));
    let empty = snapshot.total(&TimeFilter::new().for_issue(4));

    assert_eq!(recorded_zero.total_minutes, Some(0));
    assert_eq!(recorded_zero.entry_count, 1);
    assert_eq!(recorded_zero.state(), TimeTotalState::Recorded);

    assert_eq!(
        empty.total_minutes, None,
        "an issue with no entry recorded nothing, which is not `0m`"
    );
    assert_eq!(empty.entry_count, 0);
    assert_eq!(empty.malformed_count, 0);
    assert_eq!(empty.state(), TimeTotalState::Nothing);
    assert_ne!(
        empty.state(),
        recorded_zero.state(),
        "the empty scope and the recorded zero must not be readable as the same state"
    );
    assert!(
        empty.diagnostics.is_empty(),
        "nothing recorded is not a finding"
    );
}

// ---------------------------------------------------------------------------
// C-005 / T016: every malformed field, one kind each
// ---------------------------------------------------------------------------

#[test]
fn c005_each_malformed_field_is_diagnosed_with_its_own_kind_and_field() {
    let issue = memory_issue(
        7,
        vec![
            hand_made("", Some(30), Some("2026-03-01"), "alice", None),
            hand_made("e-neg", Some(-1), Some("2026-03-02"), "alice", None),
            hand_made("e-date", Some(30), Some("2026-02-30"), "alice", None),
            hand_made("e-author", Some(30), Some("2026-03-03"), "", None),
            hand_made(
                "e-note",
                Some(30),
                Some("2026-03-04"),
                "alice",
                Some("one\ntwo"),
            ),
        ],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));
    let total = snapshot.total(&TimeFilter::new());

    assert_eq!(total.malformed_count, 5);
    assert_eq!(total.entry_count, 0);
    assert_eq!(total.total_minutes, None);
    assert_eq!(
        findings(&total),
        vec![
            ("invalid_date", Some("date")),
            ("malformed_entry", Some("id")),
            ("invalid_duration", Some("duration_minutes")),
            ("missing_author", Some("author")),
            ("malformed_entry", Some("note")),
        ],
        "one finding per field problem, in the index's own entry order: `2026-02-30` \
         sorts before the March dates"
    );

    // Positive control: the same five entries with the problems repaired produce no
    // finding at all, so the measurement above can fail.
    let repaired = memory_issue(
        7,
        vec![
            entry("e-id", 30, Some("2026-03-01"), "alice"),
            entry("e-neg", 1, Some("2026-03-02"), "alice"),
            entry("e-date", 30, Some("2026-02-28"), "alice"),
            entry("e-author", 30, Some("2026-03-03"), "alice"),
            entry("e-note", 30, Some("2026-03-04"), "alice"),
        ],
    );
    let clean = TimeSnapshot::of(std::slice::from_ref(&repaired)).total(&TimeFilter::new());
    assert!(clean.diagnostics.is_empty());
    assert_eq!(clean.entry_count, 5);
    assert_eq!(clean.total_minutes, Some(121));
}

// ---------------------------------------------------------------------------
// T013: the filter, its combination rule and its boundaries
// ---------------------------------------------------------------------------

#[test]
fn t013_the_filter_combines_issue_assignee_and_period_with_and() {
    let snapshot = TimeSnapshot::of(&[
        parsed_issue(
            3,
            &format!(
                "time_entries:\n{}{}",
                entry_line("e-a1", 90, Some("2026-03-01"), "alice"),
                entry_line("e-a2", 30, Some("2026-03-15"), "@Ada"),
            ),
            &[],
        ),
        parsed_issue(
            4,
            &format!(
                "time_entries:\n{}{}",
                entry_line("e-b1", 60, Some("2026-03-05"), "ada"),
                entry_line("e-b2", 10, Some("2026-04-01"), "alice"),
            ),
            &[],
        ),
    ]);

    let everything = snapshot.total(&TimeFilter::new());
    assert_eq!(everything.total_minutes, Some(190));
    assert_eq!(everything.entry_count, 4);

    // One criterion narrows, and naming more narrows further: AND, in that order.
    let by_issue = snapshot.total(&TimeFilter::new().for_issue(4));
    assert_eq!(by_issue.total_minutes, Some(70));
    assert_eq!(by_issue.entry_count, 2);

    let by_assignee = snapshot.total(&TimeFilter::new().for_assignee("@ada"));
    assert_eq!(
        by_assignee.total_minutes,
        Some(90),
        "`@ada` and `ada` are one identity, so both of their entries match"
    );
    assert_eq!(by_assignee.entry_count, 2);

    let by_period = snapshot.total(&TimeFilter::new().between("2026-03-05", "2026-03-15"));
    assert_eq!(
        by_period.total_minutes,
        Some(90),
        "both bounds are inclusive: March 5 and March 15 are inside"
    );
    assert_eq!(by_period.entry_count, 2);

    let all_three = TimeFilter::new()
        .for_issue(3)
        .for_assignee("ada")
        .between("2026-03-01", "2026-03-31");
    let narrowed = snapshot.total(&all_three);
    assert_eq!(
        narrowed.total_minutes,
        Some(30),
        "issue 3 AND ada AND March leaves only March 15"
    );
    assert_eq!(narrowed.entry_count, 1);

    // Positive control: dropping one criterion can only ever select more.
    let without_issue = snapshot.total(&TimeFilter {
        issue: None,
        ..all_three.clone()
    });
    assert_eq!(without_issue.total_minutes, Some(90));
    assert!(without_issue.entry_count > narrowed.entry_count);
}

#[test]
fn t013_period_bounds_are_inclusive_and_an_undated_entry_is_counted_not_dropped() {
    let issue = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}{}{}",
            entry_line("e-before", 5, Some("2026-02-28"), "alice"),
            entry_line("e-edge", 15, Some("2026-03-01"), "alice"),
            entry_line("e-undated", 45, None, "alice"),
        ),
        &[],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));

    let filter = TimeFilter::new().since("2026-03-01");
    let total = snapshot.total(&filter);
    assert_eq!(
        total.total_minutes,
        Some(15),
        "the inclusive lower bound includes March 1 and excludes February 28"
    );
    assert_eq!(total.entry_count, 1);
    assert_eq!(
        total.undated_count, 1,
        "the undated entry is inside the scope but no period can place it, so it is counted"
    );
    assert!(
        total.is_partial(),
        "a total with an unplaceable entry is not the whole story"
    );

    assert_eq!(filter.place(Some("2026-03-01")), PeriodPlacement::InPeriod);
    assert_eq!(
        filter.place(Some("2026-02-28")),
        PeriodPlacement::OutOfPeriod
    );
    assert_eq!(filter.place(None), PeriodPlacement::Undated);
    assert_eq!(
        filter.place(Some("2026-02-30")),
        PeriodPlacement::Unreadable,
        "a date the validator refuses is not read as `outside the period`"
    );
    assert_eq!(
        TimeFilter::new().place(None),
        PeriodPlacement::InPeriod,
        "with no period there is nothing to fail to place"
    );

    // Positive control: the same undated entry is fully counted when no period is
    // named, so the count above measures the period rather than the entry.
    let unbounded = snapshot.total(&TimeFilter::new());
    assert_eq!(unbounded.total_minutes, Some(65));
    assert_eq!(unbounded.undated_count, 0);
    assert!(!unbounded.is_partial());

    // A scope whose only entry is valid but undated has no number and says `unknown`,
    // not `nothing`: it selected a real entry that no period can place.
    let undated_only = parsed_issue(
        9,
        &format!("time_entries:\n{}", entry_line("e-u", 45, None, "alice")),
        &[],
    );
    let undated_snapshot = TimeSnapshot::of(std::slice::from_ref(&undated_only));
    let undated_total = undated_snapshot.total(&TimeFilter::new().since("2026-03-01"));
    assert_eq!(undated_total.total_minutes, None);
    assert_eq!(undated_total.entry_count, 0);
    assert_eq!(undated_total.undated_count, 1);
    assert_eq!(undated_total.state(), TimeTotalState::Unknown);
    assert_ne!(
        undated_total.state(),
        TimeTotalState::Nothing,
        "`nothing` is reserved for a scope that selected no entry at all"
    );
    // Positive control: with no period the same scope records 45 minutes, so the
    // `unknown` above is about placement and not about the entry's validity.
    assert_eq!(
        undated_snapshot.total(&TimeFilter::new()).total_minutes,
        Some(45)
    );
}

#[test]
fn t013_the_caller_supplies_the_dates_and_no_clock_is_read() {
    // Two entries on dates no "today" could be: `1970-01-01`, the calendar
    // validator's own floor, and `2999-12-31`. They are ordinary dates here — the
    // filter resolves no clock, so what a scope contains is exactly what the
    // caller's bounds say, and running this test on any other day cannot change
    // the answer.
    let issue = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}{}",
            entry_line("e-epoch", 10, Some("1970-01-01"), "alice"),
            entry_line("e-far", 20, Some("2999-12-31"), "alice"),
        ),
        &[],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));

    assert_eq!(snapshot.total(&TimeFilter::new()).total_minutes, Some(30));
    assert_eq!(
        snapshot
            .total(&TimeFilter::new().since("1970-01-01").until("1970-01-01"))
            .total_minutes,
        Some(10),
        "the caller's one-day period selects the entry inside it"
    );
    assert_eq!(
        snapshot
            .total(&TimeFilter::new().since("2999-12-31"))
            .total_minutes,
        Some(20),
        "and a bound in the far future is a bound like any other"
    );

    // Positive control: a caller's period between the two entries selects neither,
    // so the two numbers above measure the bounds rather than a clock.
    let between = snapshot.total(&TimeFilter::new().between("2000-01-01", "2000-12-31"));
    assert_eq!(between.total_minutes, None);
    assert_eq!(between.state(), TimeTotalState::Nothing);
}

#[test]
fn t013_a_refused_filter_is_reported_before_any_entry_is_evaluated() {
    let issue = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}",
            entry_line("e-1", 90, Some("2026-03-01"), "alice")
        ),
        &[],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));

    let bad_bound = TimeFilter::new().since("2026-3-1");
    let refused = snapshot.total(&bad_bound);
    assert_eq!(refused.state(), TimeTotalState::InvalidFilter);
    assert_eq!(
        refused.total_minutes, None,
        "an unreadable bound is not read as `no bound`"
    );
    assert_eq!(refused.entry_count, 0);
    assert_eq!(
        findings(&refused),
        vec![("invalid_date", Some("date_from"))]
    );
    assert!(!refused.diagnostics[0].remedy.is_empty());

    let inverted = snapshot.total(&TimeFilter::new().between("2026-03-31", "2026-03-01"));
    assert_eq!(inverted.state(), TimeTotalState::InvalidFilter);
    assert_eq!(
        findings(&inverted),
        vec![("invalid_period", Some("period"))]
    );

    let blank_identity = snapshot.total(&TimeFilter {
        assignee: Some("   ".to_string()),
        ..TimeFilter::new()
    });
    assert_eq!(blank_identity.state(), TimeTotalState::InvalidFilter);
    assert_eq!(
        findings(&blank_identity),
        vec![("invalid_assignee", Some("assignee"))]
    );

    // Positive control: the same snapshot with valid criteria sums, so the refusals
    // above are about the filter and not about the data.
    let accepted = snapshot.total(&TimeFilter::new().since("2026-03-01"));
    assert_eq!(accepted.state(), TimeTotalState::Recorded);
    assert_eq!(accepted.total_minutes, Some(90));

    assert!(bad_bound.problems().iter().any(|problem| matches!(
        problem,
        TimeFilterError::InvalidDate {
            field: "date_from",
            ..
        }
    )));
    assert!(TimeFilter::new().validate().is_ok());
}

#[test]
fn t013_selects_refuses_an_invalid_criterion_instead_of_matching_on_it() {
    let alice = entry("e-1", 90, Some("2026-01-15"), "alice");

    // An unreadable bound is not "no bound": `"2026-01-15" >= "0"` is true, so a
    // lexicographic read would select the entry and report a wider scope than the
    // caller asked for.
    let unreadable = TimeFilter::new().since("0");
    assert_eq!(unreadable.problems().len(), 1);
    assert!(
        !unreadable.selects(3, &alice),
        "an unreadable bound must select nothing"
    );

    // A blank identity criterion is not "every author".
    let blank = TimeFilter::new().for_assignee("");
    assert!(
        blank
            .problems()
            .iter()
            .any(|problem| matches!(problem, TimeFilterError::InvalidAssignee { .. })),
        "a blank identity is a refusal, not an absent criterion"
    );
    assert!(
        !blank.selects(3, &alice),
        "a blank identity must select nothing"
    );

    // The issue criterion, too: a filter naming another issue selects nothing.
    assert!(!TimeFilter::new().for_issue(4).selects(3, &alice));

    // Positive controls: the same criteria written validly do select it, and the
    // unfiltered predicate selects everything.
    assert!(TimeFilter::new().selects(3, &alice));
    assert!(
        TimeFilter::new()
            .since("2026-01-01")
            .for_assignee("@alice")
            .selects(3, &alice)
    );
    assert!(!TimeFilter::new().since("2026-02-01").selects(3, &alice));
    assert!(!TimeFilter::new().for_assignee("bob").selects(3, &alice));
}

#[test]
fn t013_an_absent_issue_is_not_an_issue_that_recorded_nothing() {
    let snapshot = TimeSnapshot::of(&[
        parsed_issue(
            3,
            &format!(
                "time_entries:\n{}",
                entry_line("e-1", 90, Some("2026-03-01"), "alice")
            ),
            &[],
        ),
        parsed_issue(4, "time_entries: []\n", &[]),
    ]);

    let present = snapshot.total(&TimeFilter::new().for_issue(4));
    let absent = snapshot.total(&TimeFilter::new().for_issue(99));

    assert_eq!(present.state(), TimeTotalState::Nothing);
    assert_eq!(absent.state(), TimeTotalState::UnknownIssue);
    assert_ne!(
        present.state(),
        absent.state(),
        "`this issue recorded nothing` and `this snapshot never held this issue` are \
         different answers"
    );
    assert_eq!(absent.total_minutes, None);
    assert_eq!(
        findings(&absent),
        vec![("unknown_issue", None)],
        "the unknown scope carries the machine-readable name of its selector"
    );
    assert!(snapshot.holds_issue(4) && !snapshot.holds_issue(99));
}

#[test]
fn t013_filter_describe_names_one_scope_in_one_spelling() {
    assert_eq!(TimeFilter::new().describe(), "all");
    assert_eq!(
        TimeFilter::new()
            .for_issue(3)
            .for_assignee("@ada")
            .between("2026-03-01", "2026-03-31")
            .including_deleted()
            .describe(),
        "issue #3, assignee @ada, period 2026-03-01..2026-03-31, audit"
    );
    assert_eq!(
        TimeFilter::new().until("2026-03-31").describe(),
        "period ..2026-03-31"
    );
}

// ---------------------------------------------------------------------------
// T014: one snapshot, every scope; T016: one stable finding order
// ---------------------------------------------------------------------------

#[test]
fn t014_one_snapshot_answers_every_requested_scope_identically() {
    let issues = vec![
        parsed_issue(
            3,
            &format!(
                "time_entries:\n{}",
                entry_line("e-1", 90, Some("2026-03-01"), "alice")
            ),
            &[],
        ),
        parsed_issue(
            4,
            &format!(
                "time_entries:\n{}",
                entry_line("e-2", 30, Some("2026-03-02"), "ada")
            ),
            &[],
        ),
    ];
    let snapshot = TimeSnapshot::of(&issues);

    assert_eq!(snapshot.entries().len(), 2, "each entry is indexed once");
    assert_eq!(snapshot.issues(), &[3, 4]);

    let filters = [
        TimeFilter::new(),
        TimeFilter::new().for_issue(3),
        TimeFilter::new().for_assignee("ada"),
        TimeFilter::new().between("2026-03-01", "2026-03-01"),
    ];
    let batch = snapshot.totals(&filters);
    assert_eq!(batch.len(), filters.len(), "one answer per requested scope");
    for (filter, total) in filters.iter().zip(&batch) {
        assert_eq!(
            *total,
            snapshot.total(filter),
            "the batch path and the single path answer identically for {filter}"
        );
    }
    assert_eq!(
        batch
            .iter()
            .map(|total| total.total_minutes)
            .collect::<Vec<_>>(),
        vec![Some(120), Some(90), Some(30), Some(90)]
    );

    // The index is the same after every read: nothing was re-derived or mutated.
    assert_eq!(snapshot.entries().len(), 2);
    assert_eq!(snapshot.issues(), &[3, 4]);
}

#[test]
fn t016_findings_are_ordered_scope_first_then_entry_index_order() {
    let snapshot = TimeSnapshot::of(&[parsed_issue(
        3,
        &format!(
            "time_entries:\n{}{}",
            entry_line("e-bad", -5, Some("2026-03-01"), "alice"),
            entry_line("e-ok", 30, Some("2026-03-02"), "alice"),
        ),
        &[],
    )]);

    let refused = snapshot.total(&TimeFilter {
        issue: Some(3),
        assignee: Some(String::new()),
        ..TimeFilter::new()
    });
    assert_eq!(refused.diagnostics.len(), 1);
    assert!(refused.diagnostics[0].is_scope_finding());

    let total = snapshot.total(&TimeFilter::new().for_issue(3));
    assert_eq!(total.diagnostics.len(), 1);
    assert!(
        !total.diagnostics[0].is_scope_finding(),
        "an entry finding names its entry"
    );
    assert_eq!(total.diagnostics[0].entry_id.as_deref(), Some("e-bad"));
}

#[test]
fn t014_breakdowns_cover_issues_identities_and_dates_deterministically() {
    let issue3 = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}{}{}",
            entry_line("e-a1", 90, Some("2026-03-01"), "alice"),
            entry_line("e-a2", 30, Some("2026-03-15"), "@Ada"),
            entry_line("e-a3", 45, None, "alice"),
        ),
        &[],
    );
    let issue4 = parsed_issue(
        4,
        &format!(
            "time_entries:\n{}",
            entry_line("e-b1", 60, Some("2026-03-05"), "ada")
        ),
        &[],
    );
    let issue5 = parsed_issue(5, "time_entries: []\n", &[]);
    let snapshot = TimeSnapshot::of(&[issue3, issue4, issue5]);

    let by_issue = snapshot.by_issue(&TimeFilter::new());
    assert_eq!(
        by_issue
            .iter()
            .map(|total| (total.group.label(), total.total_minutes, total.entry_count))
            .collect::<Vec<_>>(),
        vec![
            ("#3".to_string(), Some(165), 3),
            ("#4".to_string(), Some(60), 1),
            ("#5".to_string(), None, 0),
        ],
        "every issue appears, including the one with no entry: its absence is a \
         `nothing` answer"
    );
    assert_eq!(by_issue[2].state(), TimeTotalState::Nothing);

    let by_assignee = snapshot.by_assignee(&TimeFilter::new());
    assert_eq!(
        by_assignee
            .iter()
            .map(|total| (total.group.label(), total.total_minutes))
            .collect::<Vec<_>>(),
        vec![
            ("@Ada".to_string(), Some(90)),
            ("@alice".to_string(), Some(135)),
        ],
        "`@Ada` and `ada` group as one identity, ordered by canonical identity"
    );

    let by_date = snapshot.by_date(&TimeFilter::new());
    assert_eq!(
        by_date
            .iter()
            .map(|total| (total.group.label(), total.total_minutes))
            .collect::<Vec<_>>(),
        vec![
            ("2026-03-01".to_string(), Some(90)),
            ("2026-03-05".to_string(), Some(60)),
            ("2026-03-15".to_string(), Some(30)),
            ("(undated)".to_string(), Some(45)),
        ],
        "dates ascend and the undated entry is shown last rather than dropped"
    );

    // A period-bounded breakdown keeps the dates inside the period, never invents a
    // group whose key the period excludes, and still shows what it could not place.
    let bounded = snapshot.by_date(&TimeFilter::new().between("2026-03-05", "2026-03-15"));
    assert_eq!(
        bounded
            .iter()
            .map(|total| (
                total.group.label(),
                total.total_minutes,
                total.undated_count,
                total.state()
            ))
            .collect::<Vec<_>>(),
        vec![
            (
                "2026-03-05".to_string(),
                Some(60),
                0,
                TimeTotalState::Recorded
            ),
            (
                "2026-03-15".to_string(),
                Some(30),
                0,
                TimeTotalState::Recorded
            ),
            ("(undated)".to_string(), None, 1, TimeTotalState::Unknown),
        ],
        "the unplaceable group reports `unknown`, never `nothing`: it selected a real entry"
    );

    let unknown = snapshot.by_issue(&TimeFilter::new().for_issue(99));
    assert_eq!(
        unknown.len(),
        1,
        "an unknown scope yields one total carrying the finding, not one group per issue"
    );
    assert_eq!(unknown[0].state(), TimeTotalState::UnknownIssue);
    assert_eq!(identity_cmp("Ada", "ada"), std::cmp::Ordering::Equal);
    assert_eq!(identity_cmp("ada", "bob"), std::cmp::Ordering::Less);
    assert_eq!(
        TimeGroup::Assignee("ADA".into()),
        TimeGroup::Assignee("ada".into())
    );
}

// ---------------------------------------------------------------------------
// T017: the audit trail is History's
// ---------------------------------------------------------------------------

#[test]
fn t017_deleted_entries_are_absent_from_current_totals_and_reported_by_audit() {
    let deleted = "- 2026-03-20T10:00:00Z \u{2014} alice \u{2014} time_entry_deleted \u{2014} \
         entry e-gone; deleted 45m on 2026-03-04 by ada: scrapped; reason: duplicate"
        .to_string();
    let corrected = "- 2026-03-21T10:00:00Z \u{2014} alice \u{2014} time_entry_updated \u{2014} \
         entry e-1; updated 60m on 2026-03-01 by alice -> 90m on 2026-03-01 by alice; \
         reason: recount"
        .to_string();
    let issue = parsed_issue(
        3,
        &format!(
            "time_entries:\n{}",
            entry_line("e-1", 90, Some("2026-03-01"), "alice")
        ),
        &[deleted, corrected],
    );
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));

    let current = snapshot.total(&TimeFilter::new());
    assert_eq!(
        current.total_minutes,
        Some(90),
        "the deleted entry's 45 minutes are History's, never added back to the \
         current total"
    );
    assert_eq!(current.entry_count, 1);
    assert_eq!(
        current.deleted_count, None,
        "normal totals do not report audit context unless it was asked for"
    );

    let audited = snapshot.total(&TimeFilter::new().including_deleted());
    assert_eq!(
        audited.total_minutes, current.total_minutes,
        "asking for the audit context changes what is reported, not what is summed"
    );
    assert_eq!(audited.deleted_count, Some(1));
    assert_eq!(audited.entry_count, 1);

    let audit = snapshot.audit(&TimeFilter::new().for_issue(3));
    assert_eq!(audit.issues.len(), 1);
    let context = &audit.issues[0];
    assert_eq!(context.issue, 3);
    assert_eq!(context.current, 1, "the current projection is one entry");
    assert_eq!(context.deletions.len(), 1);
    assert_eq!(context.deletions[0].issue, 3);
    assert_eq!(context.deletions[0].entry_id.as_deref(), Some("e-gone"));
    assert_eq!(context.deletions[0].deleted_at, "2026-03-20T10:00:00Z");
    assert_eq!(context.deletions[0].deleted_by, "alice");
    assert_eq!(
        context.corrections, 1,
        "a correction keeps a prior value too, so it is auditable rather than silent"
    );
    assert_eq!(audit.deleted_count, 1);
    assert_eq!(audit.corrected_count, 1);
    assert!(audit.diagnostics.is_empty());

    // An issue the snapshot does not hold has no audit context, and says so.
    let missing = snapshot.audit(&TimeFilter::new().for_issue(99));
    assert!(missing.issues.is_empty());
    assert_eq!(
        missing
            .diagnostics
            .iter()
            .map(|finding| finding.kind.as_str())
            .collect::<Vec<_>>(),
        vec!["unknown_issue"]
    );

    // A refusal is reported before the audit walks anything.
    let refused = snapshot.audit(&TimeFilter::new().since("2026-3-1"));
    assert!(refused.issues.is_empty());
    assert_eq!(refused.diagnostics.len(), 1);
    assert!(refused.diagnostics[0].is_scope_finding());

    assert_eq!(
        snapshot.deletions_on(3).len(),
        1,
        "the snapshot is unchanged by every read above"
    );
    assert_eq!(snapshot.corrections_on(3), 1);
    assert_eq!(snapshot.corrections_on(99), 0);
}

#[test]
fn t017_the_audit_count_covers_the_selectors_issues_not_just_the_ones_with_current_entries() {
    // Issue 3's recorded work was deleted: its current projection is empty and the
    // prior value lives only in History. A count taken from the issues that
    // contributed a *current* entry would report `Some(0)` here — a zero standing in
    // for "not read", which is the defect this mission exists to prevent.
    let deletion = |entry_id: &str| {
        format!(
            "- 2026-03-20T10:00:00Z \u{2014} alice \u{2014} time_entry_deleted \u{2014} \
             entry {entry_id}; deleted 45m on 2026-03-04 by ada: scrapped; \
             reason: duplicate"
        )
    };
    let issue3 = parsed_issue(3, "time_entries: []\n", &[deletion("e-gone-3")]);
    let issue4 = parsed_issue(
        4,
        &format!(
            "time_entries:\n{}",
            entry_line("e-keep", 30, Some("2026-03-01"), "alice")
        ),
        &[deletion("e-gone-4")],
    );
    let issue5 = parsed_issue(5, "time_entries: []\n", &[deletion("e-gone-5")]);
    let snapshot = TimeSnapshot::of(&[issue3, issue4, issue5]);

    // The scope whose current entries were all deleted: no number to show, but the
    // audit context is real and is reported.
    let only_deleted = snapshot.total(&TimeFilter::new().for_issue(3).including_deleted());
    assert_eq!(only_deleted.state(), TimeTotalState::Nothing);
    assert_eq!(only_deleted.total_minutes, None);
    assert_eq!(only_deleted.entry_count, 0);
    assert_eq!(only_deleted.deleted_count, Some(1));

    // The unfiltered scope reports every prior value the snapshot retains, not just
    // the one on the issue that still has a current entry.
    let whole = snapshot.total(&TimeFilter::new().including_deleted());
    assert_eq!(whole.deleted_count, Some(3));
    assert_eq!(whole.entry_count, 1);

    // The two public methods answer the same question for the same audit request.
    for filter in [
        TimeFilter::new().including_deleted(),
        TimeFilter::new().for_issue(3).including_deleted(),
        TimeFilter::new().for_issue(4).including_deleted(),
        TimeFilter::new().since("2026-03-01").including_deleted(),
    ] {
        assert_eq!(
            snapshot.total(&filter).deleted_count,
            Some(snapshot.audit(&filter).deleted_count),
            "{filter}: `total` and `audit` must not disagree about the prior values"
        );
    }

    // The per-issue breakdown adds up to the same count.
    let per_issue = snapshot.by_issue(&TimeFilter::new().including_deleted());
    assert_eq!(
        per_issue
            .iter()
            .map(|total| total.deleted_count.unwrap_or(0))
            .collect::<Vec<_>>(),
        vec![1, 1, 1]
    );

    // Positive control: without the audit context the field stays `None`, so the
    // numbers above measure the request rather than being always-on.
    assert_eq!(snapshot.total(&TimeFilter::new()).deleted_count, None);
    assert_eq!(
        snapshot
            .total(&TimeFilter::new().for_issue(3))
            .deleted_count,
        None
    );
}

#[test]
fn t017_a_correction_moves_the_current_total_and_stays_auditable() {
    let (tmp, dir) = repo();
    write_issue(&dir, 3, "time_entries: []\n", &[]);
    let store = store_of(&tmp);

    let created = apply(
        &store,
        &TimeMutationRequest::create("3", NewTimeEntry::new(60, "alice").on("2026-03-01"))
            .at("2026-03-01T10:00:00Z"),
    )
    .expect("the create applies");
    let entry_id = created.outcome.entry_id.clone();
    apply(
        &store,
        &TimeMutationRequest::edit("3", &entry_id, TimeEntryEdit::new().duration(90), "recount")
            .at("2026-03-02T10:00:00Z"),
    )
    .expect("the correction applies");

    let issue = issue_of(&store, 3);
    assert_eq!(issue.time_entries.len(), 1);
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));
    let total = snapshot.total(&TimeFilter::new().for_issue(3));
    assert_eq!(
        total.total_minutes,
        Some(90),
        "the current projection carries the corrected value"
    );
    assert_eq!(snapshot.corrections_on(3), 1);
    assert_eq!(snapshot.deletions_on(3).len(), 0);
    let audit = snapshot.audit(&TimeFilter::new().for_issue(3));
    assert_eq!(audit.corrected_count, 1);
    assert_eq!(audit.issues[0].current, 1);
}

// ---------------------------------------------------------------------------
// NFR-003 / C-008 / T018: determinism, read-only, and the 10k budget
// ---------------------------------------------------------------------------

#[test]
fn nfr003_the_same_input_produces_the_same_bytes_twice() {
    let build = |number| {
        parsed_issue(
            number,
            &format!(
                "time_entries:\n{}{}{}",
                entry_line("e-a1", 90, Some("2026-03-01"), "alice"),
                entry_line("e-a2", -5, Some("2026-03-02"), "@Ada"),
                entry_line("e-note", 30, Some("2026-03-03"), "carol"),
            ),
            &[
                "- 2026-03-09T00:00:00Z \u{2014} bob \u{2014} time_entry_deleted \u{2014} \
               entry e-z; deleted 15m on 2026-03-02 by bob: dedupe"
                    .to_string(),
            ],
        )
    };
    let filter = TimeFilter::new()
        .between("2026-03-01", "2026-03-31")
        .including_deleted();

    let first = TimeSnapshot::of(&[build(3)]);
    let second = TimeSnapshot::of(&[build(3)]);

    for _ in 0..2 {
        let left = bytes(&first.total(&filter));
        let right = bytes(&second.total(&filter));
        assert_eq!(left, right, "the same issues must render the same bytes");
        let left_grouped: Vec<String> = first.by_assignee(&filter).iter().map(bytes).collect();
        let right_grouped: Vec<String> = second.by_assignee(&filter).iter().map(bytes).collect();
        assert_eq!(left_grouped, right_grouped);
    }
    assert_eq!(
        first.total(&filter),
        second.total(&filter),
        "and the values compare equal, not just their render"
    );
    assert_eq!(first.total(&filter).deleted_count, Some(1));
    assert_eq!(first.total(&filter).total_minutes, Some(120));
}

#[test]
fn c008_aggregation_reads_the_issue_slice_and_writes_nothing() {
    let (tmp, dir) = repo();
    write_issue(
        &dir,
        3,
        &format!(
            "time_entries:\n{}",
            entry_line("e-1", 90, Some("2026-03-01"), "alice")
        ),
        &[
            "- 2026-03-09T00:00:00Z \u{2014} bob \u{2014} time_entry_deleted \u{2014} \
           entry e-z; deleted 15m on 2026-03-02 by bob: dedupe"
                .to_string(),
        ],
    );
    let path = dir.join(issue_filename(3));
    let before_file = fs::read_to_string(&path).unwrap();
    let store = store_of(&tmp);
    let issues = vec![issue_of(&store, 3)];
    let before_render: Vec<String> = issues.iter().map(Issue::to_file_contents).collect();

    let snapshot = TimeSnapshot::of(&issues);
    let filter = TimeFilter::new().including_deleted();
    let _ = snapshot.total(&filter);
    let _ = snapshot.totals(&[filter.clone(), TimeFilter::new().for_issue(3)]);
    let _ = snapshot.by_issue(&filter);
    let _ = snapshot.by_assignee(&filter);
    let _ = snapshot.by_date(&filter);
    let _ = snapshot.audit(&filter);

    let after_render: Vec<String> = issues.iter().map(Issue::to_file_contents).collect();
    assert_eq!(
        before_render, after_render,
        "aggregation must not touch the issue slice it was handed"
    );
    assert_eq!(
        fs::read_to_string(&path).unwrap(),
        before_file,
        "aggregation must not touch the file"
    );
    assert_eq!(
        store
            .get(IssueSelector::Number(3))
            .unwrap()
            .time_entries
            .len(),
        1
    );
}

#[test]
fn nfr001_ten_thousand_entries_aggregate_within_the_budget() {
    let mut entries = String::from("time_entries:\n");
    for index in 0..10_000usize {
        let day = (index % 28) + 1;
        let author = format!("a{}", index % 7);
        entries.push_str(&entry_line(
            &format!("e-{index}"),
            1,
            Some(&format!("2026-03-{day:02}")),
            &author,
        ));
    }
    let issue = parsed_issue(3, &entries, &[]);
    assert_eq!(issue.time_entries.len(), 10_000);

    let filter = TimeFilter::new()
        .for_assignee("a1")
        .between("2026-03-01", "2026-03-28")
        .including_deleted();
    let expected = (0..10_000usize).filter(|index| index % 7 == 1).count();

    let started = Instant::now();
    let snapshot = TimeSnapshot::of(std::slice::from_ref(&issue));
    let total = snapshot.total(&filter);
    let per_issue = snapshot.by_issue(&filter);
    let per_assignee = snapshot.by_assignee(&filter);
    let per_date = snapshot.by_date(&filter);
    let audit = snapshot.audit(&filter);
    let elapsed = started.elapsed();

    assert_eq!(per_assignee.len(), 1, "one identity did all of that work");
    assert_eq!(
        per_assignee[0].entry_count, expected,
        "every entry of that identity is counted"
    );
    assert_eq!(total.entry_count, expected);
    assert_eq!(total.total_minutes, Some(expected as i128));
    assert_eq!(per_issue.len(), 1);
    let expected_days: std::collections::BTreeSet<usize> = (0..10_000usize)
        .filter(|index| index % 7 == 1)
        .map(|index| index % 28 + 1)
        .collect();
    assert_eq!(
        per_date.len(),
        expected_days.len(),
        "one group per calendar date the selected entries fall on"
    );
    assert_eq!(
        snapshot.by_date(&TimeFilter::new()).len(),
        28,
        "and every day of March has its own group when nothing is filtered"
    );
    assert_eq!(audit.deleted_count, 0);
    assert!(
        elapsed < Duration::from_millis(500),
        "10,000 in-memory entries must aggregate within the NFR-001 budget, took {elapsed:?}"
    );

    let unbounded = snapshot.total(&TimeFilter::new());
    assert_eq!(unbounded.total_minutes, Some(10_000));
    assert_eq!(unbounded.entry_count, 10_000);
}

// ---------------------------------------------------------------------------
// The real exercise: a mixed fixture, read through a real store
// ---------------------------------------------------------------------------

/// A store holding the mixed fixture the acceptance asks for: valid entries across
/// two issues, two identities and several dates, one malformed entry per kind, one
/// issue with no entries, and a deletion History retains.
fn mixed_store() -> (TempDir, PathBuf, Store) {
    let (tmp, dir) = repo();
    let issue3 = format!(
        "time_entries:\n{}{}{}{}{}{}",
        entry_line("e-a1", 90, Some("2026-03-01"), "alice"),
        entry_line("e-a2", 30, Some("2026-03-15"), "@Ada"),
        entry_line("e-a3", 45, None, "alice"),
        entry_line("e-a4", -5, Some("2026-03-02"), "alice"),
        entry_line("e-a5", 10, Some("2026-02-30"), "carol"),
        entry_line("e-a6", 20, Some("2026-03-20"), ""),
    );
    let issue4 = format!(
        "time_entries:\n{}{}",
        entry_line("e-b1", 60, Some("2026-03-05"), "ada"),
        entry_line("e-b2", 0, Some("2026-03-06"), "alice"),
    );
    let deleted = "- 2026-01-05T00:00:00Z \u{2014} alice \u{2014} time_entry_deleted \u{2014} \
         entry e-z1; deleted 45m on 2026-01-04 by ada: scrapped; reason: duplicate"
        .to_string();
    write_issue(&dir, 3, &issue3, &[deleted]);
    write_issue(&dir, 4, &issue4, &[]);
    write_issue(&dir, 5, "time_entries: []\n", &[]);
    let store = store_of(&tmp);
    (tmp, dir, store)
}

#[test]
fn the_mixed_fixture_reports_its_totals_its_counts_and_its_findings() {
    let (_tmp, _dir, store) = mixed_store();
    let issues: Vec<Issue> = [3, 4, 5]
        .iter()
        .map(|number| issue_of(&store, *number))
        .collect();
    let snapshot = TimeSnapshot::of(&issues);

    let whole = snapshot.total(&TimeFilter::new());
    assert_eq!(whole.entry_count, 5);
    assert_eq!(whole.total_minutes, Some(225), "90 + 30 + 45 + 60 + 0");
    assert_eq!(whole.malformed_count, 3);
    assert_eq!(whole.undated_count, 0);
    assert_eq!(whole.deleted_count, None);
    assert_eq!(
        findings(&whole),
        vec![
            ("invalid_date", Some("date")),
            ("invalid_duration", Some("duration_minutes")),
            ("missing_author", Some("author")),
        ],
        "the three malformed entries are reported in index order (the February date \
         first), each with its field"
    );

    let march = TimeFilter::new()
        .between("2026-03-01", "2026-03-31")
        .including_deleted();
    let in_march = snapshot.total(&march);
    assert_eq!(
        in_march.entry_count, 4,
        "e-a3 is undated, e-a5 is unreadable"
    );
    assert_eq!(in_march.total_minutes, Some(180), "90 + 30 + 60 + 0");
    assert_eq!(
        in_march.undated_count, 1,
        "the undated 45 minutes are inside the scope but outside the period, and are counted"
    );
    assert_eq!(in_march.malformed_count, 3);
    assert_eq!(in_march.deleted_count, Some(1));
    assert!(in_march.is_partial());
    assert_eq!(in_march.state(), TimeTotalState::Recorded);

    let per_issue = snapshot.by_issue(&march);
    assert_eq!(
        per_issue
            .iter()
            .map(|total| (
                total.group.label(),
                total.total_minutes,
                total.entry_count,
                total.malformed_count
            ))
            .collect::<Vec<_>>(),
        vec![
            ("#3".to_string(), Some(120), 2, 3),
            ("#4".to_string(), Some(60), 2, 0),
            ("#5".to_string(), None, 0, 0),
        ],
        "issue 5 has no entry and still reports `nothing`; issue 3's undated entry is \
         not in the period"
    );

    let per_assignee = snapshot.by_assignee(&march);
    assert_eq!(
        per_assignee
            .iter()
            .map(|total| (
                total.group.label(),
                total.total_minutes,
                total.malformed_count
            ))
            .collect::<Vec<_>>(),
        vec![
            ("@Ada".to_string(), Some(90), 0),
            ("@alice".to_string(), Some(90), 1),
            ("@carol".to_string(), None, 1),
            ("(unattributed)".to_string(), None, 1),
        ],
        "an identity's group carries its malformed entries as counts, not as minutes"
    );

    let audit = snapshot.audit(&TimeFilter::new().for_issue(3));
    assert_eq!(audit.issues[0].current, 6);
    assert_eq!(audit.deleted_count, 1);
    assert_eq!(
        audit.issues[0].deletions[0].entry_id.as_deref(),
        Some("e-z1")
    );

    // A surface's whole picture: the totals, the counts and the findings, rendered.
    let scope = in_march.filter.describe();
    let state = in_march.state().as_str();
    let total = in_march.total_minutes;
    let counted = in_march.entry_count;
    let malformed = in_march.malformed_count;
    let undated = in_march.undated_count;
    let deleted = in_march.deleted_count;
    let mut report = format!(
        "scope={scope} state={state} total={total:?} counted={counted} \
         malformed={malformed} undated={undated} deleted={deleted:?}\n"
    );
    for group in &per_issue {
        let label = group.group.label();
        let group_state = group.state().as_str();
        let group_total = group.total_minutes;
        let group_counted = group.entry_count;
        let group_malformed = group.malformed_count;
        report.push_str(&format!(
            "  issue {label} state={group_state} total={group_total:?} \
             counted={group_counted} malformed={group_malformed}\n"
        ));
    }
    for finding in &in_march.diagnostics {
        report.push_str(&format!("  finding {}\n", finding.render()));
    }
    println!("{report}");
    assert!(report.contains("malformed=3"));
    assert!(report.contains("invalid_duration"));
}