tix-tracker 0.4.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
//! The planning registry: teams, cycles and milestones.
//!
//! Teams and cycles are names in `tix.toml` (`[teams.<label>]` /
//! `[cycles.<name>]`, FR-001/FR-002); 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`], so a
//! planning round trip is just a `tix.toml` 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::config::{Config, PlanningCycle, Team};
use crate::error::{Result, TixError};
use crate::model::Issue;
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,
}

/// 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>,
    created: String,
    updated: String,
}

/// 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 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.
    pub fn cycle(&self, name: &str) -> Option<&PlanningCycle> {
        self.config.cycles.get(name)
    }

    /// Cycle names in declaration order.
    pub fn cycle_names(&self) -> Vec<String> {
        self.config.cycles.keys().cloned().collect()
    }

    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)
    }

    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> {
        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 = store
                .list()
                .unwrap_or_default()
                .into_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 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.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 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 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);
        }
        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();
                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<()> {
        let cycle = self
            .config
            .cycles
            .get_mut(name)
            .ok_or_else(|| TixError::InvalidInput(format!("cycle `{name}` does not exist")))?;

        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.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;
        }
        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 dir = self.milestones_dir();
        if !dir.exists() {
            return Ok(Vec::new());
        }
        let mut milestones = Vec::new();
        let mut read_error = None;
        for entry in std::fs::read_dir(&dir)? {
            let Ok(entry) = entry else { continue };
            if entry.path().extension().and_then(|e| e.to_str()) != Some("md") {
                continue;
            }
            let file_name = entry.file_name();
            let Some(file_name) = file_name.to_str().map(str::to_string) else {
                continue;
            };
            match std::fs::read_to_string(entry.path()) {
                Ok(contents) => {
                    if let Some((head, body)) = Self::parse_milestone_file(&contents) {
                        milestones.push(Self::milestone_from(head, file_name, body));
                    }
                }
                Err(e) => read_error = Some(e),
            }
        }
        if let Some(e) = read_error {
            return Err(TixError::Io(e));
        }
        milestones.sort_by(|a, b| a.file_name.cmp(&b.file_name));
        Ok(milestones)
    }

    /// 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> {
        for entry in std::fs::read_dir(self.milestones_dir())? {
            let Ok(entry) = entry else { continue };
            let file_name = entry.file_name();
            let Some(file_name) = file_name.to_str().map(str::to_string) else {
                continue;
            };
            let Ok(contents) = std::fs::read_to_string(entry.path()) else {
                continue;
            };
            if let Some((head, body)) = Self::parse_milestone_file(&contents)
                && head.name == name
            {
                return Ok(Self::milestone_from(head, file_name, body));
            }
        }
        Err(TixError::NotFound(format!("milestone `{name}`")))
    }

    /// 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 dir = self.milestones_dir();
        let file_name = format!("{today}-{}.md", crate::slug::slugify(&name));
        let path = dir.join(file_name);
        if path.exists() {
            return Err(TixError::InvalidInput(format!(
                "`{}` already exists",
                path.display()
            )));
        }
        std::fs::create_dir_all(&dir)?;
        let head = MilestoneHead {
            name: name.clone(),
            target_date: target_date.map(str::to_string),
            created: today.clone(),
            updated: today,
        };
        let frontmatter = serde_yaml::to_string(&head)
            .map_err(|e| TixError::Parse(format!("cannot serialize milestone frontmatter: {e}")))?;
        let body = body_for(description);
        std::fs::write(&path, format!("---\n{frontmatter}---\n\n{body}"))?;
        Ok(path)
    }

    /// 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 dir = self.milestones_dir();
        let old_path = dir.join(&old.file_name);
        let contents = std::fs::read_to_string(&old_path).map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                TixError::NotFound(format!("milestone file `{}`", old.file_name))
            } else {
                TixError::Io(e)
            }
        })?;
        let Some((_fm, body)) = Self::split_frontmatter(&contents) else {
            return Err(TixError::Parse(format!("cannot parse `{}`", old.file_name)));
        };
        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 new_path = dir.join(new_file_name);
        if new_path.exists() {
            return Err(TixError::InvalidInput(format!(
                "`{}` already exists",
                new_path.display()
            )));
        }
        let head = MilestoneHead {
            name: new_name.to_string(),
            target_date: (!old.target_date.is_empty()).then(|| old.target_date.clone()),
            created: prefix,
            updated: crate::model::today(),
        };
        let frontmatter = serde_yaml::to_string(&head)
            .map_err(|e| TixError::Parse(format!("cannot serialize milestone frontmatter: {e}")))?;
        std::fs::write(&new_path, format!("---\n{frontmatter}---\n\n{body}"))?;
        std::fs::remove_file(&old_path)?;
        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();
                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,
            created: milestone.created.clone(),
            updated: crate::model::today(),
        };
        let frontmatter = serde_yaml::to_string(&head)
            .map_err(|e| TixError::Parse(format!("cannot serialize milestone frontmatter: {e}")))?;
        let path = self.milestones_dir().join(&milestone.file_name);
        std::fs::write(
            path,
            format!("---\n{frontmatter}---\n\n{}", body_for(Some(body))),
        )?;
        Ok(())
    }

    pub fn delete_milestone(&self, name: &str) -> Result<String> {
        let milestone = self.milestone(name)?;
        let path = self.milestones_dir().join(&milestone.file_name);
        std::fs::remove_file(path)?;
        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(head: MilestoneHead, file_name: String, body: &str) -> Milestone {
        Milestone {
            name: head.name,
            target_date: head.target_date.unwrap_or_default(),
            description: body.trim_end().to_string(),
            created: head.created,
            updated: head.updated,
            file_name,
        }
    }

    /// Split `contents` into its frontmatter text and the body (everything
    /// after the closing `---` delimiter line, with the single structural
    /// blank line consumed), reusing the same delimiter rules as
    /// [`crate::model::Issue::parse`].
    fn split_frontmatter(contents: &str) -> Option<(&str, &str)> {
        let rest = contents.strip_prefix("---\n")?;
        let mut current = rest;
        let mut fm_len = 0usize;
        loop {
            let line_end = current.find('\n').map(|i| i + 1).unwrap_or(current.len());
            let content = current[..line_end]
                .strip_suffix('\n')
                .unwrap_or(&current[..line_end]);
            if content == "---" {
                break;
            }
            fm_len += line_end;
            current = &current[line_end..];
            if current.is_empty() {
                return None;
            }
        }
        let mut body = &rest[fm_len..];
        body = body.strip_prefix("---\n").unwrap_or(body);
        if let Some(after) = body.strip_prefix('\n') {
            body = after;
        }
        Some((&rest[..fm_len], body))
    }

    /// Parse a milestone file into its head and body suffix. `None` when the
    /// file has no valid frontmatter block (skipped, not an error).
    fn parse_milestone_file(contents: &str) -> Option<(MilestoneHead, &str)> {
        let (frontmatter, body) = Self::split_frontmatter(contents)?;
        let head: MilestoneHead = serde_yaml::from_str(frontmatter).ok()?;
        Some((head, body))
    }
}

/// Render a milestone file body from its optional description: the trimmed
/// paragraph plus a single trailing newline (empty when no description).
fn body_for(description: Option<&str>) -> String {
    match description {
        Some(text) if !text.trim().is_empty() => format!("{}\n", text.trim_end()),
        _ => String::new(),
    }
}

#[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,
            },
        );
        // `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)"
        );
    }

    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!(p.list_milestones().unwrap().is_empty());
        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");
    }
}