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
//! Recorded-event classification and the idempotency/provenance index (mission
//! `burndown-scope-analytics-01M3C9J1`, WP01 T001–T006).
//!
//! # What this module is
//!
//! The vocabulary every later child consumes, and the one place the mission decides
//! *what* a recorded event means:
//!
//! - [`AnalyticsScope`] — the selected cycle/milestone, its period, and the
//!   optional closed-snapshot binding (`data-model.md` §1).
//! - [`AnalyticsEvent`] — one recorded contribution, with its stable identity, its
//!   class, its optional day, and its provenance (`data-model.md` §2).
//! - [`EventClass`] — the closed four-name classification.
//! - [`EventIndex`] — the contribution set, deduplicated by event id (C-002).
//!
//! # Recorded only, and nothing else
//!
//! Classification reads the History the tree actually holds. It never infers a
//! scope change that was not logged, never treats a missing day as zero, and never
//! compares a status *string*: a completion is decided by the category the
//! transition **recorded** (`transition_accepted`'s `to_category`), read through the
//! shared [#183 vocabulary](crate::workflow::WorkflowCategory) rather than by
//! matching a column name against a hard-coded list (C-001/C-008).
//!
//! # The four classes, and why they are the right partition
//!
//! FR-002's whole claim is that scope growth is distinguishable from completion, so
//! the partition splits the two answers a burndown chart needs on a given day:
//!
//! | class | recorded decision | count-level delta |
//! |---|---|---|
//! | `scope_addition` | `parent_set`, or a `cycle_membership_changed` that **added** a cycle | `Some(1)` for `parent_set`, `None` when only the detail can say |
//! | `completion` | `transition_accepted` whose recorded `to_category` is `completed` | `Some(1)` |
//! | `estimate_change` | `estimate_changed` | `None` (the unit is the caller's mode) |
//! | `unclassified` | every other recorded kind | `None` |
//!
//! Three things follow from that, and each is deliberate:
//!
//! 1. **A move that is not a completion is not a completion.** `transition_accepted`
//!    into `active`/`backlog`/`canceled` is a plain move and lands in
//!    `unclassified` rather than being counted as progress.
//! 2. **A removal has no class.** The vocabulary is closed at four names, and neither
//!    a `parent_cleared` nor a membership change that only *removed* cycles is an
//!    addition; both stay `unclassified` and visible, which is the honest answer for
//!    an event the class table cannot place. They are never read as growth. A
//!    membership change is read by **direction** — the detail names the before and
//!    after lists, and the event is a `scope_addition` only when the after list has a
//!    cycle the before list did not — so `cycles: Default -> none` is a removal and
//!    `cycles: none -> Default` is an addition.
//! 3. **Every other kind keeps its record.** All of #184's time-mutation kinds, the
//!    relationship/triage/health/project/epic/cycle-lifecycle kinds, `archived`,
//!    `restored` and `blocked_move_acknowledged` classify as `unclassified` — never
//!    as completion or scope — so a time entry can never move a burndown line.
//!
//! # What a class cannot see: a write nobody recorded
//!
//! A class is only as wide as the record. `tix edit --estimate` and `tix edit
//! --cycles` append the two kinds above, and `tix edit --parent` already appended its
//! own, so what the **edit seam** writes is visible here. A path that writes a field
//! without appending anything — the bulk patch service reaches `Store::update`
//! directly — leaves no event, so such a change cannot appear in `estimate_change` or
//! `scope_addition` no matter how the series is folded. That is a **coverage limit**
//! a surface reports as an explicit marker, never a licence to read the current
//! frontmatter back into the past: reconstructing unrecorded history is the mission's
//! non-goal and would defeat FR-002's whole distinction.
//!
//! # Idempotency is the index's, not the caller's care
//!
//! [`EventIndex::contribute`] deduplicates by [`AnalyticsEvent::event_id`] and
//! reports what it did ([`Contribution`]). Classifying the same recorded event twice
//! therefore contributes once, which is C-002's "the same recorded event produces
//! the same contribution"; the guard lives in the one function every contribution
//! goes through, so a caller cannot forget it.
//!
//! # Provenance
//!
//! A History event's identity is `<source-ref>#<n>`, where `n` is the entry's
//! **ordinal among the section's parsed events**, not its slot in the raw line list.
//! The section is append-only, so a new line lands at the end: an unparseable line a
//! human **inserts** occupies no ordinal, cannot renumber the events after it, and two
//! reads of one file agree on every id. The one hand edit that still moves an id is a
//! line that was a readable event and was later **mangled into unreadability** — the
//! record genuinely lost that event, so the ordinals after it close up. That is the
//! deliberate trade: the only alternative, hashing the entry's content, would give two
//! identical events appended twice the same id and make C-002's "one recorded event,
//! one contribution" collapse two real events into one. A closed snapshot's identity
//! is the snapshot's own stable `snapshot_id`, which is also its event id — so
//! repeated exports of one closed snapshot contribute once.

use std::collections::{HashMap, HashSet};
use std::fmt;

use crate::error::{Result, TixError};
use crate::model::{
    History, HistoryEntry, HistoryEvent, HistoryEventKind, TransitionDecision, validate_date,
};
use crate::planning::Planner;
use crate::workflow::WorkflowCategory;

/// Which planning entity a scope selects (`data-model.md` §1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ScopeKind {
    /// A cycle (hand-written in `[cycles.<name>]` or a generated instance).
    Cycle,
    /// A milestone.
    Milestone,
}

impl ScopeKind {
    /// Every kind, so a surface can enumerate the closed set.
    pub const ALL: [ScopeKind; 2] = [ScopeKind::Cycle, ScopeKind::Milestone];

    /// The canonical spelling used in output and comparisons.
    pub const fn as_str(self) -> &'static str {
        match self {
            ScopeKind::Cycle => "cycle",
            ScopeKind::Milestone => "milestone",
        }
    }

    /// Parse a canonical spelling; `None` for anything outside the vocabulary.
    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "cycle" => Some(ScopeKind::Cycle),
            "milestone" => Some(ScopeKind::Milestone),
            _ => None,
        }
    }
}

impl fmt::Display for ScopeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The inclusive calendar period a series covers (`data-model.md` §1).
///
/// Both bounds are **caller-supplied** `YYYY-MM-DD` strings — this module reads no
/// clock — and each is optional because a cycle need not declare its dates: an
/// absent bound is "unbounded on that side", which is coverage, not a guess. The
/// bounds come from existing planning data (`[`cycle_scope`]`/`[`milestone_scope`]`),
/// never from an assumption about when work started.
///
/// Comparison is `&str` comparison, which is chronological for that fixed-width
/// shape and needs no date arithmetic.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Period {
    /// Inclusive start, or `None` for "unbounded from the beginning".
    pub start: Option<String>,
    /// Inclusive end, or `None` for "still open".
    pub end: Option<String>,
}

impl Period {
    /// A validated period: each present bound must be a canonical calendar date and
    /// `start <= end` must hold.
    ///
    /// A malformed bound is refused here rather than silently dropped, because a
    /// period that quietly lost an end date would turn a closed series into an open
    /// one — the one thing C-006 forbids.
    pub fn new(start: Option<String>, end: Option<String>) -> Result<Self> {
        let period = Self { start, end };
        for (field, value) in [("start", &period.start), ("end", &period.end)] {
            if let Some(date) = value
                && !validate_date(date)
            {
                return Err(TixError::Config(format!(
                    "invalid_period: `{field}` is `{date}`, not a `YYYY-MM-DD` calendar date"
                )));
            }
        }
        if let (Some(start), Some(end)) = (&period.start, &period.end)
            && start > end
        {
            return Err(TixError::Config(format!(
                "invalid_period: start `{start}` is after end `{end}`"
            )));
        }
        Ok(period)
    }

    /// A period with neither bound.
    pub fn unbounded() -> Self {
        Self::default()
    }

    /// Whether the period constrains anything at all.
    pub fn is_bounded(&self) -> bool {
        self.start.is_some() || self.end.is_some()
    }

    /// Whether a canonical `YYYY-MM-DD` date falls inside the period, **both bounds
    /// inclusive**.
    ///
    /// A date that is not a canonical calendar date is *not* contained: the caller
    /// reports the unreadable day as coverage rather than placing it somewhere.
    pub fn contains(&self, date: &str) -> bool {
        if !validate_date(date) {
            return false;
        }
        if let Some(start) = self.start.as_deref()
            && date < start
        {
            return false;
        }
        if let Some(end) = self.end.as_deref()
            && date > end
        {
            return false;
        }
        true
    }
}

/// The selected cycle/milestone and its period context (`data-model.md` §1).
///
/// The `snapshot_id` is the closed-series binding: when it is present the scope
/// refers to a **closed** historical view, and events after the period's end are not
/// contributions to it (C-006 — a later edit never rewrites a closed series).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyticsScope {
    /// Which planning entity the `id` names.
    pub kind: ScopeKind,
    /// The stable planning identity (a cycle name, a milestone name).
    pub id: String,
    /// The inclusive period context.
    pub period: Period,
    /// The closed snapshot this series is bound to, when it is bound to one.
    pub snapshot_id: Option<String>,
}

impl AnalyticsScope {
    /// A scope. A blank id is refused: an unnamed scope cannot be reported or
    /// compared, and defaulting it would hide the caller's mistake.
    pub fn new(kind: ScopeKind, id: impl Into<String>, period: Period) -> Result<Self> {
        let id = id.into();
        if id.trim().is_empty() {
            return Err(TixError::Config(format!(
                "invalid_scope: a {} scope needs a name",
                kind.as_str()
            )));
        }
        Ok(Self {
            kind,
            id,
            period,
            snapshot_id: None,
        })
    }

    /// A cycle scope.
    pub fn cycle(id: impl Into<String>, period: Period) -> Result<Self> {
        Self::new(ScopeKind::Cycle, id, period)
    }

    /// A milestone scope.
    pub fn milestone(id: impl Into<String>, period: Period) -> Result<Self> {
        Self::new(ScopeKind::Milestone, id, period)
    }

    /// Bind this scope to a closed snapshot's stable identity (C-006).
    pub fn with_snapshot_id(mut self, snapshot_id: impl Into<String>) -> Self {
        let snapshot_id = snapshot_id.into();
        self.snapshot_id = (!snapshot_id.trim().is_empty()).then_some(snapshot_id);
        self
    }

    /// The inclusive period start, when the planning data declares one.
    pub fn period_start(&self) -> Option<&str> {
        self.period.start.as_deref()
    }

    /// The inclusive period end, when the planning data declares one.
    pub fn period_end(&self) -> Option<&str> {
        self.period.end.as_deref()
    }

    /// Whether this scope is closed: bound to a snapshot or bounded by an end date.
    ///
    /// A closed scope's series stops at its period, which is what keeps a later edit
    /// from extending a historical view.
    pub fn is_closed(&self) -> bool {
        self.snapshot_id.is_some() || self.period.end.is_some()
    }

    /// Whether `date` belongs to this scope's period. An event with no readable day
    /// is handled by [`EventIndex::contribute`], not here.
    pub fn contains(&self, date: &str) -> bool {
        self.period.contains(date)
    }
}

impl fmt::Display for AnalyticsScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let start = self.period_start().unwrap_or("open");
        let end = self.period_end().unwrap_or("open");
        write!(f, "{} `{}` {start}..{end}", self.kind, self.id)?;
        if let Some(snapshot_id) = self.snapshot_id.as_deref() {
            write!(f, " snapshot {snapshot_id}")?;
        }
        Ok(())
    }
}

/// Resolve a cycle scope through the existing planning registry (T001).
///
/// The period is the cycle's **own** declared `start_date`/`due_date`, so it comes
/// from existing planning data rather than from an assumption; a cycle that declares
/// neither is unbounded on that side, which the series reports as coverage.
pub fn cycle_scope(planner: &Planner, name: &str) -> Result<AnalyticsScope> {
    let cycle = planner
        .cycle(name)
        .ok_or_else(|| TixError::NotFound(format!("cycle `{name}`")))?;
    let period = Period::new(cycle.start_date.clone(), cycle.due_date.clone())?;
    AnalyticsScope::cycle(name, period)
}

/// Resolve a milestone scope through the existing planning registry (T001).
///
/// A milestone declares a target date and no start, so the period is bounded on its
/// end only — the same value the projection later forecasts against.
pub fn milestone_scope(planner: &Planner, name: &str) -> Result<AnalyticsScope> {
    let milestone = planner.milestone(name)?;
    let target = milestone.target_date.trim();
    let end = (!target.is_empty()).then(|| target.to_string());
    let period = Period::new(None, end)?;
    AnalyticsScope::milestone(name, period)
}

/// The closed classification vocabulary (`data-model.md` §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EventClass {
    /// The recorded event adds work to the selected scope's planned set.
    ScopeAddition,
    /// The recorded event completes work in the selected scope.
    Completion,
    /// The recorded event changes the planned size of work in the scope.
    EstimateChange,
    /// A recorded event this classification does not place, or one it can only
    /// partly read. Never counted as progress.
    Unclassified,
}

impl EventClass {
    /// Every class, in the order a surface renders them.
    pub const ALL: [EventClass; 4] = [
        EventClass::ScopeAddition,
        EventClass::Completion,
        EventClass::EstimateChange,
        EventClass::Unclassified,
    ];

    /// The canonical spelling (`data-model.md` §2: `scope_addition`, `completion`,
    /// `estimate_change`, `unclassified`).
    pub const fn as_str(self) -> &'static str {
        match self {
            EventClass::ScopeAddition => "scope_addition",
            EventClass::Completion => "completion",
            EventClass::EstimateChange => "estimate_change",
            EventClass::Unclassified => "unclassified",
        }
    }

    /// Parse a canonical spelling; `None` for anything outside the vocabulary.
    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "scope_addition" => Some(EventClass::ScopeAddition),
            "completion" => Some(EventClass::Completion),
            "estimate_change" => Some(EventClass::EstimateChange),
            "unclassified" => Some(EventClass::Unclassified),
            _ => None,
        }
    }

    /// Whether the event carries a class other than [`EventClass::Unclassified`].
    pub const fn is_classified(self) -> bool {
        !matches!(self, EventClass::Unclassified)
    }
}

impl fmt::Display for EventClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Where a recorded contribution came from (`data-model.md` §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EventSource {
    /// An append-only History entry.
    History,
    /// A closed cycle/milestone snapshot's own recorded value.
    Snapshot,
    /// A recorded frontmatter value.
    Frontmatter,
}

impl EventSource {
    /// Every source, in the order a surface renders them.
    pub const ALL: [EventSource; 3] = [
        EventSource::History,
        EventSource::Snapshot,
        EventSource::Frontmatter,
    ];

    /// The canonical spelling used in output.
    pub const fn as_str(self) -> &'static str {
        match self {
            EventSource::History => "history",
            EventSource::Snapshot => "snapshot",
            EventSource::Frontmatter => "frontmatter",
        }
    }

    /// Parse a canonical spelling; `None` for anything outside the vocabulary.
    pub fn parse(raw: &str) -> Option<Self> {
        match raw.trim().to_ascii_lowercase().as_str() {
            "history" => Some(EventSource::History),
            "snapshot" => Some(EventSource::Snapshot),
            "frontmatter" => Some(EventSource::Frontmatter),
            _ => None,
        }
    }
}

impl fmt::Display for EventSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One recorded contribution to a scope's series (`data-model.md` §2).
///
/// Every field is either read from the record or explicitly `None`. `delta` is the
/// **count-level** contribution of the event and is `None` where the event does not
/// carry one at that precision — a repoint, a membership change and an estimate
/// change all name their before/after values in [`Self::detail`], and inventing a
/// number for them would be the arithmetic C-003 forbids. `unit` is reserved for the
/// estimate mode's explicit conversion (WP03) and is `None` here.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalyticsEvent {
    /// Stable identity, and therefore the idempotency key (C-002).
    pub event_id: String,
    /// The canonical `YYYY-MM-DD` day the event is placed on, or `None` when the
    /// recorded timestamp carried no readable calendar date. `None` is coverage, not
    /// a fabricated day (C-005).
    pub date: Option<String>,
    /// The closed classification.
    pub class: EventClass,
    /// The issue the event belongs to, when the source ref is an issue number.
    pub issue: Option<u32>,
    /// The scope the event was classified against.
    pub scope_id: Option<String>,
    /// The count-level contribution, when the event carries one.
    pub delta: Option<i64>,
    /// The estimate unit, for the estimate mode's conversions (WP03).
    pub unit: Option<String>,
    /// Where the contribution came from.
    pub source: EventSource,
    /// The closed snapshot the contribution came from, when it is snapshot evidence.
    pub snapshot_id: Option<String>,
    /// The recorded detail, verbatim, so a reader can see the before/after values
    /// the classification did not turn into numbers.
    pub detail: String,
}

impl AnalyticsEvent {
    /// Classify one **recorded** History entry (T002–T004).
    ///
    /// `source_ref` names the file the entry lives in (an issue number, a generated
    /// cycle id) and `index` is its ordinal among that section's **parsed events**
    /// (see [`EventIndex::contribute_history`], which is what assigns it); together
    /// they are the event's stable identity, so re-reading the same file classifies
    /// the same event to the same id.
    pub fn from_history(
        source_ref: &str,
        index: usize,
        scope: &AnalyticsScope,
        event: &HistoryEvent,
    ) -> Self {
        let (class, delta) = classify(event);
        Self {
            event_id: format!("{source_ref}#{index}"),
            date: calendar_date(&event.timestamp),
            class,
            issue: source_ref.trim().parse::<u32>().ok(),
            scope_id: Some(scope.id.clone()),
            delta,
            unit: None,
            source: EventSource::History,
            snapshot_id: None,
            detail: event.detail.clone(),
        }
    }

    /// A contribution read from an immutable closed snapshot (T003/T005).
    ///
    /// The caller supplies values it **read from** the snapshot; nothing here
    /// derives a number from a schedule or a configuration, because those are
    /// exactly what a later edit is allowed to change (C-006). The event id is the
    /// snapshot's own stable `snapshot_id`, so the same closed snapshot contributes
    /// once however many times it is read.
    pub fn from_snapshot(
        snapshot_id: &str,
        date: Option<&str>,
        class: EventClass,
        scope_id: Option<&str>,
        delta: Option<i64>,
    ) -> Self {
        Self {
            event_id: format!("snapshot:{}", snapshot_id.trim()),
            date: date
                .map(str::trim)
                .filter(|d| validate_date(d))
                .map(str::to_string),
            class,
            issue: None,
            scope_id: scope_id.map(str::to_string),
            delta,
            unit: None,
            source: EventSource::Snapshot,
            snapshot_id: Some(snapshot_id.trim().to_string()),
            detail: String::new(),
        }
    }

    /// Whether the event is placed on `date`.
    pub fn is_on(&self, date: &str) -> bool {
        self.date.as_deref() == Some(date)
    }
}

/// What [`EventIndex::contribute`] did with one event.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Contribution {
    /// The event was recorded as a contribution.
    Added,
    /// The event's id was already present: a repeated classification contributes
    /// once (C-002).
    Duplicate,
    /// The event carries a day outside the scope's period, so it is not a
    /// contribution to this series. Counted, never discarded silently.
    OutsidePeriod,
}

impl Contribution {
    /// The canonical spelling used in output.
    pub const fn as_str(self) -> &'static str {
        match self {
            Contribution::Added => "added",
            Contribution::Duplicate => "duplicate",
            Contribution::OutsidePeriod => "outside_period",
        }
    }

    /// Whether this contribution changed the index.
    pub const fn contributed(self) -> bool {
        matches!(self, Contribution::Added)
    }
}

/// The contribution set for one scope: contributions in first-seen order,
/// deduplicated by event id (T005).
///
/// Inflating this type is deliberate — the count-mode fold (WP02) reads it once, so
/// a contribution cannot be counted twice by being walked twice, and the dedupe
/// lives here rather than at each caller.
#[derive(Debug, Clone)]
pub struct EventIndex {
    scope: AnalyticsScope,
    order: Vec<String>,
    events: HashMap<String, AnalyticsEvent>,
    /// Ids already refused for falling outside the scope's period.
    ///
    /// Remembered for the same reason the admitted ids are: one recorded event is one
    /// event, so classifying it again must report a duplicate rather than counting a
    /// second exclusion. Without this, a repeated fold inflated
    /// [`Self::outside_period`] and a caller reading it as a coverage size saw a count
    /// of *classifications*.
    outside_ids: HashSet<String>,
    duplicates: usize,
    outside_period: usize,
}

impl EventIndex {
    /// An empty index for a scope.
    pub fn new(scope: AnalyticsScope) -> Self {
        Self {
            scope,
            order: Vec::new(),
            events: HashMap::new(),
            outside_ids: HashSet::new(),
            duplicates: 0,
            outside_period: 0,
        }
    }

    /// The scope every contribution in this index was classified against.
    pub fn scope(&self) -> &AnalyticsScope {
        &self.scope
    }

    /// Contribute one event, reporting what happened.
    ///
    /// The duplicate check covers ids already **admitted and** ids already refused for
    /// being outside the period, and it comes first; the period check comes second. So
    /// classifying one recorded event twice is inert whichever side of the period it
    /// fell on, and both counters measure recorded events rather than classifications.
    pub fn contribute(&mut self, event: AnalyticsEvent) -> Contribution {
        if self.events.contains_key(&event.event_id) || self.outside_ids.contains(&event.event_id) {
            self.duplicates += 1;
            return Contribution::Duplicate;
        }
        if let Some(date) = event.date.as_deref()
            && !self.scope.contains(date)
        {
            self.outside_ids.insert(event.event_id);
            self.outside_period += 1;
            return Contribution::OutsidePeriod;
        }
        self.order.push(event.event_id.clone());
        self.events.insert(event.event_id.clone(), event);
        Contribution::Added
    }

    /// Contribute every parsed entry of a History section, returning how many were
    /// newly added.
    ///
    /// The ordinal an event is identified by counts **parsed events only**: an
    /// unparseable line a human inserted occupies no ordinal, so it cannot renumber
    /// the events after it and two classifications of one file agree on every id. A
    /// line that was a readable event and was mangled into unreadability does still
    /// close up the ordinals behind it — see the module's provenance note for why that
    /// is the accepted trade rather than a content hash.
    pub fn contribute_history(&mut self, source_ref: &str, history: &History) -> usize {
        let scope = self.scope.clone();
        let mut added = 0;
        let mut index = 0;
        for entry in &history.entries {
            let HistoryEntry::Event(event) = entry else {
                continue;
            };
            let event = AnalyticsEvent::from_history(source_ref, index, &scope, event);
            index += 1;
            if self.contribute(event).contributed() {
                added += 1;
            }
        }
        added
    }

    /// The contributed events, in first-seen order.
    pub fn events(&self) -> impl Iterator<Item = &AnalyticsEvent> + '_ {
        self.order.iter().filter_map(|id| self.events.get(id))
    }

    /// The contributed events of one class, in first-seen order.
    pub fn of_class(&self, class: EventClass) -> impl Iterator<Item = &AnalyticsEvent> + '_ {
        self.events().filter(move |event| event.class == class)
    }

    /// How many events of one class contributed.
    pub fn count_of(&self, class: EventClass) -> usize {
        self.of_class(class).count()
    }

    /// How many contributions the index holds.
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Whether the index holds no contribution at all — which is the honest answer
    /// for a project whose files carry no events, not an error.
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }

    /// How many repeated classifications the index rejected (C-002).
    pub fn duplicates(&self) -> usize {
        self.duplicates
    }

    /// How many recorded events fell outside the scope's period and were therefore
    /// not contributions — an **event** count, not a count of classifications, because
    /// an id already refused here is remembered (C-002). Coverage context: a non-zero
    /// count says the period excluded recorded history, never that the history is
    /// absent.
    pub fn outside_period(&self) -> usize {
        self.outside_period
    }
}

/// The recorded day a History timestamp names, when it carries one.
///
/// The timestamp is RFC 3339 (`2026-09-25T16:00:00Z`), so its first ten characters
/// are the calendar date; anything that is not a canonical date — including a
/// truncated or hand-mangled stamp — is `None` rather than a coerced guess.
pub fn calendar_date(timestamp: &str) -> Option<String> {
    let stamp = timestamp.trim();
    let date = stamp.get(..10)?;
    validate_date(date).then(|| date.to_string())
}

/// Classify one recorded event kind.
///
/// See the module documentation for the partition and why each entry is where it is.
fn classify(event: &HistoryEvent) -> (EventClass, Option<i64>) {
    match event.kind {
        // The hierarchy's membership kinds: the issue joins a scope. A *repoint*
        // names both parents in its detail, so it carries no count-level delta —
        // the departing scope's reduction is not something one event can express.
        HistoryEventKind::ParentSet => (EventClass::ScopeAddition, Some(1)),
        HistoryEventKind::ParentChanged => (EventClass::ScopeAddition, None),
        // WP01's own producer (T046/T047): a membership edit routinely adds and
        // removes in one command, so the direction is read from the detail the
        // producer writes. Only a change that **added** a cycle is an addition; a
        // change that only removed one is not growth and stays visible as unclassified.
        HistoryEventKind::CycleMembershipChanged => membership_outcome(&event.detail),
        // WP01's other producer: the planned size changed, not the membership.
        HistoryEventKind::EstimateChanged => (EventClass::EstimateChange, None),
        HistoryEventKind::TransitionAccepted => completion_outcome(event),
        // Everything else stays visible and unclassified — including every one of
        // #184's time-mutation kinds, which must never move a burndown line.
        _ => (EventClass::Unclassified, None),
    }
}

/// Whether a recorded transition completed the issue, read through the shared
/// category vocabulary the decision *recorded*.
fn completion_outcome(event: &HistoryEvent) -> (EventClass, Option<i64>) {
    let Ok(decision) = TransitionDecision::from_event(event) else {
        // A malformed or hand-edited decision is not counted as progress; the raw
        // detail is still carried on the event for a reader.
        return (EventClass::Unclassified, None);
    };
    match WorkflowCategory::from_key(&decision.to_category) {
        Some(category) if category.is_complete() => (EventClass::Completion, Some(1)),
        // A move into any other category is a move. `canceled` is terminal and is
        // *not* complete, and an unknown category is never read as one.
        _ => (EventClass::Unclassified, None),
    }
}

/// Whether a recorded membership change **added** a cycle, read from the detail the
/// producer writes.
///
/// The grammar is the one `tix edit --cycles` appends (`src/commands/edit.rs`):
/// `cycles: <before> -> <after>`, each side a comma-joined list of cycle names or
/// `none`. `--cycles` splits on commas, so a name cannot contain one, which is what
/// makes the list unambiguous. A detail that does not have that shape (a hand edit, a
/// future writer) is not guessed at: it classifies as unclassified and keeps its text
/// on the event, so a reader sees exactly what could not be read.
///
/// Only an **addition** counts. A change that removed cycles — `cycles: Default ->
/// none` — or merely reordered them has nothing to add, so it is not growth; the
/// closed four-name vocabulary has no removal class, and reading one as an addition
/// would be the exact confusion FR-002 exists to prevent.
///
/// The delta is `None` because the count a membership change carries is per *joined*
/// cycle, and which cycle the series is for is the fold's question (WP02); a
/// scope-agnostic `Some(1)` here would credit a cycle the event never named.
fn membership_outcome(detail: &str) -> (EventClass, Option<i64>) {
    let Some((before, after)) = membership_lists(detail) else {
        return (EventClass::Unclassified, None);
    };
    if after.iter().any(|name| !before.contains(name)) {
        (EventClass::ScopeAddition, None)
    } else {
        (EventClass::Unclassified, None)
    }
}

/// The before/after cycle lists a `cycle_membership_changed` detail names.
fn membership_lists(detail: &str) -> Option<(Vec<String>, Vec<String>)> {
    let rest = detail.trim().strip_prefix("cycles:")?;
    let (before, after) = rest.split_once("->")?;
    Some((membership_list(before), membership_list(after)))
}

/// One side of the membership detail: the names, or empty for `none`.
fn membership_list(side: &str) -> Vec<String> {
    let side = side.trim();
    if side.is_empty() || side == "none" {
        return Vec::new();
    }
    side.split(',')
        .map(str::trim)
        .filter(|name| !name.is_empty())
        .map(str::to_string)
        .collect()
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::utc_now_rfc3339;

    fn scope() -> AnalyticsScope {
        AnalyticsScope::cycle("Sprint 7", Period::new(None, None).unwrap()).unwrap()
    }

    fn history_event(kind: HistoryEventKind, detail: &str) -> HistoryEvent {
        HistoryEvent::new("2026-09-25T16:00:00Z", "alice", kind, detail)
    }

    #[test]
    fn t005_the_period_bounds_are_validated_and_inclusive() {
        let period = Period::new(Some("2026-09-01".into()), Some("2026-09-30".into())).unwrap();
        assert!(period.contains("2026-09-01"), "start is inclusive");
        assert!(period.contains("2026-09-30"), "end is inclusive");
        assert!(!period.contains("2026-08-31"), "the day before is out");
        assert!(!period.contains("2026-10-01"), "the day after is out");
        // The load-bearing case for the validator: a malformed day that *sorts inside*
        // the bounds (`2026-09-1` is greater than `2026-09-01` and less than
        // `2026-09-30` character by character), so the bounds comparison alone would
        // admit it. Deleting `validate_date` from `contains` makes this assertion fail.
        assert!(
            !period.contains("2026-09-1"),
            "a malformed day inside the bounds is still not placed"
        );
        assert!(
            !period.contains("2026-09-01T00:00:00Z"),
            "a stamp is not a day either"
        );
        assert!(
            !period.contains("not-a-date"),
            "an unreadable day is not placed"
        );
        assert!(Period::unbounded().contains("1999-01-01"), "open is open");

        let backwards = Period::new(Some("2026-09-30".into()), Some("2026-09-01".into()));
        assert!(backwards.is_err(), "a backwards period is refused");
        let malformed = Period::new(Some("2026-9-1".into()), None);
        assert!(malformed.is_err(), "a non-canonical bound is refused");
    }

    #[test]
    fn t006_a_blank_scope_name_is_refused() {
        assert!(AnalyticsScope::cycle("  ", Period::unbounded()).is_err());
    }

    #[test]
    fn t005_a_duplicate_event_contributes_once() {
        let mut index = EventIndex::new(scope());
        let event = history_event(HistoryEventKind::EstimateChanged, "estimate: none -> 3");
        let classified = AnalyticsEvent::from_history("7", 0, index.scope(), &event);
        assert_eq!(index.contribute(classified.clone()), Contribution::Added);
        assert_eq!(
            index.contribute(classified.clone()),
            Contribution::Duplicate
        );
        assert_eq!(index.len(), 1, "the same event contributed once");
        assert_eq!(index.duplicates(), 1);
        assert_eq!(index.of_class(EventClass::EstimateChange).count(), 1);
    }

    #[test]
    fn t001_the_scope_classifies_only_the_event_it_was_given() {
        let index = EventIndex::new(scope());
        let event = history_event(HistoryEventKind::ParentSet, "parent none -> #1");
        let classified = AnalyticsEvent::from_history("7", 3, index.scope(), &event);
        assert_eq!(classified.event_id, "7#3");
        assert_eq!(classified.issue, Some(7));
        assert_eq!(classified.scope_id.as_deref(), Some("Sprint 7"));
        assert_eq!(classified.date.as_deref(), Some("2026-09-25"));
        assert_eq!(classified.class, EventClass::ScopeAddition);
        assert_eq!(classified.delta, Some(1));
        assert_eq!(classified.source, EventSource::History);
    }

    #[test]
    fn t005_an_unreadable_timestamp_is_no_day_rather_than_a_guess() {
        assert_eq!(
            calendar_date("2026-09-25T16:00:00Z").as_deref(),
            Some("2026-09-25")
        );
        assert_eq!(
            calendar_date("2026-13-45T00:00:00Z"),
            None,
            "not a real date"
        );
        assert_eq!(calendar_date("2026-09"), None, "truncated");
        assert_eq!(calendar_date(""), None);
    }

    #[test]
    fn t005_a_snapshot_contribution_is_identified_by_its_snapshot() {
        let mut index = EventIndex::new(scope());
        let event = AnalyticsEvent::from_snapshot(
            "cs-1:000001@2026-09-30T00:00:00Z",
            Some("2026-09-30"),
            EventClass::Completion,
            Some("cs-1:000001"),
            Some(2),
        );
        assert_eq!(index.contribute(event.clone()), Contribution::Added);
        assert_eq!(index.contribute(event), Contribution::Duplicate);
        assert_eq!(index.len(), 1);
        let stored = index.events().next().unwrap();
        assert_eq!(stored.event_id, "snapshot:cs-1:000001@2026-09-30T00:00:00Z");
        assert_eq!(stored.source, EventSource::Snapshot);
        assert_eq!(
            stored.snapshot_id.as_deref(),
            Some("cs-1:000001@2026-09-30T00:00:00Z"),
            "the closed snapshot's identity is retained verbatim"
        );
    }

    #[test]
    fn t005_a_time_mutation_kind_is_never_progress() {
        for kind in [
            HistoryEventKind::TimeEntryCreated,
            HistoryEventKind::TimeEntryUpdated,
            HistoryEventKind::TimeEntryDeleted,
        ] {
            let event = history_event(kind, "entry t-1; created 30m on 2026-09-25 by alice");
            let classified = AnalyticsEvent::from_history("7", 0, &scope(), &event);
            assert_eq!(
                classified.class,
                EventClass::Unclassified,
                "{kind} must not be read as progress"
            );
            assert_eq!(classified.delta, None);
        }
    }

    #[test]
    fn t003_a_parent_cleared_event_is_not_growth() {
        let event = history_event(HistoryEventKind::ParentCleared, "parent #1 -> none");
        let classified = AnalyticsEvent::from_history("7", 0, &scope(), &event);
        assert_eq!(classified.class, EventClass::Unclassified);
        assert_eq!(classified.delta, None, "a removal is never counted as +1");
    }

    #[test]
    fn t003_a_membership_change_is_read_by_direction() {
        for (detail, class) in [
            ("cycles: none -> Default", EventClass::ScopeAddition),
            (
                "cycles: Default -> Default, Sprint 7",
                EventClass::ScopeAddition,
            ),
            ("cycles: Default -> none", EventClass::Unclassified),
            (
                "cycles: Default, Sprint 7 -> Default",
                EventClass::Unclassified,
            ),
            (
                "cycles: Default, Sprint 7 -> Sprint 7, Default",
                EventClass::Unclassified,
            ),
            ("mangled", EventClass::Unclassified),
            ("cycles: Default ->", EventClass::Unclassified),
        ] {
            let event = history_event(HistoryEventKind::CycleMembershipChanged, detail);
            let classified = AnalyticsEvent::from_history("7", 0, &scope(), &event);
            assert_eq!(classified.class, class, "{detail}");
            assert_eq!(classified.delta, None, "{detail}");
            assert_eq!(classified.detail, detail, "the record is kept verbatim");
        }
    }

    #[test]
    fn t005_a_repeated_out_of_period_event_is_a_duplicate_not_a_second_exclusion() {
        let period = Period::new(Some("2026-09-01".into()), Some("2026-09-30".into())).unwrap();
        let bounded = AnalyticsScope::cycle("Sprint 7", period).unwrap();
        let mut index = EventIndex::new(bounded);
        let event = HistoryEvent::new(
            "2026-10-05T00:00:00Z",
            "alice",
            HistoryEventKind::ParentSet,
            "parent none -> #2",
        );
        let classified = AnalyticsEvent::from_history("1", 0, index.scope(), &event);
        assert_eq!(
            index.contribute(classified.clone()),
            Contribution::OutsidePeriod
        );
        assert_eq!(
            index.contribute(classified),
            Contribution::Duplicate,
            "one recorded event, however often it is classified"
        );
        assert_eq!(
            index.outside_period(),
            1,
            "an event count, not a count of classifications"
        );
        assert_eq!(index.duplicates(), 1);
        assert_eq!(index.len(), 0);
    }

    #[test]
    fn t004_a_malformed_transition_record_is_not_a_completion() {
        let event = history_event(HistoryEventKind::TransitionAccepted, "mangled");
        let classified = AnalyticsEvent::from_history("7", 0, &scope(), &event);
        assert_eq!(classified.class, EventClass::Unclassified);
        assert_eq!(classified.detail, "mangled", "the raw record is kept");
    }

    #[test]
    fn t005_the_round_trip_of_a_recorded_file_is_idempotent() {
        let mut history = History::new();
        history.append(HistoryEvent::new(
            utc_now_rfc3339(),
            "alice",
            HistoryEventKind::EstimateChanged,
            "estimate: none -> 3",
        ));
        let mut index = EventIndex::new(scope());
        assert_eq!(index.contribute_history("7", &history), 1);
        assert_eq!(index.contribute_history("7", &history), 0, "already seen");
        assert_eq!(index.len(), 1, "the same file contributes once");
    }
}