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
//! WP04 — the deterministic local chart document, its serialization and its export
//! target (mission `burndown-scope-analytics-01M3C9J1`, T019–T023).
//!
//! Every case names the requirement it pins, and each negative claim carries a positive
//! control beside it: "a foreign document is refused by name" is asserted next to the
//! same-shaped chart document that is *read*; "an absent bound is null" is asserted next
//! to a present bound that serializes as its date; "a configured remote target is
//! diagnosed" is asserted next to the same document built with no remote target, whose
//! series data is byte-for-byte the same.
//!
//! The last case is the real exercise the work package asks for: a temporary project on
//! disk, read through [`Store::list_all`] and exported through
//! [`run_chart_core`]/[`chart_document`], showing the produced document, a byte-fixpoint
//! round trip, and the file bytes it did not touch. Run it with `--nocapture` to read the
//! document.

use std::fs;
use std::path::Path;

use tempfile::TempDir;

use tix::analytics::chart::{
    ChartExport, FORMAT, SCHEMA_VERSION, UNSUPPORTED_REMOTE_FIELD, VERSION_MISMATCH, precision_of,
};
use tix::analytics::diagnostics::AnalyticsDiagnosticKind;
use tix::analytics::events::{AnalyticsScope, Period, ScopeKind};
use tix::analytics::projection::{PROJECTION_FORMULA_VERSION, Projection, ProjectionStatus};
use tix::analytics::series::{
    BurndownSeries, COUNT_FORMULA_VERSION, Coverage, CoverageSummary, ESTIMATE_FORMULA_VERSION,
    Mode, ScopeSnapshot,
};
use tix::analytics::units::estimate_series;
use tix::commands::export::{chart_document, cycle_scope_for, run, run_chart_core};
use tix::config::Config;
use tix::cycle_schedule::identity::ScheduleIndex;
use tix::cycle_store::{CycleRecord, CycleStore};
use tix::model::{History, HistoryEvent, HistoryEventKind, Issue};
use tix::storage::Store;
use tix::sync::Tool;

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

/// The schedule index a scope's cycle references resolve through: empty, which is what a
/// repository with no generated cycle records has, so a reference resolves to its own
/// name and an issue and a scope that write the same cycle name still match.
fn index() -> ScheduleIndex {
    ScheduleIndex::default()
}

/// 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 scope_addition(timestamp: &str) -> HistoryEvent {
    recorded(timestamp, HistoryEventKind::ParentSet, "parent none -> #1")
}

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

/// An estimate change, as `tix edit --estimate` records it: both sides, never just the
/// new value.
fn estimate_change(before: Option<&str>, after: Option<&str>) -> HistoryEvent {
    recorded(
        "2026-01-07T09:00:00Z",
        HistoryEventKind::EstimateChanged,
        &format!(
            "estimate: {} -> {}",
            before.unwrap_or("none"),
            after.unwrap_or("none")
        ),
    )
}

/// An issue file's text: minimum frontmatter (with the stated estimate, when there is
/// one, and under a named cycle) plus the History section, rendered by the model's own
/// renderer so the fixture cannot disagree with the parser.
fn issue_text(number: u32, cycle: &str, estimate: Option<&str>, events: &[HistoryEvent]) -> String {
    let mut frontmatter = format!(
        "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"todo\"\nlabels: []\n\
         cycles:\n  - {cycle}\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())
}

/// An issue file's text under the usual fixture cycle.
fn issue_markdown(number: u32, estimate: Option<&str>, events: &[HistoryEvent]) -> String {
    issue_text(number, "Sprint 7", estimate, events)
}

/// A member issue carrying `events`, parsed by the crate's own parser.
fn issue(number: u32, estimate: Option<&str>, events: &[HistoryEvent]) -> Issue {
    Issue::parse(&issue_markdown(number, estimate, events)).unwrap()
}

/// A cycle scope over an explicit period.
fn cycle_scope(start: Option<&str>, end: Option<&str>) -> AnalyticsScope {
    AnalyticsScope::cycle(
        "Sprint 7",
        Period::new(start.map(str::to_string), end.map(str::to_string)).unwrap(),
    )
    .unwrap()
}

/// The one-pass snapshot over `issues` for `scope`, under the bare default board.
fn snapshot_of(issues: &[Issue], scope: &AnalyticsScope) -> ScopeSnapshot {
    ScopeSnapshot::build(&Config::default(), &index(), issues, scope)
}

/// A project whose board declares two estimate units: `points` (the base) and `hours`
/// (worth 5 points each).
fn unit_config(units: &str) -> (TempDir, Config) {
    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!(
            "issues_dir = {issues:?}\n\
             [kanban.default]\ncolumns = [\"todo\", \"doing\", \"done\"]\n\
             [kanban.default.wip.units]\n{units}\n",
            issues = issues.to_string_lossy(),
        ),
    )
    .unwrap();
    let config = Config::load(dir.path()).expect("the fixture loads");
    (dir, config)
}

/// A count-mode series with two members: additions and completions recorded on four
/// consecutive days, so the trailing day is coverage-limited and the period holds one
/// unbroken gap.
fn sprint_series() -> BurndownSeries {
    let scope = cycle_scope(Some("2026-01-05"), Some("2026-01-09"));
    let issues = [
        issue(
            1,
            None,
            &[
                scope_addition("2026-01-05T10:00:00Z"),
                completion("2026-01-07T10:00:00Z"),
            ],
        ),
        issue(
            2,
            None,
            &[
                scope_addition("2026-01-06T10:00:00Z"),
                completion("2026-01-08T10:00:00Z"),
            ],
        ),
    ];
    snapshot_of(&issues, &scope).series(Mode::Count)
}

/// The `null`-checking accessor: the JSON value at a dotted path, or `None`.
///
/// A numeric segment indexes an array (`series.points.0.scope_total`), so a test can
/// assert the *absence* of a fabricated value at the exact place it would appear.
fn value<'a>(json: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> {
    let mut current = json;
    for key in path.split('.') {
        current = match current {
            serde_json::Value::Array(items) => items.get(key.parse::<usize>().ok()?)?,
            _ => current.get(key)?,
        };
    }
    Some(current)
}

/// The document-level findings of one kind.
fn findings_of_kind<'a>(
    document: &'a ChartExport,
    kind: &str,
) -> Vec<&'a tix::analytics::chart::ChartDiagnostic> {
    document
        .diagnostics
        .iter()
        .filter(|diagnostic| diagnostic.kind() == kind)
        .collect()
}

// ---------------------------------------------------------------------------
// T019 — the versioned document
// ---------------------------------------------------------------------------

/// FR-005/NFR-002: every export identifies its format and schema version, and carries the
/// scope, period, mode, unit, precision, points, coverage and formula version — the same
/// values the series carries, not a second reading.
#[test]
fn t019_the_document_carries_the_versioned_metadata() {
    let series = sprint_series();
    let document = ChartExport::build(&series, None, &[]);

    assert_eq!(document.format(), FORMAT);
    assert_eq!(document.schema_version(), SCHEMA_VERSION);
    assert_eq!(document.scope.kind, "cycle");
    assert_eq!(document.scope.id, "Sprint 7");
    assert_eq!(document.scope.period.start.as_deref(), Some("2026-01-05"));
    assert_eq!(document.scope.period.end.as_deref(), Some("2026-01-09"));
    assert_eq!(
        document.scope.snapshot_id, None,
        "an open scope is not bound to a snapshot"
    );
    assert_eq!(document.mode, Mode::Count);
    assert_eq!(document.unit, None, "count mode is unitless");
    assert_eq!(document.precision, precision_of(Mode::Count));
    assert_eq!(document.formula_version, COUNT_FORMULA_VERSION);
    assert_eq!(
        document.coverage,
        CoverageSummary {
            known: 4,
            unknown: 0,
            coverage_limited: 1
        },
        "coverage is the shared series' own tally"
    );

    // The series node is the fold's own points and findings, verbatim.
    assert_eq!(document.series.points, series.points);
    assert_eq!(document.series.diagnostics, series.diagnostics);
    assert_eq!(document.series.formula_version, COUNT_FORMULA_VERSION);
    assert!(document.projection.is_none(), "no forecast was asked for");

    // The wire names are the contract's own.
    let json: serde_json::Value =
        serde_json::from_str(&document.to_json_pretty().unwrap()).unwrap();
    assert_eq!(value(&json, "format"), Some(&serde_json::json!(FORMAT)));
    assert_eq!(
        value(&json, "schema_version"),
        Some(&serde_json::json!(SCHEMA_VERSION))
    );
    assert_eq!(value(&json, "mode"), Some(&serde_json::json!("count")));
    assert_eq!(
        value(&json, "series.points.0.coverage"),
        Some(&serde_json::json!("known"))
    );
    assert_eq!(
        value(&json, "coverage.coverage_limited"),
        Some(&serde_json::json!(1))
    );
}

/// C-005: an absent bound is `null`, and a missing number is `null` — never an empty
/// string and never a fabricated `0`. The control is the observed day beside it, which
/// *is* a known zero because the day was read.
#[test]
fn t019_an_absent_value_is_null_and_never_zero() {
    let scope = cycle_scope(None, Some("2026-01-06"));
    let issues = [issue(1, None, &[scope_addition("2026-01-05T10:00:00Z")])];
    let series = snapshot_of(&issues, &scope).series(Mode::Count);
    let document = ChartExport::build(&series, None, &[]);

    assert_eq!(
        document.scope.period.start, None,
        "an unbounded start stays absent"
    );

    let json: serde_json::Value =
        serde_json::from_str(&document.to_json_pretty().unwrap()).unwrap();
    assert!(
        value(&json, "scope.period.start").unwrap().is_null(),
        "an absent bound serializes as null: {}",
        value(&json, "scope.period.start").unwrap()
    );
    assert_eq!(
        value(&json, "unit"),
        Some(&serde_json::Value::Null),
        "a unitless document says null, not an empty string"
    );
    assert_eq!(value(&json, "projection"), Some(&serde_json::Value::Null));

    // The unanchored origin: every level is unknown, so every level is null.
    let first = document.series.points.first().unwrap();
    assert_eq!(first.scope_total, None);
    assert_eq!(first.remaining, None);
    assert_eq!(
        value(&json, "series.points.0.scope_total"),
        Some(&serde_json::Value::Null),
        "an unanswerable level is null, never 0"
    );

    // The positive control the doc comment promises: the *observed* day beside it carries
    // a known zero — `completions` is `0` rather than null, because the day was read.
    assert_eq!(
        first.completions,
        Some(0),
        "a delta the day was read for is a known zero, not a null"
    );
    assert_eq!(
        value(&json, "series.points.0.completions"),
        Some(&serde_json::json!(0)),
        "the known zero is serialized as 0, with the unanswerable level beside it as null"
    );
}

/// T020/C-007: the same input produces identical bytes, and the emitted bytes re-read as
/// a byte fixpoint — pretty and compact alike.
#[test]
fn t020_repeated_export_is_byte_identical_and_a_fixpoint() {
    let series = sprint_series();
    let document = ChartExport::build(&series, None, &[]);

    let pretty = document.to_json_pretty().unwrap();
    assert_eq!(
        document.to_json_pretty().unwrap(),
        pretty,
        "a second serialization of one document is byte-identical"
    );
    assert_eq!(
        ChartExport::build(&series, None, &[])
            .to_json_pretty()
            .unwrap(),
        pretty,
        "two documents built from one series are byte-identical"
    );

    let read = ChartExport::from_json(&pretty).unwrap();
    assert_eq!(read, document, "the document reads back as itself");
    assert_eq!(
        read.to_json_pretty().unwrap(),
        pretty,
        "re-serializing what was read reproduces the bytes exactly"
    );

    let compact = document.to_json().unwrap();
    let read = ChartExport::from_json(&compact).unwrap();
    assert_eq!(read, document);
    assert_eq!(read.to_json().unwrap(), compact);
}

/// T020: precision is stated and mode-dependent, and `observed_rate` is the only
/// fractional quantity a document may carry.
#[test]
fn t020_precision_is_stated_for_the_mode() {
    assert_eq!(precision_of(Mode::Count), "whole_issues");
    assert_eq!(precision_of(Mode::Estimate), "whole_units");
    assert_ne!(precision_of(Mode::Count), precision_of(Mode::Estimate));
}

/// T019: unknown data lives in the document's own nested `extensions` object, so a
/// preserved key never shadows — or duplicates — a projected field, and the document
/// still reads back.
#[test]
fn t019_the_extension_bag_is_nested_and_never_shadows_a_projected_field() {
    let series = sprint_series();
    let mut document = ChartExport::build(&series, None, &[]);
    document.insert_extension("format", serde_json::json!("evil"));
    document.insert_extension("future_field", serde_json::json!({"a": 1}));

    let json: serde_json::Value =
        serde_json::from_str(&document.to_json_pretty().unwrap()).unwrap();
    assert_eq!(
        value(&json, "format"),
        Some(&serde_json::json!(FORMAT)),
        "the projected field keeps its value"
    );
    assert_eq!(
        value(&json, "extensions.format"),
        Some(&serde_json::json!("evil")),
        "the preserved key lands in the nested object"
    );
    assert_eq!(
        value(&json, "extensions.future_field.a"),
        Some(&serde_json::json!(1))
    );

    let read = ChartExport::from_json(&document.to_json_pretty().unwrap()).unwrap();
    assert_eq!(read, document, "the preserved data round trips");
    assert_eq!(read.extensions().count(), 2);
    assert_eq!(
        read.extensions().next().map(|(key, _)| key),
        Some("format"),
        "the bag is emitted in canonical (sorted) order"
    );
}

/// C-008: the mirrors are **exhaustive by construction**, not merely faithful today.
///
/// Each source value is written as an explicit struct literal (no `..Default::default()`),
/// so a field WP01/WP02/WP03 adds to `AnalyticsScope`, `BurndownSeries` or `Projection`
/// breaks this test's compilation until the mirror copies it — and every field is then
/// compared against the document. The shared leaf types are deliberately *not* re-spelled
/// here: they are reused verbatim, so a field added to one of them is a contract change
/// rather than a mirror drift.
#[test]
fn t019_the_mirrors_copy_every_field_of_their_source() {
    let folded = sprint_series();
    let scope = AnalyticsScope {
        kind: ScopeKind::Cycle,
        id: "Sprint 7".to_string(),
        period: Period {
            start: Some("2026-01-05".to_string()),
            end: Some("2026-01-09".to_string()),
        },
        snapshot_id: Some("cs-1:000007".to_string()),
    };
    let series = BurndownSeries {
        scope: scope.clone(),
        mode: Mode::Estimate,
        unit: Some("points".to_string()),
        points: folded.points.clone(),
        diagnostics: folded.diagnostics.clone(),
        formula_version: "burndown.estimate.v1".to_string(),
    };
    let projection = Projection {
        scope: scope.clone(),
        mode: series.mode,
        unit: series.unit.clone(),
        as_of: "2026-01-09".to_string(),
        end_date: "2026-01-12".to_string(),
        remaining: Some(2),
        observed_rate: Some(0.75),
        projected_completion: Some("2026-01-12".to_string()),
        meets_end_date: Some(true),
        status: ProjectionStatus::Projected,
        formula_version: "burndown.projection.v1".to_string(),
        diagnostics: folded.diagnostics.clone(),
    };

    let document = ChartExport::build(&series, Some(&projection), &[]);

    // The scope mirror, field by field.
    assert_eq!(document.scope.kind, scope.kind.as_str());
    assert_eq!(document.scope.id, scope.id);
    assert_eq!(document.scope.period.start, scope.period.start);
    assert_eq!(document.scope.period.end, scope.period.end);
    assert_eq!(document.scope.snapshot_id, scope.snapshot_id);

    // The series mirror, and the document's own summary of the same source.
    assert_eq!(document.series.scope, document.scope);
    assert_eq!(document.series.mode, series.mode);
    assert_eq!(document.series.unit, series.unit);
    assert_eq!(document.series.points, series.points);
    assert_eq!(document.series.diagnostics, series.diagnostics);
    assert_eq!(document.series.formula_version, series.formula_version);
    assert_eq!(document.mode, series.mode);
    assert_eq!(document.unit, series.unit);
    assert_eq!(document.formula_version, series.formula_version);
    assert_eq!(document.coverage, series.coverage());

    // The projection mirror, field by field.
    let mirrored = document
        .projection
        .as_ref()
        .expect("a projection was given");
    assert_eq!(mirrored.scope, document.scope);
    assert_eq!(mirrored.mode, projection.mode);
    assert_eq!(mirrored.unit, projection.unit);
    assert_eq!(mirrored.as_of, projection.as_of);
    assert_eq!(mirrored.end_date, projection.end_date);
    assert_eq!(mirrored.remaining, projection.remaining);
    assert_eq!(mirrored.observed_rate, projection.observed_rate);
    assert_eq!(
        mirrored.projected_completion,
        projection.projected_completion
    );
    assert_eq!(mirrored.meets_end_date, projection.meets_end_date);
    assert_eq!(mirrored.status, projection.status);
    assert_eq!(mirrored.formula_version, projection.formula_version);
    assert_eq!(mirrored.diagnostics, projection.diagnostics);
}

// ---------------------------------------------------------------------------
// T019 — the marker, and the version
// ---------------------------------------------------------------------------

/// T019: the marker is read before the shape, so a foreign document is refused by name —
/// while the chart document of the same shape is read.
#[test]
fn t019_a_foreign_document_is_refused_by_name() {
    let foreign = serde_json::json!({
        "format": "tix-capacity",
        "version": 1,
        "scopes": [],
    })
    .to_string();
    let error = ChartExport::from_json(&foreign).unwrap_err().to_string();
    assert!(
        error.contains("tix-capacity"),
        "the foreign format is named: {error}"
    );
    assert!(
        error.contains(FORMAT),
        "the format this build reads is named: {error}"
    );

    let malformed = ChartExport::from_json("{ not json")
        .unwrap_err()
        .to_string();
    assert!(
        malformed.contains("not a portable chart document"),
        "a non-JSON payload is refused as such: {malformed}"
    );

    // The positive control: this build's own document is read.
    let document = ChartExport::build(&sprint_series(), None, &[]);
    assert!(ChartExport::from_json(&document.to_json_pretty().unwrap()).is_ok());
}

/// T019: a document of another schema version is read, its fields kept, and the mismatch
/// reported once — and the report is merged, so the document stabilizes after one read.
#[test]
fn t019_a_version_mismatch_is_reported_once_and_stabilises() {
    let document = ChartExport::build(&sprint_series(), None, &[]);
    let mut wire: serde_json::Value =
        serde_json::from_str(&document.to_json_pretty().unwrap()).unwrap();
    wire["schema_version"] = serde_json::json!(99);
    let raw = serde_json::to_string_pretty(&wire).unwrap();

    let read = ChartExport::from_json(&raw).unwrap();
    assert_eq!(
        read.schema_version, 99,
        "the document's own version is preserved"
    );
    assert_eq!(
        findings_of_kind(&read, VERSION_MISMATCH).len(),
        1,
        "the mismatch is reported once"
    );
    assert_eq!(
        read.series.points, document.series.points,
        "its own fields are kept rather than dropped"
    );

    // The report is merged, never appended twice: re-reading the re-emitted document
    // yields the same bytes.
    let once = read.to_json_pretty().unwrap();
    let again = ChartExport::from_json(&once).unwrap();
    assert_eq!(findings_of_kind(&again, VERSION_MISMATCH).len(), 1);
    assert_eq!(again.to_json_pretty().unwrap(), once);

    // The control: a document of this build's version carries no such finding.
    assert!(findings_of_kind(&document, VERSION_MISMATCH).is_empty());
}

/// T019: the version finding promises that a newer writer's fields are preserved, so a
/// document-level key this build does not project must survive the round trip — the case
/// the projection equalities above cannot see, since they only cover fields this build
/// already projects.
#[test]
fn t019_an_unprojected_document_key_survives_the_round_trip() {
    let document = ChartExport::build(&sprint_series(), None, &[]);
    assert!(
        document.unknown().is_empty(),
        "a document this build builds projects every key it carries"
    );

    // A `tix-chart` document of a newer schema version, with a field this build has no
    // idea about.
    let bands = serde_json::json!([{"day": "2026-01-07", "low": 1, "high": 2}]);
    let mut wire: serde_json::Value =
        serde_json::from_str(&document.to_json_pretty().unwrap()).unwrap();
    wire["schema_version"] = serde_json::json!(2);
    wire["confidence_bands"] = bands.clone();
    let raw = serde_json::to_string_pretty(&wire).unwrap();

    let read = ChartExport::from_json(&raw).unwrap();
    assert_eq!(
        read.unknown().get("confidence_bands"),
        Some(&bands),
        "the unprojected key is preserved on read: {:?}",
        read.unknown().keys().collect::<Vec<_>>()
    );
    assert_eq!(read.schema_version, 2, "the newer version is kept as read");

    // ... and re-emitted: the key is where it was read, with its value verbatim, exactly
    // once in the bytes.
    let once = read.to_json_pretty().unwrap();
    let emitted: serde_json::Value = serde_json::from_str(&once).unwrap();
    assert_eq!(
        value(&emitted, "confidence_bands"),
        Some(&bands),
        "the preserved key is written back at the document level"
    );
    assert_eq!(
        once.matches("\"confidence_bands\"").count(),
        1,
        "the preserved key appears exactly once in the emitted bytes: {once}"
    );
    assert_eq!(
        value(&emitted, "format"),
        Some(&serde_json::json!(FORMAT)),
        "the projected format marker is still the projected one"
    );

    // No duplicate key at any depth: the emitted document is one this build reads back,
    // and re-emitting it is a fixpoint — a repeated projected key anywhere would be
    // refused as a `duplicate field`, exactly as serde refuses it on a hand-written
    // document.
    let again = ChartExport::from_json(&once).expect("the emitted document is re-readable");
    assert_eq!(again, read);
    assert_eq!(again.to_json_pretty().unwrap(), once);
    assert_eq!(again.unknown().get("confidence_bands"), Some(&bands));
}

// ---------------------------------------------------------------------------
// T021 — coverage, metadata and diagnostics
// ---------------------------------------------------------------------------

/// NFR-002/T021: the export states the coverage tally and carries the fold's own
/// findings — a missing history gap stays visible rather than reading as progress.
#[test]
fn t021_coverage_and_the_series_findings_are_exported() {
    let series = sprint_series();
    assert_eq!(
        series
            .diagnostics_of(AnalyticsDiagnosticKind::MissingHistory)
            .count(),
        1,
        "the fixture has one unbroken gap"
    );

    let document = ChartExport::build(&series, None, &[]);
    assert_eq!(document.coverage.coverage_limited, 1);
    assert!(
        document
            .series
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.kind == AnalyticsDiagnosticKind::MissingHistory),
        "the missing-history finding travels with the series"
    );
    assert_eq!(
        document.series.points[0].coverage,
        Coverage::Known,
        "the observed day is known"
    );
}

/// T021: estimate mode states its unit and its own formula version, and an undeclared
/// unit is *diagnosed* — the document carries the finding instead of inventing a value.
#[test]
fn t021_estimate_mode_states_its_unit_and_diagnoses_an_undeclared_one() {
    let (dir, config) = unit_config("points = 1\nhours = 5");
    let scope = cycle_scope(Some("2026-01-05"), Some("2026-01-09"));
    let issues = [issue(
        1,
        Some("3points"),
        &[scope_addition("2026-01-05T10:00:00Z")],
    )];
    let snapshot = ScopeSnapshot::build(&config, &index(), &issues, &scope);
    let series = estimate_series(&snapshot, &issues, &config, "points");
    let document = ChartExport::build(&series, None, &[]);

    assert_eq!(document.mode, Mode::Estimate);
    assert_eq!(document.unit.as_deref(), Some("points"));
    assert_eq!(document.precision, precision_of(Mode::Estimate));
    assert_eq!(document.formula_version, ESTIMATE_FORMULA_VERSION);
    assert_eq!(document.series.formula_version, ESTIMATE_FORMULA_VERSION);
    assert_eq!(document.series.points[4].scope_total, Some(3));
    drop(dir);

    // The control for the diagnosis below: a *declared* unit produces no conversion
    // finding, while an undeclared one produces exactly one and no value.
    let (dir, config) = unit_config("points = 1\nhours = 5");
    let series = estimate_series(
        &ScopeSnapshot::build(&config, &index(), &issues, &scope),
        &issues,
        &config,
        "points",
    );
    assert_eq!(
        series
            .diagnostics_of(AnalyticsDiagnosticKind::MissingConversion)
            .count(),
        0
    );

    let series = estimate_series(
        &ScopeSnapshot::build(&config, &index(), &issues, &scope),
        &issues,
        &config,
        "storypoints",
    );
    let document = ChartExport::build(&series, None, &[]);
    assert_eq!(
        document
            .series
            .diagnostics
            .iter()
            .filter(|diagnostic| diagnostic.kind == AnalyticsDiagnosticKind::MissingConversion)
            .count(),
        1,
        "an undeclared unit is reported, not converted: {:?}",
        document.series.diagnostics
    );
    assert!(
        document.is_empty(),
        "no day is folded without a resolved unit, so no value is invented"
    );
    drop(dir);
}

/// The tracer's second decision: a recorded `estimate_changed` is reported, never
/// replayed into the levels — the document carries the finding and the unchanged level.
#[test]
fn t021_a_recorded_estimate_change_is_reported_not_replayed() {
    let (dir, config) = unit_config("points = 1");
    let scope = cycle_scope(Some("2026-01-05"), Some("2026-01-09"));
    let issues = [issue(
        1,
        Some("3points"),
        &[
            scope_addition("2026-01-05T10:00:00Z"),
            estimate_change(Some("3points"), Some("8points")),
        ],
    )];
    let series = estimate_series(
        &ScopeSnapshot::build(&config, &index(), &issues, &scope),
        &issues,
        &config,
        "points",
    );
    let document = ChartExport::build(&series, None, &[]);

    assert_eq!(
        document.series.points[4].scope_total,
        Some(3),
        "the stated estimate values the contribution; the change is not replayed"
    );
    assert_eq!(
        document.series.points[2].coverage,
        Coverage::CoverageLimited,
        "the day the change was recorded is coverage-limited"
    );
    assert_eq!(
        document.series.points[2].scope_total,
        Some(3),
        "the recorded change does not restate the level"
    );
    assert!(
        document
            .series
            .diagnostics
            .iter()
            .any(
                |diagnostic| diagnostic.kind == AnalyticsDiagnosticKind::MissingHistory
                    && diagnostic.message.contains("estimate change")
            ),
        "the recorded change is reported: {:?}",
        document.series.diagnostics
    );
    drop(dir);
}

// ---------------------------------------------------------------------------
// T022 — the closed snapshot and the remote namespace
// ---------------------------------------------------------------------------

/// C-006: a closed scope keeps its snapshot provenance and its finding, and an event
/// recorded after the close is not a contribution — the document equals the document
/// folded from a series that never saw the later edit.
#[test]
fn t022_a_closed_snapshot_keeps_its_provenance_and_excludes_a_later_edit() {
    let scope = cycle_scope(Some("2026-01-05"), Some("2026-01-09")).with_snapshot_id("cs-1:000007");
    let closed = [issue(
        1,
        None,
        &[
            scope_addition("2026-01-05T10:00:00Z"),
            scope_addition("2026-02-10T10:00:00Z"),
        ],
    )];
    let without_the_later_edit = [issue(1, None, &[scope_addition("2026-01-05T10:00:00Z")])];

    let document = ChartExport::build(&snapshot_of(&closed, &scope).series(Mode::Count), None, &[]);
    let control = ChartExport::build(
        &snapshot_of(&without_the_later_edit, &scope).series(Mode::Count),
        None,
        &[],
    );

    assert_eq!(
        document.scope.snapshot_id.as_deref(),
        Some("cs-1:000007"),
        "the closed binding is carried as provenance"
    );
    assert_eq!(
        document.series.scope.snapshot_id, document.scope.snapshot_id,
        "the series node agrees with the document"
    );
    assert_eq!(
        document.series.points, control.series.points,
        "an event after the close is not part of the document"
    );
    assert!(
        document
            .series
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.kind == AnalyticsDiagnosticKind::ClosedSnapshot),
        "the closed-snapshot finding travels with the series"
    );

    // The control: the same closed scope with an *open* scope's document differs.
    let open = ChartExport::build(
        &snapshot_of(
            &closed,
            &cycle_scope(Some("2026-01-05"), Some("2026-01-09")),
        )
        .series(Mode::Count),
        None,
        &[],
    );
    assert_eq!(open.scope.snapshot_id, None);
    assert!(
        open.series
            .diagnostics
            .iter()
            .all(|diagnostic| diagnostic.kind != AnalyticsDiagnosticKind::ClosedSnapshot)
    );
}

/// T022: a configured remote target is diagnosed explicitly, and every value stays in the
/// local document. The control is the same document with no remote target: identical
/// series data, no finding.
#[test]
fn t022_a_configured_remote_target_is_diagnosed_and_the_values_stay_local() {
    let series = sprint_series();
    let local = ChartExport::build(&series, None, &[]);
    let remote = ChartExport::build(&series, None, &["gitlab", "linear"]);

    assert!(
        findings_of_kind(&local, UNSUPPORTED_REMOTE_FIELD).is_empty(),
        "no remote target configured, no finding"
    );

    let findings = findings_of_kind(&remote, UNSUPPORTED_REMOTE_FIELD);
    assert_eq!(findings.len(), 2, "one finding per configured target");
    assert_eq!(findings[0].target.as_deref(), Some("gitlab"));
    assert_eq!(findings[1].target.as_deref(), Some("linear"));
    assert_eq!(findings[0].scope.as_deref(), Some("Sprint 7"));
    assert!(
        findings[0].render().contains("[gitlab]"),
        "the rendered line names the target: {}",
        findings[0].render()
    );
    assert!(
        findings[0].reason.contains("stay local"),
        "the finding promises the values are not mapped: {}",
        findings[0].reason
    );
    assert_eq!(
        remote.series, local.series,
        "the remote finding changes no value"
    );
    assert_eq!(remote.coverage, local.coverage);

    // The namespace only: `chart` is a name `Tool::from_target` does not know, so a chart
    // target that ever *reached* that call would be refused by it. This does not observe
    // the dispatch order (it does not go through the dispatch) — that is
    // `t022_the_chart_target_is_local_and_the_remote_path_is_untouched`, whose `run` call
    // with `chart` must succeed and which a removed dispatch arm turns into exactly the
    // `unknown --target 'chart'` error this call returns deliberately.
    assert!(
        Tool::from_target("chart").is_err(),
        "chart is not a remote tool name"
    );
    assert_eq!(Tool::from_target("gitlab").unwrap(), Tool::GitLab);
    assert_eq!(Tool::from_target("linear").unwrap(), Tool::Linear);
}

// ---------------------------------------------------------------------------
// T023 — the round trip, partial and malformed shapes
// ---------------------------------------------------------------------------

/// T019/T023: a hand-written partial document — the required nodes only, the optional
/// ones and every unknown number absent — is read, and re-emitting it writes the
/// documented `null`s rather than inventing a zero.
#[test]
fn t023_a_partial_document_is_read_and_absent_stays_null() {
    let raw = r#"{
        "format": "tix-chart",
        "schema_version": 1,
        "scope": {"kind": "cycle", "id": "Sprint 7", "period": {"start": "2026-01-05"}},
        "mode": "count",
        "precision": "whole_issues",
        "series": {
            "scope": {"kind": "cycle", "id": "Sprint 7", "period": {}},
            "mode": "count",
            "points": [{"date": "2026-01-05", "coverage": "unknown", "event_ids": []}],
            "formula_version": "burndown.count.v1"
        },
        "coverage": {"known": 0, "unknown": 1, "coverage_limited": 0},
        "formula_version": "burndown.count.v1"
    }"#;

    let document = ChartExport::from_json(raw).unwrap();
    assert_eq!(document.scope.period.end, None);
    assert_eq!(document.unit, None);
    assert_eq!(document.projection, None);
    assert!(document.diagnostics.is_empty());
    assert_eq!(document.extensions().count(), 0);
    assert_eq!(document.series.points.len(), 1);
    assert_eq!(document.series.points[0].scope_added, None);
    assert_eq!(document.series.points[0].coverage, Coverage::Unknown);
    assert!(!document.is_empty());

    let json: serde_json::Value =
        serde_json::from_str(&document.to_json_pretty().unwrap()).unwrap();
    assert_eq!(value(&json, "unit"), Some(&serde_json::Value::Null));
    assert_eq!(value(&json, "extensions"), Some(&serde_json::json!({})));
    assert_eq!(
        value(&json, "series.points.0.remaining"),
        Some(&serde_json::Value::Null)
    );
    assert_eq!(
        value(&json, "scope.period.end"),
        Some(&serde_json::Value::Null)
    );
}

/// T023: a malformed series is refused with the shape error, not silently accepted.
#[test]
fn t023_a_malformed_series_is_refused() {
    let unknown_mode = r#"{"format": "tix-chart", "schema_version": 1,
        "scope": {"kind": "cycle", "id": "S", "period": {}}, "mode": "weekly",
        "precision": "whole_issues", "series": {"scope": {"kind": "cycle", "id": "S", "period": {}},
        "mode": "weekly", "formula_version": "v"}, "coverage": {"known": 0, "unknown": 0,
        "coverage_limited": 0}, "formula_version": "v"}"#;
    let error = ChartExport::from_json(unknown_mode)
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("not valid JSON of this shape"),
        "an unknown mode is a shape error: {error}"
    );

    let bad_point = r#"{"format": "tix-chart", "schema_version": 1,
        "scope": {"kind": "cycle", "id": "S", "period": {}}, "mode": "count",
        "precision": "whole_issues", "series": {"scope": {"kind": "cycle", "id": "S", "period": {}},
        "mode": "count", "points": [{"date": "2026-01-05", "coverage": "unknown",
        "event_ids": [], "scope_added": "three"}],
        "formula_version": "v"}, "coverage": {"known": 0, "unknown": 0, "coverage_limited": 0},
        "formula_version": "v"}"#;
    assert!(ChartExport::from_json(bad_point).is_err());

    // The control: the same shape with a well-typed point is read.
    let good_point = bad_point.replace("\"three\"", "3");
    let document = ChartExport::from_json(&good_point).unwrap();
    assert_eq!(document.series.points[0].scope_added, Some(3));
}

/// T023: an empty series still exports a complete document — the coverage tally and the
/// fold's refusal are carried rather than an empty screen.
#[test]
fn t023_an_empty_series_still_exports_a_complete_document() {
    let scope = cycle_scope(None, None);
    let series = snapshot_of(&[issue(1, None, &[])], &scope).series(Mode::Count);
    assert!(series.is_empty());

    let document = ChartExport::build(&series, None, &[]);
    assert!(document.is_empty());
    assert_eq!(document.coverage.total(), 0);
    assert!(
        document
            .series
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.kind == AnalyticsDiagnosticKind::InvalidPeriod),
        "the unenumerable period is reported: {:?}",
        document.series.diagnostics
    );
    // A complete, readable document all the same.
    let json = document.to_json_pretty().unwrap();
    assert_eq!(ChartExport::from_json(&json).unwrap(), document);
}

// ---------------------------------------------------------------------------
// T022 — the dispatch, and the real exercise
// ---------------------------------------------------------------------------

/// T022: `--target chart` is dispatched by name *before* the remote tool is consulted, so
/// it writes the local document even with no `[export.*]` section — while a remote target
/// name still reaches the remote path.
///
/// The dispatch-level witness: removing the `chart` arm in `run` makes the first call
/// below fail with `unknown --target 'chart'`.
#[test]
fn t022_the_chart_target_is_local_and_the_remote_path_is_untouched() {
    let (dir, config) = project_fixture();
    let store = store_for(&dir, &config);

    // The local target runs with no remote configuration at all.
    run(
        &store.config,
        &store,
        "chart",
        false,
        None,
        Some("Sprint 7"),
        None,
        false,
    )
    // This call is the dispatch witness: an inert `chart` arm in `run` turns it into
    // `unknown --target 'chart'`.
    .expect("the chart dispatch precedes Tool::from_target: no remote configuration is consulted");

    // The remote path is a different namespace: an unconfigured `gitlab` is refused by
    // the sync gate, which is what proves the chart dispatch runs first.
    let error = run(
        &store.config,
        &store,
        "gitlab",
        false,
        None,
        None,
        None,
        false,
    )
    .expect_err("an unconfigured remote target is refused");
    let message = error.to_string();
    assert!(
        message.contains("gitlab") || message.contains("export"),
        "the remote gate names its own condition: {message}"
    );
}

/// T019/T022: a generated cycle is selected by **both** of its spellings — the name its
/// record answers to and its stable `<schedule-id>:<sequence>` id — and they produce one
/// scope and one document, because the reference is folded through the crate's one cycle
/// identity adapter and canonicalized to the resolved name. The period is the record's
/// own, which `tix.toml` does not carry for a generated cycle.
///
/// This is the witness for the reference the code accepts: before the resolution went
/// through the adapter, both spellings failed with `NotFound`, and so did the name.
#[test]
fn t019_a_generated_cycle_is_selected_by_its_name_and_its_stable_id() {
    let (dir, config) = generated_fixture();
    let store = store_for(&dir, &config);
    let issues_dir = dir.path().join("issues");
    // One member writes the name and one writes the stable id: the fold keys on the
    // resolved identity, so both are members of the one cycle.
    fs::write(
        issues_dir.join("2026-01-01-issue-1.md"),
        issue_text(
            1,
            "Weekly 1",
            None,
            &[scope_addition("2026-01-05T09:00:00Z")],
        ),
    )
    .unwrap();
    fs::write(
        issues_dir.join("2026-01-01-issue-2.md"),
        issue_text(
            2,
            "cs-1:000001",
            None,
            &[scope_addition("2026-01-06T09:00:00Z")],
        ),
    )
    .unwrap();

    let by_id =
        cycle_scope_for(&store.config, &store, "cs-1:000001").expect("the stable id resolves");
    let by_name = cycle_scope_for(&store.config, &store, "Weekly 1").expect("the name resolves");
    assert_eq!(by_id, by_name, "the two spellings are one scope");
    assert_eq!(by_id.id, "Weekly 1", "the scope's id is the resolved name");
    assert_eq!(by_id.period_start(), Some("2026-01-05"));
    assert_eq!(by_id.period_end(), Some("2026-01-09"));

    let document_by_id = run_chart_core(&store.config, &store, Some("cs-1:000001")).unwrap();
    let document_by_name = run_chart_core(&store.config, &store, Some("Weekly 1")).unwrap();
    assert_eq!(
        document_by_id.to_json_pretty().unwrap(),
        document_by_name.to_json_pretty().unwrap(),
        "the two spellings produce one document"
    );
    assert_eq!(document_by_id.scope.id, "Weekly 1");
    assert_eq!(document_by_id.coverage.total(), 5);
    assert_eq!(
        document_by_id.series.points[4].scope_total,
        Some(2),
        "both spellings in the issue records are members of the one cycle"
    );

    // The control: a reference nothing resolves to is a named refusal, not an empty
    // document.
    let error = cycle_scope_for(&store.config, &store, "cs-9:000042")
        .unwrap_err()
        .to_string();
    assert!(
        error.contains("cs-9:000042"),
        "the unresolved reference is named: {error}"
    );
}

/// Write a temporary project: a board with one unit and one declared legacy cycle, plus
/// two issues carrying recorded History.
fn project_fixture() -> (TempDir, Config) {
    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!(
            "issues_dir = {issues:?}\n\
             [kanban.default]\ncolumns = [\"todo\", \"doing\", \"done\"]\n\
             [kanban.default.wip.units]\npoints = 1\n\
             [cycles.\"Sprint 7\"]\nstart_date = \"2026-01-05\"\ndue_date = \"2026-01-09\"\n",
            issues = issues.to_string_lossy(),
        ),
    )
    .unwrap();
    let config = Config::load(dir.path()).expect("the fixture loads");
    (dir, config)
}

/// The store over a fixture project's issues directory.
fn store_for(dir: &TempDir, config: &Config) -> Store {
    let issues_dir = dir.path().join("issues");
    fs::create_dir_all(&issues_dir).unwrap();
    Store {
        issues_dir,
        config: config.clone(),
    }
}

/// A project with one **generated** cycle stored in `docs/cycles/`, so its identity
/// (`cs-1:000001`) exists in the record and nowhere in `tix.toml` — the reference the
/// identity adapter resolves and the period only the record declares.
fn generated_fixture() -> (TempDir, Config) {
    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!(
            "issues_dir = {issues:?}\n\
             [kanban.default]\ncolumns = [\"todo\", \"doing\", \"done\"]\n\
             [cycle_schedules.\"cs-1\"]\nname = \"Weekly\"\ncadence = {{ kind = \"weekly\" }}\n\
             duration = {{ count = 1, unit = \"weeks\" }}\nstart_date = \"2026-01-05\"\n\
             timezone = \"UTC\"\n",
            issues = issues.to_string_lossy(),
        ),
    )
    .unwrap();
    let config = Config::load(dir.path()).expect("the fixture loads");
    let record = CycleRecord {
        name: "Weekly 1".into(),
        start_date: Some("2026-01-05".into()),
        due_date: Some("2026-01-09".into()),
        schedule_id: Some("cs-1".into()),
        sequence: Some(1),
        state: Some("active".into()),
        ..CycleRecord::default()
    };
    CycleStore::new(dir.path())
        .save_record(&record, Some("The first weekly cycle.\n"))
        .expect("the generated cycle is stored");
    (dir, config)
}

/// The real exercise: a temporary project on disk, read once and exported through
/// [`run_chart_core`] in count mode and [`chart_document`] in estimate mode with a
/// forecast — showing the produced document, a byte-fixpoint round trip, and the file
/// bytes it did not touch.
///
/// Run with `--nocapture` to read the document.
#[test]
fn the_real_exercise_exports_a_temp_project_and_round_trips() {
    let (dir, config) = project_fixture();
    let issues_dir = dir.path().join("issues");
    let store = store_for(&dir, &config);

    let write = |number: u32, body: String| {
        fs::write(
            issues_dir.join(format!("2026-01-01-issue-{number}.md")),
            body,
        )
        .unwrap();
    };
    write(
        1,
        issue_markdown(
            1,
            Some("3points"),
            &[
                scope_addition("2026-01-05T09:00:00Z"),
                completion("2026-01-07T09:00:00Z"),
            ],
        ),
    );
    // Issue 2 is edited after the period's end: its later membership event is outside the
    // period and must not reach the document.
    write(
        2,
        issue_markdown(
            2,
            Some("2points"),
            &[
                scope_addition("2026-01-06T09:00:00Z"),
                scope_addition("2026-02-10T09:00:00Z"),
            ],
        ),
    );

    let before: Vec<Vec<u8>> = [1, 2]
        .iter()
        .map(|number| fs::read(issues_dir.join(format!("2026-01-01-issue-{number}.md"))).unwrap())
        .collect();

    // The local target: the declared cycle's count-mode document.
    let document =
        run_chart_core(&store.config, &store, Some("Sprint 7")).expect("the cycle folds");
    assert_eq!(document.format(), FORMAT);
    assert_eq!(document.scope.kind, "cycle");
    assert_eq!(document.scope.id, "Sprint 7");
    assert_eq!(document.scope.period.start.as_deref(), Some("2026-01-05"));
    assert_eq!(document.scope.period.end.as_deref(), Some("2026-01-09"));
    assert_eq!(document.mode, Mode::Count);
    assert_eq!(document.unit, None);
    assert_eq!(document.coverage.total(), 5, "the period's own five days");
    assert_eq!(document.series.points[4].scope_total, Some(2));

    let json = document.to_json_pretty().unwrap();
    println!("{json}");
    let read = ChartExport::from_json(&json).expect("the document reads back");
    assert_eq!(read, document);
    assert_eq!(
        read.to_json_pretty().unwrap(),
        json,
        "the emitted bytes are a fixpoint"
    );

    // The same project, estimate mode with a forecast: the shared projection travels
    // into the document.
    let scope = cycle_scope(Some("2026-01-05"), Some("2026-01-09"));
    let estimated = chart_document(
        &store.config,
        &store,
        &scope,
        Mode::Estimate,
        Some("points"),
        Some(("2026-01-09", "2026-01-09")),
    )
    .expect("the estimate document builds");
    assert_eq!(estimated.mode, Mode::Estimate);
    assert_eq!(estimated.unit.as_deref(), Some("points"));
    assert_eq!(estimated.series.points[4].scope_total, Some(5));
    let projection = estimated
        .projection
        .as_ref()
        .expect("a forecast was asked for");
    assert_eq!(projection.as_of, "2026-01-09");
    assert_eq!(
        projection.remaining, estimated.series.points[4].remaining,
        "the forecast carries the series' own remaining work"
    );
    assert_eq!(projection.formula_version, PROJECTION_FORMULA_VERSION);
    println!(
        "projection: status={} rate={:?} completion={:?}",
        projection.status, projection.observed_rate, projection.projected_completion
    );
    for diagnostic in &estimated.diagnostics {
        println!("{}", diagnostic.render());
    }
    assert_eq!(
        ChartExport::from_json(&estimated.to_json_pretty().unwrap()).unwrap(),
        estimated
    );

    // Read-only, proven by the bytes on disk.
    for (number, bytes) in [1u32, 2].iter().zip(&before) {
        let path = issues_dir.join(format!("2026-01-01-issue-{number}.md"));
        assert_eq!(
            &fs::read(&path).unwrap(),
            bytes,
            "export mutates no issue file"
        );
    }

    // And the CLI target writes the same document to `--output`.
    let out = dir.path().join("chart.json");
    run(
        &store.config,
        &store,
        "chart",
        false,
        None,
        Some("Sprint 7"),
        Some(out.to_str().unwrap()),
        false,
    )
    .expect("the target writes to --output");
    let written = fs::read_to_string(&out).unwrap();
    assert_eq!(
        written,
        document.to_json_pretty().unwrap(),
        "the CLI writes exactly the core document"
    );
    assert!(
        !Path::new(&out).metadata().unwrap().is_dir(),
        "the output is a file"
    );
}