tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! The source-attributed roadmap projection (WP03, T012–T016, FR-005, C-004–C-006).
//!
//! A projection is a **value**, computed once per read: the ordered initiatives a
//! normalized [`RoadmapFilter`] selects, each carrying an [`InitiativeSummary`] that
//! *joins* the shared services rather than computing anything itself.
//!
//! # Join, do not blend (C-004)
//!
//! The mission's own risk list names the failure this module must not become: "the
//! roadmap becomes a second metrics engine". So an [`InitiativeSummary`] carries
//! **one contribution per referenced source entity** — the entity's kind, its
//! stable id, its derived display label, that entity's own typed value as its
//! owning service returned it ([`ProgressValue`]), and the shared health policy's
//! typed risk ([`crate::health::HealthRollup`]) with its version. It invents no
//! aggregate percentage, score or average across sources: that would be a new
//! metric formula, which this mission is forbidden to define. Where a structural
//! count is unavoidable it is a **count of contributions**, never a derived rate.
//!
//! Every figure comes from an existing entry point, called once per read:
//!
//! * a **project** reference joins [`crate::projects::ProjectIndex::health`];
//! * an **epic** reference joins [`crate::epics::EpicIndex::rollup`];
//! * every resolved reference joins [`crate::health::rollup`] for that entity's
//!   [`crate::health::HealthScope`], which is the shared, versioned risk reading;
//! * a reference that does not resolve is a [`RoadmapDiagnosticKind::MissingReference`]
//!   finding, never a dropped row and never a zero.
//!
//! # One index, one pass (T012, T016)
//!
//! [`RoadmapSources`] holds the shared snapshots — the project, epic and health
//! indices plus the consumed planning/relationship facts — built **once** per read.
//! [`project`] builds the relationship graph once, joins every row against those
//! indices (no per-row re-read of the store or of `tix.toml`), and sorts once
//! through [`crate::roadmap::order`]. It stores nothing and writes nothing.
//!
//! # The states are not one `0` (C-005/C-006)
//!
//! A summary's [`SummaryState`] distinguishes `complete`, `partial`, `empty`,
//! `missing_reference` and `unknown`, and every row carries the ordered,
//! field-aware [`RoadmapDiagnostic`]s that explain it. A genuine zero-progress
//! figure is a value on a contribution, never a stand-in for "nobody said".

use std::collections::HashSet;

use crate::config::{Config, EpicId, InitiativeId, ProjectId};
use crate::epics::{EpicIndex, EpicRollup, ReferenceTargets};
use crate::error::Result;
use crate::health::{
    HealthIndex, HealthPolicy, HealthRollup, HealthScope, HealthState, rollup as health_rollup,
};
use crate::model::Issue;
use crate::projects::{ProjectHealthReport, ProjectIndex};
use crate::relationships::{IssueView, RelationshipGraph};
use crate::roadmap::diagnostics::{self, RoadmapDiagnostic, RoadmapDiagnosticKind};
use crate::roadmap::filter::RoadmapFilter;
use crate::roadmap::order::{RoadmapEntry, filter_and_order};
use crate::roadmap::registry::{self, AssociationKind};

// ---------------------------------------------------------------------------
// The consumed inputs and the once-built source snapshot (T012)
// ---------------------------------------------------------------------------

/// The facts the projection **consumes** from their owners rather than deriving.
///
/// A projection performs no file I/O (NFR-001's exclusion) and owns no metric, so
/// the planning overdue read, the relationship graph's blocked state, the resolved
/// reference targets and the relationship done-column are gathered by the caller
/// from their owning services — exactly as
/// [`crate::commands::view::project_reports`] gathers the project inputs — and
/// passed in. The 10,000-entity tests build them in memory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoadmapConsumed {
    /// The project/milestone/cycle targets the registries resolve, from
    /// [`crate::epics::ReferenceTargets`].
    pub targets: ReferenceTargets,
    /// The board's done column, as the relationship service reports it.
    pub done_column: String,
    /// Issue numbers with an assignee, from [`crate::projects::assigned_keys`].
    pub assigned: HashSet<u32>,
    /// Issue numbers past due and not done, from the planning overdue read.
    pub overdue: HashSet<u32>,
    /// Issue numbers with an open blocker, from the relationship graph.
    pub blocked: HashSet<u32>,
}

impl Default for RoadmapConsumed {
    fn default() -> Self {
        Self {
            targets: ReferenceTargets::default(),
            done_column: "done".to_string(),
            assigned: HashSet::new(),
            overdue: HashSet::new(),
            blocked: HashSet::new(),
        }
    }
}

/// The shared snapshots a projection joins against, built **once** per read.
///
/// The three indices are each built in one pass over the issue set, so no row
/// re-reads the store; the consumed facts come from their owners. The projection
/// stores nothing and the snapshot is a value the caller drops when it is done.
#[derive(Debug, Clone)]
pub struct RoadmapSources<'a> {
    /// The issue set the indices were built from, retained so the relationship
    /// graph for epic rollups is built once here rather than per row.
    pub issues: &'a [Issue],
    /// The project index (`#178`).
    pub projects: ProjectIndex,
    /// The epic index (`#179`).
    pub epics: EpicIndex,
    /// The health index (`#177`).
    pub health: HealthIndex,
    /// The health policy in force, whose version every risk reading reports.
    pub policy: HealthPolicy,
    /// The facts consumed from the planning and relationship services.
    pub consumed: RoadmapConsumed,
}

impl<'a> RoadmapSources<'a> {
    /// Build the source snapshot in one pass over `issues`.
    ///
    /// The declared cycles and milestones the health index needs come from the
    /// registries the caller already resolved ([`RoadmapConsumed::targets`]); the
    /// index flags a member naming anything else, which the join forwards as source
    /// diagnostics.
    #[must_use]
    pub fn new(
        config: &Config,
        issues: &'a [Issue],
        policy: &HealthPolicy,
        consumed: RoadmapConsumed,
    ) -> Self {
        let projects = ProjectIndex::build(config, issues);
        let epics = EpicIndex::build(config, issues);
        let cycles: Vec<String> = config.cycles.keys().cloned().collect();
        let mut milestones: Vec<String> = consumed.targets.milestones.iter().cloned().collect();
        milestones.sort();
        let health = HealthIndex::build(issues, &cycles, &milestones, policy);
        Self {
            issues,
            projects,
            epics,
            health,
            policy: policy.clone(),
            consumed,
        }
    }
}

// ---------------------------------------------------------------------------
// The projection value (data-model §5, §6, §4)
// ---------------------------------------------------------------------------

/// How one reference resolved against its registry (data-model §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ReferenceResolution {
    /// The reference names a source entity the registry holds.
    Resolved,
    /// The reference names nothing the registry holds.
    Missing,
    /// The reference could name more than one source entity.
    ///
    /// The closed vocabulary is data-model §2's. Initiative references are keyed by
    /// a unique stable id (projects/epics) or a case-folded-unique milestone name,
    /// so this state is currently unreachable — it exists so a caller cannot
    /// mistake "unresolvable" for "resolves to nothing" if a future registry admits
    /// an ambiguous name.
    Ambiguous,
}

impl ReferenceResolution {
    /// The stable spelling a surface prints.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Resolved => "resolved",
            Self::Missing => "missing",
            Self::Ambiguous => "ambiguous",
        }
    }

    /// Whether the reference resolved to a source entity.
    #[must_use]
    pub const fn is_resolved(self) -> bool {
        matches!(self, Self::Resolved)
    }
}

/// The owning service's typed value for one resolved source entity.
///
/// One variant per owning service, carrying **that service's** returned value: a
/// project's report from [`crate::projects::ProjectIndex::health`], an epic's rollup
/// from [`crate::epics::EpicIndex::rollup`]. Nothing here is recomputed, and there
/// is no cross-source variant — a blended figure would be the second metrics engine
/// C-004 forbids.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProgressValue {
    /// A project's report, as the project service returned it.
    Project(Box<ProjectHealthReport>),
    /// An epic's rollup, as the epic service returned it.
    Epic(Box<EpicRollup>),
}

/// One referenced source entity's contribution to an [`InitiativeSummary`].
///
/// The join's atom: the source's kind, its stable id, its derived display label,
/// its own typed value, and the shared health policy's typed risk. A reference that
/// does not resolve is still a contribution — with [`ReferenceResolution::Missing`],
/// no value, no risk, and the diagnostics that say why (C-005).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SummaryContribution {
    /// The reference kind.
    pub kind: AssociationKind,
    /// The stable id (project id, epic id) or name (milestone) as recorded.
    pub target: String,
    /// The derived display label; the target itself for an unresolved reference.
    pub label: String,
    /// How the reference resolved.
    pub resolution: ReferenceResolution,
    /// The owning service's typed value, when it has one (projects and epics do;
    /// a milestone's health is its risk below).
    pub progress: Option<ProgressValue>,
    /// The shared health policy's typed risk for the source's scope.
    pub risk: Option<HealthRollup>,
    /// The policy version that produced [`Self::risk`] (`health-v1`), when present.
    pub policy_version: Option<String>,
}

impl SummaryContribution {
    /// The source entity's stable spelling, `<kind>:<id>`, for provenance.
    #[must_use]
    pub fn source_entity(&self) -> String {
        scope_of(self.kind, &self.target).as_str()
    }

    /// Whether this contribution reports anything knowable.
    ///
    /// A real zero-progress figure is knowable — it is a value, not an absence — so
    /// this is `progress.is_some()` or a risk whose state is not
    /// [`HealthState::Unknown`]. That is what keeps `0` distinct from "nobody said".
    #[must_use]
    pub fn is_knowable(&self) -> bool {
        self.progress.is_some()
            || self
                .risk
                .as_ref()
                .is_some_and(|risk| risk.state != HealthState::Unknown)
    }
}

/// The explicit state of one initiative's summary (data-model §4; C-006).
///
/// The five states are exhaustive and never conflated: an initiative that records
/// nothing is not the same as one whose references are missing, and neither is a
/// genuine zero-progress figure.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SummaryState {
    /// Every recorded reference resolved and at least one reports a knowable value.
    Complete,
    /// Some references resolved and at least one did not.
    Partial,
    /// The initiative records **no** reference: nothing can contribute (C-006).
    Empty,
    /// At least one reference is recorded and **none** of them resolve (C-005).
    MissingReference,
    /// Every reference resolved, but no resolved source reports anything knowable.
    Unknown,
}

impl SummaryState {
    /// The stable spelling a surface prints.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Complete => "complete",
            Self::Partial => "partial",
            Self::Empty => "empty",
            Self::MissingReference => "missing_reference",
            Self::Unknown => "unknown",
        }
    }
}

/// An initiative's derived, source-attributed summary (data-model §4).
///
/// A **join**: one [`SummaryContribution`] per referenced source entity, the ordered
/// source-entity ids, the ordered policy versions, and the ordered diagnostics. No
/// initiative-local metric formula exists here (C-004).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InitiativeSummary {
    /// The stable initiative id.
    pub initiative_id: String,
    /// The explicit summary state.
    pub state: SummaryState,
    /// One contribution per referenced source entity, in reference order.
    pub contributions: Vec<SummaryContribution>,
    /// The resolved source entities, `<kind>:<id>`, in contribution order.
    pub source_entities: Vec<String>,
    /// The policy versions among the contributions, ordered and de-duplicated.
    pub policy_versions: Vec<String>,
    /// The ordered, field-aware findings for this summary.
    pub diagnostics: Vec<RoadmapDiagnostic>,
}

impl InitiativeSummary {
    /// The structural count of contributions whose source reports a knowable value.
    ///
    /// A **count of contributions**, never a rate, ratio or percentage: counting is
    /// not a metric formula, and this is the only aggregate the summary exposes.
    #[must_use]
    pub fn knowable_contributions(&self) -> usize {
        self.contributions
            .iter()
            .filter(|contribution| contribution.is_knowable())
            .count()
    }
}

/// One association as the row exposes it: identity, label and resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RowReference {
    /// The reference kind.
    pub kind: AssociationKind,
    /// The recorded target.
    pub target: String,
    /// The derived display label (the target when unresolved).
    pub label: String,
    /// How the reference resolved.
    pub resolution: ReferenceResolution,
}

/// One displayable initiative row (data-model §6).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoadmapRow {
    /// The stable initiative id.
    pub id: String,
    /// The display label.
    pub name: String,
    /// The optional strategic outcome.
    pub outcome: Option<String>,
    /// The optional owner identity.
    pub owner: Option<String>,
    /// The optional initiative status.
    pub status: Option<String>,
    /// The optional priority.
    pub priority: Option<crate::model::Priority>,
    /// The filterable labels.
    pub labels: Vec<String>,
    /// The target date; `None` is the explicit undated state (C-003).
    pub target_date: Option<String>,
    /// The source-attributed summary.
    pub summary: InitiativeSummary,
    /// The record's references, with resolution.
    pub references: Vec<RowReference>,
    /// The row's ordered findings.
    pub diagnostics: Vec<RoadmapDiagnostic>,
}

/// The ordered, filterable roadmap view every surface consumes (data-model §5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RoadmapProjection {
    /// The ordered rows.
    pub initiatives: Vec<RoadmapRow>,
    /// The filter that selected them.
    pub filters: RoadmapFilter,
    /// Every row's findings, flattened and ordered.
    pub diagnostics: Vec<RoadmapDiagnostic>,
    /// The row count after filtering.
    pub total: usize,
}

// ---------------------------------------------------------------------------
// The pass (T013, T014, T015)
// ---------------------------------------------------------------------------

/// Project the filtered initiatives, joining the shared services once (T012–T016).
///
/// Validates the filter's syntax first, selects and orders through
/// [`crate::roadmap::order::filter_and_order`] — the one predicate and one sort every
/// surface shares — then joins each row against [`RoadmapSources`]. The relationship
/// graph is built once here, so an epic rollup is an index lookup rather than a
/// per-row rebuild. Read-only: `config` and `sources` are borrowed immutably.
pub fn project(
    config: &Config,
    sources: &RoadmapSources<'_>,
    filter: &RoadmapFilter,
) -> Result<RoadmapProjection> {
    let entries = filter_and_order(config, filter)?;

    // Build the relationship graph once: epic rollups consume its blocked state.
    let views: Vec<IssueView<'_>> = sources.issues.iter().map(Issue::issue_view).collect();
    let graph = RelationshipGraph::new(&views, &sources.consumed.done_column);

    let mut rows: Vec<RoadmapRow> = Vec::with_capacity(entries.len());
    for entry in &entries {
        rows.push(join_row(config, sources, &graph, entry));
    }

    // The projection-level list is exactly the rows' findings, flattened and
    // ordered, so a surface that renders one diagnostics block cannot disagree with
    // the per-row lists.
    let mut diagnostics: Vec<RoadmapDiagnostic> = rows
        .iter()
        .flat_map(|row| row.diagnostics.iter().cloned())
        .collect();
    diagnostics::order(&mut diagnostics);

    let total = rows.len();
    Ok(RoadmapProjection {
        initiatives: rows,
        filters: filter.clone(),
        diagnostics,
        total,
    })
}

/// Join one ordered entry into a displayable row.
fn join_row(
    config: &Config,
    sources: &RoadmapSources<'_>,
    graph: &RelationshipGraph<'_>,
    entry: &RoadmapEntry<'_>,
) -> RoadmapRow {
    let record = entry.initiative;
    let mut contributions: Vec<SummaryContribution> = Vec::new();
    let mut references: Vec<RowReference> = Vec::new();
    let mut findings: Vec<RoadmapDiagnostic> = Vec::new();

    let associations = InitiativeId::new(entry.id)
        .map(|id| registry::associations(config, &id))
        .unwrap_or_default();
    for association in &associations {
        let (contribution, mut diagnostics) = match association.kind {
            AssociationKind::Project => {
                join_project(config, sources, entry.id, &association.target)
            }
            AssociationKind::Epic => {
                join_epic(config, sources, graph, entry.id, &association.target)
            }
            AssociationKind::Milestone => join_milestone(sources, entry.id, &association.target),
        };
        references.push(RowReference {
            kind: contribution.kind,
            target: contribution.target.clone(),
            label: contribution.label.clone(),
            resolution: contribution.resolution,
        });
        contributions.push(contribution);
        findings.append(&mut diagnostics);
    }

    let state = summary_state(&contributions);
    match state {
        SummaryState::Empty => findings.push(
            RoadmapDiagnostic::new(
                RoadmapDiagnosticKind::EmptyScope,
                format!(
                    "initiative `{}` records no project, epic or milestone reference",
                    entry.id
                ),
            )
            .for_initiative(entry.id),
        ),
        SummaryState::Unknown => findings.push(
            RoadmapDiagnostic::new(
                RoadmapDiagnosticKind::UnknownValue,
                format!(
                    "initiative `{}` resolves every reference, but no source reports a value",
                    entry.id
                ),
            )
            .for_initiative(entry.id),
        ),
        _ => {}
    }
    if entry.target_date.is_undated() {
        findings.push(
            RoadmapDiagnostic::new(
                RoadmapDiagnosticKind::Undated,
                format!("initiative `{}` has no target date", entry.id),
            )
            .for_initiative(entry.id)
            .at_field("target_date"),
        );
    }
    diagnostics::order(&mut findings);

    let source_entities: Vec<String> = contributions
        .iter()
        .filter(|contribution| contribution.resolution.is_resolved())
        .map(SummaryContribution::source_entity)
        .collect();
    let policy_versions = ordered_policy_versions(&contributions);

    let summary = InitiativeSummary {
        initiative_id: entry.id.to_string(),
        state,
        contributions,
        source_entities,
        policy_versions,
        diagnostics: findings.clone(),
    };

    RoadmapRow {
        id: entry.id.to_string(),
        name: record.name.clone(),
        outcome: record.outcome.clone(),
        owner: record.owner.clone(),
        status: record.status.clone(),
        priority: record.priority.clone(),
        labels: record.labels.clone(),
        target_date: record.target_date.clone(),
        summary,
        references,
        diagnostics: findings,
    }
}

/// The ordered, de-duplicated policy versions among the contributions.
fn ordered_policy_versions(contributions: &[SummaryContribution]) -> Vec<String> {
    let mut versions: Vec<String> = Vec::new();
    for contribution in contributions {
        if let Some(version) = &contribution.policy_version {
            if !versions.iter().any(|seen| seen == version) {
                versions.push(version.clone());
            }
        }
    }
    versions
}

/// The explicit summary state, from the resolutions and the values (T015).
fn summary_state(contributions: &[SummaryContribution]) -> SummaryState {
    if contributions.is_empty() {
        return SummaryState::Empty;
    }
    let resolved = contributions
        .iter()
        .filter(|contribution| contribution.resolution.is_resolved())
        .count();
    if resolved == 0 {
        return SummaryState::MissingReference;
    }
    if resolved < contributions.len() {
        return SummaryState::Partial;
    }
    if contributions.iter().any(SummaryContribution::is_knowable) {
        SummaryState::Complete
    } else {
        SummaryState::Unknown
    }
}

// ---------------------------------------------------------------------------
// Per-kind joins (T013, T014)
// ---------------------------------------------------------------------------

/// Join one project reference through [`crate::projects::ProjectIndex::health`].
fn join_project(
    config: &Config,
    sources: &RoadmapSources<'_>,
    initiative: &str,
    target: &str,
) -> (SummaryContribution, Vec<RoadmapDiagnostic>) {
    let resolved = ProjectId::new(target)
        .ok()
        .and_then(|id| sources.projects.project(&id));
    let Some(project) = resolved else {
        return missing_contribution(AssociationKind::Project, target, initiative);
    };
    let scope = HealthScope::Project(project.id.to_string());
    match sources.projects.health(
        config,
        project.id.as_str(),
        &sources.consumed.assigned,
        &sources.consumed.overdue,
        &sources.consumed.blocked,
    ) {
        Ok(report) => {
            let risk = health_rollup(&sources.health, &scope, &sources.policy);
            let mut diagnostics = source_diagnostics(&scope, &risk);
            // The project's members' own dangling references are surfaced wherever
            // the project's health is shown (C-005) — forwarded, never re-derived.
            for missing in &report.health.missing_references {
                diagnostics.push(
                    RoadmapDiagnostic::new(
                        RoadmapDiagnosticKind::SourceDiagnostic,
                        &missing.reason,
                    )
                    .about_source(scope.as_str())
                    .at_field(AssociationKind::Project.field())
                    .referencing(&missing.project_id),
                );
            }
            (
                resolved_contribution(
                    AssociationKind::Project,
                    target,
                    project.name.clone(),
                    Some(ProgressValue::Project(Box::new(report))),
                    Some(&risk),
                ),
                diagnostics,
            )
        }
        Err(err) => unresolvable_contribution(
            AssociationKind::Project,
            target,
            project.name.clone(),
            &err.to_string(),
            initiative,
        ),
    }
}

/// Join one epic reference through [`crate::epics::EpicIndex::rollup`].
fn join_epic(
    config: &Config,
    sources: &RoadmapSources<'_>,
    graph: &RelationshipGraph<'_>,
    initiative: &str,
    target: &str,
) -> (SummaryContribution, Vec<RoadmapDiagnostic>) {
    let resolved = EpicId::new(target)
        .ok()
        .and_then(|id| sources.epics.epic(&id));
    let Some(epic) = resolved else {
        return missing_contribution(AssociationKind::Epic, target, initiative);
    };
    let scope = HealthScope::Epic(epic.id.to_string());
    match sources
        .epics
        .rollup(config, target, &sources.consumed.targets, graph)
    {
        Ok(rollup) => {
            let risk = health_rollup(&sources.health, &scope, &sources.policy);
            let mut diagnostics = source_diagnostics(&scope, &risk);
            for missing in &rollup.missing_references {
                diagnostics.push(
                    RoadmapDiagnostic::new(
                        RoadmapDiagnosticKind::SourceDiagnostic,
                        &missing.reason,
                    )
                    .about_source(scope.as_str())
                    .at_field(AssociationKind::Epic.field())
                    .referencing(&missing.target),
                );
            }
            (
                resolved_contribution(
                    AssociationKind::Epic,
                    target,
                    epic.name.clone(),
                    Some(ProgressValue::Epic(Box::new(rollup))),
                    Some(&risk),
                ),
                diagnostics,
            )
        }
        Err(err) => unresolvable_contribution(
            AssociationKind::Epic,
            target,
            epic.name.clone(),
            &err.to_string(),
            initiative,
        ),
    }
}

/// Join one milestone reference through the shared health rollup.
///
/// A milestone has no in-memory planning progress here — its owning derived read is
/// file-backed — so its contribution carries the health policy's risk only, which is
/// exactly "the value its owning service returned" in this build.
fn join_milestone(
    sources: &RoadmapSources<'_>,
    initiative: &str,
    target: &str,
) -> (SummaryContribution, Vec<RoadmapDiagnostic>) {
    if !sources.consumed.targets.milestone_known(target) {
        return missing_contribution(AssociationKind::Milestone, target, initiative);
    }
    let scope = HealthScope::Milestone(target.to_string());
    let risk = health_rollup(&sources.health, &scope, &sources.policy);
    let diagnostics = source_diagnostics(&scope, &risk);
    (
        resolved_contribution(
            AssociationKind::Milestone,
            target,
            target.to_string(),
            None,
            Some(&risk),
        ),
        diagnostics,
    )
}

/// Build a resolved contribution, taking the risk's version as its provenance.
fn resolved_contribution(
    kind: AssociationKind,
    target: &str,
    label: String,
    progress: Option<ProgressValue>,
    risk: Option<&HealthRollup>,
) -> SummaryContribution {
    SummaryContribution {
        kind,
        target: target.to_string(),
        label,
        resolution: ReferenceResolution::Resolved,
        progress,
        risk: risk.cloned(),
        policy_version: risk.map(|risk| risk.policy_version.clone()),
    }
}

/// Build a contribution for a reference that does not resolve, plus its finding.
fn missing_contribution(
    kind: AssociationKind,
    target: &str,
    initiative: &str,
) -> (SummaryContribution, Vec<RoadmapDiagnostic>) {
    let contribution = SummaryContribution {
        kind,
        target: target.to_string(),
        label: target.to_string(),
        resolution: ReferenceResolution::Missing,
        progress: None,
        risk: None,
        policy_version: None,
    };
    let diagnostic = RoadmapDiagnostic::new(
        RoadmapDiagnosticKind::MissingReference,
        format!(
            "`{}`: reference `{target}` does not resolve in the registry",
            kind.field()
        ),
    )
    .at_field(kind.field())
    .referencing(target);
    let diagnostic = if initiative.is_empty() {
        diagnostic
    } else {
        diagnostic.for_initiative(initiative)
    };
    (contribution, vec![diagnostic])
}

/// Build a contribution for a resolved source whose owner could not value it.
fn unresolvable_contribution(
    kind: AssociationKind,
    target: &str,
    label: String,
    reason: &str,
    initiative: &str,
) -> (SummaryContribution, Vec<RoadmapDiagnostic>) {
    let contribution = SummaryContribution {
        kind,
        target: target.to_string(),
        label,
        resolution: ReferenceResolution::Resolved,
        progress: None,
        risk: None,
        policy_version: None,
    };
    let diagnostic = RoadmapDiagnostic::new(
        RoadmapDiagnosticKind::UnresolvableRollup,
        format!(
            "`{}`: `{target}` resolved but its value could not be derived: {reason}",
            kind.field()
        ),
    )
    .at_field(kind.field())
    .referencing(target)
    .about_source(scope_of(kind, target).as_str());
    let diagnostic = if initiative.is_empty() {
        diagnostic
    } else {
        diagnostic.for_initiative(initiative)
    };
    (contribution, vec![diagnostic])
}

/// Forward the health rollup's own scope findings as source diagnostics.
fn source_diagnostics(scope: &HealthScope, risk: &HealthRollup) -> Vec<RoadmapDiagnostic> {
    risk.diagnostics
        .iter()
        .map(|finding| {
            let mut diagnostic =
                RoadmapDiagnostic::new(RoadmapDiagnosticKind::SourceDiagnostic, &finding.message)
                    .about_source(scope.as_str());
            if let Some(reference) = &finding.reference {
                diagnostic = diagnostic.referencing(reference);
            }
            match &finding.field {
                Some(field) => diagnostic.at_field(field),
                None => diagnostic,
            }
        })
        .collect()
}

/// The health scope of one association kind and target.
fn scope_of(kind: AssociationKind, target: &str) -> HealthScope {
    match kind {
        AssociationKind::Project => HealthScope::Project(target.to_string()),
        AssociationKind::Epic => HealthScope::Epic(target.to_string()),
        AssociationKind::Milestone => HealthScope::Milestone(target.to_string()),
    }
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::planning::Progress;
    use crate::projects::{ProjectHealth, ProjectProgress};

    fn contribution(kind: AssociationKind, resolution: ReferenceResolution) -> SummaryContribution {
        SummaryContribution {
            kind,
            target: "x".to_string(),
            label: "X".to_string(),
            resolution,
            progress: None,
            risk: None,
            policy_version: None,
        }
    }

    #[test]
    fn summary_state_is_exhaustive_and_never_conflates_zero_with_absence() {
        assert_eq!(summary_state(&[]), SummaryState::Empty);

        let missing = vec![contribution(
            AssociationKind::Project,
            ReferenceResolution::Missing,
        )];
        assert_eq!(summary_state(&missing), SummaryState::MissingReference);

        let partial = vec![
            contribution(AssociationKind::Project, ReferenceResolution::Resolved),
            contribution(AssociationKind::Epic, ReferenceResolution::Missing),
        ];
        assert_eq!(summary_state(&partial), SummaryState::Partial);

        // All resolved but nothing knowable -> Unknown, distinct from Empty.
        let unknown = vec![contribution(
            AssociationKind::Milestone,
            ReferenceResolution::Resolved,
        )];
        assert_eq!(summary_state(&unknown), SummaryState::Unknown);

        // A genuinely-zero but **known** figure is Complete, not Empty and not
        // Unknown: zero progress is a value, and the state must say so.
        let zero = SummaryContribution {
            kind: AssociationKind::Project,
            target: "p-zero".to_string(),
            label: "Zero".to_string(),
            resolution: ReferenceResolution::Resolved,
            progress: Some(ProgressValue::Project(Box::new(ProjectHealthReport {
                project_id: ProjectId::new("p-zero").expect("a valid id"),
                name: "Zero".to_string(),
                progress: ProjectProgress {
                    done: 0,
                    total: 0,
                    progress: Progress { done: 0, total: 0 },
                },
                health: ProjectHealth {
                    overdue: 0,
                    blocked: 0,
                    unassigned: 0,
                    missing_references: Vec::new(),
                },
            }))),
            risk: None,
            policy_version: None,
        };
        assert!(zero.is_knowable());
        assert_eq!(summary_state(&[zero]), SummaryState::Complete);
    }

    #[test]
    fn ordered_policy_versions_dedups_preserving_first_seen_order() {
        let mut a = contribution(AssociationKind::Milestone, ReferenceResolution::Resolved);
        a.policy_version = Some("health-v1".to_string());
        let mut b = contribution(AssociationKind::Milestone, ReferenceResolution::Resolved);
        b.policy_version = Some("health-v1".to_string());
        let versions = ordered_policy_versions(&[a, b]);
        assert_eq!(versions, vec!["health-v1".to_string()]);
    }

    #[test]
    fn scope_spelling_is_stable_per_kind() {
        assert_eq!(
            scope_of(AssociationKind::Project, "p-1").as_str(),
            "project:p-1"
        );
        assert_eq!(scope_of(AssociationKind::Epic, "e-1").as_str(), "epic:e-1");
        assert_eq!(
            scope_of(AssociationKind::Milestone, "m1").as_str(),
            "milestone:m1"
        );
    }
}