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
//! WP05 — the `tix analytics` CLI surface (mission `burndown-scope-analytics-01M3C9J1`,
//! T024–T028).
//!
//! Driven through the **compiled binary**, like `tests/cli.rs` and `tests/capacity_cli.rs`:
//! the fold, the unit conversion, the projection and the chart document each have their
//! own target (`analytics_series`, `analytics_projection`, `analytics_chart`). This file is
//! the *surface* half — that the CLI routes to those services, that the values it prints
//! are the DTOs' own, that a value the record cannot support is a `-` and never a zero,
//! that a request the record cannot answer is refused non-zero with a reason and a remedy,
//! and that a read writes nothing.
//!
//! Every negative claim carries a positive control beside it: the refusal for an
//! undeclared unit sits next to the declared unit that reports values; the `-` on an
//! unobserved day sits next to the observed day that reports a real `0`; the out-of-period
//! edit that the closed series must ignore sits next to the in-period edit it counts.
//!
//! TTY-free, network-free, clock-free: every project is a `TempDir`, no case reads an
//! environment variable or the current time, and every date in the fixtures is explicit.
//!
//! Requirement ids in the test names / comments: FR-001…FR-005, NFR-002, NFR-003, C-001,
//! C-003, C-004, C-005, C-006, C-007, C-008.

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

use assert_cmd::Command;
use serde_json::Value;
use tempfile::TempDir;

use tix::analytics::events::cycle_scope;
use tix::analytics::series::Mode;
use tix::commands::export::chart_document;
use tix::config::Config;
use tix::model::{History, HistoryEvent, HistoryEventKind};
use tix::planning::Planner;
use tix::storage::Store;

fn tix() -> Command {
    Command::cargo_bin("tix").unwrap()
}

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

/// The fixture project's `tix.toml`: a board declaring two estimate units (`points`, the
/// base, and `hours`, worth five points each), a **closed** cycle with both bounds, and an
/// **open** cycle with no planning end date.
const CONFIG: &str = "issues_dir = \"{issues}\"\n\n\
    [kanban.default]\ncolumns = [\"todo\", \"doing\", \"done\"]\n\n\
    [kanban.default.wip.units]\npoints = 1\nhours = 5\n\n\
    [cycles.\"Sprint 7\"]\nstart_date = \"2026-01-05\"\ndue_date = \"2026-01-09\"\n\n\
    [cycles.\"Open Cycle\"]\nstart_date = \"2026-01-05\"\n";

/// A project directory holding the fixture configuration and its issues directory.
fn project() -> (TempDir, PathBuf) {
    let dir = TempDir::new().unwrap();
    let issues = dir.path().join("issues");
    fs::create_dir_all(&issues).unwrap();
    fs::write(
        dir.path().join("tix.toml"),
        CONFIG.replace("{issues}", &issues.to_string_lossy()),
    )
    .unwrap();
    (dir, issues)
}

/// The same project with a remote GitLab target configured — the one thing a chart
/// document cannot be mapped onto (T027's "remote semantics stay diagnostic").
fn project_with_remote() -> (TempDir, PathBuf) {
    let dir = TempDir::new().unwrap();
    let issues = dir.path().join("issues");
    fs::create_dir_all(&issues).unwrap();
    fs::write(
        dir.path().join("tix.toml"),
        format!(
            "{}\n[export.gitlab]\nproject = \"acme/tix\"\n",
            CONFIG.replace("{issues}", &issues.to_string_lossy())
        ),
    )
    .unwrap();
    (dir, issues)
}

/// One recorded History event.
fn recorded(timestamp: &str, kind: HistoryEventKind, detail: &str) -> HistoryEvent {
    HistoryEvent::new(timestamp, "alice", kind, detail)
}

/// A scope addition: the recorded `parent_set` kind, which carries delta `1`.
fn addition(timestamp: &str) -> HistoryEvent {
    recorded(timestamp, HistoryEventKind::ParentSet, "parent none -> #1")
}

/// A completion: a recorded transition whose recorded category is `completed`.
fn completion(timestamp: &str) -> HistoryEvent {
    recorded(
        timestamp,
        HistoryEventKind::TransitionAccepted,
        "todo -> shipped (unstarted -> completed)",
    )
}

/// An issue file's text — minimum frontmatter plus the History section, rendered by the
/// model's own renderer so the fixture cannot disagree with the parser.
fn issue_markdown(number: u32, estimate: Option<&str>, events: &[HistoryEvent]) -> String {
    let mut frontmatter = format!(
        "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"todo\"\nlabels: []\n\
         cycles:\n  - Sprint 7\n"
    );
    if let Some(estimate) = estimate {
        frontmatter.push_str(&format!("estimate: \"{estimate}\"\n"));
    }
    frontmatter.push_str("---\n");

    let mut history = History::new();
    for event in events {
        history.append(event.clone());
    }
    format!("{frontmatter}{}", history.render())
}

/// The fixture's two member issues: issue 1 is added on the 5th and completed on the 7th,
/// issue 2 is added on the 6th and edited again **after** the period's end — the edit a
/// closed series must ignore (C-006).
fn write_fixture(issues: &Path) {
    fs::write(
        issues.join("2026-01-01-issue-1.md"),
        issue_markdown(
            1,
            Some("3points"),
            &[
                addition("2026-01-05T09:00:00Z"),
                completion("2026-01-07T09:00:00Z"),
            ],
        ),
    )
    .unwrap();
    fs::write(
        issues.join("2026-01-01-issue-2.md"),
        issue_markdown(
            2,
            Some("2points"),
            &[
                addition("2026-01-06T09:00:00Z"),
                addition("2026-02-10T09:00:00Z"),
            ],
        ),
    )
    .unwrap();
}

/// Run `tix <args>`, asserting success, and return stdout.
fn stdout(dir: &Path, args: &[&str]) -> String {
    let out = tix()
        .current_dir(dir)
        .args(args)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    String::from_utf8(out).unwrap()
}

/// Run `tix <args>` and return `(exit_code, stdout, stderr)` without asserting a status — a
/// report can exit `0` and still print findings to stderr.
fn run(dir: &Path, args: &[&str]) -> (i32, String, String) {
    let out = tix()
        .current_dir(dir)
        .args(args)
        .assert()
        .get_output()
        .clone();
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8(out.stdout).unwrap(),
        String::from_utf8(out.stderr).unwrap(),
    )
}

/// Run `tix <args>` expecting failure: `(exit_code, stdout, stderr)`.
fn refused(dir: &Path, args: &[&str]) -> (i32, String, String) {
    let out = tix()
        .current_dir(dir)
        .args(args)
        .assert()
        .failure()
        .get_output()
        .clone();
    (
        out.status.code().unwrap_or(-1),
        String::from_utf8(out.stdout).unwrap(),
        String::from_utf8(out.stderr).unwrap(),
    )
}

/// The one stdout line starting with `prefix`.
fn line<'a>(text: &'a str, prefix: &str) -> &'a str {
    text.lines()
        .find(|line| line.starts_with(prefix))
        .unwrap_or_else(|| panic!("no `{prefix}` line in:\n{text}"))
}

/// The burndown table's row for `date`.
fn row<'a>(table: &'a str, date: &str) -> &'a str {
    line(table, date)
}

/// One tab-separated cell of a table row.
fn cell(row: &str, index: usize) -> &str {
    row.split('\t')
        .nth(index)
        .unwrap_or_else(|| panic!("row `{row}` has no cell {index}"))
}

/// Every file under `root`, with its bytes — the read-only claim's evidence.
fn tree(root: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
    let mut files = BTreeMap::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        for entry in fs::read_dir(&dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                stack.push(path);
            } else {
                files.insert(path.clone(), fs::read(&path).unwrap());
            }
        }
    }
    files
}

/// The fixture's store, for the parity assertions that compare the CLI's bytes with the
/// core's.
fn store_of(issues: &Path, config: &Config) -> Store {
    Store {
        issues_dir: issues.to_path_buf(),
        config: config.clone(),
    }
}

/// The configured, resolved scope for the fixture's closed cycle.
fn sprint_scope(config: &Config, root: &Path) -> tix::analytics::events::AnalyticsScope {
    let planner = Planner::from_config(config.clone(), root.to_path_buf());
    cycle_scope(&planner, "Sprint 7").expect("the fixture declares the cycle")
}

// ---------------------------------------------------------------------------
// T024/T025 — the report is explicit: scope, period, mode, unit, coverage, findings
// ---------------------------------------------------------------------------

/// FR-001/FR-002/FR-005, NFR-002, C-005: the count-mode report names its scope, period,
/// mode, unit, formula version and coverage tally, and every daily row is the fold's own
/// value — with the unobserved days coverage-limited and their deltas `-`, never `0`.
///
/// The control on the `-` is the observed day beside it, whose `0` **is** a known zero
/// because the day was read.
#[test]
fn t025_count_report_is_explicit_and_an_unanswerable_value_is_a_dash() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
        ],
    );
    assert_eq!(code, 0, "a readable series is a report: {err}");

    // The scope, period, mode, unit and formula are all on stdout (NFR-002).
    assert_eq!(line(&out, "scope:"), "scope: cycle");
    assert_eq!(line(&out, "id:"), "id: Sprint 7");
    assert_eq!(line(&out, "period:"), "period: 2026-01-05..2026-01-09");
    assert_eq!(
        line(&out, "snapshot:"),
        "snapshot: -",
        "this build has no CLI flag that binds a snapshot, and an unbound scope says so"
    );
    assert_eq!(line(&out, "mode:"), "mode: count");
    assert_eq!(line(&out, "unit:"), "unit: -", "count mode is unitless");
    assert_eq!(line(&out, "formula:"), "formula: burndown.count.v1");
    assert_eq!(line(&out, "days:"), "days: 5");
    assert_eq!(
        line(&out, "coverage:"),
        "coverage: known=3 unknown=0 coverage_limited=2"
    );
    assert_eq!(line(&out, "diagnostics:"), "diagnostics: 1");
    assert!(
        out.contains("date\tscope_total\tremaining\tcompleted\tscope_added\tcompletions\tcoverage"),
        "the table header names every column:\n{out}"
    );

    // The observed days: the fold's own levels, additions and completions.
    let added = row(&out, "2026-01-05");
    assert_eq!(
        [
            cell(added, 1),
            cell(added, 2),
            cell(added, 3),
            cell(added, 4),
            cell(added, 5),
            cell(added, 6)
        ],
        ["1", "1", "0", "1", "0", "known"]
    );
    let second = row(&out, "2026-01-06");
    assert_eq!(
        [cell(second, 1), cell(second, 2), cell(second, 4)],
        ["2", "2", "1"]
    );
    let completed = row(&out, "2026-01-07");
    assert_eq!(
        [
            cell(completed, 1),
            cell(completed, 2),
            cell(completed, 3),
            cell(completed, 4),
            cell(completed, 5)
        ],
        ["2", "1", "1", "0", "1"],
        "scope additions and completions are separate fields (FR-002)"
    );

    // The gap: the levels carry forward, the deltas are `-`, and the coverage says why.
    for date in ["2026-01-08", "2026-01-09"] {
        let point = row(&out, date);
        assert_eq!(
            [
                cell(point, 1),
                cell(point, 2),
                cell(point, 3),
                cell(point, 4),
                cell(point, 5),
                cell(point, 6)
            ],
            ["2", "1", "1", "-", "-", "coverage_limited"],
            "{date} was not observed, so its deltas are unknown — never zero"
        );
    }

    // The finding itself is rendered to stderr, with its kind, its span and its remedy.
    assert!(
        err.contains("missing_history"),
        "the gap is named machine-readably:\n{err}"
    );
    assert!(
        err.contains("2026-01-08..2026-01-09"),
        "the gap names the days it covers:\n{err}"
    );
    assert!(
        err.contains("help:"),
        "a finding carries its remedy:\n{err}"
    );

    // C-006: the edit recorded after the period's end is not a contribution to it.
    assert_eq!(
        cell(row(&out, "2026-01-09"), 1),
        "2",
        "the issue added on 2026-02-10 does not reach the closed period"
    );
}

/// C-005: `--from`/`--to` replace the planning bound they name, which is exactly the
/// advice the shared findings give. A day the wider period *anchors* but did not observe
/// carries a **known** level (`0` — the level is known) beside **unknown** deltas (`-`),
/// which is the distinction a bare zero would erase.
#[test]
fn t024_the_period_flags_widen_the_series() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--from",
            "2026-01-01",
            "--to",
            "2026-01-11",
        ],
    );
    assert_eq!(code, 0, "{err}");
    assert_eq!(line(&out, "period:"), "period: 2026-01-01..2026-01-11");
    assert_eq!(line(&out, "days:"), "days: 11");
    assert_eq!(
        line(&out, "coverage:"),
        "coverage: known=3 unknown=0 coverage_limited=8"
    );
    assert_eq!(
        line(&out, "diagnostics:"),
        "diagnostics: 2",
        "one gap before the first recorded event and one after the last"
    );
    let anchored = row(&out, "2026-01-01");
    assert_eq!(
        [
            cell(anchored, 1),
            cell(anchored, 2),
            cell(anchored, 3),
            cell(anchored, 4),
            cell(anchored, 5)
        ],
        ["0", "0", "0", "-", "-"],
        "an anchored level is a real zero; the day's own deltas are unknown"
    );
}

/// C-003/FR-003: estimate mode counts through the project's declared conversion, and each
/// day carries the unit the values are in. The control beside it is the same mode with no
/// `--unit`, and with a unit the project declares no conversion for: both are refused,
/// non-zero, naming the reason and the remedy — never folded as a count.
#[test]
fn t025_estimate_mode_uses_the_declared_unit_and_refuses_a_missing_one() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "estimate",
            "--unit",
            "points",
        ],
    );
    assert_eq!(code, 0, "a declared unit is a report: {err}");
    assert_eq!(line(&out, "mode:"), "mode: estimate");
    assert_eq!(line(&out, "unit:"), "unit: points");
    assert_eq!(line(&out, "formula:"), "formula: burndown.estimate.v1");
    assert_eq!(
        [
            cell(row(&out, "2026-01-06"), 1),
            cell(row(&out, "2026-01-06"), 4)
        ],
        ["5", "2"],
        "3 points + 2 points on the 6th"
    );
    assert_eq!(
        [
            cell(row(&out, "2026-01-07"), 3),
            cell(row(&out, "2026-01-07"), 5)
        ],
        ["3", "3"],
        "issue 1's three points completed"
    );

    // No `--unit`: the shared `missing_conversion` kind and its own remedy.
    let (code, out, err) = refused(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "estimate",
        ],
    );
    assert_eq!(code, 1, "an unconvertible valuation is refused");
    assert!(out.is_empty(), "a refusal prints no report: {out}");
    assert!(err.contains("missing_conversion"), "stderr:\n{err}");
    assert!(
        err.contains("estimate mode needs an explicit unit conversion"),
        "the reason:\n{err}"
    );
    assert!(
        err.contains("help:") && err.contains("declare the unit under"),
        "the shared remedy:\n{err}"
    );

    // A unit the project declares no conversion for: the fold answers no day, so the
    // report refuses with the same kind rather than inventing a total.
    let (code, out, err) = refused(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "estimate",
            "--unit",
            "fortnights",
        ],
    );
    assert_eq!(code, 1);
    assert!(out.is_empty());
    assert!(err.contains("missing_conversion"), "stderr:\n{err}");

    // Count mode ignores the unit, exactly as the shared document does.
    let (code, out, _) = run(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "count",
            "--unit",
            "points",
        ],
    );
    assert_eq!(code, 0);
    assert_eq!(line(&out, "unit:"), "unit: -");
}

/// C-005/C-004: an open scope with nothing recorded is refused by name rather than
/// reported as an empty series, and the vocabulary it uses is the fold's own.
#[test]
fn t025_an_unenumerable_period_is_refused_with_its_remedy() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, out, err) = refused(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Open Cycle",
        ],
    );
    assert_eq!(code, 1);
    assert!(out.is_empty(), "there is no report to print: {out}");
    assert!(err.contains("invalid_period"), "stderr:\n{err}");
    assert!(
        err.contains("has no bound and the scope records no dated event"),
        "the fold's own reason:\n{err}"
    );
    assert!(err.contains("help:"), "and its remedy:\n{err}");
}

// ---------------------------------------------------------------------------
// T026 — the projection report
// ---------------------------------------------------------------------------

/// FR-004/C-004: the forecast is drawn against the scope's own planning end date, at the
/// caller's `--as-of`, and carries the projection's documented formula version and every
/// value the DTO derived.
#[test]
fn t026_a_projected_forecast_states_its_rate_dates_and_status() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "projection",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--as-of",
            "2026-01-09",
        ],
    );
    assert_eq!(code, 0, "a forecast is an answer: {err}");
    assert_eq!(line(&out, "formula:"), "formula: burndown.projection.v1");
    assert_eq!(line(&out, "as_of:"), "as_of: 2026-01-09");
    assert_eq!(
        line(&out, "end_date:"),
        "end_date: 2026-01-09",
        "the planning end date is the cycle's own"
    );
    assert_eq!(line(&out, "status:"), "status: projected");
    assert_eq!(line(&out, "remaining:"), "remaining: 1");
    assert_eq!(line(&out, "observed_rate:"), "observed_rate: 0.25");
    assert_eq!(
        line(&out, "projected_completion:"),
        "projected_completion: 2026-01-13"
    );
    assert_eq!(
        line(&out, "meets_end_date:"),
        "meets_end_date: false",
        "a forecast past the planning end is stated, not softened"
    );
}

/// C-004/C-005: an unanswerable forecast is an **answer** — its status and a `-` for every
/// value it could not derive — and it exits zero, because the record was asked and said so.
/// The control beside each case is the projected forecast above.
#[test]
fn t026_an_unanswerable_forecast_states_unknown_and_never_invents_a_date() {
    let (dir, issues) = project();
    write_fixture(&issues);

    // (1) An origin the series does not cover.
    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "projection",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--as-of",
            "2026-02-01",
        ],
    );
    assert_eq!(code, 0, "the status is the answer: {err}");
    assert_eq!(line(&out, "status:"), "status: insufficient_data");
    assert_eq!(
        line(&out, "projected_completion:"),
        "projected_completion: -"
    );
    assert_eq!(line(&out, "meets_end_date:"), "meets_end_date: -");
    assert_eq!(line(&out, "remaining:"), "remaining: -");
    assert!(
        err.contains("projection_unknown") && err.contains("help:"),
        "the status is explained with a remedy:\n{err}"
    );

    // (2) A window whose period records no completion at all: the levels answer, the rate
    // does not, so the status is `unknown` and the date stays `-`.
    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "projection",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--to",
            "2026-01-06",
            "--as-of",
            "2026-01-06",
        ],
    );
    assert_eq!(code, 0, "{err}");
    assert_eq!(line(&out, "end_date:"), "end_date: 2026-01-06");
    assert_eq!(line(&out, "status:"), "status: unknown");
    assert_eq!(line(&out, "remaining:"), "remaining: 2");
    assert_eq!(line(&out, "observed_rate:"), "observed_rate: 0");
    assert_eq!(
        line(&out, "projected_completion:"),
        "projected_completion: -"
    );
    assert!(err.contains("projection_unknown"), "stderr:\n{err}");
}

/// C-004: a forecast needs a planning end to be drawn against. A scope that declares none
/// is refused with the reason and the flag that resolves it, and a malformed `--as-of` is
/// refused in the shared period vocabulary.
#[test]
fn t026_a_forecast_without_a_planning_end_is_refused_with_the_flag_that_helps() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, out, err) = refused(
        dir.path(),
        &[
            "analytics",
            "projection",
            "--scope",
            "cycle",
            "--id",
            "Open Cycle",
            "--as-of",
            "2026-01-06",
        ],
    );
    assert_eq!(code, 1);
    assert!(out.is_empty(), "no report was produced: {out}");
    assert!(
        err.contains("declares no planning end date"),
        "the reason:\n{err}"
    );
    assert!(
        err.contains("--to") && err.contains("help:"),
        "the remedy names the flag that resolves it:\n{err}"
    );

    let (code, _, err) = refused(
        dir.path(),
        &[
            "analytics",
            "projection",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--as-of",
            "2026-1-9",
        ],
    );
    assert_eq!(code, 1);
    assert!(err.contains("invalid_period"), "stderr:\n{err}");
    assert!(err.contains("YYYY-MM-DD"), "the remedy:\n{err}");
}

// ---------------------------------------------------------------------------
// T024/T027 — argument vocabulary and the export verb
// ---------------------------------------------------------------------------

/// C-008: the scope kind and the mode are closed vocabularies. A word outside either is
/// refused by name, listing the words that exist, instead of being guessed at.
#[test]
fn t024_an_unknown_scope_or_mode_word_is_refused_by_name() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let (code, _, err) = refused(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "epic",
            "--id",
            "Sprint 7",
        ],
    );
    assert_eq!(code, 1);
    assert!(err.contains("unknown --scope"), "stderr:\n{err}");
    assert!(
        err.contains("`cycle`") && err.contains("`milestone`"),
        "{err}"
    );

    let (code, _, err) = refused(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "bananas",
        ],
    );
    assert_eq!(code, 1);
    assert!(err.contains("unknown --mode"), "stderr:\n{err}");
    assert!(
        err.contains("`count`") && err.contains("`estimate`"),
        "{err}"
    );
}

/// FR-005, NFR-002, C-007: the export verb emits WP04's document — every piece of metadata
/// the contract requires — and asking twice for the same scope produces the same bytes.
#[test]
fn t027_export_emits_the_versioned_document_and_is_deterministic() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let args = [
        "analytics",
        "export",
        "--scope",
        "cycle",
        "--id",
        "Sprint 7",
        "--mode",
        "count",
    ];
    let first = stdout(dir.path(), &args);
    let second = stdout(dir.path(), &args);
    assert_eq!(first, second, "the same input produces the same bytes");

    let json: Value = serde_json::from_str(&first).expect("the export is JSON");
    assert_eq!(json["format"], "tix-chart");
    assert_eq!(json["schema_version"], 1);
    assert_eq!(json["scope"]["kind"], "cycle");
    assert_eq!(json["scope"]["id"], "Sprint 7");
    assert_eq!(json["scope"]["period"]["start"], "2026-01-05");
    assert_eq!(json["scope"]["period"]["end"], "2026-01-09");
    assert!(json["scope"]["snapshot_id"].is_null());
    assert_eq!(json["mode"], "count");
    assert!(json["unit"].is_null(), "count mode is unitless");
    assert_eq!(json["precision"], "whole_issues");
    assert_eq!(json["formula_version"], "burndown.count.v1");
    assert_eq!(json["coverage"]["known"], 3);
    assert_eq!(json["coverage"]["coverage_limited"], 2);
    assert!(
        json["diagnostics"].is_array() && json["projection"].is_null(),
        "no forecast was asked for"
    );

    // The points are the same fold the burndown report printed — null, not 0, where the
    // record cannot answer.
    assert_eq!(json["series"]["points"].as_array().unwrap().len(), 5);
    assert_eq!(json["series"]["points"][3]["scope_added"], Value::Null);
    assert_eq!(json["series"]["points"][3]["coverage"], "coverage_limited");
    assert_eq!(json["series"]["points"][2]["completions"], 1);
}

/// T027/H9: the verb writes exactly the bytes WP04's core produces. The file at `--output`
/// and the document `chart_document` returns are compared byte for byte, and the same run
/// without `--output` prints the same bytes to stdout.
#[test]
fn t027_the_output_file_is_byte_identical_to_the_core_document() {
    let (dir, issues) = project();
    write_fixture(&issues);
    let config = Config::load(dir.path()).expect("the fixture loads");
    let store = store_of(&issues, &config);
    let scope = sprint_scope(&config, dir.path());

    // The core's document, the CLI's stdout, and the CLI's file: one set of bytes.
    for (mode, unit, forecast) in [
        (Mode::Count, None, None),
        (Mode::Estimate, Some("points"), None),
        (Mode::Count, None, Some(("2026-01-09", "2026-01-09"))),
    ] {
        let expected = chart_document(&config, &store, &scope, mode, unit, forecast)
            .expect("the core builds the document")
            .to_json_pretty()
            .unwrap();

        let mut args = vec![
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            mode.as_str(),
        ];
        if let Some(unit) = unit {
            args.extend(["--unit", unit]);
        }
        if let Some((as_of, _)) = forecast {
            args.extend(["--as-of", as_of]);
        }
        assert_eq!(
            stdout(dir.path(), &args),
            expected,
            "the CLI prints the core's bytes for {mode} {unit:?}"
        );

        let out = dir.path().join(format!(
            "chart-{}-{}.json",
            mode.as_str(),
            unit.unwrap_or("none")
        ));
        let mut args = args.clone();
        args.extend(["--output", out.to_str().unwrap()]);
        let printed = stdout(dir.path(), &args);
        assert_eq!(
            printed.trim_end(),
            out.to_str().unwrap(),
            "`--output` prints the path it wrote"
        );
        assert_eq!(
            fs::read_to_string(&out).unwrap(),
            expected,
            "`--output` writes the core's bytes for {mode} {unit:?}"
        );
        fs::remove_file(&out).unwrap();
    }
}

/// C-007/T027: the export carries a forecast when the caller asks for one, through the
/// same projection verb's core — and requires an explicit `--mode`, because the document
/// states the mode it was folded in.
#[test]
fn t027_export_carries_a_forecast_and_requires_its_mode() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let out = stdout(
        dir.path(),
        &[
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "count",
            "--as-of",
            "2026-01-09",
        ],
    );
    let json: Value = serde_json::from_str(&out).unwrap();
    assert_eq!(json["projection"]["status"], "projected");
    assert_eq!(json["projection"]["projected_completion"], "2026-01-13");
    assert_eq!(
        json["projection"]["formula_version"],
        "burndown.projection.v1"
    );
    assert_eq!(json["projection"]["end_date"], "2026-01-09");

    let estimated = stdout(
        dir.path(),
        &[
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "estimate",
            "--unit",
            "points",
        ],
    );
    let json: Value = serde_json::from_str(&estimated).unwrap();
    assert_eq!(json["mode"], "estimate");
    assert_eq!(json["unit"], "points");
    assert_eq!(json["precision"], "whole_units");
    assert_eq!(json["formula_version"], "burndown.estimate.v1");

    let (code, out, err) = refused(
        dir.path(),
        &[
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
        ],
    );
    assert_eq!(code, 1);
    assert!(out.is_empty(), "no document was produced: {out}");
    assert!(err.contains("`--mode`"), "the reason:\n{err}");
    assert!(
        err.contains("help:") && err.contains("--mode count"),
        "the remedy:\n{err}"
    );
}

/// C-007/H9: the export is a **document**, not a report. A request whose fold answers no
/// day still exports — with the finding in-band and a zero-day series — because a document
/// that says why it holds no day is one a script can store; `burndown` refuses the same
/// request, because there is no report to print. The two behaviours are pinned together so
/// neither can drift into the other.
#[test]
fn t027_an_export_of_an_unanswerable_fold_still_emits_its_document() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let args = [
        "analytics",
        "export",
        "--scope",
        "cycle",
        "--id",
        "Sprint 7",
        "--mode",
        "estimate",
        "--unit",
        "fortnights",
    ];
    let (code, out, err) = run(dir.path(), &args);
    assert_eq!(code, 0, "the document is still produced: {err}");
    let json: Value = serde_json::from_str(&out).expect("the export is JSON");
    assert_eq!(json["format"], "tix-chart");
    assert_eq!(json["unit"], "fortnights");
    assert_eq!(
        json["series"]["points"].as_array().unwrap().len(),
        0,
        "no day was folded"
    );
    assert_eq!(json["coverage"]["known"], 0);
    assert_eq!(
        json["series"]["diagnostics"][0]["kind"], "missing_conversion",
        "the document carries why there is no day:\n{out}"
    );

    // The control: the report verb refuses the same request.
    let (code, _, err) = refused(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "estimate",
            "--unit",
            "fortnights",
        ],
    );
    assert_eq!(code, 1, "there is no report to print: {err}");
    assert!(err.contains("missing_conversion"), "stderr:\n{err}");
}

/// C-001/T027: a configured remote target is a **diagnostic**, not a mapping. The local
/// document is still produced — no remote tool is invoked, which is what the exit code
/// proves — and the finding names the target and promises the values stay local.
#[test]
fn t027_a_configured_remote_target_is_diagnosed_and_the_values_stay_local() {
    let (dir, issues) = project_with_remote();
    write_fixture(&issues);

    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "count",
        ],
    );
    assert_eq!(
        code, 0,
        "the local document never invokes the remote tool: {err}"
    );
    let json: Value = serde_json::from_str(&out).unwrap();
    assert_eq!(json["format"], "tix-chart");
    let findings = json["diagnostics"].as_array().unwrap();
    assert_eq!(
        findings.len(),
        1,
        "one finding per configured target:\n{out}"
    );
    assert_eq!(findings[0]["kind"], "unsupported_remote_field");
    assert_eq!(findings[0]["target"], "gitlab");
    assert_eq!(
        json["series"]["points"].as_array().unwrap().len(),
        5,
        "every day stays in the local document"
    );

    // The report counts the document's own finding and renders it to stderr, beside the
    // fold's own gap finding.
    let (code, out, err) = run(
        dir.path(),
        &[
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
        ],
    );
    assert_eq!(code, 0);
    assert_eq!(
        line(&out, "diagnostics:"),
        "diagnostics: 2",
        "the fold's gap and the remote finding"
    );
    assert!(
        err.contains("unsupported_remote_field [gitlab]"),
        "the remote finding names the target:\n{err}"
    );
}

/// C-001/C-007: every analytics verb is a read. The bytes the project held are the bytes it
/// holds afterwards, no file is created inside it, and the only file written is the
/// caller's own `--output`.
#[test]
fn t028_every_verb_writes_nothing_of_its_own() {
    let (dir, issues) = project();
    write_fixture(&issues);

    let before = tree(dir.path());
    for args in [
        vec![
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
        ],
        vec![
            "analytics",
            "burndown",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "estimate",
            "--unit",
            "points",
        ],
        vec![
            "analytics",
            "projection",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--as-of",
            "2026-01-09",
        ],
        vec![
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "count",
        ],
    ] {
        let (code, _, err) = run(dir.path(), &args);
        assert_eq!(code, 0, "{args:?} failed: {err}");
    }
    assert_eq!(
        tree(dir.path()),
        before,
        "a read writes nothing and deletes nothing"
    );

    // `--output` writes exactly the one file it was given, and nothing else.
    let out = dir.path().join("charts").join("sprint.json");
    fs::create_dir_all(out.parent().unwrap()).unwrap();
    let (code, _, err) = run(
        dir.path(),
        &[
            "analytics",
            "export",
            "--scope",
            "cycle",
            "--id",
            "Sprint 7",
            "--mode",
            "count",
            "--output",
            out.to_str().unwrap(),
        ],
    );
    assert_eq!(code, 0, "{err}");
    assert!(out.is_file(), "the requested document exists");
    let after: BTreeMap<PathBuf, Vec<u8>> = tree(dir.path())
        .into_iter()
        .filter(|(path, _)| path != &out)
        .collect();
    assert_eq!(after, before, "only the caller's path was written");
}

// ---------------------------------------------------------------------------
// T028 — closed snapshots and the existing surface
// ---------------------------------------------------------------------------

// C-006's two halves are covered where their subjects live, so no case stands here:
// the CLI-level closed-scope claim is
// `t025_count_report_is_explicit_and_an_unanswerable_value_is_a_dash` (the 2026-02-10 edit
// staying out of the period), and the snapshot binding — which no CLI flag can express,
// because a scope binds a snapshot through the library — is
// `tests/analytics_chart.rs::t022_a_closed_snapshot_keeps_its_provenance_and_excludes_a_later_edit`
// (the binding through both nodes, with the closed_snapshot finding) and
// `tests/analytics_series.rs::t011_a_closed_snapshot_binds_the_period_and_excludes_later_events`.
// The case that previously stood here called `chart_document` from the library and invoked
// no binary, so it could not fail on this file's subject; a review found it.

/// C-001/C-008: adding the analytics surface changes no existing command. The board and the
/// summary still read the same issues.
#[test]
fn t028_the_existing_commands_are_unchanged() {
    let (dir, issues) = project();
    write_fixture(&issues);

    // `--all`: the default listing is scoped to your issues in the board's entry
    // column (#1711), and these fixtures are hand-written with no assignee.
    let (code, out, err) = run(dir.path(), &["list", "--all"]);
    assert_eq!(code, 0, "tix list still works: {err}");
    assert!(out.contains("Issue 1") && out.contains("Issue 2"), "{out}");

    let (code, out, err) = run(dir.path(), &["status"]);
    assert_eq!(code, 0, "tix status still works: {err}");
    assert!(out.contains("todo"), "{out}");
}