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
//! Read-only ended/due/look-ahead evaluation (WP03, T013–T017).
//!
//! # A refresh is a question, and this module answers exactly that
//!
//! A user's refresh asks: **"something is ended or due — what now?"** [`evaluate`]
//! takes the index WP02 already built ([`ScheduleIndex`]) and an **injected** local
//! date ([`RuleContext`]) and returns the ordered [`ScheduleWarning`]s a surface can
//! show. It opens no file, reads no clock, writes no configuration or frontmatter,
//! advances no cursor and appends no History — `C-004` says detection on refresh is
//! read-only, and the only way to guarantee that is to give it nothing to write with:
//! no `Store`, no clock, no `&mut` of anything.
//!
//! The date is a parameter and not a call for the same reason every other date in
//! this crate is: a test that pins the context is testing the arithmetic, not the
//! machine it runs on, and a start-time warning and a headless run agree because
//! both were handed the same date (`C-008`).
//!
//! # One indexed pass, over the index that already exists
//!
//! [`ScheduleIndex::build`] is the one pass over configuration and cycle records;
//! this module never repeats it. Every question here is a map lookup or a step
//! through the shared arithmetic owner ([`cadence_rule`] and `RecurrenceRule`), and
//! the whole pass visits each schedule once, in declaration order (T013). That is
//! what makes evaluation over 10,000 cycles a single indexed pass (NFR-001) rather
//! than a re-scan per schedule.
//!
//! # Four kinds of warning, and what makes each correct rather than plausible
//!
//! | kind | the fact | actions offered |
//! |---|---|---|
//! | [`ScheduleWarningKind::Ended`] | an `active` instance of the schedule has `due_date < today` | `close`, `extend`, `ignore` |
//! | [`ScheduleWarningKind::Due`] | an `active` instance has `due_date == today` | `close`, `extend`, `ignore` |
//! | [`ScheduleWarningKind::LookAhead`] | a candidate date that does not exist yet, up to the schedule's `look_ahead` count | `generate`, `ignore` |
//! | [`ScheduleWarningKind::Failure`] | the schedule could not be evaluated | **none** — it is a diagnostic |
//!
//! `ended`/`due` are **observed**, never inferred: the instance carries its own
//! `state` and `due_date`, and the comparison against the injected date is a plain
//! string comparison on the canonical `YYYY-MM-DD` form, which sorts chronologically
//! (that is the property `DateKey` promises). Nothing here asks the cadence whether a
//! cycle "must have" ended.
//!
//! A **failure is never a transition.** A schedule whose cadence cannot be resolved
//! to a valid rule produces failure warnings and nothing else: an ended/due answer
//! derived from a schedule that cannot be evaluated would be exactly the guess this
//! mission forbids. An unresolvable *candidate date* on an otherwise valid schedule
//! produces its observed ended/due warnings plus a failure, because those are facts
//! about instances and do not depend on the derivation.
//!
//! The look-ahead candidates come from [`ScheduleIndex::next_key`] (T015/C-004) — the
//! same value a confirmed generation would create — and each further candidate is one
//! step of the shared rule, so this module never becomes a second scheduler. A
//! candidate's own end date is *not* computed here: the duration arithmetic that turns
//! `(start_date, duration)` into a cycle's effective range belongs to the confirmed
//! generation that creates it (WP04), and inventing one here would be a second owner
//! of that rule.
//!
//! # The shared seam
//!
//! This is the one evaluator every surface calls on start/refresh (T016): the TUI's
//! startup warning dialog, the CLI's detect command, MCP and `tix lint` all render
//! *these* warnings rather than each recomputing one (`C-008`). They receive a value —
//! never a transition — and a decision remains an explicit, confirmed operation
//! (WP04/WP05).

use time::{Date, Month};

use crate::cycle_schedule::config::{CycleScheduleConfiguration, CycleScheduleId};
use crate::cycle_schedule::identity::{
    GeneratedCycle, GeneratedCycleId, NextCycleKey, ScheduleIndex, cadence_rule,
};
use crate::error::render_diagnostics;
use crate::recurrence::rule::{DateKey, RecurrenceRule, RuleContext, RuleDiagnostic};

/// The kind of question a refresh warning asks (`data-model.md` §5).
///
/// The spelling is the wire vocabulary and lives in exactly one place —
/// [`Self::as_str`] — so `look-ahead`, the one kebab spelling the data model fixes,
/// cannot drift from the payload.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScheduleWarningKind {
    /// An `active` instance of the schedule ended (`due_date < today`) and nobody
    /// closed it.
    Ended,
    /// An `active` instance ends today (`due_date == today`).
    Due,
    /// A candidate date that does not exist yet.
    LookAhead,
    /// The schedule could not be evaluated; the finding is the payload
    /// ([`ScheduleWarning::diagnostic`]).
    Failure,
}

impl ScheduleWarningKind {
    /// Every kind, in the order `evaluate` sorts warnings that share a sequence.
    pub const ALL: [Self; 4] = [Self::Ended, Self::Due, Self::LookAhead, Self::Failure];

    /// The contract's spelling, used verbatim in payloads and tests.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Ended => "ended",
            Self::Due => "due",
            Self::LookAhead => "look-ahead",
            Self::Failure => "failure",
        }
    }

    /// Whether the kind accepts an explicit decision.
    ///
    /// A failure never does — it is a diagnostic, not a question, and a surface that
    /// offered a button for it would be inviting a transition nothing can justify.
    pub const fn offers_actions(self) -> bool {
        !matches!(self, Self::Failure)
    }

    /// Where the kind sits in the fixed order (see [`CycleEvaluation`]).
    const fn rank(self) -> u8 {
        match self {
            Self::Ended => 0,
            Self::Due => 1,
            Self::LookAhead => 2,
            Self::Failure => 3,
        }
    }
}

/// One explicit decision a warning accepts (`data-model.md` §5).
///
/// The list is the whole vocabulary the data model defines, so no surface invents a
/// sixth answer; every answer is carried out by a *confirmed* operation, never by
/// evaluation. [`Self::Skip`] is part of that vocabulary but no kind this read-only
/// pass produces offers it — skipping a candidate is a lifecycle decision (WP05)
/// rather than a question about an ended or due instance.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WarningAction {
    /// Close the instance, capturing its immutable snapshot (WP05).
    Close,
    /// Push the instance's due date out (WP05).
    Extend,
    /// Record the sequence as skipped so it is never regenerated (WP05).
    Skip,
    /// Close the warning without deciding anything.
    Ignore,
    /// Create the candidate instance (WP04, confirmed).
    Generate,
}

impl WarningAction {
    /// Every action, in the data model's order.
    pub const ALL: [Self; 5] = [
        Self::Close,
        Self::Extend,
        Self::Skip,
        Self::Ignore,
        Self::Generate,
    ];

    /// The actions an ended or due instance accepts.
    pub const INSTANCE: [Self; 3] = [Self::Close, Self::Extend, Self::Ignore];

    /// The actions a not-yet-generated candidate accepts.
    pub const CANDIDATE: [Self; 2] = [Self::Generate, Self::Ignore];

    /// The stable spelling the CLI and the MCP tools print.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Close => "close",
            Self::Extend => "extend",
            Self::Skip => "skip",
            Self::Ignore => "ignore",
            Self::Generate => "generate",
        }
    }
}

/// The range an existing instance spans, for the warning that is about it.
///
/// Present exactly when the warning is about an instance that exists, which is why
/// a look-ahead candidate (nothing exists yet) has none: its start date lives in
/// [`ScheduleWarning::next_generation`], and its end date is the confirmed
/// generation's to compute.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectiveDates {
    /// The instance's effective start date, `YYYY-MM-DD`.
    pub start: String,
    /// The instance's effective due date, `YYYY-MM-DD`.
    pub due: String,
}

/// What one failure finding is, spelled in `snake_case` for payloads and tests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScheduleDiagnosticKind {
    /// The schedule names no cadence family, so no rule can be resolved.
    MissingCadence,
    /// The cadence resolves to a rule the shared validator refuses.
    InvalidCadence,
    /// A date the evaluation needs — an instance's or a candidate's — is not a
    /// canonical `YYYY-MM-DD` date, or the arithmetic produced none.
    UnresolvableDate,
}

impl ScheduleDiagnosticKind {
    /// The contract's spelling.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingCadence => "missing_cadence",
            Self::InvalidCadence => "invalid_cadence",
            Self::UnresolvableDate => "unresolvable_date",
        }
    }
}

/// One field-aware failure finding: what is wrong, which configuration field says
/// so, and one sentence a user can act on.
///
/// Rendered through the crate's one diagnostic renderer, so a refresh warning and a
/// `tix lint` finding spell the same refusal the same way.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScheduleDiagnostic {
    /// What went wrong.
    pub kind: ScheduleDiagnosticKind,
    /// The configuration field path, e.g. `cycle_schedules.cs-1.cadence.kind`.
    pub field: String,
    /// The user-facing sentence; it already leads with the field, so the renderer's
    /// kind prefix completes the line.
    pub message: String,
}

impl ScheduleDiagnostic {
    /// The finding for a schedule that names no cadence family.
    fn missing_cadence(schedule: &CycleScheduleId) -> Self {
        Self {
            kind: ScheduleDiagnosticKind::MissingCadence,
            field: format!("cycle_schedules.{schedule}.cadence.kind"),
            message: format!(
                "cadence.kind: schedule `{schedule}` names no cadence family, so no cadence \
                 can be resolved"
            ),
        }
    }

    /// The finding for a cadence the shared validator refuses, carrying the
    /// validator's own field and sentence.
    ///
    /// The rule's field names are not all configuration paths: a rule's `anchor` is
    /// the schedule's `start_date`, and the rule's `timezone` is the schedule's own
    /// key rather than a cadence field.
    fn invalid_cadence(schedule: &CycleScheduleId, diagnostic: &RuleDiagnostic) -> Self {
        let field = match diagnostic.field {
            "anchor" => "start_date".to_string(),
            "timezone" => "timezone".to_string(),
            other => format!("cadence.{other}"),
        };
        Self {
            kind: ScheduleDiagnosticKind::InvalidCadence,
            field: format!("cycle_schedules.{schedule}.{field}"),
            message: diagnostic.message.clone(),
        }
    }

    /// The finding for an instance whose stored date is not a canonical date.
    fn unreadable_date(cycle: &GeneratedCycle, field: &str, value: &str) -> Self {
        Self {
            kind: ScheduleDiagnosticKind::UnresolvableDate,
            field: format!("cycles.{}.{field}", cycle.name),
            message: format!(
                "{field}: cycle `{}` has `{value}`, which is not a `YYYY-MM-DD` calendar date, \
                 so its ended/due state cannot be decided",
                cycle.name
            ),
        }
    }

    /// 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 refresh warning: a question with a closed set of answers, or a diagnostic.
///
/// Which fields are meaningful follows the kind, and the two are checked against
/// each other in this module's tests:
///
/// * `ended`/`due` carry the instance in [`Self::cycle_id`] and its range in
///   [`Self::effective_dates`];
/// * `look-ahead` carries the candidate a confirmed generation would create in
///   [`Self::next_generation`] — and no `cycle_id`, because nothing exists yet;
/// * `failure` carries [`Self::diagnostic`] and no actions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScheduleWarning {
    /// The schedule the warning is about.
    pub schedule_id: CycleScheduleId,
    /// The existing instance the warning is about, when there is one.
    pub cycle_id: Option<GeneratedCycleId>,
    /// Which question this is.
    pub kind: ScheduleWarningKind,
    /// The existing instance's effective range, when there is one.
    pub effective_dates: Option<EffectiveDates>,
    /// The candidate a confirmed generation would create, when the warning is about
    /// one that does not exist yet (or when a failure could not give it a date).
    pub next_generation: Option<NextCycleKey>,
    /// The explicit decisions this warning accepts; empty for a failure.
    pub available_actions: Vec<WarningAction>,
    /// The field-aware finding, present exactly for
    /// [`ScheduleWarningKind::Failure`].
    pub diagnostic: Option<ScheduleDiagnostic>,
}

/// What one evaluation pass found (T015).
///
/// # Order
///
/// Warnings come out in **schedule declaration order, then by sequence, then by
/// kind** (`ended` before `due` before `look-ahead` before `failure`). Declaration
/// order is the order the schedules appear in `tix.toml`, so two runs over the same
/// file produce byte-identical output and a surface can rely on it; sequence order
/// puts a schedule's earlier instances before its later ones; the kind tie-break
/// covers the one case sequence alone does not — a failure that is *not* about one
/// instance (`missing_cadence`/`invalid_cadence`), which has no sequence and
/// therefore sorts last among its schedule's warnings.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CycleEvaluation {
    warnings: Vec<ScheduleWarning>,
    schedules_examined: usize,
}

impl CycleEvaluation {
    /// The warnings, in the order documented on the type.
    #[must_use]
    pub fn warnings(&self) -> &[ScheduleWarning] {
        &self.warnings
    }

    /// How many schedules the pass looked at, including the ones with nothing to say.
    #[must_use]
    pub fn schedules_examined(&self) -> usize {
        self.schedules_examined
    }

    /// Whether nothing is ended, due, ahead or broken.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.warnings.is_empty()
    }

    /// The warnings about one schedule.
    pub fn warnings_of(
        &self,
        schedule: &CycleScheduleId,
    ) -> impl Iterator<Item = &ScheduleWarning> {
        self.warnings
            .iter()
            .filter(move |warning| &warning.schedule_id == schedule)
    }

    /// The warnings of one kind.
    pub fn warnings_with_kind(
        &self,
        kind: ScheduleWarningKind,
    ) -> impl Iterator<Item = &ScheduleWarning> {
        self.warnings
            .iter()
            .filter(move |warning| warning.kind == kind)
    }

    /// Whether any schedule failed to evaluate.
    #[must_use]
    pub fn has_failures(&self) -> bool {
        self.warnings
            .iter()
            .any(|warning| warning.kind == ScheduleWarningKind::Failure)
    }
}

/// Evaluate every schedule in `index` against the supplied local date (T014).
///
/// One pass, in declaration order; no I/O, no clock, no writes. `context` supplies
/// the local calendar date a caller has already resolved, so the same input always
/// produces the same output — which is what makes a refresh warning and a headless
/// run agree (`C-008`).
///
/// The context's timezone does not change the answer: a schedule's own validated
/// offset is the calendar its cadence is expressed in, and date arithmetic on
/// calendar dates is offset-independent — the same reason
/// [`ScheduleIndex::next_key`] steps with a timezone-independent context.
#[must_use]
pub fn evaluate(index: &ScheduleIndex, context: &RuleContext) -> CycleEvaluation {
    let today = DateKey::from_date(context.today);
    let mut warnings = Vec::new();
    for (schedule, record) in index.schedules() {
        let mut ordered = evaluate_schedule(index, schedule, record, &today);
        ordered.sort_by_key(|warning| (warning.sequence.unwrap_or(u32::MAX), warning.kind.rank()));
        warnings.extend(ordered.into_iter().map(|ordered| ordered.warning));
    }
    CycleEvaluation {
        warnings,
        schedules_examined: index.schedule_count(),
    }
}

/// One warning plus the sequence it belongs to, so a schedule's warnings can be
/// ordered before they are handed out.
struct Ordered {
    sequence: Option<u32>,
    kind: ScheduleWarningKind,
    warning: ScheduleWarning,
}

/// Everything one schedule contributes to a pass.
fn evaluate_schedule(
    index: &ScheduleIndex,
    schedule: &CycleScheduleId,
    record: &CycleScheduleConfiguration,
    today: &DateKey,
) -> Vec<Ordered> {
    // A schedule with no cadence family cannot be evaluated at all, and the failure
    // is the whole answer: guessing an ended/due state from a definition nobody can
    // read is the transition the contract refuses.
    let Some(rule) = cadence_rule(record) else {
        return vec![failure(
            schedule,
            None,
            None,
            ScheduleDiagnostic::missing_cadence(schedule),
        )];
    };
    // The shared validator is authoritative for the cadence, and it collects every
    // finding: each one becomes its own failure warning, in the validator's
    // deterministic field order.
    if let Err(err) = rule.validate() {
        return err
            .diagnostics()
            .iter()
            .map(|diagnostic| {
                failure(
                    schedule,
                    None,
                    None,
                    ScheduleDiagnostic::invalid_cadence(schedule, diagnostic),
                )
            })
            .collect();
    }
    let mut warnings = instance_warnings(index, schedule, today);
    warnings.extend(look_ahead_warnings(index, schedule, record, &rule));
    warnings
}

/// The ended/due warnings of a schedule's existing instances.
fn instance_warnings(
    index: &ScheduleIndex,
    schedule: &CycleScheduleId,
    today: &DateKey,
) -> Vec<Ordered> {
    let mut warnings = Vec::new();
    for cycle in index.cycles_of(schedule) {
        // Only an `active` instance is a question: a closed or skipped one is a
        // record, and a paused one has already been answered.
        if !cycle.is_active() {
            continue;
        }
        // A date that is not a canonical date cannot be compared: the naive string
        // comparison would answer by accident (and silently ignore an overdue
        // cycle), so it is a finding instead.
        if let Some(diagnostic) = unreadable_date(cycle) {
            warnings.push(failure(schedule, Some(cycle.id.clone()), None, diagnostic));
            continue;
        }
        // Canonical `YYYY-MM-DD` keys sort chronologically as plain strings, so
        // "overdue" and "ends today" need no parsing (the property `DateKey`
        // promises, and the reason the identity module keeps dates canonical).
        let kind = match cycle.due_date.as_str().cmp(today.as_str()) {
            std::cmp::Ordering::Less => ScheduleWarningKind::Ended,
            std::cmp::Ordering::Equal => ScheduleWarningKind::Due,
            // Still running: no question.
            std::cmp::Ordering::Greater => continue,
        };
        warnings.push(Ordered {
            sequence: Some(cycle.sequence),
            kind,
            warning: ScheduleWarning {
                schedule_id: schedule.clone(),
                cycle_id: Some(cycle.id.clone()),
                kind,
                effective_dates: Some(EffectiveDates {
                    start: cycle.start_date.clone(),
                    due: cycle.due_date.clone(),
                }),
                next_generation: None,
                available_actions: WarningAction::INSTANCE.to_vec(),
                diagnostic: None,
            },
        });
    }
    warnings
}

/// The look-ahead warnings of a schedule: the candidates that do not exist yet.
///
/// The first comes from [`ScheduleIndex::next_key`] — the same value a confirmed
/// generation would create — and each further one is a step of the shared rule, so
/// the list needs no second scheduler. `look_ahead` is the count of candidates
/// reported, so `look_ahead = 0` reports **none**: a schedule instructed not to look
/// ahead has no candidate question to ask, and the ended/due questions about the
/// cycles that already exist are a separate pass.
///
/// All-or-nothing: if a step in the middle cannot be resolved, the list is not
/// reported at all. A candidate list with a hole in it would tell a surface that the
/// next two cycles start on dates that are not the schedule's.
fn look_ahead_warnings(
    index: &ScheduleIndex,
    schedule: &CycleScheduleId,
    record: &CycleScheduleConfiguration,
    rule: &RecurrenceRule,
) -> Vec<Ordered> {
    if record.look_ahead == 0 {
        return Vec::new();
    }
    // No candidate is not a failure: an ended schedule and a schedule whose sequence
    // space is used up both answer `None`, and both are facts about the read model.
    let Some(first) = index.next_key(schedule) else {
        return Vec::new();
    };
    // Never name a sequence the identity's fixed width cannot hold.
    let available = GeneratedCycleId::SEQUENCE_LIMIT.saturating_sub(first.sequence);
    let count = record.look_ahead.min(available);

    let mut warnings = Vec::with_capacity(count as usize);
    let mut date = first.start_date.clone();
    for sequence in (first.sequence..).take(count as usize) {
        // The candidate's date is the one thing this pass must be able to give; when
        // it cannot, the finding names the field that stopped it.
        let Some(start) = date.clone() else {
            // An unreadable date on an *active* instance was already reported as that
            // instance's own finding; saying the same thing about the same field again
            // would only bury the one thing to fix. A derivation the instance cannot
            // explain — the calendar refusing the step — is new information.
            if last_instance_start_flagged(index, schedule) {
                return Vec::new();
            }
            return vec![failure(
                schedule,
                None,
                Some(candidate(schedule, sequence, None)),
                unresolved_candidate(index, schedule),
            )];
        };
        warnings.push(Ordered {
            sequence: Some(sequence),
            kind: ScheduleWarningKind::LookAhead,
            warning: ScheduleWarning {
                schedule_id: schedule.clone(),
                cycle_id: None,
                kind: ScheduleWarningKind::LookAhead,
                effective_dates: None,
                next_generation: Some(candidate(schedule, sequence, Some(start.clone()))),
                available_actions: WarningAction::CANDIDATE.to_vec(),
                diagnostic: None,
            },
        });
        // Only consulted when another candidate is actually wanted, so a failing step
        // past the last reported candidate is not a failure.
        date = next_start(rule, &start);
    }
    warnings
}

/// One cadence step after `from`, through the shared arithmetic owner.
fn next_start(rule: &RecurrenceRule, from: &str) -> Option<String> {
    let date = as_date(from)?;
    rule.next_occurrence(&RuleContext::on(date))
        .ok()
        .map(|key| key.as_str().to_string())
}

/// The candidate key a confirmed generation would create for `sequence`.
fn candidate(
    schedule: &CycleScheduleId,
    sequence: u32,
    start_date: Option<String>,
) -> NextCycleKey {
    NextCycleKey {
        schedule_id: schedule.clone(),
        sequence,
        id: GeneratedCycleId::new(schedule, sequence),
        start_date,
    }
}

/// Why a candidate date could not be resolved, naming the field to fix.
///
/// The step reads the last instance's start date, so an instance whose date is not a
/// canonical date is named as the culprit; otherwise the cadence itself is.
fn unresolved_candidate(index: &ScheduleIndex, schedule: &CycleScheduleId) -> ScheduleDiagnostic {
    if let Some(cycle) = index.cycles_of(schedule).last()
        && !crate::model::validate_date(&cycle.start_date)
    {
        return ScheduleDiagnostic {
            kind: ScheduleDiagnosticKind::UnresolvableDate,
            field: format!("cycles.{}.start_date", cycle.name),
            message: format!(
                "start_date: cycle `{}` has `{}`, which is not a `YYYY-MM-DD` calendar date, so \
                 the next candidate date cannot be derived from it",
                cycle.name, cycle.start_date
            ),
        };
    }
    ScheduleDiagnostic {
        kind: ScheduleDiagnosticKind::UnresolvableDate,
        field: format!("cycle_schedules.{schedule}.cadence"),
        message: format!("cadence: schedule `{schedule}` produced no next candidate date"),
    }
}

/// Whether the candidate step's blocker is already reported as that instance's own
/// finding.
///
/// The step reads the **last** instance's start date, so that instance is the only one
/// that can make a candidate date unresolvable while the schedule is otherwise sound.
/// When it is active, the instance pass reported it; when it is not, nothing has said
/// the field is wrong yet and the candidate finding must.
fn last_instance_start_flagged(index: &ScheduleIndex, schedule: &CycleScheduleId) -> bool {
    index
        .cycles_of(schedule)
        .last()
        .is_some_and(|cycle| cycle.is_active() && !crate::model::validate_date(&cycle.start_date))
}

/// The finding for an active instance whose stored dates cannot be compared.
fn unreadable_date(cycle: &GeneratedCycle) -> Option<ScheduleDiagnostic> {
    for (field, value) in [
        ("start_date", cycle.start_date.as_str()),
        ("due_date", cycle.due_date.as_str()),
    ] {
        if !crate::model::validate_date(value) {
            return Some(ScheduleDiagnostic::unreadable_date(cycle, field, value));
        }
    }
    None
}

/// One failure warning; it never carries actions, because a diagnostic is not a
/// decision.
fn failure(
    schedule: &CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
    next_generation: Option<NextCycleKey>,
    diagnostic: ScheduleDiagnostic,
) -> Ordered {
    Ordered {
        // A failure about an instance or a candidate is placed by that sequence, like
        // every other warning; only a cadence failure has no sequence at all.
        sequence: cycle_id
            .as_ref()
            .map(GeneratedCycleId::sequence)
            .or_else(|| next_generation.as_ref().map(|key| key.sequence)),
        kind: ScheduleWarningKind::Failure,
        warning: ScheduleWarning {
            schedule_id: schedule.clone(),
            cycle_id,
            kind: ScheduleWarningKind::Failure,
            effective_dates: None,
            next_generation,
            available_actions: Vec::new(),
            diagnostic: Some(diagnostic),
        },
    }
}

/// A canonical `YYYY-MM-DD` date as the shared arithmetic owner's value.
///
/// The rule that a stored date is a real calendar date belongs to
/// [`crate::model::validate_date`]; this is the string→value conversion the shared
/// [`RuleContext`] needs. The `time` crate's own parser is behind a feature this
/// crate does not enable, so the same three-field split the identity module uses is
/// repeated here rather than re-exported.
fn as_date(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()
}

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

    #[test]
    fn every_warning_kind_has_a_stable_spelling() {
        let spellings: Vec<&str> = ScheduleWarningKind::ALL
            .iter()
            .map(|kind| kind.as_str())
            .collect();
        assert_eq!(
            spellings,
            vec!["ended", "due", "look-ahead", "failure"],
            "the wire vocabulary, with the data model's one kebab spelling"
        );
    }

    #[test]
    fn every_action_has_a_stable_spelling_and_a_fixed_offer_order() {
        let spellings: Vec<&str> = WarningAction::ALL
            .iter()
            .map(|action| action.as_str())
            .collect();
        assert_eq!(
            spellings,
            vec!["close", "extend", "skip", "ignore", "generate"]
        );
        assert_eq!(
            WarningAction::INSTANCE,
            [
                WarningAction::Close,
                WarningAction::Extend,
                WarningAction::Ignore
            ]
        );
        assert_eq!(
            WarningAction::CANDIDATE,
            [WarningAction::Generate, WarningAction::Ignore]
        );
    }

    #[test]
    fn a_failure_is_the_one_kind_that_offers_no_action() {
        assert!(ScheduleWarningKind::Ended.offers_actions());
        assert!(ScheduleWarningKind::Due.offers_actions());
        assert!(ScheduleWarningKind::LookAhead.offers_actions());
        assert!(!ScheduleWarningKind::Failure.offers_actions());
    }

    #[test]
    fn the_sequence_to_date_conversion_is_the_canonical_one() {
        assert!(as_date("2026-02-30").is_none(), "not a real calendar date");
        assert!(as_date("2026-2-3").is_none(), "not canonical");
        assert!(as_date("").is_none());
        let date = as_date("2026-01-05").expect("a real date");
        assert_eq!(date.to_string(), "2026-01-05");
    }

    #[test]
    fn a_rule_field_is_translated_to_the_configuration_field_it_came_from() {
        let schedule = CycleScheduleId::new("cs-1").unwrap();
        let anchor = RuleDiagnostic {
            kind: crate::recurrence::rule::RuleDiagnosticKind::InvalidAnchor,
            field: "anchor",
            value: "2026-02-30".into(),
            message: "anchor: `2026-02-30` is not a valid `YYYY-MM-DD` calendar date".into(),
        };
        let diagnostic = ScheduleDiagnostic::invalid_cadence(&schedule, &anchor);
        assert_eq!(diagnostic.field, "cycle_schedules.cs-1.start_date");
        assert_eq!(diagnostic.kind.as_str(), "invalid_cadence");

        let timezone = RuleDiagnostic {
            kind: crate::recurrence::rule::RuleDiagnosticKind::UnsupportedTimezone,
            field: "timezone",
            value: "Europe/Berlin".into(),
            message: "timezone: rule `Europe/Berlin` is a named zone".into(),
        };
        assert_eq!(
            ScheduleDiagnostic::invalid_cadence(&schedule, &timezone).field,
            "cycle_schedules.cs-1.timezone"
        );
        assert_eq!(
            ScheduleDiagnostic::missing_cadence(&schedule).field,
            "cycle_schedules.cs-1.cadence.kind"
        );
    }
}