tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
//! WP04 acceptance tests: the `tix time` CLI surface (mission
//! `per-issue-time-tracking-01M3C9A4`, subtasks T019–T023).
//!
//! Driven through the **compiled binary only**, as `tests/capacity_cli.rs` and
//! `tests/wip_cli.rs` are. The value model, the mutation service and the shared
//! aggregation have their own targets (`time_entry`, `time_history`,
//! `time_aggregate`); what this file proves is the *surface* half:
//!
//! * the command tree routes each verb to the shared service, and a number the CLI
//!   prints is the DTO's number (FR-002, FR-003, C-006, NFR-003);
//! * a mutation appends exactly one attributable History event and a deletion leaves
//!   the prior value in History (FR-001, FR-005, C-003, C-004, NFR-002);
//! * `nothing` (an empty scope) and `unknown` (entries, none usable) are visibly
//!   different from each other and from a recorded `0`; an absent value prints `-`
//!   (C-005, C-006);
//! * a malformed entry is reported with its remedy and blocks no other read (C-005);
//! * a refusal exits non-zero with a reason **and** a remedy, prints no half-total,
//!   and writes nothing at all (the tree is byte-identical);
//! * the reads write nothing, and the existing commands are unaffected (C-001, C-008).
//!
//! Every assertion about a *file* goes through the crate's own parser
//! ([`tix::model::Issue`]) rather than through the written bytes: a mutation
//! re-serializes the frontmatter, and a comparison against the hand-written spelling
//! would measure the serializer's quoting rather than what the mutation did. The
//! byte-level claims are the "wrote nothing" ones, where the whole tree is compared
//! before and after.
//!
//! TTY-free, network-free and clock-free: every project is a `TempDir`, and no case
//! reads an environment variable, a locale or the current time. A mutation's timestamp
//! is the binary's own boundary clock, so no assertion depends on its value — the
//! History claim is about the kind, the count and the detail the service wrote.
//!
//! Requirement ids in the test names / comments: FR-001, FR-002, FR-003, FR-005,
//! NFR-002, NFR-003, C-001, C-003, C-004, C-005, C-006, C-008.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use tempfile::TempDir;
use tix::model::{HistoryEventKind, Issue};
use tix::time_tracking::service::entry_id_in;

fn tix() -> String {
    env!("CARGO_BIN_EXE_tix").to_string()
}

// ---------------------------------------------------------------------------
// Fixtures and helpers
// ---------------------------------------------------------------------------

/// A project with a real `tix.toml` and an `issues/` directory.
fn project() -> (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)
}

/// 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, assignee: &str, entries: &str, history: &str) -> String {
    format!(
        "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"in progress\"\n\
         labels: []\npriority: \"medium\"\nassignee: {assignee:?}\n\
         estimate: \"3d\"\ncreated: \"2026-01-01\"\nupdated: \"2026-01-01\"\n{entries}---\n\n\
         {history}Body prose that must survive.\n"
    )
}

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

/// Write one issue into the store's directory.
fn write_issue(dir: &Path, number: u32, assignee: &str, entries: &str) {
    write_issue_with_history(dir, number, assignee, entries, "");
}

/// Write one issue that already carries a rendered `## History` block.
fn write_issue_with_history(dir: &Path, number: u32, assignee: &str, entries: &str, history: &str) {
    fs::write(
        dir.join(issue_filename(number)),
        issue_markdown(number, assignee, entries, history),
    )
    .unwrap();
}

/// One `time_entries:` list item, with the date omitted when the entry carries none.
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
}

/// A `time_entries:` block holding one valid entry.
fn one_entry(id: &str, minutes: i64, date: &str, author: &str) -> String {
    format!(
        "time_entries:\n{}",
        entry_line(id, minutes, Some(date), author)
    )
}

/// Run `tix <args>` in `dir` and return `(exit_code, stdout, stderr)`.
fn run(dir: &Path, args: &[&str]) -> (i32, String, String) {
    let out = Command::new(tix())
        .current_dir(dir)
        .args(args)
        .output()
        .expect("the binary runs");
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8(out.stdout).unwrap(),
        String::from_utf8(out.stderr).unwrap(),
    )
}

/// Run `tix <args>`, asserting success, and return stdout.
fn ok(dir: &Path, args: &[&str]) -> String {
    let (code, stdout, stderr) = run(dir, args);
    assert_eq!(
        code, 0,
        "tix {args:?} exited {code}\nstdout:\n{stdout}\nstderr:\n{stderr}"
    );
    stdout
}

/// Run `tix <args>` expecting a refusal: `(exit_code, stdout, stderr)`.
fn refused(dir: &Path, args: &[&str]) -> (i32, String, String) {
    let (code, stdout, stderr) = run(dir, args);
    assert_ne!(code, 0, "tix {args:?} unexpectedly succeeded:\n{stdout}");
    (code, stdout, stderr)
}

/// Every file under `dir`, by relative path, as raw bytes. A byte-identical map before
/// and after a command is the "nothing was written" assertion every refusal makes.
fn tree(dir: &Path) -> BTreeMap<String, Vec<u8>> {
    let mut out = BTreeMap::new();
    let mut stack = vec![dir.to_path_buf()];
    while let Some(current) = stack.pop() {
        let Ok(entries) = fs::read_dir(&current) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                stack.push(path);
            } else {
                let name = path
                    .strip_prefix(dir)
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                out.insert(name, fs::read(&path).unwrap());
            }
        }
    }
    out
}

/// The issue as the crate parses it — the typed view of what a mutation wrote.
fn parsed(dir: &Path, number: u32) -> Issue {
    let text = fs::read_to_string(dir.join(issue_filename(number)))
        .unwrap_or_else(|err| panic!("issue #{number} reads: {err}"));
    Issue::parse(&text).unwrap_or_else(|err| panic!("issue #{number} parses: {err}"))
}

/// Every time-mutation event of an issue, as `(kind, detail)`, in file order.
fn time_events(issue: &Issue) -> Vec<(HistoryEventKind, String)> {
    issue
        .history
        .events()
        .into_iter()
        .filter(|event| {
            matches!(
                event.kind,
                HistoryEventKind::TimeEntryCreated
                    | HistoryEventKind::TimeEntryUpdated
                    | HistoryEventKind::TimeEntryDeleted
            )
        })
        .map(|event| (event.kind, event.detail.clone()))
        .collect()
}

/// The one event of `kind`, asserting there is exactly one.
fn one_event(issue: &Issue, kind: HistoryEventKind) -> String {
    let matching: Vec<String> = time_events(issue)
        .into_iter()
        .filter(|(found, _)| *found == kind)
        .map(|(_, detail)| detail)
        .collect();
    assert_eq!(matching.len(), 1, "exactly one {kind}: {matching:#?}");
    matching.into_iter().next().unwrap()
}

/// The id `tix time add` reported, taken from the line it printed.
///
/// Reading it back from the output — rather than from the file — is deliberate: the
/// minted id is the service's, and the line that carries it is part of what these tests
/// pin.
fn added_id(stdout: &str) -> String {
    let line = stdout.lines().next().unwrap_or_default();
    line.split_whitespace()
        .nth(1)
        .unwrap_or_else(|| panic!("no entry id in {stdout:?}"))
        .to_string()
}

/// The `key:` names of a `key: value` block, in order.
fn keys(stdout: &str) -> Vec<&str> {
    stdout
        .lines()
        .filter_map(|line| line.split_once(':'))
        .map(|(key, _)| key)
        .collect()
}

// ---------------------------------------------------------------------------
// T019/T020 — the command tree and the mutations (FR-001, FR-005, NFR-002, C-003/C-004)
// ---------------------------------------------------------------------------

#[test]
fn add_edit_and_delete_round_trip_through_the_shared_service() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(dir, 1, "@ada", "time_entries: []\n");

    // FR-001: a create, through the service, printing the id it minted and the value it
    // stored. The entry id is generated, so the rest of this test uses what it printed.
    let added = ok(
        dir,
        &[
            "time",
            "add",
            "1",
            "--minutes",
            "90",
            "--date",
            "2026-09-25",
            "--author",
            "alice",
            "--note",
            "Pairing and review",
        ],
    );
    let id = added_id(&added);
    assert_eq!(
        added,
        format!("Added {id} to #1: 90m on 2026-09-25 by alice: Pairing and review\n")
    );

    // NFR-002/C-003: exactly one attributable event, and the current projection holds the
    // entry — the issue's other fields are untouched (C-008).
    let issue = parsed(dir, 1);
    assert_eq!(
        time_events(&issue).len(),
        1,
        "one event for one create: {:#?}",
        time_events(&issue)
    );
    let created = one_event(&issue, HistoryEventKind::TimeEntryCreated);
    assert!(
        created.contains(&format!("entry {id}; created 90m on 2026-09-25 by alice")),
        "{created}"
    );
    assert!(
        !created.contains("reason:"),
        "a create needs no reason: {created}"
    );
    assert_eq!(issue.time_entries.len(), 1);
    assert_eq!(issue.time_entries[0].id, id);
    assert_eq!(issue.time_entries[0].minutes(), Some(90));
    assert_eq!(issue.time_entries[0].date.as_deref(), Some("2026-09-25"));
    assert_eq!(issue.time_entries[0].author, "alice");
    assert_eq!(
        issue.time_entries[0].note.as_deref(),
        Some("Pairing and review")
    );
    assert!(issue.status.is("in progress"));
    // The crate normalizes the identity it parses (`@ada` -> `ada`); the point is that
    // the mutation did not change ownership (C-008).
    assert_eq!(issue.assignee.as_deref(), Some("ada"));
    assert_eq!(issue.estimate.as_deref(), Some("3d"));
    assert_eq!(issue.title, "Issue 1");

    // T021/C-006: the read is the DTO's own numbers, verbatim.
    assert_eq!(
        ok(dir, &["time", "show", "1"]),
        format!(
            "id\tminutes\tdate\tauthor\tnote\n\
             {id}\t90\t2026-09-25\talice\tPairing and review\n\
             group: all\n\
             scope: issue #1\n\
             state: recorded\n\
             total_minutes: 90\n\
             entry_count: 1\n\
             malformed_count: 0\n\
             undated_count: 0\n\
             deleted_count: -\n"
        )
    );

    // FR-005: a correction names one field, keeps the values it did not name, and carries
    // its reason. `--clear-note` is how the optional note is removed.
    assert_eq!(
        ok(
            dir,
            &[
                "time",
                "edit",
                "1",
                "--entry",
                &id,
                "--minutes",
                "120",
                "--clear-note",
                "--reason",
                "correction: paired twice",
            ],
        ),
        format!(
            "Updated {id} on #1: 90m on 2026-09-25 by alice: Pairing and review -> \
             120m on 2026-09-25 by alice\n"
        )
    );
    let issue = parsed(dir, 1);
    assert_eq!(
        time_events(&issue).len(),
        2,
        "one event per applied mutation"
    );
    let updated = one_event(&issue, HistoryEventKind::TimeEntryUpdated);
    assert!(updated.contains("correction: paired twice"), "{updated}");
    // C-004: the correction keeps the prior value in the event.
    assert!(updated.contains("Pairing and review"), "{updated}");
    assert_eq!(issue.time_entries[0].minutes(), Some(120));
    assert_eq!(
        issue.time_entries[0].date.as_deref(),
        Some("2026-09-25"),
        "the date survived"
    );
    assert_eq!(issue.time_entries[0].note, None, "the note was cleared");

    // The audit view counts the correction and reports the deletion's prior value.
    assert_eq!(
        ok(dir, &["time", "history", "1"]),
        "scope: issue #1\n\
         current: 1\n\
         deleted_count: 0\n\
         corrected_count: 1\n\
         entry\tdeleted_at\tdeleted_by\n"
    );

    // FR-005/C-004: the deletion removes the current entry and keeps its event and value.
    assert_eq!(
        ok(
            dir,
            &[
                "time",
                "delete",
                "1",
                "--entry",
                &id,
                "--reason",
                "wrong issue",
                "--confirm"
            ],
        ),
        format!("Deleted {id} from #1: 120m on 2026-09-25 by alice\n")
    );
    let issue = parsed(dir, 1);
    assert_eq!(time_events(&issue).len(), 3, "created, updated, deleted");
    let deleted = one_event(&issue, HistoryEventKind::TimeEntryDeleted);
    assert!(deleted.contains("wrong issue"), "{deleted}");
    assert!(deleted.contains("120m on 2026-09-25 by alice"), "{deleted}");
    assert_eq!(entry_id_in(&deleted), Some(id.as_str()));
    assert!(
        issue.time_entries.is_empty(),
        "the entry left the projection"
    );

    // The audit view now shows the deletion, with the entry it named and who recorded it.
    let history = ok(dir, &["time", "history", "1"]);
    let lines: Vec<&str> = history.lines().collect();
    assert_eq!(
        &lines[..5],
        &[
            "scope: issue #1",
            "current: 0",
            "deleted_count: 1",
            "corrected_count: 1",
            "entry\tdeleted_at\tdeleted_by",
        ]
    );
    let row: Vec<&str> = lines[5].split('\t').collect();
    assert_eq!(row.len(), 3, "entry, deleted_at, deleted_by: {history}");
    assert_eq!(row[0], id);
    assert!(
        row[1].ends_with('Z') && row[1].contains('T'),
        "an instant: {}",
        row[1]
    );
    assert!(!row[2].is_empty(), "an actor: {history}");

    // C-005/C-006: the projection is empty, so the total is `nothing` — not a zero, and
    // the audit count is only there when `--audit` asks for it (`-` here).
    assert_eq!(
        ok(dir, &["time", "show", "1"]),
        "id\tminutes\tdate\tauthor\tnote\n\
         group: all\n\
         scope: issue #1\n\
         state: nothing\n\
         total_minutes: -\n\
         entry_count: 0\n\
         malformed_count: 0\n\
         undated_count: 0\n\
         deleted_count: -\n"
    );
}

#[test]
fn an_edit_that_names_no_field_and_an_edit_with_no_reason_are_both_refused() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(
        dir,
        1,
        "@ada",
        &one_entry("e-one", 30, "2026-01-02", "alice"),
    );
    let before = tree(dir);

    // A reason is what makes a replacement attributable, so an edit without one is
    // refused by the service, by name, before anything is written.
    let (_, _, stderr) = refused(
        dir,
        &["time", "edit", "1", "--entry", "e-one", "--minutes", "45"],
    );
    assert!(stderr.contains("missing_reason"), "{stderr}");
    assert!(stderr.contains("--reason"), "{stderr}");
    assert_eq!(tree(dir), before, "a refusal writes nothing");

    // A reason with no field names nothing to change.
    let (_, _, stderr) = refused(
        dir,
        &["time", "edit", "1", "--entry", "e-one", "--reason", "why"],
    );
    assert!(stderr.contains("empty_edit"), "{stderr}");
    assert_eq!(tree(dir), before, "a refusal writes nothing");

    // An entry the issue does not hold is refused by name, with the id the caller wrote.
    let (_, _, stderr) = refused(
        dir,
        &[
            "time",
            "edit",
            "1",
            "--entry",
            "e-nope",
            "--minutes",
            "45",
            "--reason",
            "why",
        ],
    );
    assert!(stderr.contains("unknown_entry"), "{stderr}");
    assert!(stderr.contains("e-nope"), "{stderr}");
    assert_eq!(tree(dir), before, "a refusal writes nothing");

    // A correction that names the value the entry already carries changes nothing: the
    // service appends no event and writes no file, which is what "exactly one event per
    // applied mutation" means in the other direction too (C-003).
    assert_eq!(
        ok(
            dir,
            &[
                "time",
                "edit",
                "1",
                "--entry",
                "e-one",
                "--minutes",
                "30",
                "--reason",
                "same"
            ]
        ),
        "Unchanged e-one on #1: 30m on 2026-01-02 by alice\n"
    );
    assert_eq!(tree(dir), before, "a no-op correction writes nothing");
}

#[test]
fn a_refused_mutation_leaves_the_tree_byte_identical() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(
        dir,
        1,
        "@ada",
        &one_entry("e-one", 30, "2026-01-02", "alice"),
    );
    let before = tree(dir);

    // C-003/C-004: deleting needs a deliberate word. The refusal says why and what to do.
    let (code, stdout, stderr) = refused(
        dir,
        &[
            "time", "delete", "1", "--entry", "e-one", "--reason", "typo",
        ],
    );
    assert!(stdout.is_empty(), "a refusal prints no result: {stdout:?}");
    assert_eq!(code, 1);
    assert!(stderr.contains("--confirm"), "{stderr}");
    assert!(
        stderr.contains("History"),
        "the remedy names what survives: {stderr}"
    );

    // A confirmed deletion with no reason is refused by the service.
    let (_, _, stderr) = refused(
        dir,
        &["time", "delete", "1", "--entry", "e-one", "--confirm"],
    );
    assert!(stderr.contains("missing_reason"), "{stderr}");

    // A deletion of an entry the issue does not hold is refused by name.
    let (_, _, stderr) = refused(
        dir,
        &[
            "time",
            "delete",
            "1",
            "--entry",
            "e-nope",
            "--reason",
            "typo",
            "--confirm",
        ],
    );
    assert!(stderr.contains("unknown_entry"), "{stderr}");
    assert!(stderr.contains("e-nope"), "{stderr}");

    // A create the shared validator refuses (a negative duration) writes nothing either.
    let (_, _, stderr) = refused(
        dir,
        &["time", "add", "1", "--minutes", "-5", "--author", "alice"],
    );
    assert!(stderr.contains("invalid_duration"), "{stderr}");

    // A date the shared validator refuses, and an identity that names nobody.
    let (_, _, stderr) = refused(
        dir,
        &[
            "time",
            "add",
            "1",
            "--minutes",
            "5",
            "--author",
            "alice",
            "--date",
            "2026-99-99",
        ],
    );
    assert!(stderr.contains("invalid_date"), "{stderr}");
    let (_, _, stderr) = refused(
        dir,
        &["time", "add", "1", "--minutes", "5", "--author", " "],
    );
    assert!(stderr.contains("missing_author"), "{stderr}");

    assert_eq!(tree(dir), before, "every refusal left the tree untouched");

    // The positive control: the same measurement moves when the mutation is applied, so
    // the equality above is not a fixture that can never change.
    let deleted = ok(
        dir,
        &[
            "time",
            "delete",
            "1",
            "--entry",
            "e-one",
            "--reason",
            "wrong issue",
            "--confirm",
        ],
    );
    assert_eq!(
        deleted,
        "Deleted e-one from #1: 30m on 2026-01-02 by alice\n"
    );
    assert_ne!(tree(dir), before);
    // C-004: the value survives in History, after the deletion.
    let deleted_event = one_event(&parsed(dir, 1), HistoryEventKind::TimeEntryDeleted);
    assert!(
        deleted_event.contains("30m on 2026-01-02 by alice"),
        "{deleted_event}"
    );
    assert!(deleted_event.contains("wrong issue"), "{deleted_event}");
}

// ---------------------------------------------------------------------------
// T021 — filters, totals and the breakdown (FR-002, FR-003, C-006, NFR-003)
// ---------------------------------------------------------------------------

#[test]
fn totals_come_from_the_shared_calculation_under_every_filter() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    // Issue #1: one dated entry. Issue #2: one dated and one **undated** entry — the case
    // a period-bounded scope cannot place, so it is counted and never silently dropped.
    write_issue(dir, 1, "@ada", &one_entry("e-a", 30, "2026-09-01", "alice"));
    write_issue(
        dir,
        2,
        "@bob",
        &format!(
            "time_entries:\n{first}{second}",
            first = entry_line("e-b", 45, Some("2026-10-01"), "bob"),
            second = entry_line("e-c", 15, None, "carol"),
        ),
    );

    // FR-002: the whole project's total. Every entry counts, whatever its date: the
    // caller supplied no period, and the surface never resolves a `today` of its own.
    assert_eq!(
        ok(dir, &["time", "total"]),
        "group: all\n\
         scope: all\n\
         state: recorded\n\
         total_minutes: 90\n\
         entry_count: 3\n\
         malformed_count: 0\n\
         undated_count: 0\n\
         deleted_count: -\n"
    );

    // FR-003: an identity filter selects the entries that identity did.
    assert_eq!(
        ok(dir, &["time", "total", "--assignee", "alice"]),
        "group: all\n\
         scope: assignee @alice\n\
         state: recorded\n\
         total_minutes: 30\n\
         entry_count: 1\n\
         malformed_count: 0\n\
         undated_count: 0\n\
         deleted_count: -\n"
    );

    // FR-003/C-005: an inclusive period, and the entry no period can place is reported as
    // undated — its value is real, so it is counted rather than dropped or zeroed.
    assert_eq!(
        ok(
            dir,
            &[
                "time",
                "total",
                "--from",
                "2026-09-01",
                "--to",
                "2026-09-30"
            ]
        ),
        "group: all\n\
         scope: period 2026-09-01..2026-09-30\n\
         state: recorded\n\
         total_minutes: 30\n\
         entry_count: 1\n\
         malformed_count: 0\n\
         undated_count: 1\n\
         deleted_count: -\n"
    );

    // The scope's own total is always printed first, so a breakdown is anchored to the
    // answer it splits; every group carries the shared DTO's own label and numbers.
    assert_eq!(
        ok(dir, &["time", "total", "--by", "issue"]),
        "group: all\n\
         scope: all\n\
         state: recorded\n\
         total_minutes: 90\n\
         entry_count: 3\n\
         malformed_count: 0\n\
         undated_count: 0\n\
         deleted_count: -\n\
         \n\
         group: #1\n\
         scope: all\n\
         state: recorded\n\
         total_minutes: 30\n\
         entry_count: 1\n\
         malformed_count: 0\n\
         undated_count: 0\n\
         deleted_count: -\n\
         \n\
         group: #2\n\
         scope: all\n\
         state: recorded\n\
         total_minutes: 60\n\
         entry_count: 2\n\
         malformed_count: 0\n\
         undated_count: 0\n\
         deleted_count: -\n"
    );

    // A date breakdown puts the undated entry in the DTO's own `(undated)` group.
    let by_date = ok(dir, &["time", "total", "--by", "date"]);
    assert_eq!(
        by_date
            .lines()
            .filter(|line| line.starts_with("group:"))
            .collect::<Vec<&str>>(),
        [
            "group: all",
            "group: 2026-09-01",
            "group: 2026-10-01",
            "group: (undated)"
        ]
    );

    // An identity breakdown groups by the canonical identity, and a filter narrows one
    // issue's total — by its stable number, through `--issue`.
    let by_assignee = ok(dir, &["time", "total", "--by", "assignee"]);
    assert!(
        by_assignee.contains("group: @alice") && by_assignee.contains("group: @bob"),
        "{by_assignee}"
    );
    let scoped = ok(dir, &["time", "total", "--issue", "1", "--by", "all"]);
    assert!(scoped.contains("scope: issue #1"), "{scoped}");
    assert!(scoped.contains("total_minutes: 30"), "{scoped}");
    // `--by all` is the explicit spelling of no breakdown, so there is one block.
    assert_eq!(scoped.matches("group:").count(), 1, "{scoped}");
}

#[test]
fn an_absent_total_is_a_dash_and_never_a_zero() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    // #1 records nothing at all; #2 records a genuine zero; #3 holds only a malformed
    // entry, so it has entries and no usable duration.
    write_issue(dir, 1, "@ada", "time_entries: []\n");
    write_issue(
        dir,
        2,
        "@ada",
        &one_entry("e-zero", 0, "2026-01-02", "alice"),
    );
    write_issue(
        dir,
        3,
        "@ada",
        "time_entries:\n- id: e-bad\n  duration_minutes: -5\n  author: \"alice\"\n",
    );

    // `nothing`: the scope selected no entry. The DTO's state says so, and the number is
    // absent — `-`, the crate's mark for "no value".
    let nothing = ok(dir, &["time", "show", "1"]);
    assert!(nothing.contains("state: nothing"), "{nothing}");
    assert!(nothing.contains("total_minutes: -\n"), "{nothing}");
    assert!(!nothing.contains("total_minutes: 0"), "{nothing}");

    // `unknown`: entries were selected and none carried a usable duration. A different
    // state with the same absent number, and the finding on stderr explains it.
    let (code, unknown, stderr) = run(dir, &["time", "show", "3"]);
    assert_eq!(code, 0, "a partial read is a report, not a failure");
    assert!(unknown.contains("state: unknown"), "{unknown}");
    assert!(unknown.contains("total_minutes: -\n"), "{unknown}");
    assert!(unknown.contains("malformed_count: 1"), "{unknown}");
    // T022: the malformed row is listed with its absent fields as `-`, and its finding
    // names the entry and carries a remedy.
    assert!(unknown.contains("e-bad\t-\t-\talice\t-"), "{unknown}");
    assert!(stderr.contains("warning[E-tix-time]"), "{stderr}");
    assert!(stderr.contains("kind: invalid_duration"), "{stderr}");
    assert!(stderr.contains("entry: e-bad"), "{stderr}");
    assert!(stderr.contains("= help:"), "{stderr}");

    // The positive control: a recorded zero IS a zero — `Some(0)`, not an absent value.
    let recorded = ok(dir, &["time", "show", "2"]);
    assert!(recorded.contains("state: recorded"), "{recorded}");
    assert!(recorded.contains("total_minutes: 0\n"), "{recorded}");
    assert!(
        recorded.contains("e-zero\t0\t2026-01-02\talice\t-"),
        "{recorded}"
    );
}

#[test]
fn a_malformed_entry_is_reported_without_blocking_another_issues_read() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(
        dir,
        1,
        "@ada",
        &one_entry("e-good", 60, "2026-09-05", "alice"),
    );
    write_issue(
        dir,
        2,
        "@bob",
        "time_entries:\n\
         - id: e-bad\n  duration_minutes: -5\n  date: \"not-a-date\"\n  author: \"\"\n",
    );

    // C-005: the unrelated issue reads clean, with nothing on stderr at all.
    let (code, clean, stderr) = run(dir, &["time", "show", "1"]);
    assert_eq!(code, 0);
    assert!(clean.contains("total_minutes: 60"), "{clean}");
    assert!(
        stderr.is_empty(),
        "no finding belongs to a clean issue: {stderr}"
    );

    // The malformed issue's own read reports it and still answers for the rest.
    let (code, malformed, stderr) = run(dir, &["time", "show", "2"]);
    assert_eq!(code, 0);
    assert!(malformed.contains("malformed_count: 1"), "{malformed}");
    assert!(stderr.contains("entry: e-bad"), "{stderr}");

    // And a project-wide total is not blocked by it either: the good entry still sums,
    // the malformed one is counted and excluded, and the finding names its issue.
    let (code, total, stderr) = run(dir, &["time", "total"]);
    assert_eq!(code, 0);
    assert!(total.contains("total_minutes: 60"), "{total}");
    assert!(total.contains("entry_count: 1"), "{total}");
    assert!(total.contains("malformed_count: 1"), "{total}");
    assert!(total.contains("state: recorded"), "{total}");
    assert!(stderr.contains("issue: #2"), "{stderr}");
}

#[test]
fn the_audit_context_is_opt_in_and_never_added_to_the_total() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    // One issue with a current entry **and** a deletion History retains, so the audit
    // count has something to report for an issue the total also draws from (T017).
    let history = "## History\n\n\
        - 2026-01-02T03:04:05Z \u{2014} alice \u{2014} time_entry_deleted \u{2014} \
        entry e-old; deleted 300m on 2026-01-02 by alice\n\n";
    write_issue_with_history(
        dir,
        1,
        "@ada",
        &one_entry("e-a", 30, "2026-09-01", "alice"),
        history,
    );

    // Without `--audit`, the audit context is absent — `-`, not a zero: a count nobody
    // asked for and a count of zero are different facts.
    let plain = ok(dir, &["time", "total"]);
    assert!(plain.contains("scope: all"), "{plain}");
    assert!(plain.contains("deleted_count: -\n"), "{plain}");
    assert!(plain.contains("total_minutes: 30"), "{plain}");

    // With `--audit`, the DTO's own scope label says so and the retained deletion is
    // counted — and the total is unchanged, because the audit context is never added to
    // the sum (the deleted 300m does not appear).
    let audit = ok(dir, &["time", "total", "--audit"]);
    assert!(audit.contains("scope: audit"), "{audit}");
    assert!(audit.contains("deleted_count: 1"), "{audit}");
    assert!(audit.contains("total_minutes: 30"), "{audit}");
    assert!(audit.contains("entry_count: 1"), "{audit}");
    assert!(
        !audit.contains("330"),
        "the deleted value is never summed: {audit}"
    );

    // The per-issue audit view names the deleted entry, its instant and its actor.
    let history = ok(dir, &["time", "history", "1"]);
    assert!(history.contains("deleted_count: 1"), "{history}");
    assert!(
        history.contains("e-old\t2026-01-02T03:04:05Z\talice"),
        "{history}"
    );
    assert!(history.contains("current: 1"), "{history}");
}

#[test]
fn an_archived_issue_is_read_by_name_and_refused_as_a_project_scope() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(dir, 1, "@ada", &one_entry("e-a", 30, "2026-09-01", "alice"));
    write_issue(
        dir,
        7,
        "@ada",
        &one_entry("e-arch", 90, "2026-09-02", "alice"),
    );
    ok(dir, &["archive", "7"]);
    let before = tree(dir);

    // The project scope is the active issues — the family behaviour `tix list`,
    // `tix wip` and `tix capacity` share — so #7's 90m is not in it, and an archived
    // issue is not a finding on a project total either.
    let (code, total, stderr) = run(dir, &["time", "total"]);
    assert_eq!(code, 0, "{stderr}");
    assert!(total.contains("total_minutes: 30"), "{total}");
    assert!(total.contains("entry_count: 1"), "{total}");
    assert!(
        stderr.is_empty(),
        "an archived issue is not a project-total finding: {stderr}"
    );

    // Naming it still reads it: `show` and `history` index the one issue a selector
    // resolves, whatever the project view holds.
    let show = ok(dir, &["time", "show", "7"]);
    assert!(show.contains("e-arch\t90\t2026-09-02\talice\t-"), "{show}");
    assert!(show.contains("state: recorded"), "{show}");
    assert!(show.contains("total_minutes: 90"), "{show}");
    let history = ok(dir, &["time", "history", "7"]);
    assert!(history.contains("current: 1"), "{history}");

    // A project total cannot, and says so with the real condition and a followable
    // remedy — rather than claiming the issue is unknown, whose remedy ("read that issue
    // into the scope") the caller has already followed.
    for args in [
        vec!["time", "total", "7"],
        vec!["time", "total", "--issue", "7"],
    ] {
        let (code, stdout, stderr) = refused(dir, &args);
        assert_eq!(code, 1, "tix {args:?}");
        assert!(stdout.is_empty(), "tix {args:?} printed a total: {stdout}");
        assert!(stderr.starts_with("error[E-tix-time]:"), "{stderr}");
        assert!(stderr.contains("kind: archived_issue"), "{stderr}");
        assert!(stderr.contains("issue: #7"), "{stderr}");
        assert!(stderr.contains("is archived"), "{stderr}");
        assert!(stderr.contains("`tix time show 7`"), "{stderr}");
        assert!(stderr.contains("`tix time history 7`"), "{stderr}");
    }

    // A number no issue answers to keeps the *aggregation's* own finding: this surface
    // only names the archived case it can see.
    let (code, _, stderr) = refused(dir, &["time", "total", "--issue", "404"]);
    assert_eq!(code, 1, "{stderr}");
    assert!(stderr.contains("kind: unknown_issue"), "{stderr}");

    assert_eq!(tree(dir), before, "the refusals wrote nothing");
}

#[test]
fn deleting_a_malformed_entry_prints_the_surfaces_absent_mark() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(
        dir,
        3,
        "@ada",
        "time_entries:\n- id: e-bad\n  duration_minutes: -5\n  author: \"\"\n",
    );

    // C-005: an entry the validator refuses is still removable — refusing the removal
    // would strand it — and the line it prints uses this surface's absent mark, never the
    // History detail's `?m`/`by ?` marks.
    let deleted = ok(
        dir,
        &[
            "time",
            "delete",
            "3",
            "--entry",
            "e-bad",
            "--reason",
            "malformed",
            "--confirm",
        ],
    );
    assert_eq!(deleted, "Deleted e-bad from #3: - on - by -\n");
    assert!(!deleted.contains("?m"), "{deleted}");
    assert!(!deleted.contains("by ?"), "{deleted}");

    // The removal is real, and History keeps the evidence of what was removed.
    let issue = parsed(dir, 3);
    assert!(
        issue.time_entries.is_empty(),
        "the malformed entry left the projection"
    );
    assert_eq!(time_events(&issue).len(), 1, "one deletion event");

    // The same mark on a *valid* undated entry: one shape, whatever the file holds.
    let added = ok(
        dir,
        &["time", "add", "3", "--minutes", "10", "--author", "alice"],
    );
    assert_eq!(
        added,
        format!("Added {} to #3: 10m on - by alice\n", added_id(&added))
    );
}

// ---------------------------------------------------------------------------
// Refusals: a non-zero exit with a reason and a remedy, and nothing written
// ---------------------------------------------------------------------------

#[test]
fn a_refused_scope_says_what_is_wrong_and_what_to_do_and_writes_nothing() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(dir, 1, "@ada", &one_entry("e-a", 30, "2026-09-01", "alice"));
    let before = tree(dir);

    // A bound that is not a calendar date, an inverted period, an identity that names
    // nobody and an issue the snapshot does not hold: four scope refusals, each rendered
    // through the shared finding's remedy table, at **error** severity (the level must
    // agree with the exit code), with no half-total on stdout.
    let cases: [(&[&str], &str, &str); 4] = [
        (
            &["time", "total", "--from", "2026-30-01"],
            "invalid_date",
            "is not a `YYYY-MM-DD` calendar date",
        ),
        (
            &[
                "time",
                "total",
                "--from",
                "2026-10-01",
                "--to",
                "2026-09-01",
            ],
            "invalid_period",
            "the period holds no date",
        ),
        (
            &["time", "total", "--assignee", " "],
            "invalid_assignee",
            "names no identity",
        ),
        (
            &["time", "total", "--issue", "99"],
            "unknown_issue",
            "is not among the issues this snapshot holds",
        ),
    ];
    for (args, kind, reason) in cases {
        let (code, stdout, stderr) = refused(dir, args);
        assert_eq!(code, 1, "tix {args:?} should exit 1");
        assert!(
            stdout.is_empty(),
            "tix {args:?} printed a total before refusing:\n{stdout}"
        );
        assert!(
            stderr.starts_with("error[E-tix-time]:"),
            "tix {args:?} should render an error block:\n{stderr}"
        );
        assert!(stderr.contains(&format!("kind: {kind}")), "{stderr}");
        assert!(
            stderr.contains(reason),
            "the shared reason is the headline:\n{stderr}"
        );
        assert!(
            stderr.contains("= help:"),
            "the remedy is the help footer:\n{stderr}"
        );
    }

    // A dimension outside the vocabulary, and one issue named two ways, are this
    // surface's own refusals: both name the alternatives.
    let (_, stdout, stderr) = refused(dir, &["time", "total", "--by", "sprint"]);
    assert!(stdout.is_empty(), "{stdout:?}");
    assert!(stderr.contains("unknown --by dimension"), "{stderr}");
    assert!(
        stderr.contains("`issue`, `assignee` and `date`"),
        "{stderr}"
    );
    let (_, stdout, stderr) = refused(dir, &["time", "total", "1", "--issue", "2"]);
    assert!(stdout.is_empty(), "{stdout:?}");
    assert!(stderr.contains("names its issue once"), "{stderr}");

    // An issue selector that resolves to nothing is the crate's own not-found (exit 2).
    let (code, _, stderr) = refused(dir, &["time", "show", "99"]);
    assert_eq!(code, 2, "{stderr}");
    assert!(stderr.contains("issue #99"), "{stderr}");

    assert_eq!(tree(dir), before, "no refused scope wrote anything");
}

// ---------------------------------------------------------------------------
// C-001/C-008 — the reads, and the commands that were already there
// ---------------------------------------------------------------------------

#[test]
fn every_time_read_writes_nothing_and_leaves_the_other_commands_alone() {
    let (_tmp, dir) = project();
    let dir = dir.as_path();
    write_issue(dir, 1, "@ada", &one_entry("e-a", 30, "2026-09-01", "alice"));
    write_issue(dir, 2, "@bob", &one_entry("e-b", 45, "2026-10-01", "bob"));

    let before = tree(dir);
    for args in [
        vec!["time", "show", "1"],
        vec!["time", "history", "1"],
        vec!["time", "total"],
        vec!["time", "total", "--by", "assignee"],
        vec!["time", "total", "--audit"],
        vec!["time", "total", "2"],
        vec!["list", "--all"],
        vec!["view", "1"],
        vec!["status"],
    ] {
        ok(dir, &args);
        assert_eq!(tree(dir), before, "tix {args:?} wrote something");
    }

    // C-008: a time mutation changes the current entries and History and nothing else —
    // not status, ownership, estimate, title or body.
    ok(
        dir,
        &["time", "add", "1", "--minutes", "10", "--author", "alice"],
    );
    let issue = parsed(dir, 1);
    assert!(issue.status.is("in progress"));
    assert_eq!(issue.assignee.as_deref(), Some("ada"));
    assert_eq!(issue.estimate.as_deref(), Some("3d"));
    assert_eq!(issue.title, "Issue 1");
    assert!(issue.body.contains("Body prose that must survive."));

    // The existing surfaces still see the issue — with its time data present.
    // `--all`: the default listing is scoped to your issues in the board's entry
    // column (#1711).
    let list = ok(dir, &["list", "--all"]);
    assert!(
        list.contains("Issue 1") && list.contains("Issue 2"),
        "{list}"
    );
    let view = ok(dir, &["view", "1"]);
    assert!(view.contains("Issue 1"), "{view}");

    // And a read after the write reports the new value — the `total` figure is the shared
    // calculation's, in the shape every block of this surface prints.
    let total = ok(dir, &["time", "total"]);
    assert!(total.contains("total_minutes: 85"), "{total}");
    assert!(total.contains("entry_count: 3"), "{total}");
    assert_eq!(
        keys(&total),
        [
            "group",
            "scope",
            "state",
            "total_minutes",
            "entry_count",
            "malformed_count",
            "undated_count",
            "deleted_count"
        ]
    );
}