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
//! Stable cycle identity, sequence keys, the generation cursor, and the legacy
//! adapter (WP02, T007–T012).
//!
//! # What is identity, and what is only a label
//!
//! A generated cycle's identity is **the schedule it came from plus its sequence**
//! within that schedule — `[{schedule-id}:{sequence}]`, held by [`GeneratedCycleId`].
//! Nothing else is identity:
//!
//! * the cycle's **name** is a mutable reference label. It is the value an issue's
//!   `cycles` frontmatter holds, so it must stay resolvable by the normal cycle
//!   machinery (readers, the picker, `tix cycle show`) — which is why a generated
//!   cycle *is* a [`CycleRecord`](crate::cycle_store::CycleRecord) with its identity
//!   in three optional fields, and not a second file format;
//! * the **issue number** is a label;
//! * the **row position** in a listing is a label.
//!
//! Renaming a cycle therefore changes what a human reads and nothing else: the id,
//! the sequence, and every closed snapshot hanging off them are untouched (C-003).
//! A schedule's own identity is the same story one level up — [`CycleScheduleId`] is
//! the registry key, and `name` is a label.
//!
//! # The cursor is derived, and that is deliberate
//!
//! [`GenerationCursor`] is the data model's persisted position of a schedule, and it
//! **is** persisted (in `[cycle_schedules.<id>.cursor]`, beside the definition it
//! belongs to — the same shape the recurring-issues mission uses, where the cursor
//! lives in the series definition). But it is also *recomputable* from the instances
//! themselves, and this module always computes that too and reports a disagreement as
//! a [`IdentityDiagnostic`] rather than trusting the stored copy.
//!
//! The reason is the failure the mission names: a cursor that can advance without an
//! instance — or an instance that can exist without the cursor — is exactly "cursor
//! drift", and a cursor is only ever an *optimisation* of `max(sequence)`. Recomputing
//! it costs one pass over a map that is already built, and it turns a silent
//! inconsistency into a reportable one.
//!
//! # Read-only, and indexed once
//!
//! [`ScheduleIndex::build`] is the one pass: schedules by id, schedules by display
//! name, instances by id, instances by schedule and sequence, and instances by the
//! **name** an issue reference holds. Every accessor after it is a lookup, so an
//! evaluation over thousands of cycles does not re-read configuration or re-scan
//! issues (T011, NFR-001). Nothing here writes: the cursor is returned as a value, and
//! advancing it is a confirmed operation belonging to generation (WP04) and lifecycle
//! (WP05).

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

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

use crate::config::Config;
use crate::cycle_schedule::config::{
    CycleScheduleConfiguration, CycleScheduleExtensions, CycleScheduleId,
};
use crate::cycle_store::CycleRecord;
use crate::error::{Result, TixError, render_diagnostics};
use crate::recurrence::rule::{RecurrenceRule, RuleContext};

/// The stable identity of a generated cycle: `{schedule-id}:{sequence}`.
///
/// Derived, never allocated: two builds given the same schedule and sequence produce
/// the same id, which is what makes generation idempotent for a stable key (C-006)
/// and what lets a snapshot's identity outlive any rename (C-003). The sequence is
/// zero-padded to a fixed width so ids sort chronologically as plain strings — the
/// same trick `DateKey` uses, and for the same reason.
///
/// The split is on the **last** `:`, because `CycleScheduleId` accepts `:` inside an
/// id (`cs-1:2` is a legal schedule id) while the tail is always the sequence.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct GeneratedCycleId(String);

impl GeneratedCycleId {
    /// How many digits the sequence carries. Six is `999_999` cycles in one schedule
    /// before the width stops sorting — far past the mission's 10,000-cycle target, and
    /// a wider field would only make every id longer.
    pub const SEQUENCE_WIDTH: usize = 6;

    /// The first sequence that no longer fits [`Self::SEQUENCE_WIDTH`], i.e. `10^6`.
    ///
    /// Literal because `10u32.pow` is not `const`; the unit suite asserts the two stay
    /// in step. A sequence at or above this can never be named by a
    /// [`GeneratedCycleId`], so it is refused where it enters ([`GeneratedCycle::from_record`])
    /// and never handed out ([`ScheduleIndex::next_key`]).
    pub const SEQUENCE_LIMIT: u32 = 1_000_000;

    /// The id for `sequence` within `schedule`.
    ///
    /// A sequence of zero is refused: sequences start at 1, so `0` is a bug in the
    /// caller rather than a cycle to name.
    #[must_use]
    pub fn new(schedule: &CycleScheduleId, sequence: u32) -> Self {
        debug_assert!(sequence > 0, "sequences start at 1");
        Self(format!(
            "{}:{:0width$}",
            schedule.as_str(),
            sequence,
            width = Self::SEQUENCE_WIDTH
        ))
    }

    /// Parse a stored id, validating the shape the other registries' ids follow.
    pub fn parse(raw: &str) -> Result<Self> {
        let (schedule, sequence) = raw.rsplit_once(':').ok_or_else(|| {
            TixError::Config(format!(
                "generated cycle id `{raw}` must be `<schedule-id>:<sequence>`"
            ))
        })?;
        CycleScheduleId::new(schedule)
            .map_err(|err| TixError::Config(format!("generated cycle id `{raw}`: {err}")))?;
        if sequence.len() != Self::SEQUENCE_WIDTH || !sequence.bytes().all(|b| b.is_ascii_digit()) {
            return Err(TixError::Config(format!(
                "generated cycle id `{raw}` must carry a {}-digit sequence",
                Self::SEQUENCE_WIDTH
            )));
        }
        let parsed: u32 = sequence.parse().map_err(|_| {
            TixError::Config(format!(
                "generated cycle id `{raw}` has an unreadable sequence"
            ))
        })?;
        if parsed == 0 {
            return Err(TixError::Config(format!(
                "generated cycle id `{raw}` has sequence 0; sequences start at 1"
            )));
        }
        Ok(Self(raw.to_string()))
    }

    /// The id as written.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The owning schedule's id, as written.
    #[must_use]
    pub fn schedule_id(&self) -> &str {
        self.0
            .rsplit_once(':')
            .map_or(self.0.as_str(), |(schedule, _)| schedule)
    }

    /// The sequence within the schedule.
    #[must_use]
    pub fn sequence(&self) -> u32 {
        self.0
            .rsplit_once(':')
            .and_then(|(_, sequence)| sequence.parse().ok())
            .unwrap_or(0)
    }

    /// Whether `schedule` owns this id.
    #[must_use]
    pub fn belongs_to(&self, schedule: &CycleScheduleId) -> bool {
        self.schedule_id() == schedule.as_str()
    }
}

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

impl TryFrom<String> for GeneratedCycleId {
    type Error = TixError;

    fn try_from(raw: String) -> Result<Self> {
        Self::parse(&raw)
    }
}

impl From<GeneratedCycleId> for String {
    fn from(id: GeneratedCycleId) -> Self {
        id.0
    }
}

/// A generated cycle's lifecycle state (data-model §2).
///
/// `closed` and `skipped` are terminal: a closed cycle has a snapshot, and a skipped
/// sequence stays recorded so it is never silently regenerated (C-006). `paused` is the
/// schedule's own state applied to one instance.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GeneratedCycleState {
    /// Generated, running, and the current candidate.
    #[default]
    Active,
    /// Explicitly closed; its snapshot is the historical record.
    Closed,
    /// Explicitly skipped; the sequence is consumed and stays recorded.
    Skipped,
    /// Explicitly paused with the schedule.
    Paused,
}

impl GeneratedCycleState {
    /// The contract's spelling, used verbatim in payloads and diagnostics.
    pub const fn as_str(self) -> &'static str {
        match self {
            GeneratedCycleState::Active => "active",
            GeneratedCycleState::Closed => "closed",
            GeneratedCycleState::Skipped => "skipped",
            GeneratedCycleState::Paused => "paused",
        }
    }

    /// Parse a stored spelling.
    pub fn parse(raw: &str) -> Result<Self> {
        match raw {
            "active" => Ok(Self::Active),
            "closed" => Ok(Self::Closed),
            "skipped" => Ok(Self::Skipped),
            "paused" => Ok(Self::Paused),
            other => Err(TixError::Config(format!(
                "generated cycle state `{other}` is not one of `active`, `closed`, `skipped`, `paused`"
            ))),
        }
    }

    /// Whether no further transition leaves this state.
    pub const fn is_terminal(self) -> bool {
        matches!(self, Self::Closed | Self::Skipped)
    }
}

/// One generated cycle: its stable identity plus the fields its cycle record carries.
///
/// Built from a [`CycleRecord`] and written back to one, so the file a user can read
/// and the identity the machinery keys on are the same artifact.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GeneratedCycle {
    /// The stable identity.
    pub id: GeneratedCycleId,
    /// The schedule that generated it.
    pub schedule_id: CycleScheduleId,
    /// The sequence within the schedule.
    pub sequence: u32,
    /// The reference label an issue's `cycles` value holds.
    pub name: String,
    /// The effective start date.
    pub start_date: String,
    /// The effective due date.
    pub due_date: String,
    /// The instance's lifecycle state.
    pub state: GeneratedCycleState,
}

impl GeneratedCycle {
    /// The instance a [`CycleRecord`] carries, or `None` when the record is a
    /// hand-written cycle.
    ///
    /// A record with *some* identity fields but not all of them is refused rather than
    /// half-read: a sequence without a schedule (or the reverse) cannot resolve to an
    /// id, and inventing the missing half is exactly the guess this mission forbids.
    pub fn from_record(record: &CycleRecord) -> Result<Option<Self>> {
        let (Some(schedule_raw), Some(sequence), Some(state_raw)) = (
            record.schedule_id.as_deref(),
            record.sequence,
            record.state.as_deref(),
        ) else {
            if record.schedule_id.is_none() && record.sequence.is_none() && record.state.is_none() {
                return Ok(None);
            }
            return Err(TixError::Config(format!(
                "cycle `{}` carries a partial generated identity: `schedule_id`, `sequence` \
                 and `state` are written together or not at all",
                record.name
            )));
        };
        // The sequence is the untrusted side: it comes from a file a human can edit, and
        // an id built from one that does not fit the field would be refused by
        // `GeneratedCycleId::parse` — i.e. this module would index, and the cursor would
        // later store, an identity nothing can read back. Refuse it as a finding instead.
        if sequence == 0 || sequence >= GeneratedCycleId::SEQUENCE_LIMIT {
            return Err(TixError::Config(format!(
                "cycle `{}` carries generated sequence `{sequence}`; sequences start at 1 and \
                 must fit {} digits",
                record.name,
                GeneratedCycleId::SEQUENCE_WIDTH
            )));
        }
        // A generated cycle is a *box with dates*: evaluation and generation both need
        // the interval. Absence is refused rather than carried as an empty string, which
        // would re-serialize as a blank date the loader itself rejects.
        let (Some(start_date), Some(due_date)) =
            (record.start_date.clone(), record.due_date.clone())
        else {
            return Err(TixError::Config(format!(
                "generated cycle `{}` needs both `start_date` and `due_date`",
                record.name
            )));
        };
        let schedule_id = CycleScheduleId::new(schedule_raw)?;
        let state = GeneratedCycleState::parse(state_raw)?;
        let id = GeneratedCycleId::new(&schedule_id, sequence);
        Ok(Some(Self {
            id,
            schedule_id,
            sequence,
            name: record.name.clone(),
            start_date,
            due_date,
            state,
        }))
    }

    /// This instance as the cycle record to store.
    #[must_use]
    pub fn to_record(&self) -> CycleRecord {
        CycleRecord {
            name: self.name.clone(),
            description: None,
            start_date: Some(self.start_date.clone()),
            due_date: Some(self.due_date.clone()),
            schedule_id: Some(self.schedule_id.as_str().to_string()),
            sequence: Some(self.sequence),
            state: Some(self.state.as_str().to_string()),
        }
    }

    /// Whether this instance still counts as an active candidate.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.state == GeneratedCycleState::Active
    }
}

/// The next candidate a confirmed generation would create for a schedule (T009).
///
/// A **value**, computed without touching anything: asking twice returns the same
/// answer, and asking never advances a cursor or creates a cycle (C-004).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NextCycleKey {
    /// The schedule the candidate belongs to.
    pub schedule_id: CycleScheduleId,
    /// The sequence it would take.
    pub sequence: u32,
    /// Its stable identity.
    pub id: GeneratedCycleId,
    /// Its start date, or `None` when the cadence cannot be resolved to a date (an
    /// unreachable state for a loaded schedule, since the configuration is validated
    /// first — reported rather than guessed if it ever happens).
    pub start_date: Option<String>,
}

/// The persisted generation position of a schedule (data-model §3).
///
/// Stored in `[cycle_schedules.<id>.cursor]`. Every field is optional and omitted when
/// absent, so a schedule that has never generated carries no cursor at all and a
/// legacy `tix.toml` gains no key.
///
/// See the module note: this value is **reconciled** against the instances rather than
/// trusted, so `next_sequence` here is a fast path and `max(sequence) + 1` is the
/// truth.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct GenerationCursor {
    /// The next candidate sequence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_sequence: Option<u32>,
    /// The next candidate start date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_start: Option<String>,
    /// The id most recently generated, as progress evidence.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_generated_key: Option<GeneratedCycleId>,
    /// The last sequence the look-ahead covered.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub look_ahead_applied_through: Option<u32>,
    /// Unknown metadata, preserved verbatim.
    #[serde(flatten)]
    pub extensions: CycleScheduleExtensions,
}

impl GenerationCursor {
    /// Whether nothing is recorded yet.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self == &Self::default()
    }

    /// The recognized cursor fields, for the extension-shadow check.
    pub const KNOWN_FIELDS: &'static [&'static str] = &[
        "next_sequence",
        "next_start",
        "last_generated_key",
        "look_ahead_applied_through",
    ];
}

/// What a cycle reference resolves to (T010).
///
/// The value an issue's `cycles` frontmatter holds is a **name**, and a name may be a
/// hand-written cycle or a generated one. Resolution is therefore a question with three
/// answers, and the third one matters: an unknown name is reported, never rebound to
/// whatever record happens to be nearby.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CycleReference {
    /// A hand-written cycle in the registry.
    Legacy {
        /// The name that was resolved.
        name: String,
    },
    /// A cycle a schedule generated.
    Generated {
        /// The name that was resolved.
        name: String,
        /// The stable identity behind the name.
        id: GeneratedCycleId,
        /// The generating schedule.
        schedule_id: CycleScheduleId,
    },
    /// Nothing by that name.
    Unknown {
        /// The name that did not resolve.
        name: String,
    },
}

/// What an identity problem is, spelled in `snake_case` for payloads and tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IdentityDiagnosticKind {
    /// A generated cycle names a schedule that is not in the registry.
    MissingSchedule,
    /// Two records claim one `(schedule, sequence)`.
    DuplicateSequence,
    /// A record's id disagrees with its own schedule/sequence pair.
    IdentityMismatch,
    /// Two cycles claim one reference name.
    ReferenceCollision,
    /// The stored cursor disagrees with the instances.
    CursorDrift,
    /// A record carries a partial identity or an unreadable state.
    MalformedIdentity,
}

impl IdentityDiagnosticKind {
    /// The contract's spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            IdentityDiagnosticKind::MissingSchedule => "missing_schedule",
            IdentityDiagnosticKind::DuplicateSequence => "duplicate_sequence",
            IdentityDiagnosticKind::IdentityMismatch => "identity_mismatch",
            IdentityDiagnosticKind::ReferenceCollision => "reference_collision",
            IdentityDiagnosticKind::CursorDrift => "cursor_drift",
            IdentityDiagnosticKind::MalformedIdentity => "malformed_identity",
        }
    }
}

/// One identity finding, produced by [`ScheduleIndex::build`].
///
/// Rendered through the crate's one diagnostic renderer, so `tix lint`, the CLI and
/// MCP spell the same refusal the same way.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IdentityDiagnostic {
    /// What is wrong.
    pub kind: IdentityDiagnosticKind,
    /// The schedule it concerns, when the finding has one.
    pub schedule_id: Option<CycleScheduleId>,
    /// The cycle it concerns, when the finding has one.
    pub cycle_id: Option<GeneratedCycleId>,
    /// The field path, e.g. `cycle_schedules.cs-1.cursor.next_sequence`.
    pub field: String,
    /// One sentence saying what to do about it.
    pub message: String,
}

impl IdentityDiagnostic {
    /// A finding about `field`.
    fn new(
        kind: IdentityDiagnosticKind,
        schedule_id: Option<CycleScheduleId>,
        field: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            schedule_id,
            cycle_id: None,
            field: field.into(),
            message: message.into(),
        }
    }

    /// Attach the cycle the finding came from.
    #[must_use]
    fn on_cycle(mut self, id: GeneratedCycleId) -> Self {
        self.cycle_id = Some(id);
        self
    }

    /// Render through the crate's one diagnostic renderer.
    #[must_use]
    pub fn render(&self) -> String {
        render_diagnostics(
            "E-tix-cycle-schedule",
            std::iter::once((self.kind.as_str(), self.message.as_str())),
        )
    }
}

/// One entry of a cycle record as the index sees it: the record and where it came from.
#[derive(Debug, Clone, PartialEq, Eq)]
struct IndexedCycle {
    cycle: GeneratedCycle,
}

/// A one-pass, read-only index over schedules and the cycles they generated (T011).
///
/// Built from the configuration and the cycle records that already exist; every
/// question after that is a map lookup. Nothing here reads a clock, writes a file,
/// advances a cursor or appends History — the whole type is a value.
#[derive(Debug, Clone, Default)]
pub struct ScheduleIndex {
    schedules: IndexMap<CycleScheduleId, CycleScheduleConfiguration>,
    by_name: BTreeMap<String, CycleScheduleId>,
    cycles: BTreeMap<GeneratedCycleId, IndexedCycle>,
    by_schedule: BTreeMap<CycleScheduleId, BTreeMap<u32, GeneratedCycleId>>,
    by_reference: BTreeMap<String, GeneratedCycleId>,
    legacy_names: BTreeSet<String>,
    diagnostics: Vec<IdentityDiagnostic>,
}

impl ScheduleIndex {
    /// Build the index from the configuration and every stored cycle record.
    ///
    /// The records are what [`crate::cycle_store::CycleStore::list`] returns: hand-written
    /// cycles and generated ones together, because a generated cycle *is* a cycle. A
    /// record with no identity fields is indexed as a legacy name and nothing else.
    ///
    /// Findings are collected rather than refused: an index that cannot be built cannot
    /// be diagnosed, and a hand-edited file must stay loadable (C-005).
    #[must_use]
    pub fn build(config: &Config, records: &[CycleRecord]) -> Self {
        let mut index = Self::default();
        for (raw, schedule) in &config.cycle_schedules {
            let Ok(id) = CycleScheduleId::new(raw) else {
                continue;
            };
            index
                .by_name
                .insert(schedule.name.trim().to_lowercase(), id.clone());
            index.schedules.insert(id, schedule.clone());
        }
        for record in records {
            index.add_record(record);
        }
        index.reconcile_cursors(config);
        index
    }

    /// Index one cycle record.
    fn add_record(&mut self, record: &CycleRecord) {
        let parsed = match GeneratedCycle::from_record(record) {
            Ok(parsed) => parsed,
            Err(err) => {
                self.diagnostics.push(IdentityDiagnostic::new(
                    IdentityDiagnosticKind::MalformedIdentity,
                    None,
                    format!("cycles.{}", record.name),
                    err.to_string(),
                ));
                return;
            }
        };
        let Some(cycle) = parsed else {
            // The reverse direction of the same collision: a hand-written cycle claiming a
            // name a generated cycle already took (the records arrive in file order, so
            // either kind can be the second one to arrive).
            if let Some(existing) = self.by_reference.get(&record.name) {
                self.diagnostics.push(
                    IdentityDiagnostic::new(
                        IdentityDiagnosticKind::ReferenceCollision,
                        None,
                        format!("cycles.{}", record.name),
                        format!(
                            "hand-written cycle `{}` and generated cycle `{existing}` both answer \
                             to the name `{}`; an issue reference would resolve to whichever is \
                             read first",
                            record.name, record.name
                        ),
                    )
                    .on_cycle(existing.clone()),
                );
            }
            self.legacy_names.insert(record.name.clone());
            return;
        };
        let schedule = cycle.schedule_id.clone();
        let sequence = cycle.sequence;
        let id = cycle.id.clone();

        if !self.schedules.contains_key(&schedule) {
            self.diagnostics.push(
                IdentityDiagnostic::new(
                    IdentityDiagnosticKind::MissingSchedule,
                    Some(schedule.clone()),
                    format!("{id}.schedule_id"),
                    format!(
                        "generated cycle `{id}` names schedule `{schedule}`, which is not in \
                         `cycle_schedules`; the cycle is kept and reported rather than rebound"
                    ),
                )
                .on_cycle(id.clone()),
            );
        }
        if id.sequence() != sequence {
            self.diagnostics.push(
                IdentityDiagnostic::new(
                    IdentityDiagnosticKind::IdentityMismatch,
                    Some(schedule.clone()),
                    format!("{id}.sequence"),
                    format!("generated cycle `{id}` disagrees with its own sequence `{sequence}`"),
                )
                .on_cycle(id.clone()),
            );
        }
        if self
            .by_schedule
            .get(&schedule)
            .is_some_and(|sequences| sequences.contains_key(&sequence))
        {
            self.diagnostics.push(
                IdentityDiagnostic::new(
                    IdentityDiagnosticKind::DuplicateSequence,
                    Some(schedule.clone()),
                    format!("cycle_schedules.{schedule}.sequences.{sequence}"),
                    format!("two cycles claim sequence {sequence} of schedule `{schedule}`"),
                )
                .on_cycle(id.clone()),
            );
        }
        // A name must identify exactly one cycle, and that has to hold across the two
        // kinds: a generated cycle whose name a hand-written cycle already answers to is
        // the same collision as two generated cycles sharing one, and reporting only the
        // latter is what let `resolve` silently shadow the hand-written cycle.
        let claimed_by_generated = self
            .by_reference
            .get(&cycle.name)
            .filter(|other| *other != &id);
        let claimed_by_legacy = self.legacy_names.contains(&cycle.name);
        if claimed_by_generated.is_some() || claimed_by_legacy {
            let other = match claimed_by_generated {
                Some(existing) => format!("generated cycle `{existing}`"),
                None => "a hand-written cycle".to_string(),
            };
            self.diagnostics.push(
                IdentityDiagnostic::new(
                    IdentityDiagnosticKind::ReferenceCollision,
                    Some(schedule.clone()),
                    format!("cycles.{}", cycle.name),
                    format!(
                        "generated cycle `{id}` and {other} both answer to the name `{}`; an \
                         issue reference would resolve to whichever is read first",
                        cycle.name
                    ),
                )
                .on_cycle(id.clone()),
            );
        }

        self.by_reference.insert(cycle.name.clone(), id.clone());
        self.by_schedule
            .entry(schedule)
            .or_default()
            .insert(sequence, id.clone());
        self.cycles.insert(id, IndexedCycle { cycle });
    }

    /// Compare every stored cursor against what the instances say.
    fn reconcile_cursors(&mut self, config: &Config) {
        for (id, schedule) in &config.cycle_schedules {
            let Ok(schedule_id) = CycleScheduleId::new(id) else {
                continue;
            };
            let Some(stored) = schedule.cursor.as_ref() else {
                continue;
            };
            // A cursor that records nothing is not a disagreement: `[cycle_schedules.x.cursor]`
            // written empty (or by a tool that wrote the table before its first generation)
            // agrees with an empty instance set by definition.
            if stored.is_empty() {
                continue;
            }
            let derived = self.derive_cursor(&schedule_id);
            for (field, stored_value, derived_value) in [
                (
                    "next_sequence",
                    stored.next_sequence.map(|v| v.to_string()),
                    derived.next_sequence.map(|v| v.to_string()),
                ),
                (
                    "next_start",
                    stored.next_start.clone(),
                    derived.next_start.clone(),
                ),
                (
                    "last_generated_key",
                    stored
                        .last_generated_key
                        .as_ref()
                        .map(|k| k.as_str().to_string()),
                    derived
                        .last_generated_key
                        .as_ref()
                        .map(|k| k.as_str().to_string()),
                ),
                (
                    "look_ahead_applied_through",
                    stored.look_ahead_applied_through.map(|v| v.to_string()),
                    derived.look_ahead_applied_through.map(|v| v.to_string()),
                ),
            ] {
                if stored_value != derived_value {
                    self.diagnostics.push(IdentityDiagnostic::new(
                        IdentityDiagnosticKind::CursorDrift,
                        Some(schedule_id.clone()),
                        format!("cycle_schedules.{schedule_id}.cursor.{field}"),
                        format!(
                            "the stored cursor field `{field}` says {} but the generated cycles \
                             say {}; the instances are authoritative and the stored value is \
                             stale",
                            stored_value.as_deref().unwrap_or("nothing"),
                            derived_value.as_deref().unwrap_or("nothing")
                        ),
                    ));
                }
            }
        }
    }

    /// Every schedule, in declaration order.
    pub fn schedules(
        &self,
    ) -> impl Iterator<Item = (&CycleScheduleId, &CycleScheduleConfiguration)> {
        self.schedules.iter()
    }

    /// One schedule by its stable id.
    #[must_use]
    pub fn schedule(&self, id: &CycleScheduleId) -> Option<&CycleScheduleConfiguration> {
        self.schedules.get(id)
    }

    /// One schedule by its display name (case-folded, as the registry validates it).
    #[must_use]
    pub fn schedule_by_name(&self, name: &str) -> Option<&CycleScheduleConfiguration> {
        self.by_name
            .get(&name.trim().to_lowercase())
            .and_then(|id| self.schedules.get(id))
    }

    /// How many schedules the index holds.
    #[must_use]
    pub fn schedule_count(&self) -> usize {
        self.schedules.len()
    }

    /// One generated cycle by its stable id.
    #[must_use]
    pub fn cycle(&self, id: &GeneratedCycleId) -> Option<&GeneratedCycle> {
        self.cycles.get(id).map(|indexed| &indexed.cycle)
    }

    /// The generated cycles of one schedule, in sequence order.
    pub fn cycles_of(
        &self,
        schedule: &CycleScheduleId,
    ) -> impl Iterator<Item = &GeneratedCycle> + '_ {
        self.by_schedule
            .get(schedule)
            .into_iter()
            .flat_map(|sequences| sequences.values())
            .filter_map(|id| self.cycle(id))
    }

    /// How many generated cycles the index holds.
    #[must_use]
    pub fn generated_count(&self) -> usize {
        self.cycles.len()
    }

    /// Whether any finding was recorded.
    #[must_use]
    pub fn is_consistent(&self) -> bool {
        self.diagnostics.is_empty()
    }

    /// Every finding, in a deterministic order.
    #[must_use]
    pub fn diagnostics(&self) -> &[IdentityDiagnostic] {
        &self.diagnostics
    }

    /// Resolve the name an issue's `cycles` value holds (T010).
    ///
    /// A generated cycle, a hand-written cycle, or nothing — and without migrating or
    /// rewriting either.
    ///
    /// A name is meant to identify exactly one cycle, so the two sets are not supposed
    /// to overlap; if they do (only a hand-edited filename can arrange it, since equal
    /// names share a file), the collision was already recorded as a
    /// [`IdentityDiagnosticKind::ReferenceCollision`] finding when the index was built.
    /// Generated is therefore checked first as a *tie-break that has already been
    /// reported*, not as a precedence rule the caller should rely on.
    #[must_use]
    pub fn resolve(&self, name: &str) -> CycleReference {
        if let Some(id) = self.by_reference.get(name)
            && let Some(cycle) = self.cycle(id)
        {
            return CycleReference::Generated {
                name: name.to_string(),
                id: id.clone(),
                schedule_id: cycle.schedule_id.clone(),
            };
        }
        if self.legacy_names.contains(name) {
            return CycleReference::Legacy {
                name: name.to_string(),
            };
        }
        CycleReference::Unknown {
            name: name.to_string(),
        }
    }

    /// The cursor for `schedule`, computed from the cycles that exist.
    ///
    /// Always the **derived** value: `max(sequence) + 1` and the next date are facts
    /// about the instances, and the stored copy is a cached copy of them. A disagreement
    /// between the two does not change what this returns — it was recorded as a
    /// [`IdentityDiagnosticKind::CursorDrift`] finding when the index was built, which is
    /// the point: the disagreement is reported rather than silently resolved in favour
    /// of either side.
    ///
    /// Reading it never advances anything and never writes.
    #[must_use]
    pub fn cursor(&self, schedule: &CycleScheduleId) -> GenerationCursor {
        self.derive_cursor(schedule)
    }

    /// What the instances say the position is.
    fn derive_cursor(&self, schedule: &CycleScheduleId) -> GenerationCursor {
        let last = self
            .by_schedule
            .get(schedule)
            .and_then(|sequences| sequences.iter().next_back());
        let Some((sequence, id)) = last else {
            return GenerationCursor {
                next_sequence: Some(1),
                next_start: self
                    .schedules
                    .get(schedule)
                    .map(|record| record.start_date.clone()),
                last_generated_key: None,
                look_ahead_applied_through: None,
                extensions: CycleScheduleExtensions::default(),
            };
        };
        let Some(cycle) = self.cycle(id) else {
            return GenerationCursor::default();
        };
        GenerationCursor {
            next_sequence: Some(sequence.saturating_add(1)),
            next_start: self.next_start_after(schedule, &cycle.start_date),
            last_generated_key: Some(id.clone()),
            look_ahead_applied_through: Some(*sequence),
            extensions: CycleScheduleExtensions::default(),
        }
    }

    /// One cadence step after `after`, through the shared arithmetic owner.
    ///
    /// `None` when the step cannot be resolved — an absent cadence family, or a date the
    /// rule refuses. It is never a guess: the caller reports "no candidate date" rather
    /// than inventing one.
    fn next_start_after(&self, schedule: &CycleScheduleId, after: &str) -> Option<String> {
        let record = self.schedules.get(schedule)?;
        let rule = record.cadence.to_rule(record)?;
        let date = date_value(after)?;
        rule.next_occurrence(&RuleContext::on(date))
            .ok()
            .map(|key| key.as_str().to_string())
    }

    /// The next candidate key for `schedule`, or `None` when the schedule is unknown or
    /// has ended (T009/C-004: an ended schedule generates nothing).
    #[must_use]
    pub fn next_key(&self, schedule: &CycleScheduleId) -> Option<NextCycleKey> {
        let record = self.schedules.get(schedule)?;
        if record.state.is_terminal() {
            return None;
        }
        let cursor = self.cursor(schedule);
        let sequence = cursor.next_sequence?;
        // A schedule whose sequences are used up has no next candidate, the same way an
        // ended one does — and never a *duplicate*, which is what handing back an
        // already-taken sequence would be (C-006).
        if sequence >= GeneratedCycleId::SEQUENCE_LIMIT {
            return None;
        }
        Some(NextCycleKey {
            id: GeneratedCycleId::new(schedule, sequence),
            sequence,
            start_date: cursor.next_start.clone(),
            schedule_id: schedule.clone(),
        })
    }
}

/// A canonical `YYYY-MM-DD` date as the arithmetic owner's value.
///
/// The *rule* that a stored date is a real calendar date belongs to
/// [`crate::model::validate_date`] and has already been applied by the time a schedule
/// is loaded; this is the string→value conversion the shared [`RuleContext`] needs, so
/// it lives here once instead of at every call site.
fn date_value(value: &str) -> Option<Date> {
    if !crate::model::validate_date(value) {
        return None;
    }
    let year: i32 = value.get(0..4)?.parse().ok()?;
    let month: u8 = value.get(5..7)?.parse().ok()?;
    let day: u8 = value.get(8..10)?.parse().ok()?;
    Date::from_calendar_date(year, Month::try_from(month).ok()?, day).ok()
}

/// The rule a schedule's cadence resolves to, for a caller that needs the arithmetic
/// owner without an index (WP03/WP04).
#[must_use]
pub fn cadence_rule(record: &CycleScheduleConfiguration) -> Option<RecurrenceRule> {
    record.cadence.to_rule(record)
}

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

    fn schedule_id() -> CycleScheduleId {
        CycleScheduleId::new("cs-test").unwrap()
    }

    #[test]
    fn a_generated_id_round_trips_and_sorts_by_sequence() {
        let schedule = schedule_id();
        let first = GeneratedCycleId::new(&schedule, 1);
        let tenth = GeneratedCycleId::new(&schedule, 10);
        assert_eq!(first.as_str(), "cs-test:000001");
        assert_eq!(first.sequence(), 1);
        assert_eq!(first.schedule_id(), "cs-test");
        assert!(first.belongs_to(&schedule));
        assert!(
            first < tenth,
            "a fixed width is what keeps plain-string order"
        );

        let parsed = GeneratedCycleId::parse(first.as_str()).unwrap();
        assert_eq!(parsed, first);
    }

    #[test]
    fn a_schedule_id_may_itself_contain_a_colon() {
        let schedule = CycleScheduleId::new("cs-1:2").unwrap();
        let id = GeneratedCycleId::new(&schedule, 7);
        assert_eq!(id.as_str(), "cs-1:2:000007");
        assert_eq!(id.schedule_id(), "cs-1:2");
        assert_eq!(id.sequence(), 7);
        assert_eq!(GeneratedCycleId::parse(id.as_str()).unwrap(), id);
    }

    #[test]
    fn the_sequence_limit_is_exactly_the_field_width() {
        assert_eq!(
            GeneratedCycleId::SEQUENCE_LIMIT,
            10u32.pow(GeneratedCycleId::SEQUENCE_WIDTH as u32),
            "the limit must be the first sequence the field cannot hold"
        );
        let schedule = schedule_id();
        let last = GeneratedCycleId::new(&schedule, GeneratedCycleId::SEQUENCE_LIMIT - 1);
        assert_eq!(
            GeneratedCycleId::parse(last.as_str()).unwrap(),
            last,
            "the highest nameable sequence must round-trip"
        );
        assert_eq!(last.as_str(), "cs-test:999999");
    }

    #[test]
    fn a_malformed_id_is_refused_with_the_shape_it_wanted() {
        for raw in [
            "cs-test",
            "cs-test:1",
            "cs-test:000000",
            "cs-test:00000a",
            "cs-test:1000000",
        ] {
            let error = GeneratedCycleId::parse(raw).err();
            assert!(error.is_some(), "`{raw}` must be refused");
        }
    }

    #[test]
    fn a_partial_identity_on_a_record_is_refused_rather_than_half_read() {
        let record = CycleRecord {
            name: "Sprint 1".into(),
            sequence: Some(1),
            ..CycleRecord::default()
        };
        let error =
            GeneratedCycle::from_record(&record).expect_err("a partial identity is refused");
        assert!(error.to_string().contains("written together"), "{error}");

        let legacy = CycleRecord {
            name: "Cycle 1".into(),
            ..CycleRecord::default()
        };
        assert!(GeneratedCycle::from_record(&legacy).unwrap().is_none());
    }
}