tix-tracker 0.12.0

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

/// Carry out one confirmed lifecycle action for a project.
///
/// Returns an outcome rather than an error for every *decision* the action makes;
/// only a genuine I/O failure while reading the stores propagates. `config` is the
/// caller's registry and is mutated only after a record write has succeeded, so a
/// failed action leaves the in-memory configuration exactly as it was. `root` is the
/// project root: it locates the cycle records, the snapshots and the `tix.toml` the
/// schedule state and cursor are persisted through.
///
/// The read model is rebuilt here from the records on disk rather than taken from the
/// caller: a stale snapshot must not be able to drive a write (the same reason WP04
/// asks the durable records, not the caller's index, what a key is).
#[allow(clippy::too_many_lines)]
pub fn apply(
    config: &mut Config,
    root: &Path,
    request: &LifecycleRequest,
) -> Result<LifecycleOutcome> {
    let action = request.action;
    let schedule_id = request.schedule_id.clone();

    // C-004: consent first. An unconfirmed request touches nothing at all.
    if !request.confirmed {
        return Ok(refused(
            action,
            schedule_id,
            request.cycle_id.clone(),
            LifecycleDiagnosticKind::NotConfirmed,
            format!("cycle_schedules.{}", request.schedule_id),
            "a lifecycle action must be confirmed: detection reports a warning, a caller or person \
             decides, and only then is anything written",
        ));
    }
    // A reason the action records but the request omitted is refused by name.
    if action.requires_reason() && request.reason_text().is_empty() {
        return Ok(refused(
            action,
            schedule_id,
            request.cycle_id.clone(),
            LifecycleDiagnosticKind::MissingReason,
            format!("cycle_schedules.{}.reason", request.schedule_id),
            format!(
                "`{}` records a reason; supply one so the decision is auditable",
                action.as_str()
            ),
        ));
    }
    // WP04: the one gate every audited field passes through before it can reach a
    // `## History` entry. It runs here, before anything is read or written, so no
    // action — and no detail `close` composes from its reason — can render an entry
    // that is really two. See `history_text_hazard` for what is refused and why.
    if !request.reason_text().is_empty()
        && let Some(hazard) = history_text_hazard(request.reason_text(), true)
    {
        return Ok(refused(
            action,
            schedule_id,
            request.cycle_id.clone(),
            LifecycleDiagnosticKind::InvalidReason,
            format!("cycle_schedules.{}.reason", request.schedule_id),
            format!(
                "the reason contains {hazard}; a `## History` entry is one line, so a reason \
                 carrying one would render as more than one entry and a reader would take the \
                 extra line for an event nobody wrote"
            ),
        ));
    }
    // Every writing action records an actor and an explicit instant (T027): there is
    // no clock, so a caller that wants an audit entry supplies the time.
    if action.writes() {
        let actor = request.actor.trim();
        if actor.is_empty() {
            return Ok(refused(
                action,
                schedule_id,
                request.cycle_id.clone(),
                LifecycleDiagnosticKind::MissingActor,
                format!("cycle_schedules.{}.actor", request.schedule_id),
                format!(
                    "`{}` records who decided; the actor is blank",
                    action.as_str()
                ),
            ));
        }
        if let Some(hazard) = history_text_hazard(actor, false) {
            return Ok(refused(
                action,
                schedule_id,
                request.cycle_id.clone(),
                LifecycleDiagnosticKind::InvalidActor,
                format!("cycle_schedules.{}.actor", request.schedule_id),
                format!(
                    "the actor contains {hazard}; a `## History` entry is one line, so an actor \
                     carrying one would render as more than one entry and a reader would take the \
                     extra line for an event nobody wrote"
                ),
            ));
        }
        let Some(timestamp) = request.timestamp.as_deref().map(str::trim) else {
            return Ok(refused(
                action,
                schedule_id,
                request.cycle_id.clone(),
                LifecycleDiagnosticKind::MissingTimestamp,
                format!("cycle_schedules.{}.timestamp", request.schedule_id),
                format!(
                    "`{}` records when it happened; supply an explicit RFC 3339 timestamp",
                    action.as_str()
                ),
            ));
        };
        if !validate_timestamp(timestamp) {
            return Ok(refused(
                action,
                schedule_id,
                request.cycle_id.clone(),
                LifecycleDiagnosticKind::InvalidTimestamp,
                format!("cycle_schedules.{}.timestamp", request.schedule_id),
                format!(
                    "`{timestamp}` is not a `YYYY-MM-DDTHH:MM:SSZ` instant; an audit time is \
                     evidence and is never invented"
                ),
            ));
        }
    }

    let store = CycleStore::new(root);
    let index = ScheduleIndex::build(config, &store.list()?);
    let Some(schedule) = index.schedule(&schedule_id).cloned() else {
        return Ok(refused(
            action,
            schedule_id,
            request.cycle_id.clone(),
            LifecycleDiagnosticKind::UnknownSchedule,
            format!("cycle_schedules.{}", request.schedule_id),
            format!("no cycle schedule `{}` is defined", request.schedule_id),
        ));
    };

    match action {
        LifecycleAction::Close => close(&store, root, &index, request),
        LifecycleAction::Reopen => reopen(root, &store, &index, request),
        LifecycleAction::Skip => skip(&store, &index, &schedule, request),
        LifecycleAction::Extend => extend(config, &store, &index, &schedule, request),
        LifecycleAction::Pause => set_state(
            config,
            root,
            &store,
            &index,
            &schedule,
            request,
            (ScheduleState::Paused, GeneratedCycleState::Paused),
        ),
        LifecycleAction::Resume => set_state(
            config,
            root,
            &store,
            &index,
            &schedule,
            request,
            (ScheduleState::Active, GeneratedCycleState::Active),
        ),
        LifecycleAction::AdjustFuture => {
            adjust_future(config, root, &store, &index, &schedule, request)
        }
        LifecycleAction::Ignore => Ok(ignore(&index, request)),
    }
}

/// `close`: capture the immutable snapshot, mark the record closed, log the event.
///
/// The snapshot is written **first**, so the historical evidence exists before the
/// live record claims to be closed; a failed record write removes the snapshot again
/// (and any directory the capture created), leaving the tree exactly as it was. A
/// repeat (already `closed`) is a no-op and never appends a second snapshot or event
/// (T024/T028, C-003/C-007).
#[allow(clippy::too_many_lines)]
pub(super) fn close(
    store: &CycleStore,
    root: &Path,
    index: &ScheduleIndex,
    request: &LifecycleRequest,
) -> Result<LifecycleOutcome> {
    let action = LifecycleAction::Close;
    let schedule_id = request.schedule_id.clone();
    let Some(cycle_id) = request.cycle_id.clone() else {
        return Ok(missing_cycle(action, schedule_id, "closing"));
    };
    if cycle_id.schedule_id() != schedule_id.as_str() {
        return Ok(not_owned(action, schedule_id, cycle_id));
    }
    let Some(cycle) = index.cycle(&cycle_id).cloned() else {
        return Ok(unknown_cycle(action, schedule_id, cycle_id));
    };
    match cycle.state {
        GeneratedCycleState::Closed => {
            return Ok(no_op(
                action,
                schedule_id,
                Some(cycle_id),
                "the instance is already closed; its snapshot and event are the record and nothing \
                 was written",
            ));
        }
        GeneratedCycleState::Skipped => {
            return Ok(refused(
                action,
                schedule_id,
                Some(cycle_id.clone()),
                LifecycleDiagnosticKind::TerminalCycle,
                format!("cycles.{cycle_id}.state"),
                format!(
                    "cycle `{cycle_id}` is skipped, which is terminal; a skipped sequence is not \
                     closed, it stays recorded"
                ),
            ));
        }
        GeneratedCycleState::Active | GeneratedCycleState::Paused => {}
    }

    let stored = read_stored(store, &cycle.name);
    let snapshots = CycleSnapshotStore::new(root);
    let already = match snapshots.occupant(&cycle_id)? {
        SnapshotOccupant::Same(_) => true,
        SnapshotOccupant::Foreign { filename } => {
            return Ok(refused(
                action,
                schedule_id,
                Some(cycle_id.clone()),
                LifecycleDiagnosticKind::SnapshotCollision,
                format!("docs/cycle_snapshots/{filename}"),
                format!(
                    "`docs/cycle_snapshots/{filename}` already exists and is not `{cycle_id}`'s \
                     snapshot; a snapshot is immutable, so nothing was overwritten"
                ),
            ));
        }
        SnapshotOccupant::Absent => false,
    };
    // WP04/T019: the capacity evidence this close records. `None` on the request — every
    // caller written before the field existed — leaves the issue-181 empty map, so an
    // un-updated caller captures exactly what it always did. The payload is built from
    // the calculation the caller computed, never recomputed here: this function holds no
    // `Config` and reads no issue.
    let measurements =
        request
            .capacity
            .as_ref()
            .map_or_else(CycleSnapshotMetadata::new, |calculation| {
                CapacitySnapshot::capture(
                    &cycle_id,
                    request.timestamp.as_deref().unwrap_or_default(),
                    &request.actor,
                    calculation,
                )
                .to_measurements()
            });
    let snapshot = CycleSnapshot {
        cycle_id: cycle_id.clone(),
        schedule_id: schedule_id.clone(),
        sequence: cycle.sequence,
        start_date: cycle.start_date.clone(),
        due_date: cycle.due_date.clone(),
        closed_at: request
            .timestamp
            .as_deref()
            .unwrap_or_default()
            .trim()
            .to_string(),
        closed_by: request.actor.trim().to_string(),
        state_summary: GeneratedCycleState::Closed.as_str().to_string(),
        measurements,
        extensions: CycleSnapshotMetadata::new(),
    };
    let snapshot_dirs = missing_ancestors(snapshots.dir());
    let mut wrote_snapshot = false;
    if !already {
        snapshots.capture(&snapshot)?;
        wrote_snapshot = true;
    }

    let path = format!(
        "docs/cycle_snapshots/{}",
        CycleSnapshotStore::filename_for(&cycle_id)
    );
    let mut record = base_record(&cycle, stored.as_ref());
    record.state = Some(GeneratedCycleState::Closed.as_str().to_string());
    let body = append_event(
        stored_body(stored.as_ref()),
        request,
        HistoryEventKind::CycleClosed,
        &format!(
            "reason: {}; state: closed; snapshot: {path}",
            request.reason_text()
        ),
    );
    if let Err(error) = write_cycle(store, &record, &body) {
        let mut undone = Vec::new();
        if wrote_snapshot {
            if let Err(failure) = snapshots.discard(&cycle_id) {
                undone.push(format!("the snapshot `{path}` was left behind: {failure}"));
            } else {
                remove_empty_dirs(&snapshot_dirs);
            }
        }
        let tail = if !wrote_snapshot {
            // This call captured nothing, so it removed nothing: saying otherwise hides
            // the fact that the snapshot on disk is a pre-existing one (the "crashed
            // close being completed" case) rather than this call's residue.
            "no snapshot was written by this call, so the snapshot already on disk is \
             untouched and only the record is unchanged"
                .to_string()
        } else if undone.is_empty() {
            "the snapshot was removed again and the record is unchanged".to_string()
        } else {
            undone.join("; ")
        };
        return Ok(refused(
            action,
            schedule_id,
            Some(cycle_id.clone()),
            LifecycleDiagnosticKind::SchedulingFailed,
            format!("cycles.{cycle_id}"),
            format!("the cycle record for `{cycle_id}` could not be written: {error}; {tail}"),
        ));
    }
    let message = if already {
        format!("marked `{cycle_id}` closed; its snapshot was already captured and is unchanged")
    } else {
        format!("closed `{cycle_id}` and captured `{path}`")
    };
    Ok(LifecycleOutcome::Applied {
        action,
        schedule_id,
        cycle_id: Some(cycle_id),
        snapshot_path: Some(path),
        dates: None,
        message,
    })
}

/// `reopen`: restore a closed instance's record to `active` and log the one event.
///
/// `close`'s inverse, and deliberately not its mirror. A closed cycle's capacity is the
/// immutable snapshot captured at close (C-008/NFR-002), and reopening is the one way
/// it may be configured again — so this **writes no snapshot**: it restores the record's
/// `state`, appends exactly one `cycle_reopened` event naming the snapshot the close
/// captured, and nothing else. The prior snapshot's bytes and every prior
/// `## History` entry are retained verbatim; a reader can see which evidence the reopen
/// is about from the event's own detail.
///
/// The prior evidence is looked up **read-only** ([`CapacitySnapshot::read`]), so a
/// cycle closed before this mission — one whose snapshot has no capacity payload — is
/// reopened with the detail saying `snapshot: none` rather than failing.
///
/// A repeat is a `no-op`, because the postcondition (this instance is open) already
/// holds: a second reopen must not append a second event. `paused` counts as open for
/// that purpose, and a `skipped` sequence is refused, because it was never generated.
pub(super) fn reopen(
    root: &Path,
    store: &CycleStore,
    index: &ScheduleIndex,
    request: &LifecycleRequest,
) -> Result<LifecycleOutcome> {
    let action = LifecycleAction::Reopen;
    let schedule_id = request.schedule_id.clone();
    let Some(cycle_id) = request.cycle_id.clone() else {
        return Ok(missing_cycle(action, schedule_id, "reopening"));
    };
    if cycle_id.schedule_id() != schedule_id.as_str() {
        return Ok(not_owned(action, schedule_id, cycle_id));
    }
    let Some(cycle) = index.cycle(&cycle_id).cloned() else {
        return Ok(unknown_cycle(action, schedule_id, cycle_id));
    };
    match cycle.state {
        GeneratedCycleState::Active | GeneratedCycleState::Paused => {
            return Ok(no_op(
                action,
                schedule_id,
                Some(cycle_id),
                "the instance is not closed; reopening an open cycle is a no-op and nothing was \
                 written",
            ));
        }
        GeneratedCycleState::Skipped => {
            return Ok(refused(
                action,
                schedule_id,
                Some(cycle_id.clone()),
                LifecycleDiagnosticKind::TerminalCycle,
                format!("cycles.{cycle_id}.state"),
                format!(
                    "cycle `{cycle_id}` is skipped, which is terminal; a skipped sequence was \
                     never generated, so there is nothing to reopen"
                ),
            ));
        }
        GeneratedCycleState::Closed => {}
    }

    // Read-only: the prior evidence the event names. Nothing captures, discards or
    // rewrites a snapshot on this path.
    let prior = CapacitySnapshot::read(&CycleSnapshotStore::new(root), &cycle_id)?;
    let (kind, detail) =
        crate::capacity::snapshot::reopen_event(request.reason_text(), prior.as_ref())
            .expect("`apply` refuses a missing reason before any action runs");
    let stored = read_stored(store, &cycle.name);
    let mut record = base_record(&cycle, stored.as_ref());
    record.state = Some(GeneratedCycleState::Active.as_str().to_string());
    let body = append_event(stored_body(stored.as_ref()), request, kind, &detail);
    if let Err(error) = write_cycle(store, &record, &body) {
        return Ok(refused(
            action,
            schedule_id,
            Some(cycle_id.clone()),
            LifecycleDiagnosticKind::SchedulingFailed,
            format!("cycles.{cycle_id}"),
            format!(
                "the cycle record for `{cycle_id}` could not be written: {error}; no event was \
                 appended and the snapshot on disk is untouched"
            ),
        ));
    }
    let message = match prior.as_ref() {
        Some(evidence) => format!(
            "reopened `{cycle_id}`; the snapshot `{}` is unchanged and stays readable, and the \
             current calculation is derived again",
            evidence.snapshot_id
        ),
        None => format!(
            "reopened `{cycle_id}`; it has no capacity snapshot, so there is none to preserve"
        ),
    };
    Ok(LifecycleOutcome::Applied {
        action,
        schedule_id,
        cycle_id: Some(cycle_id),
        snapshot_path: None,
        dates: None,
        message,
    })
}

/// `skip`: record the sequence as skipped so it is never silently regenerated.
///
/// A skip of a sequence that has no record yet is allowed only for the schedule's
/// **next candidate** sequence. Skipping further ahead would create a record above an
/// unrecorded earlier sequence, and `derive_cursor` would then report
/// `next_sequence = skipped + 1` — a cursor forked past a hole that generation (which
/// never creates a sequence beyond a gap, WP04) could no longer fill. Such a skip is
/// refused with the missing sequence named.
#[allow(clippy::too_many_lines)]
pub(super) fn skip(
    store: &CycleStore,
    index: &ScheduleIndex,
    schedule: &CycleScheduleConfiguration,
    request: &LifecycleRequest,
) -> Result<LifecycleOutcome> {
    let action = LifecycleAction::Skip;
    let schedule_id = request.schedule_id.clone();
    let Some(cycle_id) = request.cycle_id.clone() else {
        return Ok(missing_cycle(action, schedule_id, "skipping"));
    };
    if cycle_id.schedule_id() != schedule_id.as_str() {
        return Ok(not_owned(action, schedule_id, cycle_id));
    }

    let (stored, mut record) = if let Some(cycle) = index.cycle(&cycle_id).cloned() {
        match cycle.state {
            GeneratedCycleState::Skipped => {
                return Ok(no_op(
                    action,
                    schedule_id,
                    Some(cycle_id),
                    "the sequence is already recorded as skipped; nothing was written",
                ));
            }
            GeneratedCycleState::Closed => {
                return Ok(refused(
                    action,
                    schedule_id,
                    Some(cycle_id.clone()),
                    LifecycleDiagnosticKind::TerminalCycle,
                    format!("cycles.{cycle_id}.state"),
                    format!(
                        "cycle `{cycle_id}` is closed, which is terminal; a closed cycle cannot be \
                         skipped"
                    ),
                ));
            }
            GeneratedCycleState::Active | GeneratedCycleState::Paused => {}
        }
        let stored = read_stored(store, &cycle.name);
        let record = base_record(&cycle, stored.as_ref());
        (stored, record)
    } else {
        // No record yet: only the next candidate may be materialised, or the cursor
        // would fork past a hole.
        let sequence = cycle_id.sequence();
        let next = index.cursor(&schedule_id).next_sequence.unwrap_or(1);
        if sequence > next {
            return Ok(refused(
                action,
                schedule_id.clone(),
                Some(cycle_id.clone()),
                LifecycleDiagnosticKind::MissingSequence,
                format!("cycle_schedules.{schedule_id}.cursor"),
                format!(
                    "sequence {sequence} of `{schedule_id}` is not the next candidate and no \
                     record exists for sequence {next}; skipping it would leave {next} unrecorded \
                     and generation never creates a sequence beyond a gap — record {next} first"
                ),
            ));
        }
        let Some(rule) = cadence_rule(schedule) else {
            return Ok(missing_cadence(action, schedule_id, Some(cycle_id)));
        };
        if let Err(error) = rule.validate() {
            return Ok(invalid_cadence(
                action,
                schedule_id,
                Some(cycle_id),
                &error,
                request,
            ));
        }
        let Some(start) = nth_occurrence(&rule, sequence) else {
            return Ok(unresolvable(action, schedule_id, Some(cycle_id)));
        };
        let due = match nominal_due(&schedule_id, schedule, &start) {
            Ok(due) => due,
            Err(diagnostic) => {
                return Ok(LifecycleOutcome::Rejected {
                    action,
                    schedule_id,
                    cycle_id: Some(cycle_id),
                    diagnostics: vec![diagnostic],
                });
            }
        };
        let name = reference_name(&schedule.name, &start, sequence);
        if !matches!(index.resolve(&name), CycleReference::Unknown { .. }) {
            return Ok(refused(
                action,
                schedule_id,
                Some(cycle_id),
                LifecycleDiagnosticKind::ReferenceCollision,
                format!("cycles.{name}"),
                format!(
                    "the reference label `{name}` already answers to another cycle; rename that \
                     cycle before skipping this sequence"
                ),
            ));
        }
        let filename = format!("{}.md", crate::slug::slugify(&name));
        if store.dir().join(&filename).exists() {
            return Ok(refused(
                action,
                schedule_id,
                Some(cycle_id.clone()),
                LifecycleDiagnosticKind::NameCollision,
                format!("docs/cycles/{filename}"),
                format!(
                    "`docs/cycles/{filename}` is already occupied and is not `{cycle_id}`; \
                     refusing to lose whatever is there"
                ),
            ));
        }
        let record = CycleRecord {
            name,
            description: None,
            start_date: Some(start.clone()),
            due_date: Some(due.clone()),
            schedule_id: Some(schedule_id.as_str().to_string()),
            sequence: Some(sequence),
            state: Some(GeneratedCycleState::Skipped.as_str().to_string()),
        };
        (None, record)
    };

    record.state = Some(GeneratedCycleState::Skipped.as_str().to_string());
    let dates = format!(
        "{}->{}",
        record.start_date.as_deref().unwrap_or_default(),
        record.due_date.as_deref().unwrap_or_default()
    );
    let body = append_event(
        stored_body(stored.as_ref()),
        request,
        HistoryEventKind::CycleSkipped,
        &format!(
            "reason: {}; state: skipped; dates: {dates}",
            request.reason_text()
        ),
    );
    if let Err(error) = write_cycle(store, &record, &body) {
        return Ok(refused(
            action,
            schedule_id,
            Some(cycle_id.clone()),
            LifecycleDiagnosticKind::SchedulingFailed,
            format!("cycles.{cycle_id}"),
            format!("the cycle record for `{cycle_id}` could not be written: {error}"),
        ));
    }
    Ok(LifecycleOutcome::Applied {
        action,
        schedule_id,
        cycle_id: Some(cycle_id),
        snapshot_path: None,
        dates: None,
        message: "`".to_string() + &record.name + "` is now recorded as skipped",
    })
}

/// `extend`: push the instance's due date out by one cadence period.
///
/// The target is derived from the instance's own **start date** (which no lifecycle
/// action changes), so applying the action twice computes the same target and the
/// second call is a no-op — the due date is never moved twice (T025). The in-memory
/// `config.cycles` entry is kept in step, or a later `Config::save` in the same
/// process would rewrite the record from that stale map and revert the extension.
pub(super) fn extend(
    config: &mut Config,
    store: &CycleStore,
    index: &ScheduleIndex,
    schedule: &CycleScheduleConfiguration,
    request: &LifecycleRequest,
) -> Result<LifecycleOutcome> {
    let action = LifecycleAction::Extend;
    let schedule_id = request.schedule_id.clone();
    let Some(cycle_id) = request.cycle_id.clone() else {
        return Ok(missing_cycle(action, schedule_id, "extending"));
    };
    if cycle_id.schedule_id() != schedule_id.as_str() {
        return Ok(not_owned(action, schedule_id, cycle_id));
    }
    let Some(cycle) = index.cycle(&cycle_id).cloned() else {
        return Ok(unknown_cycle(action, schedule_id, cycle_id));
    };
    if cycle.state.is_terminal() {
        return Ok(refused(
            action,
            schedule_id,
            Some(cycle_id.clone()),
            LifecycleDiagnosticKind::TerminalCycle,
            format!("cycles.{cycle_id}.state"),
            format!(
                "cycle `{cycle_id}` is {}, which is terminal; it cannot be extended",
                cycle.state.as_str()
            ),
        ));
    }
    let Some(rule) = cadence_rule(schedule) else {
        return Ok(missing_cadence(action, schedule_id, Some(cycle_id)));
    };
    if let Err(error) = rule.validate() {
        return Ok(invalid_cadence(
            action,
            schedule_id,
            Some(cycle_id),
            &error,
            request,
        ));
    }
    let Some(next_start) = step_from(&rule, &cycle.start_date) else {
        return Ok(unresolvable(action, schedule_id, Some(cycle_id)));
    };
    let target_due = match nominal_due(&schedule_id, schedule, &next_start) {
        Ok(due) => due,
        Err(diagnostic) => {
            return Ok(LifecycleOutcome::Rejected {
                action,
                schedule_id,
                cycle_id: Some(cycle_id),
                diagnostics: vec![diagnostic],
            });
        }
    };
    if cycle.due_date == target_due {
        return Ok(no_op(
            action,
            schedule_id,
            Some(cycle_id),
            format!("the instance already ends {target_due}; extending is idempotent"),
        ));
    }
    let stored = read_stored(store, &cycle.name);
    let mut record = base_record(&cycle, stored.as_ref());
    record.due_date = Some(target_due.clone());
    let body = append_event(
        stored_body(stored.as_ref()),
        request,
        HistoryEventKind::CycleExtended,
        &format!("reason: {}; due: {target_due}", request.reason_text()),
    );
    if let Err(error) = write_cycle(store, &record, &body) {
        return Ok(refused(
            action,
            schedule_id,
            Some(cycle_id.clone()),
            LifecycleDiagnosticKind::SchedulingFailed,
            format!("cycles.{cycle_id}"),
            format!("the cycle record for `{cycle_id}` could not be written: {error}"),
        ));
    }
    // Keep the in-memory map in step so a later `Config::save` does not revert it.
    config
        .cycles
        .insert(record.name.clone(), PlanningCycle::from(record));
    Ok(LifecycleOutcome::Applied {
        action,
        schedule_id,
        cycle_id: Some(cycle_id.clone()),
        snapshot_path: None,
        dates: Some((cycle.start_date, target_due)),
        message: format!("extended `{cycle_id}` by one cadence period"),
    })
}

/// `pause`/`resume`: write the schedule's own state, every affected instance's state,
/// and one event per touched record.
///
/// The affected instances are the named one, or — when none is named — every
/// non-terminal instance of the schedule. Each touched record gets exactly one
/// `cycle_paused`/`cycle_resumed` entry; a repeat (every state already at its target)
/// is a no-op.
pub(super) fn set_state(
    config: &mut Config,
    root: &Path,
    store: &CycleStore,
    index: &ScheduleIndex,
    schedule: &CycleScheduleConfiguration,
    request: &LifecycleRequest,
    target: (ScheduleState, GeneratedCycleState),
) -> Result<LifecycleOutcome> {
    let (schedule_state, cycle_state) = target;
    let action = request.action;
    let schedule_id = request.schedule_id.clone();
    if schedule.state.is_terminal() {
        return Ok(refused(
            action,
            schedule_id,
            request.cycle_id.clone(),
            LifecycleDiagnosticKind::TerminalSchedule,
            format!("cycle_schedules.{}.state", request.schedule_id),
            format!(
                "schedule `{}` is ended, which is terminal; `{}` is refused for good",
                request.schedule_id,
                action.as_str()
            ),
        ));
    }
    let targets: Vec<GeneratedCycle> = match request.cycle_id.clone() {
        Some(cycle_id) => {
            if cycle_id.schedule_id() != schedule_id.as_str() {
                return Ok(not_owned(action, schedule_id, cycle_id));
            }
            let Some(cycle) = index.cycle(&cycle_id).cloned() else {
                return Ok(unknown_cycle(action, schedule_id, cycle_id));
            };
            if cycle.state.is_terminal() {
                return Ok(refused(
                    action,
                    schedule_id,
                    Some(cycle_id.clone()),
                    LifecycleDiagnosticKind::TerminalCycle,
                    format!("cycles.{cycle_id}.state"),
                    format!(
                        "cycle `{cycle_id}` is {}, which is terminal; the action names it",
                        cycle.state.as_str()
                    ),
                ));
            }
            vec![cycle]
        }
        None => index
            .cycles_of(&schedule_id)
            .filter(|cycle| !cycle.state.is_terminal())
            .cloned()
            .collect(),
    };
    let instances_at_target = targets.iter().all(|cycle| cycle.state == cycle_state);
    if schedule.state == schedule_state && instances_at_target {
        return Ok(no_op(
            action,
            schedule_id,
            request.cycle_id.clone(),
            format!(
                "the schedule is already {} and every affected instance matches",
                schedule_state.as_str()
            ),
        ));
    }

    let kind = action.history_kind().expect("pause/resume write events");
    let detail = match request.reason_text() {
        "" => format!("state: {}", schedule_state.as_str()),
        reason => format!("state: {}; reason: {reason}", schedule_state.as_str()),
    };
    // Write every instance that actually changes, remembering each original so a
    // failure can put the tree back exactly.
    let mut written: Vec<(String, Option<StoredCycle>)> = Vec::new();
    for cycle in &targets {
        if cycle.state == cycle_state {
            continue;
        }
        let stored = read_stored(store, &cycle.name);
        let mut record = base_record(cycle, stored.as_ref());
        record.state = Some(cycle_state.as_str().to_string());
        let body = append_event(stored_body(stored.as_ref()), request, kind, &detail);
        if let Err(error) = write_cycle(store, &record, &body) {
            let undone = roll_back(store, &written);
            return Ok(refused(
                action,
                schedule_id,
                request.cycle_id.clone(),
                LifecycleDiagnosticKind::SchedulingFailed,
                format!("cycles.{}", cycle.id),
                format!(
                    "a cycle record could not be written: {error}; {}",
                    roll_back_tail(&undone, written.len())
                ),
            ));
        }
        written.push((record.name.clone(), stored));
    }

    if schedule.state != schedule_state {
        if let Some(entry) = config.cycle_schedules.get_mut(schedule_id.as_str()) {
            entry.state = schedule_state;
        }
        let config_path = root.join("tix.toml");
        if let Err(error) = config.save(&config_path) {
            let undone = roll_back(store, &written);
            if let Some(entry) = config.cycle_schedules.get_mut(schedule_id.as_str()) {
                entry.state = schedule.state;
            }
            return Ok(refused_rollback(
                action,
                schedule_id,
                request.cycle_id.clone(),
                &config_path.display().to_string(),
                &error,
                (!undone.is_empty()).then(|| undone.join("; ")),
            ));
        }
    }

    Ok(LifecycleOutcome::Applied {
        action,
        schedule_id,
        cycle_id: request.cycle_id.clone(),
        snapshot_path: None,
        dates: None,
        message: format!(
            "schedule is now {}; {} instance record(s) updated",
            schedule_state.as_str(),
            written.len()
        ),
    })
}

/// `adjust-future`: re-derive every future instance's dates from the schedule's own
/// definition, log the event, and re-derive the cursor.
///
/// Only non-terminal (`active`/`paused`) instances are rewritten; a closed cycle's
/// dates and its snapshot are historical evidence and are never touched (C-003/C-007).
/// When the request names a cycle, only that instance and the ones after it (by
/// sequence) are adjusted. Each instance's dates come from its own `sequence` and the
/// schedule's anchor through the shared rule, so the action is idempotent (T026/T028).
#[allow(clippy::too_many_lines)]
pub(super) fn adjust_future(
    config: &mut Config,
    root: &Path,
    store: &CycleStore,
    index: &ScheduleIndex,
    schedule: &CycleScheduleConfiguration,
    request: &LifecycleRequest,
) -> Result<LifecycleOutcome> {
    let action = LifecycleAction::AdjustFuture;
    let schedule_id = request.schedule_id.clone();
    let from_sequence = match request.cycle_id.clone() {
        Some(cycle_id) => {
            if cycle_id.schedule_id() != schedule_id.as_str() {
                return Ok(not_owned(action, schedule_id, cycle_id));
            }
            let Some(cycle) = index.cycle(&cycle_id).cloned() else {
                return Ok(unknown_cycle(action, schedule_id, cycle_id));
            };
            cycle.sequence
        }
        None => 1,
    };
    let Some(rule) = cadence_rule(schedule) else {
        return Ok(missing_cadence(
            action,
            schedule_id,
            request.cycle_id.clone(),
        ));
    };
    if let Err(error) = rule.validate() {
        return Ok(invalid_cadence(
            action,
            schedule_id,
            request.cycle_id.clone(),
            &error,
            request,
        ));
    }

    // The future instances whose dates the schedule's current definition moves.
    let kind = action
        .history_kind()
        .expect("adjust-future writes an event");
    let mut plans: Vec<(String, Option<StoredCycle>, CycleRecord, String)> = Vec::new();
    for cycle in index.cycles_of(&schedule_id) {
        if cycle.state.is_terminal() || cycle.sequence < from_sequence {
            continue;
        }
        let Some(start) = nth_occurrence(&rule, cycle.sequence) else {
            return Ok(unresolvable(action, schedule_id, Some(cycle.id.clone())));
        };
        let due = match nominal_due(&schedule_id, schedule, &start) {
            Ok(due) => due,
            Err(diagnostic) => {
                return Ok(LifecycleOutcome::Rejected {
                    action,
                    schedule_id,
                    cycle_id: Some(cycle.id.clone()),
                    diagnostics: vec![diagnostic],
                });
            }
        };
        if start == cycle.start_date && due == cycle.due_date {
            continue;
        }
        let stored = read_stored(store, &cycle.name);
        let mut record = stored
            .as_ref()
            .map_or_else(|| cycle.to_record(), |stored| stored.record.clone());
        record.start_date = Some(start.clone());
        record.due_date = Some(due.clone());
        let body = append_event(
            stored_body(stored.as_ref()),
            request,
            kind,
            &format!("reason: {}; dates: {start}->{due}", request.reason_text()),
        );
        plans.push((cycle.name.clone(), stored, record, body));
    }

    // What the cursor would be once the window is adjusted. Re-derived from the
    // instances, never accumulated — the same reconciled value the identity index
    // reports (`GenerationCursor`'s module note).
    let by_name: BTreeMap<String, CycleRecord> = plans
        .iter()
        .map(|(name, _, record, _)| (name.clone(), record.clone()))
        .collect();
    let projected: Vec<CycleRecord> = store
        .list()?
        .into_iter()
        .map(|record| by_name.get(&record.name).cloned().unwrap_or(record))
        .collect();
    let derived = ScheduleIndex::build(config, &projected).cursor(&schedule_id);
    let previous_cursor = config
        .cycle_schedules
        .get(schedule_id.as_str())
        .and_then(|record| record.cursor.clone());
    if plans.is_empty() && previous_cursor.as_ref() == Some(&derived) {
        return Ok(no_op(
            action,
            schedule_id,
            request.cycle_id.clone(),
            "every future instance already matches the schedule and the cursor is current",
        ));
    }

    let mut written: Vec<(String, Option<StoredCycle>)> = Vec::new();
    for (name, stored, record, body) in &plans {
        if let Err(error) = write_cycle(store, record, body) {
            let undone = roll_back(store, &written);
            return Ok(refused(
                action,
                schedule_id,
                request.cycle_id.clone(),
                LifecycleDiagnosticKind::SchedulingFailed,
                format!("cycles.{name}"),
                format!(
                    "a future instance record could not be written: {error}; {}",
                    roll_back_tail(&undone, written.len())
                ),
            ));
        }
        written.push((name.clone(), stored.clone()));
    }

    // `Config::save` rewrites the cycle files from the in-memory legacy map, so the
    // adjusted dates must be reflected there too, or the save would clobber them.
    let previous_cycles: Vec<(String, Option<PlanningCycle>)> = plans
        .iter()
        .map(|(name, _, _, _)| (name.clone(), config.cycles.get(name).cloned()))
        .collect();
    for (name, _, record, _) in &plans {
        config
            .cycles
            .insert(name.clone(), PlanningCycle::from(record.clone()));
    }
    if let Some(entry) = config.cycle_schedules.get_mut(schedule_id.as_str()) {
        entry.cursor = Some(derived.clone());
    }
    let config_path = root.join("tix.toml");
    if let Err(error) = config.save(&config_path) {
        let undone = roll_back(store, &written);
        for (name, previous) in previous_cycles {
            match previous {
                Some(planning) => {
                    config.cycles.insert(name, planning);
                }
                None => {
                    config.cycles.shift_remove(&name);
                }
            }
        }
        if let Some(entry) = config.cycle_schedules.get_mut(schedule_id.as_str()) {
            entry.cursor = previous_cursor;
        }
        return Ok(refused_rollback(
            action,
            schedule_id,
            request.cycle_id.clone(),
            &config_path.display().to_string(),
            &error,
            (!undone.is_empty()).then(|| undone.join("; ")),
        ));
    }

    let dates = plans.last().map(|(_, _, record, _)| {
        (
            record.start_date.clone().unwrap_or_default(),
            record.due_date.clone().unwrap_or_default(),
        )
    });
    Ok(LifecycleOutcome::Applied {
        action,
        schedule_id,
        cycle_id: request.cycle_id.clone(),
        snapshot_path: None,
        dates,
        message: format!(
            "re-derived {} future instance(s) from the schedule and refreshed the cursor",
            plans.len()
        ),
    })
}

/// `ignore`: the explicit "no action" decision. Nothing is written.
pub(super) fn ignore(index: &ScheduleIndex, request: &LifecycleRequest) -> LifecycleOutcome {
    let action = LifecycleAction::Ignore;
    let schedule_id = request.schedule_id.clone();
    if let Some(cycle_id) = request.cycle_id.clone() {
        if cycle_id.schedule_id() != schedule_id.as_str() {
            return not_owned(action, schedule_id, cycle_id);
        }
        if index.cycle(&cycle_id).is_none() {
            return unknown_cycle(action, schedule_id, cycle_id);
        }
    }
    no_op(
        action,
        schedule_id,
        request.cycle_id.clone(),
        "ignore records nothing: the warning is closed and no file, cursor, record or snapshot \
         is written",
    )
}