tix-tracker 0.10.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
//! Explicit, confirmed lifecycle actions (WP05, T024–T029).
//!
//! # Eight actions, one confirmed request, one outcome each
//!
//! [`apply`] carries out exactly one of the eight actions
//! ([`LifecycleAction`]) and returns exactly one [`LifecycleOutcome`] with a stable
//! spelling — `applied`, `no-op` or `rejected`. [`LifecycleRequest::confirmed`] must
//! be set first: naming a cycle is not consent, so an unconfirmed request is refused
//! before anything is read or written (C-004). A reason is *required* for the four
//! actions whose whole point is an auditable decision — `close`, `extend`, `skip` and
//! `adjust-future` — refused by name when it is missing, and every action that writes
//! carries an explicit timestamp and actor (there is no clock here).
//!
//! # Where the evidence of an action lives
//!
//! The mission's evidence for a cycle is its **record**, its **snapshot**, the
//! **cursor**, and — for an applied decision — one line of the record's own
//! `## History` (T027). Cycles are not issues: the events are appended to the
//! **generated cycle record's Markdown body** through the crate's one
//! [`History`] grammar ([`HistoryEventKind::CycleClosed`] and siblings), never to an
//! issue, and there is no second log. No issue is created, moved, relabelled or
//! rewritten, and the normal move workflow is untouched (C-007).
//!
//! * `close` sets the cycle record's `state` to `closed`, appends a `cycle_closed`
//!   event, **and** captures an immutable snapshot under `docs/cycle_snapshots/`
//!   (the historical record, see [`crate::cycle_schedule::snapshot`]);
//! * `reopen` (mission `cycle-capacity-planning-01M3C85C`, WP04) is `close`'s inverse
//!   and deliberately writes **no** snapshot: it restores the record's `state` to
//!   `active` and appends exactly one `cycle_reopened` event naming the snapshot the
//!   close captured. The prior snapshot and every prior event are retained verbatim
//!   (C-008/NFR-002) — a reopen is the one way a closed cycle may be configured
//!   again, not a second capture;
//! * `skip` records the sequence as a cycle record with `state = "skipped"` plus a
//!   `cycle_skipped` event, creating the record from the schedule's own anchor when
//!   it does not exist yet, so a later generation sees the key and reports it a
//!   no-op (C-006);
//! * `pause`/`resume` write the schedule's own `state`, every affected instance's
//!   state (the named one, or all non-terminal ones), and one event per touched
//!   record;
//! * `extend` rewrites the instance's `due_date` to one more cadence period, and
//!   `adjust-future` rewrites every *future* instance's dates and re-derives the
//!   cursor — both through the shared [`RecurrenceRule`], never by hand;
//! * `ignore` writes nothing at all: it is the "no action" outcome and says so.
//!
//! # Every write carries the record's description and body forward
//!
//! A cycle record is a [`CycleRecord`] frontmatter plus a Markdown body. The identity
//! adapter ([`GeneratedCycle::to_record`]) has no notion of either, so a lifecycle
//! write never rebuilds a record from it: it reads the **stored** record and body
//! first (`crate::records::RecordStore::get`) and merges the change onto that. A
//! `tix cycle edit --description …`, a hand-written body, or a previously appended
//! `## History` entry therefore survives every action — and every rollback restores
//! exactly what was there, description and body included.
//!
//! # Inertness is the contract, not a nicety
//!
//! An action that cannot be coherent — closing a skipped cycle, resuming an ended
//! schedule, extending a terminal one, a cycle id that belongs to another schedule,
//! an unknown cycle, a missing reason/actor/timestamp, a malformed timestamp, a skip
//! that would fork the cursor past a hole — is `rejected` with a field-aware
//! diagnostic and **zero writes**. A **repeated** action, whose postcondition already
//! holds, is a `no-op`: it must never append a second snapshot, a second event, or
//! move a date twice. A *returned* error from the storage seam is compensated as a
//! unit — every record this call wrote is restored (or removed) and every directory it
//! created is removed when empty — so even a failure leaves the tree byte-identical
//! (or says exactly what could not be undone).
//!
//! # Idempotency by construction
//!
//! `extend` and `adjust-future` are **derived**, not accumulated: `extend` computes
//! the instance's target due date from its own (invariant) `start_date`, and
//! `adjust-future` recomputes every instance's dates from the schedule's anchor and
//! its own `sequence`. Applying either twice is therefore the *same computation*, so
//! the second call finds the postcondition already true and is a no-op.
//!
//! # No clock, no daemon
//!
//! Nothing here reads `Instant`/`SystemTime`: a close's `closed_at` and every event
//! timestamp is the explicit string the request carries, validated by
//! [`validate_timestamp`](crate::cycle_schedule::snapshot::validate_timestamp). The
//! whole module is a confirmed function call, not a service.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use time::{Date, Month};

use crate::capacity::calculate::CapacityCalculation;
use crate::capacity::snapshot::CapacitySnapshot;
use crate::config::{Config, PlanningCycle};
use crate::cycle_schedule::config::{CycleScheduleConfiguration, CycleScheduleId, ScheduleState};
use crate::cycle_schedule::identity::{
    CycleReference, GeneratedCycle, GeneratedCycleId, GeneratedCycleState, ScheduleIndex,
    cadence_rule,
};
use crate::cycle_schedule::snapshot::{
    CycleSnapshot, CycleSnapshotMetadata, CycleSnapshotStore, SnapshotOccupant, validate_timestamp,
};
use crate::cycle_store::{CycleRecord, CycleStore};
use crate::error::{Result, TixError, render_diagnostics};
use crate::model::{History, HistoryEvent, HistoryEventKind};
use crate::records::RecordStore;
use crate::recurrence::rule::{RecurrenceRule, RuleContext, RuleKind};

/// One of the seven lifecycle actions (`data-model.md` §6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LifecycleAction {
    /// Capture the instance's immutable snapshot, mark it closed, and log the event.
    Close,
    /// Reopen a closed instance: restore `state` to `active` and log the event.
    ///
    /// WP04 of mission `cycle-capacity-planning-01M3C85C`. `close`'s inverse, and
    /// deliberately **not** its mirror: a closed cycle's capacity snapshot is
    /// immutable historical evidence (C-008/NFR-002), so a reopen restores the record's
    /// state and appends one `cycle_reopened` event naming the snapshot it reopens —
    /// and captures nothing. It is the one way a closed cycle may be configured again.
    Reopen,
    /// Push the instance's due date out by one cadence period.
    Extend,
    /// Record the sequence as skipped so it is never regenerated.
    Skip,
    /// Pause the schedule and every affected instance.
    Pause,
    /// Resume the schedule and every affected instance.
    Resume,
    /// Re-derive every future instance's dates from the schedule's own definition,
    /// and re-derive the cursor.
    AdjustFuture,
    /// The explicit "no action" decision: nothing is written.
    Ignore,
}

impl LifecycleAction {
    /// Every action, in the data model's order — with WP04's `reopen` beside its
    /// inverse `close`.
    pub const ALL: [Self; 8] = [
        Self::Close,
        Self::Reopen,
        Self::Extend,
        Self::Skip,
        Self::Pause,
        Self::Resume,
        Self::AdjustFuture,
        Self::Ignore,
    ];

    /// The contract's spelling, used verbatim in payloads and tests.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Close => "close",
            Self::Reopen => "reopen",
            Self::Extend => "extend",
            Self::Skip => "skip",
            Self::Pause => "pause",
            Self::Resume => "resume",
            Self::AdjustFuture => "adjust-future",
            Self::Ignore => "ignore",
        }
    }

    /// Whether the action records a reason, and therefore refuses a missing one.
    ///
    /// `close`, `reopen`, `extend`, `skip` and `adjust-future` change what a cycle
    /// *is*; each is an auditable decision, so the request must carry the reason it was
    /// taken. `pause`/`resume` are state toggles, and `ignore` decides nothing.
    #[must_use]
    pub const fn requires_reason(self) -> bool {
        matches!(
            self,
            Self::Close | Self::Reopen | Self::Extend | Self::Skip | Self::AdjustFuture
        )
    }

    /// Whether the action writes anything at all. Only `ignore` does not, and it is
    /// therefore the only action exempt from the actor/timestamp requirement.
    #[must_use]
    pub const fn writes(self) -> bool {
        !matches!(self, Self::Ignore)
    }

    /// The `## History` kind an applied action appends, or `None` for `ignore`.
    #[must_use]
    const fn history_kind(self) -> Option<HistoryEventKind> {
        match self {
            Self::Close => Some(HistoryEventKind::CycleClosed),
            Self::Reopen => Some(HistoryEventKind::CycleReopened),
            Self::Extend => Some(HistoryEventKind::CycleExtended),
            Self::Skip => Some(HistoryEventKind::CycleSkipped),
            Self::Pause => Some(HistoryEventKind::CyclePaused),
            Self::Resume => Some(HistoryEventKind::CycleResumed),
            Self::AdjustFuture => Some(HistoryEventKind::CycleAdjusted),
            Self::Ignore => None,
        }
    }

    /// Parse a stored or CLI spelling.
    pub fn parse(raw: &str) -> Result<Self> {
        match raw {
            "close" => Ok(Self::Close),
            "reopen" => Ok(Self::Reopen),
            "extend" => Ok(Self::Extend),
            "skip" => Ok(Self::Skip),
            "pause" => Ok(Self::Pause),
            "resume" => Ok(Self::Resume),
            "adjust-future" => Ok(Self::AdjustFuture),
            "ignore" => Ok(Self::Ignore),
            other => Err(TixError::InvalidInput(format!(
                "`{other}` is not a lifecycle action; expected one of `close`, `reopen`, `extend`, \
                 `skip`, `pause`, `resume`, `adjust-future`, `ignore`"
            ))),
        }
    }
}

/// The explicit, confirmed intent to carry out one lifecycle action.
///
/// Every field is supplied and none is inferred. `timestamp` is the caller's explicit
/// instant — this codebase has no clock — required by every action that writes;
/// `reason` is required by the five actions that record one (see
/// [`LifecycleAction::requires_reason`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LifecycleRequest {
    /// Which action to carry out.
    pub action: LifecycleAction,
    /// The schedule to act on, by stable id.
    pub schedule_id: CycleScheduleId,
    /// The instance to act on, when the action names one.
    pub cycle_id: Option<GeneratedCycleId>,
    /// Who asked — the audit actor.
    pub actor: String,
    /// Why, when the action records one.
    pub reason: Option<String>,
    /// The explicit instant (RFC 3339, `YYYY-MM-DDTHH:MM:SSZ`) the action happened.
    pub timestamp: Option<String>,
    /// Whether the caller confirmed the action. An unconfirmed request is inert.
    pub confirmed: bool,
    /// The capacity calculation a `close` records as its evidence, when the caller
    /// computed one (mission `cycle-capacity-planning-01M3C85C`, WP04).
    ///
    /// **The caller supplies this, and a later reader must not "fix" that by teaching
    /// [`apply`] to build one.** The `close` path has no `Config` and no issue store —
    /// only the cycle records, the schedule index and this request — so it cannot run
    /// the calculation, and threading a store through `apply` would change every CLI,
    /// TUI and MCP call site for a value those surfaces already hold. The caller that
    /// owns the project configuration and the issue store computes it (one
    /// [`CapacityCalculation::for_scope`]) and sets it here.
    ///
    /// `None` — the default, and what every caller written before this field did —
    /// means the close captures no capacity evidence, which is exactly the
    /// issue-181 behaviour: a snapshot with an empty `measurements` map. A payload
    /// this mission wrote reads back as "no capacity evidence", never an error, so an
    /// un-updated caller is not broken by the field's arrival.
    pub capacity: Option<CapacityCalculation>,
}

impl LifecycleRequest {
    /// A request that is **not** yet confirmed.
    #[must_use]
    pub fn new(
        action: LifecycleAction,
        schedule_id: CycleScheduleId,
        actor: impl Into<String>,
    ) -> Self {
        Self {
            action,
            schedule_id,
            cycle_id: None,
            actor: actor.into(),
            reason: None,
            timestamp: None,
            confirmed: false,
            capacity: None,
        }
    }

    /// Record the capacity calculation a `close` should capture as its evidence.
    #[must_use]
    pub fn with_capacity(mut self, calculation: CapacityCalculation) -> Self {
        self.capacity = Some(calculation);
        self
    }

    /// Record the confirmation.
    #[must_use]
    pub fn confirm(mut self) -> Self {
        self.confirmed = true;
        self
    }

    /// Name the instance the action targets.
    #[must_use]
    pub fn for_cycle(mut self, cycle_id: GeneratedCycleId) -> Self {
        self.cycle_id = Some(cycle_id);
        self
    }

    /// Record why.
    #[must_use]
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Record the explicit instant.
    #[must_use]
    pub fn with_timestamp(mut self, timestamp: impl Into<String>) -> Self {
        self.timestamp = Some(timestamp.into());
        self
    }

    /// The trimmed reason, empty when none was supplied.
    fn reason_text(&self) -> &str {
        self.reason.as_deref().map(str::trim).unwrap_or_default()
    }
}

/// What a refusal was, spelled in `snake_case` for payloads and tests.
///
/// The vocabulary is shared with the other cycle-schedule diagnostics where the fact
/// is the same (`unknown_schedule`, `missing_cadence`, `invalid_cadence`,
/// `unresolvable_date` are WP03's/WP04's spellings), so one refusal reads the same
/// whichever surface produced it (C-008).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LifecycleDiagnosticKind {
    /// The request was not confirmed, so nothing was even read.
    NotConfirmed,
    /// The action records a reason and the request carried none.
    MissingReason,
    /// The reason carries a character a `## History` entry cannot hold.
    ///
    /// WP04 of mission `cycle-capacity-planning-01M3C85C`. A History entry is one line
    /// whose fields are separated by U+2014, so a reason carrying a line break would
    /// render as more than one line — and the extra line would parse as an event nobody
    /// wrote. It is refused rather than trimmed: silently rewriting a person's reason
    /// would put text in the audit log that they did not write.
    InvalidReason,
    /// The actor carries a line break, which would split the entry in two.
    InvalidActor,
    /// No schedule with that id is defined.
    UnknownSchedule,
    /// The action names an instance that does not exist.
    UnknownCycle,
    /// The action must name an instance and the request named none.
    MissingCycle,
    /// The cycle id belongs to a different schedule.
    CycleNotOwned,
    /// The action records an actor and the request carried none.
    MissingActor,
    /// The action records a time and the request carried none.
    MissingTimestamp,
    /// The timestamp is not the crate's `YYYY-MM-DDTHH:MM:SSZ` shape.
    InvalidTimestamp,
    /// The schedule is ended, which is terminal.
    TerminalSchedule,
    /// The instance is closed or skipped, which is terminal for this action.
    TerminalCycle,
    /// The schedule names no cadence family.
    MissingCadence,
    /// The cadence resolves to a rule the shared validator refuses.
    InvalidCadence,
    /// The duration is missing or a step the shared owner refuses.
    InvalidDuration,
    /// A date the action needs cannot be derived.
    UnresolvableDate,
    /// A skip would leave an earlier sequence unrecorded, forking the cursor past a
    /// hole generation can no longer fill.
    MissingSequence,
    /// A file is already at the instance's snapshot path and is not its own snapshot.
    SnapshotCollision,
    /// The reference label the placeholder would take is already taken.
    ReferenceCollision,
    /// The file the placeholder would be written to is already occupied.
    NameCollision,
    /// A record write failed; nothing else was attempted.
    SchedulingFailed,
    /// The configuration (schedule state or cursor) could not be persisted; the
    /// record writes were rolled back.
    ConfigNotPersisted,
}

impl LifecycleDiagnosticKind {
    /// The contract's spelling, used verbatim in payloads and tests.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotConfirmed => "not_confirmed",
            Self::MissingReason => "missing_reason",
            Self::InvalidReason => "invalid_reason",
            Self::InvalidActor => "invalid_actor",
            Self::UnknownSchedule => "unknown_schedule",
            Self::UnknownCycle => "unknown_cycle",
            Self::MissingCycle => "missing_cycle",
            Self::CycleNotOwned => "cycle_not_owned",
            Self::MissingActor => "missing_actor",
            Self::MissingTimestamp => "missing_timestamp",
            Self::InvalidTimestamp => "invalid_timestamp",
            Self::TerminalSchedule => "terminal_schedule",
            Self::TerminalCycle => "terminal_cycle",
            Self::MissingCadence => "missing_cadence",
            Self::InvalidCadence => "invalid_cadence",
            Self::InvalidDuration => "invalid_duration",
            Self::UnresolvableDate => "unresolvable_date",
            Self::MissingSequence => "missing_sequence",
            Self::SnapshotCollision => "snapshot_collision",
            Self::ReferenceCollision => "reference_collision",
            Self::NameCollision => "name_collision",
            Self::SchedulingFailed => "scheduling_failure",
            Self::ConfigNotPersisted => "config_not_persisted",
        }
    }
}

/// One field-aware reason an action was refused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LifecycleDiagnostic {
    /// What was wrong.
    pub kind: LifecycleDiagnosticKind,
    /// The configuration or cycle path the caller must fix.
    pub field: String,
    /// One sentence saying what to do about it.
    pub message: String,
}

impl LifecycleDiagnostic {
    /// A finding about `field`.
    fn new(
        kind: LifecycleDiagnosticKind,
        field: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            field: field.into(),
            message: message.into(),
        }
    }

    /// 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())),
        )
    }
}

/// What one confirmed lifecycle action did (`data-model.md` §6, T029).
///
/// Exactly one of three shapes, each a *result* rather than an error, so a surface
/// reports it instead of catching it. Exactly one outcome per action.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LifecycleOutcome {
    /// The action changed something. `snapshot_path` is present on a close that
    /// captured one, and `dates` on an action that moved a window.
    Applied {
        /// The action that was carried out.
        action: LifecycleAction,
        /// The schedule it acted on.
        schedule_id: CycleScheduleId,
        /// The instance it acted on, when it named one.
        cycle_id: Option<GeneratedCycleId>,
        /// The captured snapshot, project-relative, when one was written.
        snapshot_path: Option<String>,
        /// The resulting `(start_date, due_date)`, when the action moved a window.
        dates: Option<(String, String)>,
        /// One sentence for a surface.
        message: String,
    },
    /// The action's postcondition already held; nothing was written.
    NoOp {
        /// The action that was requested.
        action: LifecycleAction,
        /// The schedule it named.
        schedule_id: CycleScheduleId,
        /// The instance it named, when it named one.
        cycle_id: Option<GeneratedCycleId>,
        /// One sentence saying why nothing was written.
        message: String,
    },
    /// The action was refused. Nothing was written.
    Rejected {
        /// The action that was requested.
        action: LifecycleAction,
        /// The schedule it named.
        schedule_id: CycleScheduleId,
        /// The instance it named, when it named one.
        cycle_id: Option<GeneratedCycleId>,
        /// Every reason, in the order they were found.
        diagnostics: Vec<LifecycleDiagnostic>,
    },
}

impl LifecycleOutcome {
    /// The stable word a surface prints: `applied`, `no-op` or `rejected`.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Applied { .. } => "applied",
            Self::NoOp { .. } => "no-op",
            Self::Rejected { .. } => "rejected",
        }
    }

    /// Whether something was written.
    #[must_use]
    pub fn is_applied(&self) -> bool {
        matches!(self, Self::Applied { .. })
    }

    /// Whether the postcondition already held.
    #[must_use]
    pub fn is_noop(&self) -> bool {
        matches!(self, Self::NoOp { .. })
    }

    /// Whether the action was refused.
    #[must_use]
    pub fn is_rejected(&self) -> bool {
        matches!(self, Self::Rejected { .. })
    }

    /// The action the outcome is about.
    #[must_use]
    pub fn action(&self) -> LifecycleAction {
        match self {
            Self::Applied { action, .. }
            | Self::NoOp { action, .. }
            | Self::Rejected { action, .. } => *action,
        }
    }

    /// The schedule the outcome is about.
    #[must_use]
    pub fn schedule_id(&self) -> &CycleScheduleId {
        match self {
            Self::Applied { schedule_id, .. }
            | Self::NoOp { schedule_id, .. }
            | Self::Rejected { schedule_id, .. } => schedule_id,
        }
    }

    /// The instance the outcome concerns, when it concerns one.
    #[must_use]
    pub fn cycle_id(&self) -> Option<&GeneratedCycleId> {
        match self {
            Self::Applied { cycle_id, .. }
            | Self::NoOp { cycle_id, .. }
            | Self::Rejected { cycle_id, .. } => cycle_id.as_ref(),
        }
    }

    /// The captured snapshot, project-relative, present on an applied close.
    #[must_use]
    pub fn snapshot_path(&self) -> Option<&str> {
        match self {
            Self::Applied { snapshot_path, .. } => snapshot_path.as_deref(),
            Self::NoOp { .. } | Self::Rejected { .. } => None,
        }
    }

    /// The resulting dates, present on an action that moved a window.
    #[must_use]
    pub fn dates(&self) -> Option<&(String, String)> {
        match self {
            Self::Applied { dates, .. } => dates.as_ref(),
            Self::NoOp { .. } | Self::Rejected { .. } => None,
        }
    }

    /// Every diagnostic, empty for `applied` and `no-op`.
    #[must_use]
    pub fn diagnostics(&self) -> &[LifecycleDiagnostic] {
        match self {
            Self::Rejected { diagnostics, .. } => diagnostics,
            Self::Applied { .. } | Self::NoOp { .. } => &[],
        }
    }

    /// One line for a surface.
    #[must_use]
    pub fn render(&self) -> String {
        match self {
            Self::Applied {
                action,
                cycle_id,
                snapshot_path,
                dates,
                message,
                ..
            } => {
                let mut line = format!("{} `{}` applied", action.as_str(), self.schedule_id());
                if let Some(cycle_id) = cycle_id {
                    line.push_str(&format!(" to `{cycle_id}`"));
                }
                if let Some(path) = snapshot_path {
                    line.push_str(&format!(" (snapshot `{path}`)"));
                }
                if let Some((start, due)) = dates {
                    line.push_str(&format!(" ({start} → {due})"));
                }
                format!("{line}: {message}")
            }
            Self::NoOp {
                action, message, ..
            } => {
                format!(
                    "{} `{}` no-op: {message}",
                    action.as_str(),
                    self.schedule_id()
                )
            }
            Self::Rejected { diagnostics, .. } => {
                let first = diagnostics
                    .first()
                    .map(LifecycleDiagnostic::render)
                    .unwrap_or_else(|| "rejected".to_string());
                if diagnostics.len() > 1 {
                    format!("{first} (and {} more)", diagnostics.len() - 1)
                } else {
                    first
                }
            }
        }
    }
}

/// 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).
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).
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.
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.
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.
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.
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).
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.
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",
    )
}

// ---------------------------------------------------------------------------
// Record and History helpers
// ---------------------------------------------------------------------------

/// A cycle record as stored, with its Markdown body.
///
/// The identity adapter ([`GeneratedCycle`]) carries neither, so every write reads
/// this first and merges the change onto it — that is what preserves a description,
/// a hand-written body and any previously appended `## History` entry.
#[derive(Debug, Clone, PartialEq, Eq)]
struct StoredCycle {
    record: CycleRecord,
    body: String,
}

/// Read the stored record and body for `name`, when a file holds one.
fn read_stored(store: &CycleStore, name: &str) -> Option<StoredCycle> {
    RecordStore::new(store.dir())
        .get::<CycleRecord>(name)
        .ok()
        .map(|file| StoredCycle {
            record: file.value,
            body: file.body,
        })
}

/// The stored body, or empty when there is no stored record.
fn stored_body(stored: Option<&StoredCycle>) -> &str {
    stored.map_or("", |stored| stored.body.as_str())
}

/// The record to write for `cycle`, merging onto the stored record when one exists.
///
/// Description and any other carried field come from the stored record; the identity
/// fields (name, schedule, sequence, state, dates) always come from the generated
/// cycle, because they are the action's subject. Callers override the one field their
/// action changes afterwards.
fn base_record(cycle: &GeneratedCycle, stored: Option<&StoredCycle>) -> CycleRecord {
    let mut record = match stored {
        Some(stored) => stored.record.clone(),
        None => cycle.to_record(),
    };
    record.name = cycle.name.clone();
    record.schedule_id = Some(cycle.schedule_id.as_str().to_string());
    record.sequence = Some(cycle.sequence);
    record.state = Some(cycle.state.as_str().to_string());
    record.start_date = Some(cycle.start_date.clone());
    record.due_date = Some(cycle.due_date.clone());
    record
}

/// Append one rendered `## History` entry to `body`, preserving everything already
/// there (including unparseable lines, via [`History::parse_front`]).
///
/// **The `detail` and the request's actor are validated before they reach here.**
/// [`HistoryEvent::render`] writes each field raw, so text carrying a line break would
/// render as more than one entry and a reader would take the extra line for an event
/// nobody wrote. The guarantee therefore lives at the two places an event can enter a
/// cycle's log — `apply`'s audit gate and [`append_cycle_event`] — rather than here,
/// where it could only be asserted: this function has no way to refuse.
fn append_event(
    body: &str,
    request: &LifecycleRequest,
    kind: HistoryEventKind,
    detail: &str,
) -> String {
    let (mut history, rest) = History::parse_front(body);
    history.append(HistoryEvent::new(
        request.timestamp.as_deref().unwrap_or_default().trim(),
        request.actor.trim(),
        kind,
        detail,
    ));
    format!("{}{rest}", history.render())
}

/// Write a cycle record with its body — the one write path every action uses.
fn write_cycle(store: &CycleStore, record: &CycleRecord, body: &str) -> Result<()> {
    store.save_record(record, Some(body))
}

/// The characters a rendered `## History` entry cannot hold, or `None` when the text is
/// safe (WP04, `cycle-capacity-planning-01M3C85C`).
///
/// # Why this is here rather than in a builder
///
/// A [`HistoryEvent`] is **one line** whose four fields are separated by U+2014, and
/// [`HistoryEvent::render`] writes each field raw. So:
///
/// * text carrying a line break renders as **two** lines, and the second parses as an
///   event nobody wrote — a reason of `ok\n- <instant> — mallory — cycle_closed — …`
///   would make one `apply` call produce two entries, the second attributed to
///   `mallory`. That is the worst kind of corruption, because the log is the thing an
///   auditor trusts;
/// * text carrying U+2014 shifts [`HistoryEvent::parse`]'s separator split, so the entry
///   stops parsing as the kind it is.
///
/// Both are refused wherever an event can enter a cycle record's log — [`apply`]'s audit
/// gate (which covers `close`, `reopen` and every other writing action, including the
/// `reason:` detail `close` has always written) and [`append_cycle_event`] (the seam a
/// surface outside this module uses) — so the guarantee cannot be bypassed by reaching
/// for one entry point rather than the other. The builders in
/// [`crate::capacity::snapshot`] deliberately do **not** repeat this policy: one place
/// owns it, and this is it.
///
/// `check_separator` says whether the text is written in a **detail** position, where
/// U+2014 is refused too. The actor is written *between* two separators: an em dash in it
/// costs the entry its parse — which is already true of every issue event in this codebase,
/// and is a loss rather than a forgery — and an identity may legitimately contain one, so
/// refusing it would be a behaviour change nobody asked for. A line break forges an entry
/// in **every** field, so every field refuses one.
fn history_text_hazard(text: &str, check_separator: bool) -> Option<&'static str> {
    if text.contains('\n') || text.contains('\r') {
        Some("a line break")
    } else if check_separator && text.contains('\u{2014}') {
        Some("the em dash (U+2014) a `## History` entry separates its fields with")
    } else {
        None
    }
}

/// Append **one** `## History` entry to a generated cycle record's own body, and
/// nothing else (mission `cycle-capacity-planning-01M3C85C`, WP04/T021).
///
/// This is the narrow seam a closed-cycle change outside the lifecycle needs — a
/// capacity edit applied through `tix capacity`/`tix cycle reopen` — so that the
/// *event's* construction stays where it is tested
/// ([`crate::capacity::snapshot::capacity_edit_event`],
/// [`crate::capacity::snapshot::reopen_event`]) and the *write* stays here, beside the
/// one `append_event` grammar every other cycle event uses.
///
/// # The guarantee, in the signature
///
/// **One applied change appends exactly one entry, and the cycle's snapshot is never
/// rewritten.** Concretely:
///
/// * the entry is appended through [`History::parse_front`] + [`History::append`] +
///   [`History::render`], so every existing line — the `cycle_closed` entry, a
///   hand-edited body, an unparseable line — keeps its position and its bytes;
/// * if the identical decision is **already the log's last entry**, the call is a
///   no-op: it returns `Ok(false)` and writes *nothing at all* (not even a re-render),
///   so re-applying the same edit twice does not double the entry. That is the
///   "repeated action, whose postcondition already holds" rule this module applies
///   everywhere, and it is sound because a genuinely different before/after or reason
///   produces a different `detail`;
/// * the snapshot is not read, moved or written by this function — a caller can only
///   lose evidence by writing the snapshot file itself, which nothing here does;
/// * a blank actor or an off-shape timestamp is refused, because the entry is audit
///   evidence and this codebase never invents an actor or a clock;
/// * an actor carrying a line break, and a `detail` carrying a line break **or** the
///   U+2014 the entry separates its fields with, are refused by the same
///   [`history_text_hazard`] `apply`'s audit gate runs — so calling this seam directly
///   cannot smuggle a second, attacker-chosen entry into the log.
///
/// `kind` must be one of the cycle lifecycle's own kinds; an issue-vocabulary kind is
/// refused, because this writes a cycle record's log and a mislabel would make the
/// entry unreadable to the readers of that log.
///
/// `Ok(true)` means an entry was appended. `Err` is a genuine I/O or validation failure;
/// a store error is returned rather than reported as a decision, matching
/// [`apply`]'s own split.
pub fn append_cycle_event(
    root: &Path,
    cycle_id: &GeneratedCycleId,
    actor: &str,
    timestamp: &str,
    kind: HistoryEventKind,
    detail: &str,
) -> Result<bool> {
    if !is_cycle_history_kind(kind) {
        return Err(TixError::InvalidInput(format!(
            "`{kind}` is not a cycle lifecycle event; a cycle record's `## History` carries only \
             the cycle kinds, so an issue's vocabulary is refused rather than written into the \
             wrong log"
        )));
    }
    let actor = actor.trim();
    if actor.is_empty() {
        return Err(TixError::InvalidInput(
            "a closed-cycle change records who decided; the actor is blank".into(),
        ));
    }
    // The same validator `apply` runs, so the single-line guarantee is enforced on both
    // entrances to a cycle's log and cannot be bypassed by calling this seam directly.
    if let Some(hazard) = history_text_hazard(actor, false) {
        return Err(TixError::InvalidInput(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"
        )));
    }
    if let Some(hazard) = history_text_hazard(detail, true) {
        return Err(TixError::InvalidInput(format!(
            "the detail contains {hazard}; a `## History` entry is one line, so a detail carrying \
             one would render as more than one entry and a reader would take the extra line for an \
             event nobody wrote"
        )));
    }
    let timestamp = timestamp.trim();
    if !validate_timestamp(timestamp) {
        return Err(TixError::InvalidInput(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 Some(stored) = stored_cycle_by_id(&store, cycle_id)? else {
        return Err(TixError::NotFound(format!(
            "generated cycle `{cycle_id}` has no record in `docs/cycles/`, so there is nothing to \
             append an event to"
        )));
    };
    let (mut history, rest) = History::parse_front(&stored.body);
    let already = history
        .events()
        .last()
        .is_some_and(|event| event.kind == kind && event.detail == detail);
    if already {
        // The identical decision is already the log's last entry: writing anything —
        // even a re-render — would be a change the caller did not make.
        return Ok(false);
    }
    history.append(HistoryEvent::new(timestamp, actor, kind, detail));
    // The record's frontmatter and its body (description, hand-written prose, every
    // prior event) are carried forward unchanged; only the one line is added.
    write_cycle(
        &store,
        &stored.record,
        &format!("{}{rest}", history.render()),
    )?;
    Ok(true)
}

/// The stored record and body of a generated cycle, looked up by its **stable id**.
///
/// The same identity rule the rest of the boundary follows: the id is matched against
/// each record's parsed generated identity (never against a display name), so a rename
/// of the label cannot make this append to the wrong cycle's log. A record whose
/// generated identity is half written is skipped rather than guessed at — it cannot be
/// the cycle `cycle_id` names, and rewriting it would be a migration.
fn stored_cycle_by_id(
    store: &CycleStore,
    cycle_id: &GeneratedCycleId,
) -> Result<Option<StoredCycle>> {
    for file in RecordStore::new(store.dir()).list::<CycleRecord>()? {
        if let Ok(Some(cycle)) = GeneratedCycle::from_record(&file.value)
            && cycle.id == *cycle_id
        {
            return Ok(Some(StoredCycle {
                record: file.value,
                body: file.body,
            }));
        }
    }
    Ok(None)
}

/// Whether a `## History` kind belongs to a **cycle record's** log.
///
/// The cycle lifecycle's kinds and nothing else: an issue's vocabulary written into a
/// cycle record would be a log no reader of either side expects.
fn is_cycle_history_kind(kind: HistoryEventKind) -> bool {
    matches!(
        kind,
        HistoryEventKind::CycleClosed
            | HistoryEventKind::CycleReopened
            | HistoryEventKind::CycleExtended
            | HistoryEventKind::CycleSkipped
            | HistoryEventKind::CyclePaused
            | HistoryEventKind::CycleResumed
            | HistoryEventKind::CycleAdjusted
            | HistoryEventKind::CycleCapacityEdited
    )
}

/// Undo the record writes this call made: restore each original, or remove a file
/// that had no original.
///
/// Returns **what could not be undone**. A rollback that fails is the one case where a
/// re-run may be needed, and swallowing it is what let a refusal say "the project is
/// exactly as it was" while a record still held the rolled-forward state.
fn roll_back(store: &CycleStore, written: &[(String, Option<StoredCycle>)]) -> Vec<String> {
    let mut failures = Vec::new();
    for (name, original) in written.iter().rev() {
        match original {
            Some(stored) => {
                if let Err(error) = store.save_record(&stored.record, Some(&stored.body)) {
                    failures.push(format!("restoring `{name}` failed: {error}"));
                }
            }
            None => {
                if let Err(error) = store.delete(name) {
                    failures.push(format!("removing `{name}` failed: {error}"));
                }
            }
        }
    }
    failures
}

/// How a refusal describes what a rollback did — and what it did not.
///
/// `restored` is how many records the call had written. An empty `undone` means the
/// tree really is back where it started; anything else names what is still wrong,
/// because that is the useful fact and "everything was restored" is a claim the code
/// cannot always make.
fn roll_back_tail(undone: &[String], restored: usize) -> String {
    if undone.is_empty() {
        format!("the {restored} record(s) already written were restored")
    } else {
        format!(
            "restoring the records already written also failed ({}), so a re-run may be needed",
            undone.join("; ")
        )
    }
}

/// The directories below `dir` that do not exist yet, deepest first.
///
/// A write creates its directory chain on demand, so a rolled-back capture has to
/// remove the chain it created as well as the file in it, or it would leave a (now
/// empty) `docs/cycle_snapshots/` behind that changes what a later write sees.
fn missing_ancestors(dir: &Path) -> Vec<PathBuf> {
    let mut missing = Vec::new();
    let mut current = Some(dir.to_path_buf());
    while let Some(path) = current {
        if path.exists() {
            break;
        }
        missing.push(path.clone());
        current = path.parent().map(Path::to_path_buf);
    }
    missing
}

/// Remove the directories a rolled-back write created, when they are still empty.
fn remove_empty_dirs(dirs: &[PathBuf]) {
    for dir in dirs {
        let empty = std::fs::read_dir(dir)
            .map(|mut entries| entries.next().is_none())
            .unwrap_or(false);
        if empty {
            let _ = std::fs::remove_dir(dir);
        }
    }
}

// ---------------------------------------------------------------------------
// Shared construction and arithmetic helpers
// ---------------------------------------------------------------------------

/// A refusal with one reason.
fn refused(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
    kind: LifecycleDiagnosticKind,
    field: impl Into<String>,
    message: impl Into<String>,
) -> LifecycleOutcome {
    LifecycleOutcome::Rejected {
        action,
        schedule_id,
        cycle_id,
        diagnostics: vec![LifecycleDiagnostic::new(kind, field, message)],
    }
}

/// A `no-op` with its reason.
fn no_op(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
    message: impl Into<String>,
) -> LifecycleOutcome {
    LifecycleOutcome::NoOp {
        action,
        schedule_id,
        cycle_id,
        message: message.into(),
    }
}

/// A refusal for an action that must name an instance but named none.
fn missing_cycle(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    verb: &str,
) -> LifecycleOutcome {
    refused(
        action,
        schedule_id.clone(),
        None,
        LifecycleDiagnosticKind::MissingCycle,
        format!("cycle_schedules.{schedule_id}.cycle_id"),
        format!("{verb} names the instance to act on; none was given"),
    )
}

/// A refusal for an instance the request did not name.
fn not_owned(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: GeneratedCycleId,
) -> LifecycleOutcome {
    let field = format!("cycles.{cycle_id}");
    let message = format!(
        "cycle id `{cycle_id}` belongs to schedule `{}`, not `{schedule_id}`",
        cycle_id.schedule_id()
    );
    refused(
        action,
        schedule_id,
        Some(cycle_id),
        LifecycleDiagnosticKind::CycleNotOwned,
        field,
        message,
    )
}

/// A refusal for an instance that does not exist.
fn unknown_cycle(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: GeneratedCycleId,
) -> LifecycleOutcome {
    refused(
        action,
        schedule_id,
        Some(cycle_id.clone()),
        LifecycleDiagnosticKind::UnknownCycle,
        format!("cycles.{cycle_id}"),
        format!("generated cycle `{cycle_id}` does not exist"),
    )
}

/// A refusal for a schedule with no cadence family.
fn missing_cadence(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
) -> LifecycleOutcome {
    refused(
        action,
        schedule_id.clone(),
        cycle_id,
        LifecycleDiagnosticKind::MissingCadence,
        format!("cycle_schedules.{schedule_id}.cadence.kind"),
        format!("schedule `{schedule_id}` names no cadence family"),
    )
}

/// A refusal for a cadence the shared validator rejects.
fn invalid_cadence(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
    error: &crate::recurrence::rule::RuleError,
    request: &LifecycleRequest,
) -> LifecycleOutcome {
    refused(
        action,
        schedule_id,
        cycle_id,
        LifecycleDiagnosticKind::InvalidCadence,
        format!("cycle_schedules.{}.cadence", request.schedule_id),
        error.first().message.clone(),
    )
}

/// A refusal for a date the shared rule could not resolve.
fn unresolvable(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
) -> LifecycleOutcome {
    refused(
        action,
        schedule_id.clone(),
        cycle_id,
        LifecycleDiagnosticKind::UnresolvableDate,
        format!("cycle_schedules.{schedule_id}.cadence"),
        format!(
            "schedule `{schedule_id}` could not resolve a candidate date for the sequence through \
             its cadence"
        ),
    )
}

/// A refusal when the configuration could not be persisted, naming any rollback that
/// itself failed.
fn refused_rollback(
    action: LifecycleAction,
    schedule_id: CycleScheduleId,
    cycle_id: Option<GeneratedCycleId>,
    config_path: &str,
    error: &TixError,
    rollback_failure: Option<String>,
) -> LifecycleOutcome {
    let message = match rollback_failure {
        None => format!(
            "the configuration could not be persisted through `{config_path}`: {error}; the record \
             writes were rolled back, so the project is exactly as it was"
        ),
        Some(failure) => format!(
            "the configuration could not be persisted through `{config_path}`: {error}; rolling \
             back a record also failed ({failure}), so a re-run may be needed"
        ),
    };
    refused(
        action,
        schedule_id,
        cycle_id,
        LifecycleDiagnosticKind::ConfigNotPersisted,
        config_path,
        message,
    )
}

/// The `sequence`-th occurrence of `rule`'s cadence, counted from its own anchor.
///
/// `1` is the anchor itself; each further occurrence is one [`RecurrenceRule`] step
/// (never hand-written arithmetic), so month-end re-anchoring and leap days are the
/// shared owner's. `None` when a step cannot be resolved.
fn nth_occurrence(rule: &RecurrenceRule, sequence: u32) -> Option<String> {
    let mut date = rule.anchor_key().ok()?.as_str().to_string();
    for _ in 1..sequence {
        date = step_from(rule, &date)?;
    }
    Some(date)
}

/// One cadence step after `from`, through the shared arithmetic owner.
fn step_from(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())
}

/// `start_date + duration`, through the shared arithmetic owner.
///
/// The duration is expressed as the rule the shared owner already understands — a
/// step of `count` `unit`s anchored at the instance's own start — so its first
/// occurrence strictly after that anchor *is* the due date. This mirrors WP04's
/// `duration` computation so a lifecycle-adjusted window and a generated one agree.
fn nominal_due(
    schedule_id: &CycleScheduleId,
    record: &CycleScheduleConfiguration,
    start_date: &str,
) -> std::result::Result<String, LifecycleDiagnostic> {
    let field = format!("cycle_schedules.{schedule_id}.duration");
    let Some(unit) = record.duration.unit else {
        return Err(LifecycleDiagnostic::new(
            LifecycleDiagnosticKind::InvalidDuration,
            format!("{field}.unit"),
            "duration.unit: how long one cycle lasts is not configured; give `days`, `weeks` or \
             `months`",
        ));
    };
    if record.duration.count == 0 {
        return Err(LifecycleDiagnostic::new(
            LifecycleDiagnosticKind::InvalidDuration,
            format!("{field}.count"),
            "duration.count: a cycle must last at least one unit",
        ));
    }
    let Some(start) = as_date(start_date) else {
        return Err(LifecycleDiagnostic::new(
            LifecycleDiagnosticKind::UnresolvableDate,
            format!("{field}.count"),
            format!(
                "the instance's start date `{start_date}` is not a `YYYY-MM-DD` calendar date, so \
                 its duration cannot be added"
            ),
        ));
    };
    let rule = RecurrenceRule {
        kind: RuleKind::Interval,
        interval: Some(record.duration.count),
        anchor: Some(start_date.to_string()),
        timezone: record.timezone.clone(),
        expression: None,
        unit: Some(unit),
        extensions: BTreeMap::new(),
    };
    rule.next_occurrence(&RuleContext::on(start))
        .map(|due| due.as_str().to_string())
        .map_err(|error| {
            let first = error.first();
            LifecycleDiagnostic::new(
                LifecycleDiagnosticKind::InvalidDuration,
                format!("{field}.count"),
                first.message.clone(),
            )
        })
}

/// The reference label a not-yet-generated skip placeholder takes.
///
/// Mirrors WP04's label exactly (`"<name> <date> <sequence>"`, with the name component
/// truncated to leave the date and the padded sequence intact), so a placeholder and
/// a later generation of the same sequence would agree on the label. The identity is
/// never the label, but they must not disagree.
fn reference_name(schedule_name: &str, start_date: &str, sequence: u32) -> String {
    let component: String = schedule_name
        .trim()
        .chars()
        .take(NAME_COMPONENT_BUDGET)
        .collect();
    let component = component.trim_end();
    format!(
        "{component} {start_date} {sequence:0width$}",
        width = GeneratedCycleId::SEQUENCE_WIDTH
    )
}

/// `slugify`'s cap on a filename stem (mirrored from WP04).
const FILENAME_STEM_LIMIT: usize = 80;

/// The length of a canonical `YYYY-MM-DD` date.
const CANONICAL_DATE_LEN: usize = 10;

/// How much of a schedule's display name a reference label keeps (mirrored from WP04).
const NAME_COMPONENT_BUDGET: usize =
    FILENAME_STEM_LIMIT - 1 - CANONICAL_DATE_LEN - 1 - GeneratedCycleId::SEQUENCE_WIDTH;

/// A canonical `YYYY-MM-DD` date as the shared arithmetic owner's value.
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()
}