tix-tracker 0.11.0

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

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

use serde::{Deserialize, Serialize};

use crate::capacity::scope::IssueSnapshot;
use crate::config::{Config, PlanningCycle, Team};
use crate::cycle_schedule::identity::ScheduleIndex;
use crate::cycle_store::{
    CycleStore, DEFAULT_CYCLE_NAME, IMPLICIT_DEFAULT_CYCLE, is_implicit_default,
};
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::records::{HasName, RecordStore};
use crate::storage::Store;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RolloverTarget {
    pub from_cycle: String,
    pub to_cycle: String,
    pub issues: Vec<u32>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Progress {
    pub done: usize,
    pub total: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameImpact {
    pub changed_issue_count: usize,
    pub issues: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Impact {
    pub referencing_issues: Vec<String>,
}

/// A milestone as materialized from its registry file. `description` is the
/// markdown body (the work summary); `file_name` is the registry filename
/// (`{created}-{slug}.md`, `contracts/milestone-file-format.md`). `created`
/// is the creation date (the filename prefix); `target_date` is the optional
/// `YYYY-MM-DD` due date (empty string when absent).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Milestone {
    pub name: String,
    pub target_date: String,
    pub description: String,
    pub created: String,
    pub updated: String,
    pub file_name: String,
    /// An optional color name for the milestone (tix #1530), from the record's
    /// `color:` field. A milestone with none renders uncolored.
    pub color: Option<String>,
}

/// The YAML frontmatter of a milestone file (`contracts/milestone-file-format.md`).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
struct MilestoneHead {
    name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    target_date: Option<String>,
    /// An optional color name (tix #1530); a milestone file may carry one and it
    /// round-trips, while creation omits it.
    #[serde(skip_serializing_if = "Option::is_none")]
    color: Option<String>,
    created: String,
    updated: String,
}

impl HasName for MilestoneHead {
    fn name(&self) -> &str {
        &self.name
    }
}

/// A working snapshot of the planning registry, bound to a repo root.
#[derive(Debug, Clone)]
pub struct Planner {
    root: PathBuf,
    config: Config,
}

impl Planner {
    /// Load the planning registry from `tix.toml` in the current directory,
    /// on the crate-wide assumption that commands run from the repo root.
    pub fn load() -> Result<Self> {
        Self::load_from(Path::new("tix.toml"))
    }

    /// Load the planning registry from an explicit config path.
    pub fn load_from(path: &Path) -> Result<Self> {
        let config = Config::load_with_warning(path, |token| {
            eprintln!(
                "warning: {} embeds a cleartext {} token; prefer an environment variable",
                path.display(),
                token
            );
        })?;
        let root = path
            .parent()
            .filter(|p| !p.as_os_str().is_empty())
            .map(Path::to_path_buf)
            .unwrap_or_else(|| PathBuf::from("."));
        Ok(Self::from_config(config, root))
    }

    /// Build a planner from an already-loaded config (used by `tix init` and
    /// tests). The config is not persisted here; mutators save on demand.
    pub fn from_config(config: Config, root: PathBuf) -> Self {
        Self { root, config }
    }

    /// The backing config this planner currently mirrors.
    pub fn config(&self) -> &Config {
        &self.config
    }

    /// The resolution this planner's board maps through.
    ///
    /// Built here rather than stored, because a `Planner` is a short-lived view
    /// over a config and caching it would be the per-object rebuild the service's
    /// "built once per config load" rule exists to avoid. The expensive part of a
    /// sweep is not building this — it is a handful of hash inserts per column —
    /// it is *not* re-deriving it per issue, and that is what callers do wrong.
    pub fn category_resolution(&self) -> crate::workflow::CategoryResolution {
        let board = self.config.default_config();
        crate::workflow::resolution(&self.config, board, "default")
    }

    /// Whether `issue` is complete, by the service's definition.
    ///
    /// Delegates rather than comparing `issue.status` to `done_column()` directly.
    /// The comparison it replaced was a **second** notion of completion: it read
    /// the board's `done_column` and ignored categories entirely, so a board whose
    /// `done_column` was `shipped` and whose `category_map` said something else
    /// answered differently from the category rule (C-004). The two agree on a
    /// board with no `category_map` — which is every existing configuration — and
    /// disagree on exactly the boards this mission exists to support.
    fn is_done_issue(&self, issue: &Issue) -> bool {
        let resolution = self.category_resolution();
        crate::workflow::is_completed(issue, &resolution)
    }

    /// The cycle-identity index this planner's records resolve through (issue #181).
    ///
    /// One read of `docs/cycles/` — or of the legacy `[cycles.<name>]` tables when
    /// there is no store, which is the loader's own rule — through
    /// [`crate::capacity::schedule_index`]. It is the same index
    /// [`crate::cycle_schedule::registry::load_index`] builds, and the same one
    /// [`crate::capacity::resolve_cycle`] resolves a capacity scope reference
    /// against, so a caller never has to build a second one.
    pub fn schedule_index(&self) -> Result<ScheduleIndex> {
        crate::capacity::schedule_index(&self.config, &self.root)
    }

    /// One indexed capacity snapshot over the issues a caller already read (WP02).
    ///
    /// The cycle records are read once ([`Planner::schedule_index`]) and the issues are
    /// indexed once ([`IssueSnapshot::build`]): cycle, team, and assignee membership,
    /// #183's completion answer, and every estimate parse and explicit conversion are
    /// resolved there, so no calculation needs to read the store or re-parse an
    /// estimate again (NFR-001). This is the entry point WP03's calculation service
    /// reads.
    pub fn capacity_snapshot_from(&self, issues: &[Issue]) -> Result<IssueSnapshot> {
        let index = self.schedule_index()?;
        Ok(IssueSnapshot::build(&self.config, &index, issues))
    }

    /// [`Planner::capacity_snapshot_from`] over a store, read **once** here.
    ///
    /// The store read and the index build are the only I/O a capacity calculation
    /// performs; everything a surface then asks is a lookup into the returned snapshot.
    pub fn capacity_snapshot(&self, store: &Store) -> Result<IssueSnapshot> {
        self.capacity_snapshot_from(&store.list()?)
    }

    /// The resolved milestones directory, relative to the repo root.
    pub fn milestones_dir(&self) -> PathBuf {
        self.root.join(self.config.milestones_dir())
    }

    /// Persist the current config snapshot to `tix.toml`.
    fn save(&self) -> Result<()> {
        self.config.save(&self.root.join("tix.toml"))
    }

    /// Look up a team by label.
    pub fn team(&self, label: &str) -> Option<&Team> {
        self.config.teams.get(label)
    }

    /// Look up a cycle by name.
    ///
    /// The implicit `Default` cycle answers even when it has no file, so a
    /// fresh project can name it.
    pub fn cycle(&self, name: &str) -> Option<&PlanningCycle> {
        if let Some(cycle) = self.config.cycles.get(name) {
            return Some(cycle);
        }
        if name == DEFAULT_CYCLE_NAME {
            return Some(&IMPLICIT_DEFAULT_CYCLE);
        }
        None
    }

    /// Cycle names in declaration order.
    ///
    /// The implicit `Default` cycle is not invented here: a project with no
    /// store shows only what it has actually configured, and the legacy
    /// `tix.toml` listing is preserved. [`CycleStore::list`] is where the
    /// implicit default is surfaced (the cycle mode lists through it), and
    /// [`Planner::cycle`] answers for the name regardless.
    pub fn cycle_names(&self) -> Vec<String> {
        self.config.cycles.keys().cloned().collect()
    }

    /// The cycle file store rooted at this planner's repo root.
    fn cycle_store(&self) -> CycleStore {
        CycleStore::new(&self.root)
    }

    /// Write this planner's cycle records to the file store.
    ///
    /// The store is used once it exists or once a cycle beyond the implicit
    /// `Default` is present; until then cycles stay in `tix.toml` and no
    /// directory is created. This is the one-time migration path: the first
    /// real cycle writes every configured cycle to `docs/cycles/`.
    fn persist_cycles(&self) -> Result<()> {
        let store = self.cycle_store();
        let file_mode = store.exists()
            || self
                .config
                .cycles
                .iter()
                .any(|(name, cycle)| !is_implicit_default(name, cycle));
        if !file_mode {
            return Ok(());
        }
        for (name, cycle) in &self.config.cycles {
            if is_implicit_default(name, cycle) {
                continue;
            }
            let filename = format!("{}.md", crate::slug::slugify(name));
            let body = RecordStore::new(store.dir()).body_of(&filename);
            store.save(name, cycle, body.as_deref())?;
        }
        Ok(())
    }

    pub fn is_overdue(issue: &Issue, today: &str) -> bool {
        issue.due_date.as_deref().is_some_and(|due| due < today)
    }

    pub fn cycle_expired(cycle: &PlanningCycle, today: &str) -> bool {
        cycle.due_date.as_deref().is_some_and(|due| due < today)
    }

    /// Whether `cycle` is *running* on `today`: its `start_date` is present and
    /// `<= today`, and its `due_date` is either absent (open-ended) or
    /// `>= today`. Both bounds are inclusive, so a cycle runs on its first and
    /// its last day. The implicit, date-less `Default` cycle has no start date
    /// and therefore never runs.
    pub fn is_running(cycle: &PlanningCycle, today: &str) -> bool {
        cycle
            .start_date
            .as_deref()
            .is_some_and(|start| start <= today)
            && cycle.due_date.as_deref().is_none_or(|due| due >= today)
    }

    /// The single cycle running on `today`, if *exactly one* is.
    ///
    /// `None` when no cycle runs — there is nothing to assign — and `None` when
    /// two or more do, because an ambiguous date range must fall back to the
    /// configured `[planning].default_cycle` rather than guess which one the
    /// caller meant. See [`Planner::is_running`] for the running rule; the
    /// implicit `Default` cycle is never a candidate.
    pub fn running_cycle(&self, today: &str) -> Option<String> {
        let mut running = self
            .config
            .cycles
            .iter()
            .filter(|(_, cycle)| Self::is_running(cycle, today))
            .map(|(name, _)| name.clone());
        let first = running.next()?;
        running.next().is_none().then_some(first)
    }

    /// Names of the cycles whose date window intersects `name`'s.
    ///
    /// A cycle's window is `[start_date, due_date]`, both bounds inclusive; an
    /// absent `due_date` leaves the window open-ended, so it meets every later
    /// window. Touching endpoints intersect (the shared day is in both). A cycle
    /// with no `start_date` has no window: it never overlaps anything, and a
    /// `name` that has no `start_date` reports no overlaps. `name` is never
    /// reported against itself, and the result follows config declaration order.
    pub fn overlapping_cycles(&self, name: &str) -> Vec<String> {
        let Some(start) = self
            .config
            .cycles
            .get(name)
            .and_then(|cycle| cycle.start_date.as_deref())
        else {
            return Vec::new();
        };
        let due = self.config.cycles[name].due_date.as_deref();
        self.config
            .cycles
            .iter()
            .filter(|(other, _)| other.as_str() != name)
            .filter(|(_, cycle)| {
                let Some(other_start) = cycle.start_date.as_deref() else {
                    return false;
                };
                let other_ends_after_target_starts =
                    cycle.due_date.as_deref().is_none_or(|end| start <= end);
                let target_ends_after_other_starts = due.is_none_or(|end| other_start <= end);
                other_ends_after_target_starts && target_ends_after_other_starts
            })
            .map(|(other, _)| other.clone())
            .collect()
    }

    pub fn successor<'a>(
        &'a self,
        cycle: &str,
        today: &str,
    ) -> Option<(&'a str, &'a PlanningCycle)> {
        self.config
            .cycles
            .iter()
            .filter(|(name, c)| {
                *name != cycle && c.start_date.as_deref().is_some_and(|s| s >= today)
            })
            .min_by(|a, b| {
                let by_start = a.1.start_date.cmp(&b.1.start_date);
                if by_start == std::cmp::Ordering::Equal {
                    a.0.cmp(b.0)
                } else {
                    by_start
                }
            })
            .map(|(name, c)| (name.as_str(), c))
    }

    pub fn overdue_batch(&self, store: &Store, today: &str) -> Vec<Issue> {
        store
            .list()
            .unwrap_or_default()
            .into_iter()
            .filter(|issue| !self.is_done_issue(issue) && Self::is_overdue(issue, today))
            .collect()
    }

    pub fn rollover_plan(&self, store: &Store, today: &str) -> Vec<RolloverTarget> {
        self.rollover_plan_from(&store.list().unwrap_or_default(), today)
    }

    /// [`Planner::rollover_plan`] over an **already-read** issue set (tix #1518).
    ///
    /// The TUI reads the tree once at startup and hands the same slice to the
    /// board, the corpus and this plan, instead of walking the store again for
    /// every expired cycle. The result is identical to [`Planner::rollover_plan`]:
    /// the enumeration is the only thing that moved out of the loop.
    pub fn rollover_plan_from(&self, all: &[Issue], today: &str) -> Vec<RolloverTarget> {
        let mut out = Vec::new();
        for (from_cycle, cycle) in &self.config.cycles {
            if !Self::cycle_expired(cycle, today) {
                continue;
            }
            let Some((to_cycle, _successor)) = self.successor(from_cycle, today) else {
                continue;
            };
            let issues = all
                .iter()
                .filter(|issue| {
                    issue
                        .cycles
                        .as_ref()
                        .is_some_and(|cycles| cycles.iter().any(|c| c == from_cycle))
                        && !self.is_done_issue(issue)
                        && !issue
                            .cycles
                            .as_ref()
                            .is_some_and(|cycles| cycles.iter().any(|c| c == to_cycle))
                })
                .map(|issue| issue.number)
                .collect::<Vec<_>>();
            if !issues.is_empty() {
                out.push(RolloverTarget {
                    from_cycle: from_cycle.clone(),
                    to_cycle: to_cycle.to_string(),
                    issues,
                });
            }
        }
        out
    }

    pub fn cycle_progress(&self, store: &Store, name: &str) -> Progress {
        let mut done = 0usize;
        let mut total = 0usize;
        for issue in store.list().unwrap_or_default() {
            if issue
                .cycles
                .as_ref()
                .is_some_and(|cycles| cycles.iter().any(|cycle| cycle == name))
            {
                total += 1;
                if self.is_done_issue(&issue) {
                    done += 1;
                }
            }
        }
        Progress { done, total }
    }

    pub fn milestone_progress(&self, store: &Store, name: &str) -> Progress {
        let mut done = 0usize;
        let mut total = 0usize;
        for issue in store.list().unwrap_or_default() {
            if issue
                .milestones
                .as_ref()
                .is_some_and(|milestones| milestones.iter().any(|milestone| milestone == name))
            {
                total += 1;
                if self.is_done_issue(&issue) {
                    done += 1;
                }
            }
        }
        Progress { done, total }
    }

    /// The next auto cycle name. Skips forward past any existing `Cycle N`
    /// keys and permanently bumps `[planning].cycle_number` one past the
    /// returned name, per the seed's `cycle_number = 1` successor semantics.
    /// The bump is persisted by the mutator that calls this.
    pub fn next_cycle_name(&mut self) -> String {
        let mut n = self.config.planning.cycle_number;
        loop {
            let candidate = format!("Cycle {n}");
            if !self.config.cycles.contains_key(&candidate) {
                self.config.planning.cycle_number = n + 1;
                return candidate;
            }
            n += 1;
        }
    }

    /// Create a named or auto cycle. An explicit name must not collide with
    /// the current auto-counter successor (`Cycle {cycle_number}`), a config
    /// error, so hand-authored keys and generated ones never overlap.
    pub fn add_cycle(&mut self, name: Option<String>) -> Result<String> {
        let name = match name {
            Some(name) => name,
            None => self.next_cycle_name(),
        };
        let name = name.trim().to_string();
        if name.is_empty() {
            return Err(TixError::InvalidInput(
                "cycle name must not be blank".into(),
            ));
        }
        if name == DEFAULT_CYCLE_NAME && !self.config.cycles.contains_key(&name) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{name}` already exists"
            )));
        }
        if self.config.cycles.contains_key(&name) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{name}` already exists"
            )));
        }
        if let Some(auto) = self.current_auto_name()
            && name == auto
        {
            return Err(TixError::Config(format!(
                "cycle `{name}` collides with the auto-cycle counter; pick another name or let it auto-increment"
            )));
        }
        self.config
            .cycles
            .insert(name.clone(), PlanningCycle::default());
        self.persist_cycles()?;
        self.save()?;
        Ok(name)
    }

    /// Rename a cycle, moving its declaration order slot and rebasing
    /// `default_cycle` when it pointed at the old name.
    pub fn rename_cycle(&mut self, old: &str, new: &str) -> Result<()> {
        let new = new.trim().to_string();
        if old == new {
            return Ok(());
        }
        if !self.config.cycles.contains_key(old) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{old}` does not exist"
            )));
        }
        if new.is_empty() {
            return Err(TixError::InvalidInput(
                "cycle name must not be blank".into(),
            ));
        }
        if new == DEFAULT_CYCLE_NAME && !self.config.cycles.contains_key(&new) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{new}` already exists"
            )));
        }
        if self.config.cycles.contains_key(&new) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{new}` already exists"
            )));
        }
        if let Some(auto) = self.current_auto_name()
            && new == auto
        {
            return Err(TixError::Config(format!(
                "cycle `{new}` collides with the auto-cycle counter"
            )));
        }
        let had_file = self.cycle_store().get(old).is_ok();
        let cycle = self
            .config
            .cycles
            .shift_remove(old)
            .expect("existence checked above");
        self.config.cycles.insert(new.clone(), cycle);
        if self.config.planning.default_cycle.as_deref() == Some(old) {
            self.config.planning.default_cycle = Some(new.clone());
        }
        if had_file {
            self.cycle_store().rename(old, &new)?;
        }
        self.persist_cycles()?;
        self.save()?;
        Ok(())
    }

    pub fn delete_impact(&self, store: &Store, name: &str) -> Result<Impact> {
        let mut referencing_issues = Vec::new();
        for issue in store.list()? {
            if issue
                .cycles
                .as_ref()
                .is_some_and(|cycles| cycles.iter().any(|cycle| cycle == name))
            {
                referencing_issues.push(issue.filename);
            }
        }
        Ok(Impact { referencing_issues })
    }

    pub fn rename_cycle_cascade(
        &mut self,
        store: &Store,
        old: &str,
        new: &str,
    ) -> Result<RenameImpact> {
        let new = new.trim();
        if new.is_empty() {
            return Err(TixError::InvalidInput(
                "cycle name must not be blank".into(),
            ));
        }
        if !self.config.cycles.contains_key(old) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{old}` does not exist"
            )));
        }
        if old != new && self.config.cycles.contains_key(new) {
            return Err(TixError::InvalidInput(format!(
                "cycle `{new}` already exists"
            )));
        }
        let mut issues = Vec::new();
        for mut issue in store.list()? {
            let Some(cycles) = issue.cycles.as_mut() else {
                continue;
            };
            let mut changed = false;
            for cycle in cycles.iter_mut() {
                if cycle == old {
                    *cycle = new.to_string();
                    changed = true;
                }
            }
            if changed {
                issue.bump_updated();
                issue.filename = store.update(&issue.filename, &issue)?;
                issues.push(issue.filename);
            }
        }
        self.rename_cycle(old, new)?;
        Ok(RenameImpact {
            changed_issue_count: issues.len(),
            issues,
        })
    }

    pub fn set_cycle_fields(
        &mut self,
        name: &str,
        description: Option<&str>,
        start_date: Option<&str>,
        due_date: Option<&str>,
    ) -> Result<()> {
        if !self.config.cycles.contains_key(name) {
            if name == DEFAULT_CYCLE_NAME {
                self.config
                    .cycles
                    .insert(name.to_string(), PlanningCycle::default());
            } else {
                return Err(TixError::InvalidInput(format!(
                    "cycle `{name}` does not exist"
                )));
            }
        }
        let cycle = self.config.cycles.get_mut(name).expect("inserted above");

        if let Some(description) = description {
            let description = description.trim();
            cycle.description = if description.is_empty() {
                None
            } else {
                Some(description.to_string())
            };
        }
        if let Some(start_date) = start_date {
            let start_date = start_date.trim();
            if start_date.is_empty() {
                cycle.start_date = None;
            } else {
                if !crate::model::validate_date(start_date) {
                    return Err(TixError::InvalidInput(format!(
                        "start_date `{start_date}` must be a `YYYY-MM-DD` calendar date"
                    )));
                }
                cycle.start_date = Some(start_date.to_string());
            }
        }
        if let Some(due_date) = due_date {
            let due_date = due_date.trim();
            if due_date.is_empty() {
                cycle.due_date = None;
            } else {
                if !crate::model::validate_date(due_date) {
                    return Err(TixError::InvalidInput(format!(
                        "due_date `{due_date}` must be a `YYYY-MM-DD` calendar date"
                    )));
                }
                cycle.due_date = Some(due_date.to_string());
            }
        }
        self.config.validate()?;
        self.persist_cycles()?;
        self.save()
    }

    pub fn delete_cycle(&mut self, name: &str) -> Result<()> {
        if self.config.cycles.shift_remove(name).is_none() {
            return Err(TixError::InvalidInput(format!(
                "cycle `{name}` does not exist"
            )));
        }
        if self.config.planning.default_cycle.as_deref() == Some(name) {
            self.config.planning.default_cycle = None;
        }
        let store = self.cycle_store();
        if store.exists() && store.get(name).is_ok() {
            store.delete(name)?;
        }
        self.persist_cycles()?;
        self.save()
    }

    /// Add a member to a team, creating the team when absent. Duplicate
    /// members and blank inputs are rejected.
    pub fn add_team_member(&mut self, label: &str, member: &str) -> Result<()> {
        let label = label.trim();
        let member = member.trim();
        if label.is_empty() {
            return Err(TixError::InvalidInput(
                "team label must not be blank".into(),
            ));
        }
        if member.is_empty() {
            return Err(TixError::InvalidInput("member must not be blank".into()));
        }
        let team = self.config.teams.entry(label.to_string()).or_default();
        if team.members.iter().any(|m| m == member) {
            return Err(TixError::InvalidInput(format!(
                "`{member}` is already a member of team `{label}`"
            )));
        }
        team.members.push(member.to_string());
        self.config.validate()?;
        self.save()?;
        Ok(())
    }

    /// All milestones, sorted by filename (which sorts by `target_date` then
    /// slug — the registry is a directory listing, never a stored list).
    pub fn list_milestones(&self) -> Result<Vec<Milestone>> {
        let store = RecordStore::new(self.milestones_dir());
        let records = store.list::<MilestoneHead>()?;
        Ok(records.into_iter().map(Self::milestone_from).collect())
    }

    /// Milestone names in listing order.
    pub fn milestone_names(&self) -> Result<Vec<String>> {
        Ok(self
            .list_milestones()?
            .into_iter()
            .map(|m| m.name)
            .collect())
    }

    /// Look up a milestone by its frontmatter `name`.
    pub fn milestone(&self, name: &str) -> Result<Milestone> {
        let store = RecordStore::new(self.milestones_dir());
        match store.get::<MilestoneHead>(name) {
            Ok(record) => Ok(Self::milestone_from(record)),
            Err(TixError::NotFound(_)) => Err(TixError::NotFound(format!("milestone `{name}`"))),
            Err(e) => Err(e),
        }
    }

    /// Create a milestone registry file. The filename is
    /// `{created}-{slug}.md` where `created` is today's date; an optional
    /// `target_date` is stored in the frontmatter and must be a valid
    /// `YYYY-MM-DD` calendar date when given (FR-007). The markdown body is
    /// the optional description. Refuses to overwrite an existing file.
    pub fn create_milestone_file(
        &self,
        name: &str,
        target_date: Option<&str>,
        description: Option<&str>,
    ) -> Result<PathBuf> {
        let name = name.trim().to_string();
        if name.is_empty() {
            return Err(TixError::InvalidInput(
                "milestone name must not be blank".into(),
            ));
        }
        if let Some(date) = target_date
            && !crate::model::validate_date(date)
        {
            return Err(TixError::InvalidInput(format!(
                "target_date `{date}` must be a `YYYY-MM-DD` calendar date"
            )));
        }
        let today = crate::model::today();
        let file_name = format!("{today}-{}.md", crate::slug::slugify(&name));
        let head = MilestoneHead {
            name: name.clone(),
            target_date: target_date.map(str::to_string),
            color: None,
            created: today.clone(),
            updated: today,
        };
        RecordStore::new(self.milestones_dir()).write(&file_name, &head, description)
    }

    /// Rename a milestone file, keeping the `created` date prefix, bumping
    /// `updated` and rebasing the frontmatter `name`; the body is preserved
    /// verbatim (the cascade back into referencing issues is FR-009/IC-08
    /// work that lives in the issue layer, not the registry).
    pub fn rename_milestone_file(&self, old: &Milestone, new_name: &str) -> Result<PathBuf> {
        let new_name = new_name.trim();
        if new_name.is_empty() {
            return Err(TixError::InvalidInput(
                "milestone name must not be blank".into(),
            ));
        }
        let prefix = if old.created.is_empty() {
            crate::model::today()
        } else {
            old.created.clone()
        };
        let new_file_name = format!("{prefix}-{}.md", crate::slug::slugify(new_name));
        let head = MilestoneHead {
            name: new_name.to_string(),
            target_date: (!old.target_date.is_empty()).then(|| old.target_date.clone()),
            color: old.color.clone(),
            created: prefix,
            updated: crate::model::today(),
        };
        let store = RecordStore::new(self.milestones_dir());
        let new_path = store.write(&new_file_name, &head, Some(&old.description))?;
        store.delete_file(&old.file_name)?;
        Ok(new_path)
    }

    pub fn milestone_delete_impact(&self, store: &Store, name: &str) -> Result<Impact> {
        let mut referencing_issues = Vec::new();
        for issue in store.list()? {
            if issue
                .milestones
                .as_ref()
                .is_some_and(|milestones| milestones.iter().any(|milestone| milestone == name))
            {
                referencing_issues.push(issue.filename);
            }
        }
        Ok(Impact { referencing_issues })
    }

    pub fn rename_milestone_cascade(
        &self,
        store: &Store,
        old: &Milestone,
        new_name: &str,
    ) -> Result<RenameImpact> {
        let _ = self.rename_milestone_file(old, new_name)?;
        let mut issues = Vec::new();
        for mut issue in store.list()? {
            let Some(milestones) = issue.milestones.as_mut() else {
                continue;
            };
            let mut changed = false;
            for milestone in milestones.iter_mut() {
                if milestone == &old.name {
                    *milestone = new_name.to_string();
                    changed = true;
                }
            }
            if changed {
                issue.bump_updated();
                issue.filename = store.update(&issue.filename, &issue)?;
                issues.push(issue.filename);
            }
        }
        Ok(RenameImpact {
            changed_issue_count: issues.len(),
            issues,
        })
    }

    pub fn update_milestone(
        &self,
        name: &str,
        target_date: Option<&str>,
        description: Option<&str>,
    ) -> Result<()> {
        let milestone = self.milestone(name)?;
        let next_target = match target_date {
            Some(value) => {
                let value = value.trim();
                if value.is_empty() {
                    None
                } else {
                    if !crate::model::validate_date(value) {
                        return Err(TixError::InvalidInput(format!(
                            "target_date `{value}` must be a `YYYY-MM-DD` calendar date"
                        )));
                    }
                    Some(value.to_string())
                }
            }
            None => (!milestone.target_date.is_empty()).then_some(milestone.target_date.clone()),
        };
        let body = description.unwrap_or(&milestone.description);
        let head = MilestoneHead {
            name: milestone.name.clone(),
            target_date: next_target,
            color: milestone.color.clone(),
            created: milestone.created.clone(),
            updated: crate::model::today(),
        };
        RecordStore::new(self.milestones_dir()).overwrite(
            &milestone.file_name,
            &head,
            Some(body),
        )?;
        Ok(())
    }

    pub fn delete_milestone(&self, name: &str) -> Result<String> {
        let milestone = self.milestone(name)?;
        RecordStore::new(self.milestones_dir()).delete_file(&milestone.file_name)?;
        Ok(milestone.file_name)
    }

    /// The auto successor name the counter currently implies.
    fn current_auto_name(&self) -> Option<String> {
        Some(format!("Cycle {}", self.config.planning.cycle_number))
    }

    fn milestone_from(record: crate::records::RecordFile<MilestoneHead>) -> Milestone {
        let head = record.value;
        Milestone {
            name: head.name,
            target_date: head.target_date.unwrap_or_default(),
            description: record.body.trim_end().to_string(),
            created: head.created,
            updated: head.updated,
            file_name: record.filename,
            color: head.color,
        }
    }
}

#[cfg(test)]
mod tests {
    /// The delegation to `workflow::is_completed` is **load-bearing only on a
    /// board that declares a `category_map`**, and that is asserted here rather
    /// than assumed.
    ///
    /// Reverting `is_done_issue` to its previous body — comparing the status to
    /// `done_column()` — left the whole suite **green**. The two rules agree on
    /// every board without a `category_map`, which is every existing configuration,
    /// so the delegation was unverified: a refactor that looked correct and proved
    /// nothing. This fixture is the configuration where they disagree, reached
    /// through the public `overdue_batch`, which filters on completion.
    ///
    /// The board: `shipped` is the `done_column` but maps to `active`, and
    /// `archived` is what actually completes. Under the old rule an issue in
    /// `shipped` was done and therefore not overdue; under the category rule it is
    /// active work and therefore still overdue. `archived` is the mirror image.
    #[test]
    fn completion_follows_the_category_not_the_done_column() {
        use crate::config::{BoardConfiguration, OrderBy};
        use indexmap::IndexMap;
        let tmp = tempfile::TempDir::new().unwrap();
        let issues_dir = tmp.path().join("docs").join("issues");
        std::fs::create_dir_all(&issues_dir).unwrap();

        // Absolute, not the config default: `Store` resolves `issues_dir` against
        // the process working directory, so a relative path reads some other
        // repository's issues and the batch comes back empty.
        let mut config = Config {
            issues_dir: issues_dir.clone(),
            ..Default::default()
        };
        let mut category_map = IndexMap::new();
        category_map.insert("wip".to_string(), "active".to_string());
        category_map.insert("shipped".to_string(), "active".to_string());
        category_map.insert("archived".to_string(), "completed".to_string());
        config.kanban.configurations.insert(
            "default".to_string(),
            BoardConfiguration {
                columns: vec![
                    "wip".to_string(),
                    "shipped".to_string(),
                    "archived".to_string(),
                ],
                done_column: Some("shipped".to_string()),
                category_map,
                hidden_columns: vec![],
                show_mismatch: false,
                wrap_titles: true,
                title_lines: 3,
                card_order: vec![],
                order_by: OrderBy::CreatedAtDesc,
                wip: crate::wip::WipConfig::default(),
            },
        );
        // `archived` is the only completing column, so load accepts the mapping.
        config
            .validate()
            .expect("the fixture must be a valid config");

        let write = |name: &str, number: u32, status: &str, due: &str| {
            std::fs::write(
                issues_dir.join(name),
                format!(
                    "---\nnumber: {number}\ntitle: \"{status}\"\nstatus: \"{status}\"\n\
                     labels: []\npriority: \"medium\"\ndue_date: \"{due}\"\n\
                     created: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n"
                ),
            )
            .unwrap();
        };
        write("2026-01-01-wip.md", 1, "wip", "2026-01-02");
        write("2026-01-01-shipped.md", 2, "shipped", "2026-01-02");
        write("2026-01-01-archived.md", 3, "archived", "2026-01-02");

        let store = crate::storage::Store::open(&config).unwrap();
        let planner = Planner::from_config(config, tmp.path().to_path_buf());
        let today = "2026-06-01";
        let mut overdue: Vec<u32> = planner
            .overdue_batch(&store, today)
            .iter()
            .map(|i| i.number)
            .collect();
        // Sorted before comparing: `overdue_batch` does not promise an order, and
        // the claim here is about *membership*. The first version of this test
        // asserted a fixed order and failed on `[2, 1]` — the right two issues in
        // an order nothing specifies.
        overdue.sort_unstable();

        assert_eq!(
            overdue,
            vec![1, 2],
            "`wip` and `shipped` are both `active`, so both are still overdue; \
             `archived` is the only completing column"
        );
        // And the specific claim: `shipped` is the done_column, so the old
        // comparison would have dropped it from the batch.
        assert!(
            overdue.contains(&2),
            "an issue in the `done_column` is not complete when its category is \
             `active` — the category is the only completion definition (C-004)"
        );
    }

    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::today;
    use std::fs;
    use tempfile::TempDir;

    fn planner_in(tmp: &TempDir) -> Planner {
        Planner::from_config(Config::default(), tmp.path().to_path_buf())
    }

    #[test]
    fn milestones_dir_resolves_configured_and_default() {
        let tmp = TempDir::new().unwrap();
        let p = planner_in(&tmp);
        assert_eq!(p.milestones_dir(), tmp.path().join("docs/milestones"));

        let mut cfg = Config {
            milestones_dir: Some(PathBuf::from("tasks/milestones")),
            ..Config::default()
        };
        let p = Planner::from_config(cfg.clone(), tmp.path().to_path_buf());
        assert_eq!(p.milestones_dir(), tmp.path().join("tasks/milestones"));
        cfg.milestones_dir = None;
        let p = Planner::from_config(cfg, tmp.path().to_path_buf());
        assert_eq!(p.milestones_dir(), tmp.path().join("docs/milestones"));
    }

    #[test]
    fn auto_cycle_names_skip_existing_and_bump_counter() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        assert_eq!(p.next_cycle_name(), "Cycle 1");
        assert_eq!(p.config.planning.cycle_number, 2);
        assert_eq!(p.add_cycle(None).unwrap(), "Cycle 2");
        assert_eq!(p.next_cycle_name(), "Cycle 3");
    }

    #[test]
    fn add_cycle_rejects_duplicates_and_counter_collision() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        p.config
            .cycles
            .insert("Cycle 1".into(), PlanningCycle::default());
        let err = p.add_cycle(Some("Cycle 1".into())).unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
        assert!(err.to_string().contains("already exists"));
        // Counter is 1 and "Cycle 1" exists as a hand-authored key → config error.
        let err = p.add_cycle(Some("Cycle 1".into())).unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
    }

    #[test]
    fn add_cycle_collision_with_current_counter_is_config_error() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        let err = p.add_cycle(Some("Cycle 1".into())).unwrap_err();
        assert!(matches!(err, TixError::Config(_)), "got {err:?}");
        assert!(err.to_string().contains("collides"));
    }

    #[test]
    fn rename_cycle_moves_slot_and_rebases_default() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        p.config
            .cycles
            .insert("Old".into(), PlanningCycle::default());
        p.config.planning.default_cycle = Some("Old".into());
        p.rename_cycle("Old", "New").unwrap();
        assert!(p.cycle("Old").is_none());
        assert!(p.cycle("New").is_some());
        assert_eq!(p.config.planning.default_cycle.as_deref(), Some("New"));
        let err = p.rename_cycle("Old", "X").unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
    }

    #[test]
    fn add_team_member_creates_and_dedupes() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        p.add_team_member("platform", "@alice").unwrap();
        assert_eq!(p.team("platform").unwrap().members, ["@alice"]);
        let err = p.add_team_member("platform", "@alice").unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
        assert!(err.to_string().contains("already a member"));
        let err = p.add_team_member("", "@alice").unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
    }

    #[test]
    fn milestone_file_writes_contract_format_and_reads_back() {
        let tmp = TempDir::new().unwrap();
        let p = planner_in(&tmp);
        let today = today();
        let path = p
            .create_milestone_file("Ship V1", Some("2026-12-01"), Some("The launch"))
            .unwrap();
        // Filename prefix is the creation date, not target_date.
        assert_eq!(
            path.file_name().unwrap(),
            format!("{today}-ship-v1.md").as_str()
        );
        let raw = fs::read_to_string(&path).unwrap();
        assert!(raw.starts_with("---\n"));
        assert!(raw.contains("target_date: 2026-12-01"));
        assert!(raw.contains(&format!("created: {today}")));
        assert!(raw.contains(&format!("updated: {today}")));
        let ms = p.milestone("Ship V1").unwrap();
        assert_eq!(ms.target_date, "2026-12-01");
        assert_eq!(ms.description, "The launch");
        assert_eq!(ms.created, today);
        assert_eq!(ms.file_name, format!("{today}-ship-v1.md"));
        let names = p.milestone_names().unwrap();
        assert_eq!(names, ["Ship V1"]);
    }

    #[test]
    fn milestone_without_target_date_omits_the_key() {
        let tmp = TempDir::new().unwrap();
        let p = planner_in(&tmp);
        let path = p.create_milestone_file("Backlog", None, None).unwrap();
        let raw = fs::read_to_string(&path).unwrap();
        assert!(
            !raw.contains("target_date"),
            "no target_date expected:\n{raw}"
        );
        assert!(raw.contains("name: Backlog"));
        let ms = p.milestone("Backlog").unwrap();
        assert_eq!(ms.target_date, "");
        assert_eq!(ms.description, "");
    }

    #[test]
    fn milestone_rejects_invalid_dates_and_overwrites() {
        let tmp = TempDir::new().unwrap();
        let p = planner_in(&tmp);
        let err = p
            .create_milestone_file("X", Some("2026-13-99"), None)
            .unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
        assert!(err.to_string().contains("target_date"));
        p.create_milestone_file("X", None, None).unwrap();
        let err = p.create_milestone_file("X", None, None).unwrap_err();
        assert!(matches!(err, TixError::InvalidInput(_)), "got {err:?}");
        assert!(err.to_string().contains("already exists"));
    }

    #[test]
    fn rename_milestone_file_preserves_body_and_bumps_updated() {
        let tmp = TempDir::new().unwrap();
        let p = planner_in(&tmp);
        let today = today();
        p.create_milestone_file("Alpha", None, Some("old body text"))
            .unwrap();
        let old = p.milestone("Alpha").unwrap();
        let new_path = p.rename_milestone_file(&old, "Beta").unwrap();
        assert_eq!(
            new_path.file_name().unwrap(),
            format!("{today}-beta.md").as_str()
        );
        assert!(p.milestone("Alpha").is_err());
        let beta = p.milestone("Beta").unwrap();
        assert_eq!(beta.created, today);
        assert_eq!(beta.updated, today);
        assert_eq!(beta.description, "old body text");
        let raw = fs::read_to_string(&new_path).unwrap();
        assert!(raw.contains("name: Beta"), "renamed frontmatter:\n{raw}");
        assert!(
            !raw.contains("name: Alpha"),
            "old name must be rebased:\n{raw}"
        );
        assert!(
            raw.contains("old body text"),
            "body preserved verbatim:\n{raw}"
        );
    }

    #[test]
    fn list_milestones_is_empty_before_directory_exists() {
        let tmp = TempDir::new().unwrap();
        let p = planner_in(&tmp);
        assert_eq!(
            p.list_milestones().unwrap(),
            [] as [crate::planning::Milestone; 0]
        );
        assert!(p.milestone("nope").is_err());
    }

    #[test]
    fn team_and_cycle_index_maps_preserve_insertion_order() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        p.config.cycles.insert("C".into(), PlanningCycle::default());
        p.config.cycles.insert("A".into(), PlanningCycle::default());
        assert_eq!(p.cycle_names(), ["C", "A"]);
        let final_cfg = Config::load_with_warning(&p.root.join("tix.toml"), |_| {});
        assert!(final_cfg.is_err(), "nothing persisted, nothing to load");
    }

    #[test]
    fn cycle_store_add_and_fields_are_lazy_and_file_backed() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        let cycles_dir = tmp.path().join("docs/cycles");

        // Defaults only: no directory, and the implicit `Default` cycle answers.
        assert!(
            !cycles_dir.exists(),
            "a defaults-only project needs no cycles directory"
        );
        assert_eq!(p.cycle_names(), [] as [std::string::String; 0]);
        assert!(p.cycle("Default").is_some());

        p.add_cycle(Some("Sprint 7".into())).unwrap();
        assert!(
            cycles_dir.is_dir(),
            "adding a second cycle creates the directory"
        );
        assert!(
            !cycles_dir.join("default.md").exists(),
            "the implicit Default cycle is never a file"
        );
        assert!(
            p.cycle("Default").is_some(),
            "Default stays addressable alongside configured cycles"
        );

        p.set_cycle_fields(
            "Sprint 7",
            Some("September sprint"),
            Some("2026-09-01"),
            Some("2026-09-14"),
        )
        .unwrap();

        let reloaded = Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {}).unwrap();
        let cycle = reloaded
            .cycles
            .get("Sprint 7")
            .expect("the cycle is read back from its file");
        assert_eq!(cycle.description.as_deref(), Some("September sprint"));
        assert_eq!(cycle.start_date.as_deref(), Some("2026-09-01"));
        assert_eq!(cycle.due_date.as_deref(), Some("2026-09-14"));
        assert!(
            reloaded.cycles.contains_key("Default"),
            "the implicit Default cycle is available once the store exists"
        );
        let toml = fs::read_to_string(tmp.path().join("tix.toml")).unwrap();
        assert!(
            !toml.contains("[cycles"),
            "cycle records move out of tix.toml:\n{toml}"
        );
        assert_eq!(
            p.cycle("Sprint 7").unwrap().start_date.as_deref(),
            Some("2026-09-01")
        );
    }

    #[test]
    fn cycle_rename_cascade_and_delete_impact_use_the_file_store() {
        let tmp = TempDir::new().unwrap();
        let issues_dir = tmp.path().join("docs").join("issues");
        fs::create_dir_all(&issues_dir).unwrap();

        // Absolute, not the config default: `Store` resolves `issues_dir`
        // against the process working directory.
        let config = Config {
            issues_dir: issues_dir.clone(),
            ..Config::default()
        };
        let mut p = Planner::from_config(config, tmp.path().to_path_buf());
        p.add_cycle(Some("Sprint 7".into())).unwrap();
        p.set_cycle_fields("Sprint 7", None, Some("2026-09-01"), None)
            .unwrap();

        for (filename, number) in [("2026-01-01-a.md", 1), ("2026-01-01-b.md", 2)] {
            fs::write(
                issues_dir.join(filename),
                format!(
                    "---\nnumber: {number}\ntitle: \"Issue {number}\"\nstatus: \"todo\"\n\
                     labels: []\npriority: \"medium\"\ncycles:\n- Sprint 7\n\
                     created: 2026-01-01\nupdated: 2026-01-01\n---\n\nBody.\n"
                ),
            )
            .unwrap();
        }

        let store = crate::storage::Store::open(p.config()).unwrap();
        assert_eq!(
            p.delete_impact(&store, "Sprint 7")
                .unwrap()
                .referencing_issues
                .len(),
            2
        );

        let impact = p
            .rename_cycle_cascade(&store, "Sprint 7", "Sprint Seven")
            .unwrap();
        assert_eq!(impact.changed_issue_count, 2);
        for issue in store.list().unwrap() {
            assert_eq!(
                issue.cycles.as_deref(),
                Some(&["Sprint Seven".to_string()][..])
            );
        }

        let cycles_dir = tmp.path().join("docs/cycles");
        assert!(!cycles_dir.join("sprint-7.md").exists(), "old file moved");
        assert!(cycles_dir.join("sprint-seven.md").exists());

        // Delete reports the references and leaves them in place.
        assert_eq!(
            p.delete_impact(&store, "Sprint Seven")
                .unwrap()
                .referencing_issues
                .len(),
            2
        );
        p.delete_cycle("Sprint Seven").unwrap();
        assert!(!cycles_dir.join("sprint-seven.md").exists());
        assert_eq!(
            p.delete_impact(&store, "Sprint Seven")
                .unwrap()
                .referencing_issues
                .len(),
            2
        );
    }

    fn cycle_with(start: Option<&str>, due: Option<&str>) -> PlanningCycle {
        PlanningCycle {
            description: None,
            start_date: start.map(str::to_string),
            due_date: due.map(str::to_string),
        }
    }

    #[test]
    fn running_cycle_is_the_single_window_that_contains_today() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);

        // The date-less implicit `Default` cycle has no start date, so it never
        // runs — here written the way `tix init` seeds it.
        p.config
            .cycles
            .insert(DEFAULT_CYCLE_NAME.into(), PlanningCycle::default());
        assert_eq!(
            p.running_cycle("2026-10-02"),
            None,
            "a date-less cycle (Default included) is never running"
        );

        // Start-only window: open-ended and therefore running.
        p.config
            .cycles
            .insert("October 2026".into(), cycle_with(Some("2026-10-01"), None));
        assert_eq!(
            p.running_cycle("2026-10-02").as_deref(),
            Some("October 2026")
        );
        assert_eq!(p.running_cycle("2026-09-30"), None, "before the start");
        assert_eq!(
            p.running_cycle("2026-10-01").as_deref(),
            Some("October 2026"),
            "the start bound is inclusive"
        );

        // A bounded window runs inside its box and not outside it.
        p.config.cycles.insert(
            "September".into(),
            cycle_with(Some("2026-09-01"), Some("2026-09-30")),
        );
        assert_eq!(p.running_cycle("2026-09-30").as_deref(), Some("September"));
        assert_eq!(
            p.running_cycle("2026-10-02").as_deref(),
            Some("October 2026"),
            "September has ended, October still runs"
        );

        // Two overlapping windows → ambiguous → no automatic assignment.
        p.config.cycles.insert(
            "Q4 2026".into(),
            cycle_with(Some("2026-10-01"), Some("2026-12-31")),
        );
        assert_eq!(
            p.running_cycle("2026-10-02"),
            None,
            "two running cycles are ambiguous"
        );
    }

    #[test]
    fn overlapping_cycles_is_the_intersection_of_inclusive_windows() {
        let tmp = TempDir::new().unwrap();
        let mut p = planner_in(&tmp);
        p.config.cycles.insert(
            "B".into(),
            cycle_with(Some("2026-01-15"), Some("2026-02-15")),
        );
        p.config.cycles.insert(
            "C".into(),
            cycle_with(Some("2026-01-10"), Some("2026-01-12")),
        );
        p.config.cycles.insert(
            "D".into(),
            cycle_with(Some("2026-03-01"), Some("2026-03-31")),
        );
        p.config.cycles.insert(
            "E".into(),
            cycle_with(Some("2026-01-31"), Some("2026-02-28")),
        );
        p.config
            .cycles
            .insert("F".into(), cycle_with(None, Some("2026-06-30")));
        p.config
            .cycles
            .insert("Open".into(), cycle_with(Some("2026-01-20"), None));
        p.config.cycles.insert(
            "A".into(),
            cycle_with(Some("2026-01-01"), Some("2026-01-31")),
        );

        // B partially overlaps, C is contained in A, E touches A's last day, and
        // the open-ended Open has already started. D is disjoint and F has no
        // start date at all. Reported in declaration order.
        assert_eq!(
            p.overlapping_cycles("A"),
            ["B", "C", "E", "Open"],
            "partial overlap, containment, touching endpoints and an open-ended window"
        );

        // A cycle with no start date has no window: it overlaps nothing, and a
        // start-less target reports nothing.
        assert_eq!(p.overlapping_cycles("F"), [] as [std::string::String; 0]);
        assert_eq!(
            p.overlapping_cycles("missing"),
            [] as [std::string::String; 0]
        );

        // An open-ended target meets every later window, but not one that ended
        // before it began.
        p.config.cycles.clear();
        p.config
            .cycles
            .insert("Open".into(), cycle_with(Some("2026-02-01"), None));
        p.config.cycles.insert(
            "EndedBefore".into(),
            cycle_with(Some("2026-01-01"), Some("2026-01-15")),
        );
        p.config.cycles.insert(
            "StartsLater".into(),
            cycle_with(Some("2026-05-01"), Some("2026-05-31")),
        );
        assert_eq!(
            p.overlapping_cycles("Open"),
            ["StartsLater"],
            "an open-ended window meets a later one but not one that already ended"
        );
    }
}