tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
//! Stable series identity, lifecycle metadata, and the occurrence-key index
//! (mission `recurring-issues-01M3C7G7`, WP02; `data-model.md` §1/§3/§4 and
//! `contracts/series-generator.md`).
//!
//! # Identity is the pair, never the label
//!
//! A series is identified by its **stable id**, and one scheduled occurrence by
//! the pair (**series id**, canonical date key). The display name, the issue
//! number and the title slug are none of them identity: a rename or a renumber
//! must not change what an occurrence *is*, or the next detection would generate
//! it again. C-002 says the same in one line, and [`OccurrenceKey`] is that
//! sentence as a type.
//!
//! # Where the data lives
//!
//! Both roles are one table in issue frontmatter — `series:` — so the series
//! definition **is** an issue (C-001: Markdown is canonical; there is no queue
//! database and no daemon to own it). Which role a table carries is decided by
//! its fields, not by a flag a writer could set inconsistently:
//!
//! * a **definition** carries `rule` (and `name`, `state`, `next_cursor`,
//!   `skipped`);
//! * an **occurrence** carries the `key` and `date` it was generated for.
//!
//! # This module indexes; it does not write
//!
//! [`SeriesIndex`] is built from issues the caller already read and answers three
//! questions: which series exist, which occurrence keys are already taken
//! (generated **or** skipped), and whether the data is internally consistent. It
//! reports every finding instead of failing on the first, because a repository
//! with one malformed series must still list the others.
//!
//! Generation, detection and lifecycle transitions are **not** here: WP03 owns
//! read-only detection, WP04 the confirmed generator, WP05 the lifecycle. The one
//! thing this module refuses on behalf of all of them is a **cycle**. The only
//! reference this model forms is occurrence → series, so the only cycle is a
//! definition that is its own occurrence, reported as
//! [`SeriesDiagnosticKind::SeriesIsItsOwnOccurrence`].

use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::{Deserialize, Serialize};
use time::{Date, Month};

use crate::error::render_diagnostics;
use crate::model::{Issue, SeriesRef, SeriesRule};
use crate::recurrence::rule::{DateKey, IntervalUnit, RecurrenceRule, RuleKind, Timezone};

/// Which role a `series:` table plays.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SeriesRole {
    /// The issue *is* the recurring definition: it carries the rule.
    Definition,
    /// The issue was generated from a series: it carries an occurrence key.
    Occurrence,
}

impl SeriesRef {
    /// The role this table plays, decided by its fields (see the module docs).
    ///
    /// A table with a `rule` is a definition; anything else is an occurrence — a
    /// table with neither is an occurrence missing its key, which
    /// [`SeriesIndex::build`] reports rather than guessing at.
    pub fn role(&self) -> SeriesRole {
        if self.rule.is_some() {
            SeriesRole::Definition
        } else {
            SeriesRole::Occurrence
        }
    }
}

/// The lifecycle state of a series (`data-model.md` §4).
///
/// `Ended` is terminal for generation; `Paused` suspends it until an explicit
/// resume. Neither reaches back into the occurrences already generated: an
/// occurrence is an independent issue (C-005).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum SeriesLifecycle {
    /// Generating occurrences is allowed.
    #[default]
    Active,
    /// Generating is suspended until an explicit resume.
    Paused,
    /// Terminal: no further occurrence is generated.
    Ended,
}

impl SeriesLifecycle {
    /// The persisted spelling, which is also what the CLI prints.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Active => "active",
            Self::Paused => "paused",
            Self::Ended => "ended",
        }
    }

    /// Whether this state allows a new occurrence to be generated. Only `Active`
    /// does; `Paused` is a suspension and `Ended` a terminus.
    pub const fn allows_generation(self) -> bool {
        matches!(self, Self::Active)
    }
}

/// A series id: a stable, non-empty token.
///
/// The shape is deliberately strict — ASCII letters, digits, `-`, `_`, `.` —
/// because the id is embedded in a derived occurrence key that is parsed back out
/// of frontmatter. An id that needed quoting would be a second grammar in a field
/// whose whole point is that it needs none. `SeriesId::generate` mints `s-` plus
/// eight Crockford base32 characters, the same alphabet [`crate::id`] gives
/// issues.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SeriesId(String);

impl SeriesId {
    /// Validate `raw` as a series id.
    pub fn parse(raw: &str) -> Result<Self, SeriesError> {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            return Err(SeriesError::single(SeriesDiagnostic::new(
                SeriesDiagnosticKind::InvalidSeriesId,
                "series.id",
                "a series id cannot be empty",
            )));
        }
        if !trimmed
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.')
        {
            return Err(SeriesError::single(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::InvalidSeriesId,
                    "series.id",
                    "a series id may hold only ASCII letters, digits, `-`, `_` and `.`",
                )
                .with_value(raw),
            ));
        }
        Ok(Self(trimmed.to_string()))
    }

    /// Mint a fresh id: `s-` plus eight Crockford base32 characters.
    pub fn generate() -> Self {
        Self(format!("s-{}", crate::id::generate_issue_id()))
    }

    /// The id as a string.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

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

/// One scheduled occurrence's stable identity (`data-model.md` §3).
///
/// The key is `<series-id>@<YYYY-MM-DD>`: the same series and the same canonical
/// date always produce the same key, so a second generation attempt is a lookup
/// and never a duplicate. It is **stored** (in `series.key`) rather than
/// re-derived, so a file whose key the rule would no longer produce is still
/// readable — and still a no-op (C-006).
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct OccurrenceKey(String);

impl OccurrenceKey {
    /// The key for `series` on `date`.
    pub fn new(series: &SeriesId, date: &DateKey) -> Self {
        Self(format!("{}@{}", series.as_str(), date.as_str()))
    }

    /// The key as a string, as `series.key` stores it.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Parse a stored key back into its two parts.
    ///
    /// The separator is `@`, which no series id and no date key can contain — the
    /// id is validated above and a date key is exactly `YYYY-MM-DD`.
    pub fn parse(raw: &str) -> Result<(SeriesId, DateKey), SeriesError> {
        let Some((id, date)) = raw.split_once('@') else {
            return Err(SeriesError::single(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::MalformedKey,
                    "series.key",
                    "a key is `<series-id>@<YYYY-MM-DD>`",
                )
                .with_value(raw),
            ));
        };
        let id = SeriesId::parse(id)?;
        let date = parse_date_key(date).ok_or_else(|| {
            SeriesError::single(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::MalformedKey,
                    "series.key",
                    "the date half must be a real `YYYY-MM-DD` calendar date",
                )
                .with_value(raw),
            )
        })?;
        Ok((id, date))
    }
}

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

/// A series definition, as its issue carries it (`data-model.md` §1 + §4).
///
/// Built from the frontmatter by [`Series::from_ref`]. The defining issue's number
/// and filename are carried for diagnostics and listing, never for identity.
#[derive(Debug, Clone, PartialEq)]
pub struct Series {
    /// The stable id.
    pub id: SeriesId,
    /// The mutable display name.
    pub name: String,
    /// The validated rule.
    pub rule: RecurrenceRule,
    /// The lifecycle state.
    pub state: SeriesLifecycle,
    /// The generation cursor, when one is recorded.
    pub next_cursor: Option<DateKey>,
    /// Occurrence dates that were skipped, so generation never recreates them.
    pub skipped: BTreeSet<DateKey>,
    /// The issue that defines this series.
    pub issue_number: u32,
    /// The defining issue's filename, for diagnostics.
    pub filename: String,
}

impl Series {
    /// Read a definition out of a `series:` table.
    ///
    /// `Ok(None)` for a table that is an occurrence (no `rule`), so a caller can
    /// map over a whole corpus without classifying it first. Every field a
    /// definition needs is checked here: an unusable id, a missing name, and a
    /// rule that does not validate are field-aware diagnostics, and nothing is
    /// defaulted silently.
    pub fn from_ref(
        reference: &SeriesRef,
        issue_number: u32,
        filename: &str,
    ) -> Result<Option<Self>, SeriesError> {
        if reference.role() != SeriesRole::Definition {
            return Ok(None);
        }
        let mut diagnostics: Vec<SeriesDiagnostic> = Vec::new();
        let id = match SeriesId::parse(&reference.id) {
            Ok(id) => Some(id),
            Err(error) => {
                diagnostics.extend(error.diagnostics().iter().cloned());
                None
            }
        };
        let name = reference.name.clone().unwrap_or_default();
        if name.trim().is_empty() {
            diagnostics.push(SeriesDiagnostic::new(
                SeriesDiagnosticKind::MissingField,
                "series.name",
                "a series definition needs a display name (`series.name`)",
            ));
        }
        let stored = reference
            .rule
            .as_ref()
            .expect("`role()` says a rule is set");
        let rule = match typed_rule(stored) {
            Ok(rule) => Some(rule),
            Err(error) => {
                diagnostics.extend(error.diagnostics().iter().cloned());
                None
            }
        };
        if let Some(rule) = rule.as_ref()
            && let Err(error) = rule.validate()
        {
            diagnostics.extend(error.diagnostics().iter().map(|diagnostic| {
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::InvalidRule,
                    format!("series.rule.{}", diagnostic.field),
                    diagnostic.message.clone(),
                )
            }));
        }
        if !diagnostics.is_empty() {
            return Err(SeriesError::new(diagnostics));
        }
        Ok(Some(Self {
            id: id.expect("an unusable id is a diagnostic"),
            name,
            rule: rule.expect("a rule that does not build is a diagnostic"),
            state: reference.state.unwrap_or_default(),
            next_cursor: reference.next_cursor.as_deref().and_then(parse_date_key),
            skipped: reference
                .skipped
                .iter()
                .filter_map(|raw| parse_date_key(raw))
                .collect(),
            issue_number,
            filename: filename.to_string(),
        }))
    }

    /// Whether this series may generate a new occurrence right now.
    pub const fn allows_generation(&self) -> bool {
        self.state.allows_generation()
    }

    /// The occurrence key for `date` under this series.
    pub fn key_for(&self, date: &DateKey) -> OccurrenceKey {
        OccurrenceKey::new(&self.id, date)
    }

    /// Whether `date` was explicitly skipped, so generation must not recreate it.
    pub fn is_skipped(&self, date: &DateKey) -> bool {
        self.skipped.contains(date)
    }
}

/// One occurrence, as the index resolved it from the issues it was built over.
#[derive(Debug, Clone, PartialEq)]
pub struct OccurrenceRecord {
    /// The series it belongs to.
    pub series_id: SeriesId,
    /// The canonical date it was generated for.
    pub date: DateKey,
    /// Its idempotency key.
    pub key: OccurrenceKey,
    /// The issue that carries it.
    pub issue_number: u32,
    /// That issue's filename, for diagnostics.
    pub filename: String,
}

/// What the index can say about a key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum KeyState {
    /// An occurrence issue exists for it.
    Generated,
    /// The series recorded the date as skipped.
    Skipped,
    /// Neither: the key is free to generate.
    Free,
}

/// The kinds of inconsistency the index reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SeriesDiagnosticKind {
    /// A series id is not a usable token.
    InvalidSeriesId,
    /// Two issues define the same series id.
    DuplicateSeriesId,
    /// A definition is missing a field the model requires.
    MissingField,
    /// The rule itself is invalid; the diagnostic carries the rule's own message.
    InvalidRule,
    /// A `series.key` is not `<id>@<date>`.
    MalformedKey,
    /// `series.id` and the id half of `series.key` disagree.
    KeySeriesMismatch,
    /// `series.date` and the date half of `series.key` disagree.
    KeyDateMismatch,
    /// An occurrence carries no key, so it could never be recognised again.
    MissingOccurrenceKey,
    /// Two issues claim the same occurrence key.
    DuplicateOccurrenceKey,
    /// A definition is also an occurrence of itself — this model's only cycle.
    SeriesIsItsOwnOccurrence,
}

impl SeriesDiagnosticKind {
    /// The stable spelling `tix lint` and the CLI print.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::InvalidSeriesId => "invalid_series_id",
            Self::DuplicateSeriesId => "duplicate_series_id",
            Self::MissingField => "missing_series_field",
            Self::InvalidRule => "invalid_series_rule",
            Self::MalformedKey => "malformed_occurrence_key",
            Self::KeySeriesMismatch => "occurrence_key_series_mismatch",
            Self::KeyDateMismatch => "occurrence_key_date_mismatch",
            Self::MissingOccurrenceKey => "missing_occurrence_key",
            Self::DuplicateOccurrenceKey => "duplicate_occurrence_key",
            Self::SeriesIsItsOwnOccurrence => "series_is_its_own_occurrence",
        }
    }
}

/// One actionable finding, naming the issue and the field it is about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeriesDiagnostic {
    /// What is wrong.
    pub kind: SeriesDiagnosticKind,
    /// The issue the finding is about; `0` before it is attached to one.
    pub issue_number: u32,
    /// The issue's filename, empty before it is attached to one.
    pub filename: String,
    /// The field path, e.g. `series.key`.
    pub field: String,
    /// One sentence saying what to do about it.
    pub message: String,
}

impl SeriesDiagnostic {
    /// A finding about `field`, before it is attached to an issue.
    pub fn new(
        kind: SeriesDiagnosticKind,
        field: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            issue_number: 0,
            filename: String::new(),
            field: field.into(),
            message: message.into(),
        }
    }

    /// Name the offending value in the message.
    pub fn with_value(mut self, raw: &str) -> Self {
        self.message = format!("{} (got `{raw}`)", self.message);
        self
    }

    /// Attach the finding to the issue it came from.
    pub fn on(mut self, issue_number: u32, filename: &str) -> Self {
        self.issue_number = issue_number;
        self.filename = filename.to_string();
        self
    }

    /// Render through the crate's one diagnostic renderer, so the CLI, the TUI,
    /// MCP and `tix lint` spell a refusal the same way.
    pub fn render(&self) -> String {
        render_diagnostics(
            "E-tix-series",
            std::iter::once((self.kind.as_str(), self.message.as_str())),
        )
    }
}

/// A set of findings, reported together.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeriesError {
    diagnostics: Vec<SeriesDiagnostic>,
}

impl SeriesError {
    /// Wrap the findings.
    pub fn new(diagnostics: Vec<SeriesDiagnostic>) -> Self {
        Self { diagnostics }
    }

    /// A single finding.
    pub fn single(diagnostic: SeriesDiagnostic) -> Self {
        Self {
            diagnostics: vec![diagnostic],
        }
    }

    /// Every finding, in the order produced.
    pub fn diagnostics(&self) -> &[SeriesDiagnostic] {
        &self.diagnostics
    }

    /// The first finding, for a caller that can only show one.
    pub fn first(&self) -> &SeriesDiagnostic {
        &self.diagnostics[0]
    }
}

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

/// The series and occurrence picture over a set of issues.
///
/// One pass over issues the caller already holds: no I/O, no clock, no writes.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct SeriesIndex {
    series: BTreeMap<SeriesId, Series>,
    occurrences: BTreeMap<OccurrenceKey, OccurrenceRecord>,
    diagnostics: Vec<SeriesDiagnostic>,
}

impl SeriesIndex {
    /// Index `issues`.
    ///
    /// Every issue is examined once: a definition is parsed and validated, an
    /// occurrence is parsed into its key, and anything inconsistent becomes a
    /// diagnostic while the rest of the index stays usable.
    pub fn build(issues: &[Issue]) -> Self {
        let mut index = Self::default();
        for issue in issues {
            if let Some(reference) = issue.series.as_ref() {
                index.absorb(issue, reference);
            }
        }
        index.check_cycles(issues);
        index
    }

    fn absorb(&mut self, issue: &Issue, reference: &SeriesRef) {
        match reference.role() {
            SeriesRole::Definition => self.absorb_definition(issue, reference),
            SeriesRole::Occurrence => self.absorb_occurrence(issue, reference),
        }
    }

    fn absorb_definition(&mut self, issue: &Issue, reference: &SeriesRef) {
        match Series::from_ref(reference, issue.number, &issue.filename) {
            Ok(Some(series)) => {
                if let Some(previous) = self.series.get(&series.id) {
                    self.diagnostics.push(
                        SeriesDiagnostic::new(
                            SeriesDiagnosticKind::DuplicateSeriesId,
                            "series.id",
                            format!(
                                "series `{}` is already defined by {}; two issues cannot share \
                                 one series id",
                                series.id, previous.filename
                            ),
                        )
                        .on(issue.number, &issue.filename),
                    );
                    return;
                }
                self.series.insert(series.id.clone(), series);
            }
            Ok(None) => {}
            Err(error) => self.diagnostics.extend(
                error
                    .diagnostics()
                    .iter()
                    .cloned()
                    .map(|diagnostic| diagnostic.on(issue.number, &issue.filename)),
            ),
        }
    }

    fn absorb_occurrence(&mut self, issue: &Issue, reference: &SeriesRef) {
        let Some(raw_key) = reference.key.as_deref() else {
            self.diagnostics.push(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::MissingOccurrenceKey,
                    "series.key",
                    "an occurrence needs the key it was generated for \
                     (`<series-id>@<YYYY-MM-DD>`)",
                )
                .on(issue.number, &issue.filename),
            );
            return;
        };
        let (series_id, date) = match OccurrenceKey::parse(raw_key) {
            Ok(parts) => parts,
            Err(error) => {
                self.diagnostics.extend(
                    error
                        .diagnostics()
                        .iter()
                        .cloned()
                        .map(|diagnostic| diagnostic.on(issue.number, &issue.filename)),
                );
                return;
            }
        };
        if series_id.as_str() != reference.id {
            self.diagnostics.push(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::KeySeriesMismatch,
                    "series.key",
                    format!(
                        "the key names series `{series_id}` but `series.id` is `{}`",
                        reference.id
                    ),
                )
                .on(issue.number, &issue.filename),
            );
        }
        if let Some(declared) = reference.date.as_deref()
            && declared != date.as_str()
        {
            self.diagnostics.push(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::KeyDateMismatch,
                    "series.date",
                    format!("`series.date` is `{declared}` but the key names `{date}`"),
                )
                .on(issue.number, &issue.filename),
            );
        }
        let key = OccurrenceKey::new(&series_id, &date);
        if let Some(previous) = self.occurrences.get(&key) {
            self.diagnostics.push(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::DuplicateOccurrenceKey,
                    "series.key",
                    format!(
                        "occurrence `{key}` already belongs to {}; one key is one occurrence",
                        previous.filename
                    ),
                )
                .on(issue.number, &issue.filename),
            );
            return;
        }
        self.occurrences.insert(
            key.clone(),
            OccurrenceRecord {
                series_id,
                date,
                key,
                issue_number: issue.number,
                filename: issue.filename.clone(),
            },
        );
    }

    /// The model's only possible cycle: an issue that is both a definition and an
    /// occurrence. The reference graph is occurrence → series, so a cycle needs one
    /// issue to sit on both sides of that edge — and while it does, "generate the
    /// next occurrence" could target the definition itself.
    ///
    /// A `key` on a definition is the whole test: `role()` says definition because
    /// the rule is set, and the key says the same issue is also an occurrence.
    fn check_cycles(&mut self, issues: &[Issue]) {
        for issue in issues {
            let Some(reference) = issue.series.as_ref() else {
                continue;
            };
            if reference.role() != SeriesRole::Definition {
                continue;
            }
            let Some(raw_key) = reference.key.as_deref() else {
                continue;
            };
            self.diagnostics.push(
                SeriesDiagnostic::new(
                    SeriesDiagnosticKind::SeriesIsItsOwnOccurrence,
                    "series.key",
                    format!(
                        "issue {} defines series `{}` and also carries the occurrence key \
                         `{raw_key}`; a definition cannot be an occurrence of the series it \
                         would generate",
                        issue.number, reference.id
                    ),
                )
                .on(issue.number, &issue.filename),
            );
        }
    }

    /// The definitions, in id order.
    pub fn series(&self) -> impl Iterator<Item = &Series> {
        self.series.values()
    }

    /// One definition by id.
    pub fn series_by_id(&self, id: &SeriesId) -> Option<&Series> {
        self.series.get(id)
    }

    /// How many definitions the index holds.
    pub fn series_count(&self) -> usize {
        self.series.len()
    }

    /// One occurrence by key.
    pub fn occurrence(&self, key: &OccurrenceKey) -> Option<&OccurrenceRecord> {
        self.occurrences.get(key)
    }

    /// Every occurrence, in key order — chronological per series, and stable
    /// across runs.
    pub fn occurrences(&self) -> impl Iterator<Item = &OccurrenceRecord> {
        self.occurrences.values()
    }

    /// What the index knows about `key`.
    pub fn key_state(&self, key: &OccurrenceKey) -> KeyState {
        if self.occurrences.contains_key(key) {
            return KeyState::Generated;
        }
        if let Ok((id, date)) = OccurrenceKey::parse(key.as_str())
            && self
                .series
                .get(&id)
                .is_some_and(|series| series.is_skipped(&date))
        {
            return KeyState::Skipped;
        }
        KeyState::Free
    }

    /// Whether `key` is taken — generated **or** explicitly skipped, which is what
    /// keeps a skipped date from being generated the next time detection runs
    /// (C-006).
    pub fn is_taken(&self, key: &OccurrenceKey) -> bool {
        self.key_state(key) != KeyState::Free
    }

    /// Every finding, in the order the issues were visited.
    pub fn diagnostics(&self) -> &[SeriesDiagnostic] {
        &self.diagnostics
    }

    /// Whether the index is internally consistent.
    pub fn is_consistent(&self) -> bool {
        self.diagnostics.is_empty()
    }
}

/// Build the typed rule from the shape the file stores (`data-model.md` §2).
///
/// Every named field is read from the stored table and the result is validated by
/// the rule's own `validate`, so a series whose rule is wrong is reported with the
/// rule's field-aware diagnostics and not with a type error. An unknown cadence
/// key is carried through: the stored shape is flat, like every other preserved
/// metadata area in this crate, and it is the model that keeps the file's own
/// table — this value is for validation and arithmetic.
fn typed_rule(stored: &SeriesRule) -> Result<RecurrenceRule, SeriesError> {
    let mut diagnostics = Vec::new();
    let kind = match stored.kind.as_deref().map(str::trim) {
        Some(raw) => match parse_kind(raw) {
            Some(kind) => Some(kind),
            None => {
                diagnostics.push(
                    SeriesDiagnostic::new(
                        SeriesDiagnosticKind::InvalidRule,
                        "series.rule.kind",
                        "the rule kind must be one of `daily`, `weekly`, `monthly`,                          `interval`, `cron-like`",
                    )
                    .with_value(raw),
                );
                None
            }
        },
        None => {
            diagnostics.push(SeriesDiagnostic::new(
                SeriesDiagnosticKind::InvalidRule,
                "series.rule.kind",
                "a series rule needs a kind (`series.rule.kind`)",
            ));
            None
        }
    };
    let unit = match stored.unit.as_deref().map(str::trim) {
        Some(raw) => match parse_unit(raw) {
            Some(unit) => Some(unit),
            None => {
                diagnostics.push(
                    SeriesDiagnostic::new(
                        SeriesDiagnosticKind::InvalidRule,
                        "series.rule.unit",
                        "the unit must be one of `days`, `weeks`, `months`",
                    )
                    .with_value(raw),
                );
                None
            }
        },
        None => None,
    };
    if !diagnostics.is_empty() {
        return Err(SeriesError::new(diagnostics));
    }
    Ok(RecurrenceRule {
        kind: kind.expect("a missing kind is a diagnostic"),
        interval: stored.interval,
        anchor: stored.anchor.clone(),
        timezone: stored.timezone.as_deref().map(Timezone::parse),
        expression: stored.expression.clone(),
        unit,
        extensions: stored
            .extensions
            .iter()
            .map(|(key, value)| (key.clone(), serde_yaml::Value::String(value.clone())))
            .collect(),
    })
}

/// The family a stored kind names, or `None` when it names one this build does
/// not support. The spellings are the contract's and match `RuleKind::as_str`.
fn parse_kind(raw: &str) -> Option<RuleKind> {
    match raw {
        "daily" => Some(RuleKind::Daily),
        "weekly" => Some(RuleKind::Weekly),
        "monthly" => Some(RuleKind::Monthly),
        "interval" => Some(RuleKind::Interval),
        "cron-like" => Some(RuleKind::CronLike),
        _ => None,
    }
}

/// The unit a stored spelling names, or `None` when it names one this build does
/// not support. Matches `IntervalUnit::as_str`.
fn parse_unit(raw: &str) -> Option<IntervalUnit> {
    match raw {
        "days" => Some(IntervalUnit::Days),
        "weeks" => Some(IntervalUnit::Weeks),
        "months" => Some(IntervalUnit::Months),
        _ => None,
    }
}

/// Parse a canonical `YYYY-MM-DD` date key.
///
/// The calendar authority is [`crate::model::validate_date`] — the same check
/// every other stored date passes — so a series date cannot be "a date" to one
/// part of the crate and not another; `time` provides the value.
fn parse_date_key(raw: &str) -> Option<DateKey> {
    if !crate::model::validate_date(raw) {
        return None;
    }
    let year: i32 = raw.get(0..4)?.parse().ok()?;
    let month: u8 = raw.get(5..7)?.parse().ok()?;
    let day: u8 = raw.get(8..10)?.parse().ok()?;
    let date = Date::from_calendar_date(year, Month::try_from(month).ok()?, day).ok()?;
    Some(DateKey::from_date(date))
}

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

    /// An issue from a frontmatter block, through the real parser: the `series:`
    /// contract is the file format, so the fixtures use the file format.
    fn issue(number: u32, filename: &str, series: &str) -> Issue {
        let contents = format!(
            "---\nnumber: {number}\ntitle: \"Fixture {number}\"\nstatus: \"todo\"\n\
             created: \"2026-01-01\"\nupdated: \"2026-01-01\"\n{series}---\n\nBody.\n"
        );
        let mut issue = Issue::parse(&contents).expect("the fixture parses");
        issue.filename = filename.to_string();
        issue
    }

    fn date(raw: &str) -> DateKey {
        parse_date_key(raw).expect("a real date")
    }

    /// The key a lookup uses: parsed and re-derived, so the test exercises the
    /// parse path and the identity at once.
    fn key(raw: &str) -> OccurrenceKey {
        let (id, date) = OccurrenceKey::parse(raw).expect("a well-formed key");
        OccurrenceKey::new(&id, &date)
    }

    fn definition(number: u32, filename: &str, id: &str, extra: &str) -> Issue {
        issue(
            number,
            filename,
            &format!(
                "series:\n  id: {id}\n  name: Nightly\n  rule:\n    kind: daily\n    \
                 anchor: 2026-01-01\n{extra}"
            ),
        )
    }

    fn occurrence(number: u32, filename: &str, id: &str, key: &str, date: &str) -> Issue {
        issue(
            number,
            filename,
            &format!("series:\n  id: {id}\n  date: {date}\n  key: {key}\n"),
        )
    }

    #[test]
    fn a_key_is_the_series_and_the_date() {
        let id = SeriesId::parse("s-abc").unwrap();
        let key = OccurrenceKey::new(&id, &date("2026-02-28"));
        assert_eq!(key.as_str(), "s-abc@2026-02-28");
        let (parsed_id, parsed_date) = OccurrenceKey::parse(key.as_str()).unwrap();
        assert_eq!(parsed_id, id);
        assert_eq!(parsed_date, date("2026-02-28"));
    }

    #[test]
    fn a_malformed_key_names_what_a_key_is() {
        assert_eq!(
            OccurrenceKey::parse("no-separator")
                .unwrap_err()
                .first()
                .kind,
            SeriesDiagnosticKind::MalformedKey
        );
        // `2026-02-30` is not a calendar date, so the date half is refused.
        assert_eq!(
            OccurrenceKey::parse("s-abc@2026-02-30")
                .unwrap_err()
                .first()
                .kind,
            SeriesDiagnosticKind::MalformedKey
        );
    }

    #[test]
    fn an_unsafe_id_is_refused() {
        assert_eq!(
            SeriesId::parse("").unwrap_err().first().kind,
            SeriesDiagnosticKind::InvalidSeriesId
        );
        assert_eq!(
            SeriesId::parse("s abc").unwrap_err().first().kind,
            SeriesDiagnosticKind::InvalidSeriesId
        );
        assert_eq!(SeriesId::parse("s-abc_1.2").unwrap().as_str(), "s-abc_1.2");
        assert!(SeriesId::generate().as_str().starts_with("s-"));
    }

    #[test]
    fn the_index_separates_definitions_from_occurrences() {
        let issues = vec![
            definition(1, "nightly.md", "s-abc", ""),
            occurrence(2, "a.md", "s-abc", "s-abc@2026-01-01", "2026-01-01"),
        ];
        let index = SeriesIndex::build(&issues);
        assert!(index.is_consistent(), "{:?}", index.diagnostics());
        assert_eq!(index.series_count(), 1);
        assert_eq!(index.occurrences().count(), 1);
        assert_eq!(
            index.key_state(&key("s-abc@2026-01-01")),
            KeyState::Generated
        );
        assert_eq!(index.key_state(&key("s-abc@2026-01-02")), KeyState::Free);
    }

    #[test]
    fn a_duplicate_series_id_is_reported_and_the_first_definition_wins() {
        let issues = vec![
            definition(1, "first.md", "s-abc", ""),
            definition(2, "second.md", "s-abc", ""),
        ];
        let index = SeriesIndex::build(&issues);
        assert_eq!(index.series_count(), 1);
        assert_eq!(
            index.diagnostics()[0].kind,
            SeriesDiagnosticKind::DuplicateSeriesId
        );
        assert_eq!(
            index
                .series_by_id(&SeriesId::parse("s-abc").unwrap())
                .unwrap()
                .issue_number,
            1
        );
    }

    #[test]
    fn a_key_that_contradicts_its_declared_series_or_date_is_reported() {
        let issues = vec![
            definition(1, "nightly.md", "s-abc", ""),
            occurrence(2, "a.md", "s-abc", "s-xyz@2026-01-01", "2026-01-01"),
            occurrence(3, "b.md", "s-abc", "s-abc@2026-01-02", "2026-01-03"),
        ];
        let index = SeriesIndex::build(&issues);
        let kinds: Vec<_> = index.diagnostics().iter().map(|d| d.kind).collect();
        assert!(
            kinds.contains(&SeriesDiagnosticKind::KeySeriesMismatch),
            "{kinds:?}"
        );
        assert!(
            kinds.contains(&SeriesDiagnosticKind::KeyDateMismatch),
            "{kinds:?}"
        );
    }

    #[test]
    fn an_occurrence_without_a_key_is_reported_rather_than_guessed() {
        let broken = issue(2, "a.md", "series:\n  id: s-abc\n  date: 2026-01-01\n");
        let index = SeriesIndex::build(&[broken]);
        assert_eq!(
            index.diagnostics()[0].kind,
            SeriesDiagnosticKind::MissingOccurrenceKey
        );
    }

    #[test]
    fn two_issues_cannot_share_one_occurrence_key() {
        let issues = vec![
            occurrence(2, "a.md", "s-abc", "s-abc@2026-01-01", "2026-01-01"),
            occurrence(3, "b.md", "s-abc", "s-abc@2026-01-01", "2026-01-01"),
        ];
        let index = SeriesIndex::build(&issues);
        assert_eq!(index.occurrences().count(), 1);
        assert_eq!(
            index.diagnostics()[0].kind,
            SeriesDiagnosticKind::DuplicateOccurrenceKey
        );
    }

    #[test]
    fn a_definition_that_is_its_own_occurrence_is_the_model_s_only_cycle() {
        let mut own = definition(1, "nightly.md", "s-abc", "");
        if let Some(reference) = own.series.as_mut() {
            reference.key = Some("s-abc@2026-01-01".to_string());
            reference.date = Some("2026-01-01".to_string());
        }
        let index = SeriesIndex::build(&[own]);
        assert!(
            index
                .diagnostics()
                .iter()
                .any(|d| d.kind == SeriesDiagnosticKind::SeriesIsItsOwnOccurrence),
            "{:?}",
            index.diagnostics()
        );
    }

    #[test]
    fn a_skipped_date_is_taken_and_never_free() {
        let series = definition(1, "nightly.md", "s-abc", "  skipped:\n  - 2026-01-02\n");
        let index = SeriesIndex::build(&[series]);
        let skipped = key("s-abc@2026-01-02");
        assert_eq!(index.key_state(&skipped), KeyState::Skipped);
        assert!(index.is_taken(&skipped), "a skipped key is not free");
        assert!(!index.is_taken(&key("s-abc@2026-01-03")));
    }

    #[test]
    fn only_active_allows_generation() {
        let ended = definition(1, "nightly.md", "s-abc", "  state: ended\n");
        let index = SeriesIndex::build(&[ended]);
        let stored = index
            .series_by_id(&SeriesId::parse("s-abc").unwrap())
            .unwrap();
        assert_eq!(stored.state, SeriesLifecycle::Ended);
        assert!(!stored.allows_generation());
        assert!(!SeriesLifecycle::Paused.allows_generation());
        assert!(SeriesLifecycle::Active.allows_generation());
    }

    #[test]
    fn identity_is_the_key_not_the_issue_number_or_the_title() {
        // Same id, same date, different issue numbers and titles: one key, so the
        // collision is reported against the *key*.
        let first = occurrence(7, "a.md", "s-abc", "s-abc@2026-01-01", "2026-01-01");
        let mut renamed = occurrence(99, "b.md", "s-abc", "s-abc@2026-01-01", "2026-01-01");
        renamed.title = "Renamed".to_string();
        let index = SeriesIndex::build(&[first, renamed]);
        assert_eq!(
            index.diagnostics()[0].kind,
            SeriesDiagnosticKind::DuplicateOccurrenceKey
        );
        let key = key("s-abc@2026-01-01");
        assert_eq!(index.occurrence(&key).unwrap().issue_number, 7);
    }

    #[test]
    fn a_definition_without_a_name_or_with_a_broken_rule_is_reported() {
        let unnamed = issue(
            1,
            "nightly.md",
            "series:\n  id: s-abc\n  rule:\n    kind: daily\n    anchor: 2026-01-01\n",
        );
        let index = SeriesIndex::build(&[unnamed]);
        assert_eq!(
            index.diagnostics()[0].kind,
            SeriesDiagnosticKind::MissingField
        );
        assert_eq!(index.diagnostics()[0].field, "series.name");

        let bad_rule = issue(
            2,
            "other.md",
            "series:\n  id: s-xyz\n  name: Broken\n  rule:\n    kind: interval\n    \
             anchor: 2026-01-01\n    interval: 0\n    unit: days\n",
        );
        let index = SeriesIndex::build(&[bad_rule]);
        assert!(
            index
                .diagnostics()
                .iter()
                .any(|d| d.kind == SeriesDiagnosticKind::InvalidRule),
            "{:?}",
            index.diagnostics()
        );
    }

    #[test]
    fn a_finding_renders_through_the_shared_renderer() {
        let rendered = SeriesDiagnostic::new(
            SeriesDiagnosticKind::InvalidSeriesId,
            "series.id",
            "a series id cannot be empty",
        )
        .render();
        assert!(
            rendered.contains("error[E-tix-series]") && rendered.contains("invalid_series_id"),
            "{rendered}"
        );
    }
}