tix-tracker 0.12.0

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

/// The derived members of an epic (data-model §4).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicMembership {
    /// The epic the members belong to.
    pub epic_id: EpicId,
    /// Members ordered by issue number.
    pub members: Vec<MemberRef>,
    /// `members.len()`.
    pub member_count: usize,
}

/// The derived epic view over one snapshot of issues and the registry.
///
/// Built once and read many times. The bucket map is the NFR-001 index; the epic
/// map is an `IndexMap` so declaration order is the display order; the label and
/// status maps carry what a member listing and the completion read need. Nothing
/// here is stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicIndex {
    /// Epics in declaration order, each carrying its derived members and children.
    epics: IndexMap<EpicId, Epic>,
    /// The reverse index: epic -> member issue keys, ascending.
    buckets: HashMap<EpicId, Vec<IssueKey>>,
    /// Recorded parent per epic, id-typed and only for resolvable ids.
    parents: HashMap<EpicId, EpicId>,
    /// Child epics per epic, in declaration order.
    children: HashMap<EpicId, Vec<EpicId>>,
    /// References whose epic does not resolve, deterministically ordered.
    missing: Vec<EpicReferenceResolution>,
    /// Issue number -> display label, for member listings.
    labels: HashMap<IssueKey, String>,
    /// Issue number -> status, for the completion read.
    statuses: HashMap<IssueKey, String>,
}

impl EpicIndex {
    /// Build the index in **one pass** over the issue set.
    ///
    /// Membership comes from each issue's `epics` list, never from the registry.
    /// A reference whose epic does not resolve is kept in [`Self::missing`] rather
    /// than dropped: a silently absent reference is the failure C-005 forbids, and
    /// [`resolve_references`] reports exactly this set.
    pub fn build<N: EpicNode>(config: &Config, issues: &[N]) -> Self {
        Self::build_from_registry(&config.epics, issues)
    }

    /// [`Self::build`] against a bare registry, for callers that hold only the
    /// `[epics.<id>]` table (the contract's `registry + issue set` operations).
    pub fn build_from_registry<N: EpicNode>(
        registry: &IndexMap<String, EpicConfiguration>,
        issues: &[N],
    ) -> Self {
        let known: HashSet<String> = registry.keys().cloned().collect();

        let mut labels: HashMap<IssueKey, String> = HashMap::new();
        let mut statuses: HashMap<IssueKey, String> = HashMap::new();
        let mut buckets: HashMap<EpicId, Vec<IssueKey>> = HashMap::new();
        let mut missing: Vec<EpicReferenceResolution> = Vec::new();

        for issue in issues {
            let key = IssueKey::new(issue.number());
            labels.insert(
                key,
                crate::hierarchy::display_label(issue.number(), issue.title()),
            );
            statuses.insert(key, issue.status().to_string());

            // A duplicated id on one issue is one reference: reported once,
            // bucketed once (T007 step 7).
            let mut seen: HashSet<&str> = HashSet::new();
            for raw in issue.epic_ids() {
                if !seen.insert(raw.as_str()) {
                    continue;
                }
                let holder = ReferenceHolder::Issue(key);
                match EpicId::new(raw) {
                    Ok(id) if known.contains(id.as_str()) => {
                        buckets.entry(id).or_default().push(key);
                    }
                    Ok(_) => missing.push(EpicReferenceResolution {
                        holder: holder.clone(),
                        target_kind: EpicReferenceKind::Epic,
                        target: raw.clone(),
                        reason: missing_epic_reason(&holder, raw),
                    }),
                    Err(_) => missing.push(EpicReferenceResolution {
                        holder,
                        target_kind: EpicReferenceKind::Issue,
                        target: raw.clone(),
                        reason: malformed_epic_reason(issue.number(), raw),
                    }),
                }
            }
        }

        for members in buckets.values_mut() {
            members.sort_unstable();
        }

        // The hierarchy, derived from the registry's `parent` fields. A parent id
        // that is not a valid [`EpicId`] shape is retained in the view's `parent`
        // (for repair) but cannot enter the typed parent map.
        let mut children: HashMap<EpicId, Vec<EpicId>> = HashMap::new();
        let mut ordered: Vec<(EpicId, EpicConfiguration)> = Vec::new();
        let parents: HashMap<EpicId, EpicId> = resolved_parents(registry);
        for (raw, record) in registry {
            let Ok(id) = EpicId::new(raw) else {
                continue;
            };
            if let Some(parent) = parents.get(&id) {
                children.entry(parent.clone()).or_default().push(id.clone());
            }
            ordered.push((id, record.clone()));
        }

        let mut epics: IndexMap<EpicId, Epic> = IndexMap::new();
        for (id, record) in ordered {
            let members: Vec<MemberRef> = buckets
                .get(&id)
                .map(|keys| {
                    keys.iter()
                        .map(|key| MemberRef {
                            issue: *key,
                            display: labels.get(key).cloned().unwrap_or_else(|| key.to_string()),
                        })
                        .collect()
                })
                .unwrap_or_default();
            let kid_refs: Vec<EpicRef> = children
                .get(&id)
                .map(|ids| {
                    ids.iter()
                        .filter_map(|child| {
                            registry
                                .get(child.as_str())
                                .map(|record| EpicRef::new(child, &record.name))
                        })
                        .collect()
                })
                .unwrap_or_default();
            epics.insert(
                id.clone(),
                Epic::from_configuration(id, &record, members, kid_refs),
            );
        }

        missing.sort_by(reference_order);

        Self {
            epics,
            buckets,
            parents,
            children,
            missing,
            labels,
            statuses,
        }
    }

    /// The reverse index, as the contract spells it.
    #[must_use]
    pub fn buckets(&self) -> &HashMap<EpicId, Vec<IssueKey>> {
        &self.buckets
    }

    /// Issue number -> its resolved epic ids, in registry declaration order (WP09
    /// item C).
    ///
    /// The **inverse** of [`Self::buckets`], and the one owner of it: the board's
    /// epic partition, `tix list --group epic`/`--sort epic`, and
    /// `tix status --group epic` all read this rather than re-reading the issues'
    /// `epics` lists, so a filter and a partition cannot disagree about who is a
    /// member. A stored reference the registry does not hold is **not** a member and
    /// therefore contributes no id (the repair path is the filter's raw-string
    /// match, deliberately — see [`crate::search::StructuredFilter::epic_matches`]).
    #[must_use]
    pub fn memberships_by_issue(&self) -> HashMap<u32, Vec<String>> {
        let order: HashMap<&str, usize> = self
            .epics
            .keys()
            .enumerate()
            .map(|(position, id)| (id.as_str(), position))
            .collect();
        let mut memberships: HashMap<u32, Vec<String>> = HashMap::new();
        for (id, keys) in &self.buckets {
            for key in keys {
                memberships
                    .entry(key.number())
                    .or_default()
                    .push(id.to_string());
            }
        }
        // Declaration order within each issue, so the rank and the bucket label are
        // deterministic whatever order the bucket map iterated in.
        for ids in memberships.values_mut() {
            ids.sort_by_key(|id| order.get(id.as_str()).copied().unwrap_or(usize::MAX));
        }
        memberships
    }

    /// The member keys of one epic.
    ///
    /// `None` **only** for an epic the registry does not hold. A known epic with
    /// no members returns an empty slice, so "not an epic" and "an epic with no
    /// members yet" stay distinguishable to a caller.
    #[must_use]
    pub fn bucket(&self, id: &EpicId) -> Option<&[IssueKey]> {
        if !self.epics.contains_key(id) {
            return None;
        }
        Some(self.buckets.get(id).map_or(&[][..], Vec::as_slice))
    }

    /// Epics in declaration order.
    #[must_use]
    pub fn epics(&self) -> Vec<&Epic> {
        self.epics.values().collect()
    }

    /// One epic by id.
    #[must_use]
    pub fn epic(&self, id: &EpicId) -> Option<&Epic> {
        self.epics.get(id)
    }

    /// The issue display label the index recorded.
    #[must_use]
    pub fn label(&self, key: IssueKey) -> Option<&str> {
        self.labels.get(&key).map(String::as_str)
    }

    /// An issue's status, as the index recorded it.
    #[must_use]
    pub fn status_of(&self, key: IssueKey) -> Option<&str> {
        self.statuses.get(&key).map(String::as_str)
    }

    /// The diagnosed **issue-held** references of this snapshot.
    ///
    /// Epic-held references are diagnosed per epic by [`Self::missing_for`],
    /// because they live on the record rather than in the issue set.
    #[must_use]
    pub fn missing(&self) -> &[EpicReferenceResolution] {
        &self.missing
    }

    /// Resolve an epic by id (first) or by name.
    pub fn resolve(&self, reference: &str) -> Result<&Epic, EpicError> {
        if let Ok(id) = EpicId::new(reference) {
            if let Some(epic) = self.epics.get(&id) {
                return Ok(epic);
            }
        }
        let normalized = reference.trim().to_lowercase();
        self.epics
            .values()
            .find(|epic| epic.name.to_lowercase() == normalized)
            .ok_or_else(|| EpicError::UnknownEpic {
                reference: reference.to_string(),
            })
    }

    /// The ordered membership of an epic.
    pub fn membership(&self, reference: &str) -> Result<EpicMembership, EpicError> {
        let epic = self.resolve(reference)?;
        Ok(EpicMembership {
            epic_id: epic.id.clone(),
            members: epic.members.clone(),
            member_count: epic.member_count,
        })
    }

    /// Consume the index into its reverse map (the contract's return shape).
    #[must_use]
    pub fn into_buckets(self) -> HashMap<EpicId, Vec<IssueKey>> {
        self.buckets
    }

    /// Consume the index into its missing-reference list.
    #[must_use]
    pub fn into_missing(self) -> Vec<EpicReferenceResolution> {
        self.missing
    }

    /// Consume the index into its declaration-ordered epic list.
    #[must_use]
    pub fn into_epics(self) -> Vec<Epic> {
        self.epics.into_values().collect()
    }
}

/// Build the reverse index once for one read (`HashMap<EpicId, Vec<IssueKey>>`).
///
/// An epic filter is then a bucket lookup rather than a scan (NFR-001).
#[must_use]
pub fn membership_index<N: EpicNode>(
    config: &Config,
    issues: &[N],
) -> HashMap<EpicId, Vec<IssueKey>> {
    EpicIndex::build(config, issues).into_buckets()
}

/// Issue number -> its resolved epic ids, in declaration order (WP09 item C).
///
/// [`EpicIndex::memberships_by_issue`] over one snapshot, for the callers — the
/// board's partition, `tix list --group epic`/`--sort epic`, and
/// `tix status --group epic` — that need the inverse membership without holding
/// the index.
#[must_use]
pub fn memberships_by_issue<N: EpicNode>(
    config: &Config,
    issues: &[N],
) -> HashMap<u32, Vec<String>> {
    EpicIndex::build(config, issues).memberships_by_issue()
}

/// The ordered membership of an epic, by id or name.
pub fn membership<N: EpicNode>(
    config: &Config,
    issues: &[N],
    reference: &str,
) -> Result<EpicMembership, EpicError> {
    EpicIndex::build(config, issues).membership(reference)
}

/// The epics in declaration order, with derived member and child counts.
///
/// Never errors: an empty registry is an empty list, and a registry with no
/// issues is a list with zero members.
#[must_use]
pub fn list_epics<N: EpicNode>(config: &Config, issues: &[N]) -> Vec<Epic> {
    EpicIndex::build(config, issues).into_epics()
}

/// Resolve an epic by id (first) or by name.
pub fn resolve<N: EpicNode>(
    config: &Config,
    issues: &[N],
    reference: &str,
) -> Result<Epic, EpicError> {
    EpicIndex::build(config, issues).resolve(reference).cloned()
}

/// The diagnosed state of an epic whose recorded parent no longer exists
/// (data-model §5, contract §3.4).
///
/// The epic's record is **not** modified when its parent is deleted: the
/// reference survives so it can be repaired. Any cascade would be an escalation
/// trigger.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnresolvedEpicParent {
    /// The epic holding the reference.
    pub epic: EpicId,
    /// The reference exactly as stored, retained for repair.
    pub recorded_parent: String,
    /// Human-readable text, reused verbatim by lint, the CLI, the TUI and MCP.
    pub reason: String,
}

/// The derived hierarchy view for one epic (data-model §5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicHierarchy {
    /// The epic the view is about.
    pub epic: EpicId,
    /// The recorded parent id, exactly as stored; retained even when unresolved.
    pub recorded_parent: Option<String>,
    /// The resolved parent, `None` when there is none or it does not resolve.
    pub parent: Option<EpicRef>,
    /// Direct children, in registry declaration order.
    pub children: Vec<EpicRef>,
    /// `children.len()`.
    pub child_count: usize,
    /// Ancestors, root-first.
    pub ancestors: Vec<EpicRef>,
    /// Distance from the root: the number of resolved ancestors walked.
    pub depth: usize,
    /// Present when the recorded parent no longer exists.
    pub unresolved: Option<UnresolvedEpicParent>,
}

/// The chain that closes a cycle if `epic` were pointed at `parent`, or `None`.
///
/// **Iterative**, from `parent` upward through the recorded parents. Because each
/// epic has at most one parent the hierarchy is a *functional* graph, so this is
/// the only walk needed — there is no branching to explore. Recursion would
/// overflow the stack on a 10,000-deep chain (NFR-001), so the loop carries its
/// own `visited` set and terminates on the first repeat or the root.
///
/// Only a repeat of **the proposed epic** closes a cycle. A walk that merely
/// *enters* a stored cycle the epic is not part of must not be reported as one:
/// attaching an unrelated epic under a cyclic subtree is a legitimate edit, and
/// the pre-existing loop is [`validate_epic_chains`]'s to report. Reporting it
/// here would refuse valid edits and emit a spurious `cycle` for every acyclic
/// epic whose chain happens to run into the loop.
pub(super) fn epic_cycle_path(
    parents: &HashMap<EpicId, EpicId>,
    epic: &EpicId,
    parent: &EpicId,
) -> Option<Vec<EpicId>> {
    let mut path = vec![epic.clone()];
    let mut visited: HashSet<EpicId> = HashSet::new();
    visited.insert(epic.clone());
    let mut current = parent.clone();
    loop {
        if current == *epic {
            // The proposed edge closes the loop, and `path` is the cycle itself:
            // the epic, then the chain from the proposed parent back to it.
            return Some(path);
        }
        if !visited.insert(current.clone()) {
            // A pre-existing loop that does not contain `epic`, so the proposed
            // edge closes nothing. `validate_epic_chains` reports that loop.
            return None;
        }
        path.push(current.clone());
        {
            let next = parents.get(&current)?;
            current = next.clone()
        }
    }
}

/// The resolvable parent edges of a registry: epic id -> recorded parent id.
///
/// The one home of "which edges exist", shared by the derived index and by the
/// chain validation so the two cannot drift. A parent that is not a well-formed
/// id, or that the registry does not hold, is **not** an edge: it is the
/// unresolved state [`EpicHierarchy::unresolved`] surfaces and
/// [`EpicIndex::missing_for`] diagnoses.
pub(super) fn resolved_parents(
    registry: &IndexMap<String, EpicConfiguration>,
) -> HashMap<EpicId, EpicId> {
    let known: HashSet<String> = registry.keys().cloned().collect();
    let mut parents: HashMap<EpicId, EpicId> = HashMap::new();
    for (raw, record) in registry {
        let Ok(id) = EpicId::new(raw) else {
            continue;
        };
        if let Some(parent) = record
            .parent
            .as_deref()
            .and_then(|p| EpicId::new(p).ok())
            .filter(|p| known.contains(p.as_str()))
        {
            parents.insert(id, parent);
        }
    }
    parents
}

/// Validate a proposed parent for `epic`, returning the resolved parent id.
///
/// The two rules of contract §3 apply, and both run **before any write**:
///
/// 1. `epic == parent` is always a self-parent;
/// 2. a proposed parent chain that would close a cycle is refused, with the
///    offending path in the diagnostic.
///
/// The walk is the dedicated **epic chain** walk, not the issue-parent walk from
/// source issue 170's Mission (C-002); it follows the same shape and the same
/// single-owner rule, and it is iterative so a 10,000-node chain cannot overflow
/// the stack (NFR-001).
pub fn validate_epic_parent(
    registry: &IndexMap<String, EpicConfiguration>,
    epic: &EpicId,
    parent_reference: &str,
) -> Result<EpicId, EpicError> {
    let parent = resolve_epic_id(registry, parent_reference)?;
    if &parent == epic {
        return Err(EpicError::SelfParent { epic: epic.clone() });
    }
    if let Some(path) = epic_cycle_path(&resolved_parents(registry), epic, &parent) {
        return Err(EpicError::Cycle {
            epic: epic.clone(),
            path,
        });
    }
    Ok(parent)
}

/// Every stored epic-chain defect in the registry, deterministically ordered.
///
/// **Never** returns an error — lint consumes the list directly — and performs one
/// pass over the registry. Reports each self-parent and each stored cycle once,
/// named by the epic whose parent edge closes it.
#[must_use]
pub fn validate_epic_chains(registry: &IndexMap<String, EpicConfiguration>) -> Vec<EpicError> {
    let parents = resolved_parents(registry);
    let mut out: Vec<EpicError> = Vec::new();
    let mut ids: Vec<EpicId> = registry
        .keys()
        .filter_map(|raw| EpicId::new(raw).ok())
        .collect();
    ids.sort();

    // A self-parent is one defect, not two: its chain is trivially cyclic, so it
    // is reported here and seeded into `seen` to keep the cycle sweep off it.
    let mut seen: HashSet<EpicId> = HashSet::new();
    for id in &ids {
        if parents.get(id) == Some(id) {
            seen.insert(id.clone());
            out.push(EpicError::SelfParent { epic: id.clone() });
        }
    }
    for id in &ids {
        if seen.contains(id) {
            continue;
        }
        let Some(parent) = parents.get(id) else {
            continue;
        };
        if let Some(path) = epic_cycle_path(&parents, id, parent) {
            for node in &path {
                seen.insert(node.clone());
            }
            out.push(EpicError::Cycle {
                epic: id.clone(),
                path,
            });
        }
    }
    out.sort_by(|a, b| {
        a.kind()
            .cmp(&b.kind())
            .then_with(|| chain_epic(a).cmp(&chain_epic(b)))
    });
    out
}

/// The epic a chain diagnostic is about, for deterministic ordering.
pub(super) fn chain_epic(err: &EpicError) -> Option<&EpicId> {
    match err {
        EpicError::SelfParent { epic } | EpicError::Cycle { epic, .. } => Some(epic),
        _ => None,
    }
}

impl EpicIndex {
    /// The derived hierarchy of one epic (contract §1, data-model §5).
    ///
    /// Reads the pre-built parent and child maps, so navigation is a lookup
    /// rather than a scan. `ancestors` is root-first and `depth` is the number of
    /// resolved ancestors walked; a **recorded parent that no longer exists** is
    /// surfaced as [`EpicHierarchy::unresolved`] rather than dropped (C-005,
    /// contract §3.4).
    pub fn hierarchy(&self, reference: &str) -> Result<EpicHierarchy, EpicError> {
        let epic = self.resolve(reference)?;
        let id = epic.id.clone();

        let parent = self.parents.get(&id).and_then(|parent| self.ref_of(parent));
        let mut ancestors: Vec<EpicRef> = Vec::new();
        let mut visited: HashSet<EpicId> = HashSet::new();
        visited.insert(id.clone());
        let mut current = self.parents.get(&id).cloned();
        while let Some(node) = current {
            if !visited.insert(node.clone()) {
                // A stored cycle: stop rather than loop. `validate_epic_chains`
                // reports it; navigation stays total.
                break;
            }
            if let Some(reference) = self.ref_of(&node) {
                ancestors.push(reference);
            }
            current = self.parents.get(&node).cloned();
        }
        ancestors.reverse();

        let children: Vec<EpicRef> = self
            .children
            .get(&id)
            .map(|ids| ids.iter().filter_map(|child| self.ref_of(child)).collect())
            .unwrap_or_default();

        let unresolved = epic.parent.as_deref().and_then(|recorded| {
            let resolves = self
                .parents
                .get(&id)
                .is_some_and(|p| p.as_str() == recorded);
            if resolves {
                return None;
            }
            Some(UnresolvedEpicParent {
                epic: id.clone(),
                recorded_parent: recorded.to_string(),
                reason: unresolved_parent_reason(&id, recorded),
            })
        });

        Ok(EpicHierarchy {
            epic: id,
            recorded_parent: epic.parent.clone(),
            parent,
            child_count: children.len(),
            children,
            depth: ancestors.len(),
            ancestors,
            unresolved,
        })
    }

    /// A derived reference to an epic the index knows, by id.
    pub(super) fn ref_of(&self, id: &EpicId) -> Option<EpicRef> {
        self.epics.get(id).map(|epic| EpicRef::new(id, &epic.name))
    }
}

/// The ordered hierarchy of an epic, by id or name.
pub fn hierarchy<N: EpicNode>(
    config: &Config,
    issues: &[N],
    reference: &str,
) -> Result<EpicHierarchy, EpicError> {
    EpicIndex::build(config, issues).hierarchy(reference)
}

impl EpicIndex {
    /// This epic's **unresolvable** references, deterministically ordered.
    ///
    /// The epic-held half of [`resolve_references`]: the recorded parent (when it
    /// no longer resolves), the project ids absent from the project registry, and
    /// the milestone and cycle names absent from the planner's lookups. Turns the
    /// epic's own fields, not the issue set, so it is a constant-time read.
    #[must_use]
    pub fn missing_for(
        &self,
        id: &EpicId,
        targets: &ReferenceTargets,
    ) -> Vec<EpicReferenceResolution> {
        let Some(epic) = self.epics.get(id) else {
            return Vec::new();
        };
        let holder = ReferenceHolder::Epic(id.clone());
        let mut out: Vec<EpicReferenceResolution> = Vec::new();

        if let Some(recorded) = epic.parent.as_deref() {
            let resolves = self.parents.get(id).is_some_and(|p| p.as_str() == recorded);
            if !resolves {
                out.push(EpicReferenceResolution {
                    holder: holder.clone(),
                    target_kind: EpicReferenceKind::Epic,
                    target: recorded.to_string(),
                    reason: missing_epic_reason(&holder, recorded),
                });
            }
        }
        for project in &epic.projects {
            if !targets.project_known(project) {
                out.push(EpicReferenceResolution {
                    holder: holder.clone(),
                    target_kind: EpicReferenceKind::Project,
                    target: project.clone(),
                    reason: missing_project_reason(id, project),
                });
            }
        }
        if let Some(milestone) = epic.milestone.as_deref() {
            if !targets.milestone_known(milestone) {
                out.push(EpicReferenceResolution {
                    holder: holder.clone(),
                    target_kind: EpicReferenceKind::Milestone,
                    target: milestone.to_string(),
                    reason: missing_milestone_reason(id, milestone),
                });
            }
        }
        if let Some(cycle) = epic.cycle.as_deref() {
            if !targets.cycle_known(cycle) {
                out.push(EpicReferenceResolution {
                    holder: holder.clone(),
                    target_kind: EpicReferenceKind::Cycle,
                    target: cycle.to_string(),
                    reason: missing_cycle_reason(id, cycle),
                });
            }
        }
        out.sort_by(reference_order);
        out
    }
}

impl EpicIndex {
    /// Progress, child count, weight, and blocked work for one epic
    /// (contract §1, FR-003, C-008).
    ///
    /// This is the **only** place an epic's figures are computed: every surface
    /// renders this value rather than formatting its own figure.
    ///
    /// - Completion reads the board's **configured** completion column through
    ///   the workflow service ([`crate::workflow::active_resolution`]), never a
    ///   literal `"done"`.
    /// - Membership is the pre-built bucket, so the figures are a bucket lookup
    ///   rather than a scan (contract §7).
    /// - `blocked` is **consumed** from source issue 169's derived read: the
    ///   graph's [`RelationshipGraph::blocked_state`] decides, and its `reason`
    ///   text is carried through verbatim. Nothing here re-derives blocked work
    ///   (research R4), and a **done** member is never counted as blocked.
    /// - `missing_references` is this epic's own unresolvable references, so an
    ///   unresolved reference is visible wherever progress is shown (C-005).
    pub fn rollup(
        &self,
        config: &Config,
        reference: &str,
        targets: &ReferenceTargets,
        graph: &RelationshipGraph<'_>,
    ) -> Result<EpicRollup, EpicError> {
        let epic = self.resolve(reference)?;
        let id = epic.id.clone();
        let (_, resolution) = crate::workflow::active_resolution(config);

        let members = self.bucket(&id).unwrap_or(&[]);
        let done_board: HashSet<IssueKey> = members
            .iter()
            .filter(|key| {
                self.status_of(**key)
                    .and_then(|status| resolution.resolve(status))
                    .is_some_and(crate::workflow::WorkflowCategory::is_complete)
            })
            .copied()
            .collect();
        let done = done_board.len();
        let total = members.len();

        let blocked_members: Vec<BlockedMember> = self
            .blocked_members(&id, graph)
            .into_iter()
            .filter(|member| !done_board.contains(&member.issue))
            .collect();

        Ok(EpicRollup {
            name: epic.name.clone(),
            progress: EpicProgress {
                done,
                total,
                progress: Progress { done, total },
            },
            child_count: epic.child_count,
            weighted_progress: self.weighted_progress(config, &id, &resolution),
            blocked: blocked_members.len(),
            blocked_members,
            missing_references: self.missing_for(&id, targets),
            epic_id: id,
        })
    }

    /// The epic's members with an open blocker, consuming the owner's derived read.
    ///
    /// The predicate is [`RelationshipGraph::blocked_state`]'s and so is the
    /// `reason` text: this function only shapes the owner's answer, it never
    /// re-derives it (research R4). Ordered by issue number.
    #[must_use]
    pub fn blocked_members(
        &self,
        id: &EpicId,
        graph: &RelationshipGraph<'_>,
    ) -> Vec<BlockedMember> {
        let Some(members) = self.buckets.get(id) else {
            return Vec::new();
        };
        let mut out: Vec<BlockedMember> = members
            .iter()
            .filter_map(|key| {
                let state = graph.blocked_state(key.number());
                if !state.is_blocked {
                    return None;
                }
                Some(BlockedMember {
                    issue: *key,
                    display: self
                        .label(*key)
                        .map(str::to_string)
                        .unwrap_or_else(|| key.to_string()),
                    reason: state.reason,
                })
            })
            .collect();
        out.sort_by_key(|member| member.issue);
        out
    }

    /// The weight-aware figure for one epic (data-model §6).
    ///
    /// `resolution` is the active board's category seam, resolved once by the
    /// caller, so a child's completion is judged by the same rule as the epic's
    /// own completion rather than by a second lookup per child.
    pub(super) fn weighted_progress(
        &self,
        config: &Config,
        id: &EpicId,
        resolution: &crate::workflow::CategoryResolution,
    ) -> WeightedProgress {
        let own_weight = config.epics.get(id.as_str()).and_then(|r| r.weight);
        let Some(children) = self.children.get(id) else {
            return WeightedProgress {
                own_weight,
                weighted_children: 0,
                unweighted_children: 0,
                done_weight: 0,
                total_weight: 0,
                percent: None,
            };
        };
        let mut weighted = 0usize;
        let mut unweighted = 0usize;
        let mut done_weight = 0i64;
        let mut total_weight = 0i64;
        for child in children {
            let Some(weight) = config.epics.get(child.as_str()).and_then(|r| r.weight) else {
                unweighted += 1;
                continue;
            };
            weighted += 1;
            total_weight += weight;
            if self.child_is_complete(child, resolution) {
                done_weight += weight;
            }
        }
        let percent = whole_percent(done_weight, total_weight);
        WeightedProgress {
            own_weight,
            weighted_children: weighted,
            unweighted_children: unweighted,
            done_weight,
            total_weight,
            percent,
        }
    }

    /// Whether a child epic has members and all of them are complete.
    pub(super) fn child_is_complete(
        &self,
        child: &EpicId,
        resolution: &crate::workflow::CategoryResolution,
    ) -> bool {
        let Some(members) = self.buckets.get(child) else {
            return false;
        };
        if members.is_empty() {
            return false;
        }
        members.iter().all(|key| {
            self.status_of(*key)
                .and_then(|status| resolution.resolve(status))
                .is_some_and(crate::workflow::WorkflowCategory::is_complete)
        })
    }
}

/// `done / total` as a floored whole percentage.
///
/// Weights are positive `i64` values, and the fold itself can sum past either `u32`
/// or `i64` in a constructible in-memory fixture. Widening both operands before the
/// multiply keeps the percentage exact; the result is saturated only when it exceeds
/// the `u32` field's range.
fn whole_percent(done: i64, total: i64) -> Option<u32> {
    (total > 0).then(|| {
        let numerator = i128::from(done.max(0)) * 100;
        let percent = numerator / i128::from(total);
        u32::try_from(percent).unwrap_or(u32::MAX)
    })
}