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
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
use crate::commands::link;
use crate::commands::parse_selector;
use crate::config::ProjectId;
use crate::error::Result;
use crate::model::Issue;
use crate::projects::{ProjectHealthReport, ProjectIndex};
use crate::relationships::IssueView;
use crate::relationships::RelationshipGraph;
use crate::storage::Store;
use std::collections::{BTreeMap, HashSet};

/// The WP04 adapter for project health.
///
/// [`crate::projects::HealthNode`] is a WP04-local trait, and `src/projects.rs`
/// stays free of the issue model (its module contract). WP03 owns
/// `src/model.rs`, which this WP may not edit, so the one impl for the real record
/// lives here, in the work package's authoritative surface.
impl crate::projects::HealthNode for Issue {
    fn assignee(&self) -> Option<&str> {
        self.assignee.as_deref()
    }
}

/// `tix view <issue>`: print the full issue (frontmatter + `---` + body)
/// verbatim to stdout. No trailing newline beyond what the issue file
/// contains.
///
/// `--show relationships` appends the service-derived block: every relationship
/// touching this issue, its transitive chain, and its blocked reason. It is
/// behind a flag because the default output is the **file**, and
/// `tix view <n> > copy.md` is a thing people do. Appending derived state
/// unconditionally would make the output no longer a valid issue file, which
/// would trade a readability feature for a round-trip regression.
pub fn run(store: &Store, raw: &str, show: Option<&str>) -> Result<()> {
    // Validate `--show` **before** anything is printed.
    //
    // The order matters for the stdout contract. Printing first and validating
    // second means `tix view 0 --show bogus` writes the whole issue file to
    // stdout and *then* exits non-zero โ€” so a consumer that redirects stdout has
    // a file that looks complete and a status code that says it failed, and
    // cannot tell which to believe. A rejected invocation must produce no output.
    let want_relationships = link::wants_relationships(show)?;
    let issue = get(store, raw)?;
    print!("{}", issue.to_file_contents());
    // The hierarchy block is **unconditional** โ€” `contracts/cli-surface.md` ยง2 says
    // "detail includes a parent block and, for a parent, its rollup", with no flag
    // in the spelling, unlike the relationships block beside it. A parent is
    // structural rather than extra detail, and behind a flag `tix show` on a child
    // would silently omit the one fact that explains why it is a child.
    //
    // Every figure comes from the shared `HierarchyFacts`, so this block and
    // `tix parent show` cannot describe different snapshots (parity contract ยง2).
    {
        let (index, issues, done_column) = crate::commands::parent::source(store)?;
        let facts = crate::commands::parent::facts_for(&index, &issues, issue.number, &done_column);
        print!("{}", crate::commands::parent::detail_block(&facts));
    }
    // The category block, **unconditional**, for the same reason the hierarchy
    // block is: `contracts/cli-surface.md` ยง2 puts the category in the detail view
    // with no flag, and the category is the answer to "what stage is this in?",
    // which a status column alone does not give on a board whose columns and
    // categories differ.
    //
    // Appended *after* the hierarchy block and before relationships, so the file
    // comes first, then the structural facts, then the extra detail โ€” the order a
    // reader scans them in.
    {
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        print!("{}", category_block(&issue, &resolution));
    }
    // The project block, **unconditional** (`contracts/cli-surface.md` ยง4: detail
    // includes the issue's project references and their health context, with no
    // flag in the spelling). It renders nothing at all for an issue in no project.
    print!("{}", projects_block(store, &issue)?);
    // The epic block, **unconditional**, for the same reason the project block is:
    // `contracts/cli-surface.md` ยง3 puts the issue's epic references and their
    // progress context in the detail view with no flag in the spelling. It renders
    // nothing at all for an issue in no epic (T017 step 5).
    print!("{}", epics_block(store, &issue)?);
    // The mentions block (OpenSpec change `issue-mentions`, task 6.1): the pending
    // mentions for the **local user** on this issue, so `tix view` surfaces a mention
    // the way the TUI's notice does. Not behind a flag, for the reason the hierarchy
    // and category blocks are not: a mention addressed to you is the one fact that
    // explains why the issue is on your plate. It renders nothing at all when there are
    // none, so `tix view <n> > copy.md` is unchanged for an unmentioned issue.
    print!("{}", mentions_block(store, &issue)?);
    if want_relationships {
        // One graph for all three derived reads, so the relationships, the
        // chain, and the blocked reason cannot describe different snapshots.
        let (issues, done_column) = store.graph_source()?;
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        print!("{}", link::derived_block(&graph, issue.number));
    }
    Ok(())
}

/// The mentions block appended to `tix view`'s output (OpenSpec change
/// `issue-mentions`).
///
/// Empty when the feature is off, when the local user's git identity is unknown, or when
/// the issue carries no unread mention for them โ€” the three cases in which there is
/// nothing to say. Otherwise one row per mention, naming the id that `tix mentions read`
/// takes, so the block is actionable rather than merely informative.
pub fn mentions_block(store: &Store, issue: &Issue) -> Result<String> {
    let Some(mentions) = store.mention_store() else {
        return Ok(String::new());
    };
    let pending =
        mentions.pending_for_issue(&crate::mentions::identity::local_candidates(), issue.number);
    if pending.is_empty() {
        return Ok(String::new());
    }
    let mut out = String::new();
    let _ = std::fmt::Write::write_fmt(
        &mut out,
        format_args!("\nMentions for you ({}):\n\n", pending.len()),
    );
    for mention in &pending {
        let _ = std::fmt::Write::write_fmt(
            &mut out,
            format_args!("  {}  {}\n", mention.id, mention.context),
        );
    }
    let _ = std::fmt::Write::write_fmt(
        &mut out,
        format_args!("\n  act with: tix mentions read <id> | ignore <id> | jump <id>\n"),
    );
    Ok(out)
}

/// The derived category block appended to `tix show`'s output (WP08 T036).
///
/// Two lines, and the second is the one that matters:
///
/// - `category: <key> (<label>)` โ€” the **key** because a script wants a stable
///   word, the **label** because a human reads it. The list column shows the label
///   only (`--show category` is a narrow column); the detail view has room for
///   both, and `t035_the_category_label_is_identical_on_every_path` pins the label
///   to the same string both render.
/// - `workflow: <what this category means>` โ€” `complete`, `terminal, not complete`,
///   or `in progress`. T036 step 2 asks for the completion context precisely so a
///   reader cannot conclude from a `canceled` issue that the work was finished:
///   `canceled` is terminal and is **not** complete, and a detail view that said
///   only `Canceled` would leave that to be guessed.
///
/// The label comes from the service's `label()`, never from a local string, and
/// the *unmapped* case is spelled the way the list column spells it (`(unmapped)`)
/// rather than blanked or turned into an error โ€” T036 step 3.
pub fn category_block(issue: &Issue, resolution: &crate::workflow::CategoryResolution) -> String {
    let (key, label, meaning) = match crate::workflow::category_of(issue, resolution) {
        Some(c) => {
            let meaning = if c.is_complete() {
                "complete"
            } else if c.is_terminal() {
                "terminal, not complete"
            } else {
                "in progress"
            };
            (c.key(), c.label(), meaning)
        }
        None => (
            "(unmapped)",
            "(unmapped)",
            "unmapped column: this board configures no category for it",
        ),
    };
    format!("\n## Workflow\n\n- category: {key} ({label})\n- workflow: {meaning}\n")
}

/// The typed project health values for one snapshot (WP04 T015/T016, C-006).
///
/// One [`ProjectIndex`] build and one health read per project, so every surface
/// reads the same value for the same snapshot and no figure is computed twice. The
/// consumed inputs are gathered here from the **existing** reads โ€” the planning
/// overdue read and the relationship graph's blocked state โ€” and are never
/// recomputed (research R4); `src/projects.rs` owns counting them.
///
/// `pub(crate)` because `tix list --show progress` reads the same value for the
/// same snapshot, which is what makes the two surfaces agree by construction rather
/// than by convention.
pub(crate) fn project_reports(
    store: &Store,
    issues: &[Issue],
) -> Result<(ProjectIndex, BTreeMap<ProjectId, ProjectHealthReport>)> {
    let index = ProjectIndex::build(&store.config, issues);
    let assigned = crate::projects::assigned_keys(issues);
    let planner =
        crate::planning::Planner::from_config(store.config.clone(), std::path::PathBuf::new());
    let overdue: HashSet<u32> = planner
        .overdue_batch(store, &crate::model::today())
        .iter()
        .map(|issue| issue.number)
        .collect();
    let blocked = blocked_keys(store)?;
    let mut reports = BTreeMap::new();
    for project in index.projects() {
        let report = index.health(
            &store.config,
            project.id.as_str(),
            &assigned,
            &overdue,
            &blocked,
        )?;
        reports.insert(project.id.clone(), report);
    }
    Ok((index, reports))
}

/// The blocked issue numbers of the snapshot, from the relationship service.
///
/// The derivation lives in `RelationshipGraph::blocked_state` and is **consumed**
/// here, never reimplemented (research R4).
fn blocked_keys(store: &Store) -> Result<HashSet<u32>> {
    let (issues, done_column) = store.graph_source()?;
    let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
    let graph = RelationshipGraph::new(&views, &done_column);
    Ok(issues
        .iter()
        .filter(|issue| graph.blocked_state(issue.number).is_blocked)
        .map(|issue| issue.number)
        .collect())
}

/// The shared rendering of one project's figures, so the detail block and the
/// list column cannot word the same value differently (T019's cross-surface rule).
pub(crate) fn health_suffix(report: &ProjectHealthReport) -> String {
    format!(
        " done, overdue {}, blocked {}, unassigned {}",
        report.health.overdue, report.health.blocked, report.health.unassigned
    )
}

/// One referenced epic as presentation rows (WP04 T017/T019, FR-003).
///
/// The **content** every surface renders: a heading that carries the epic's id and
/// name, then one context line per fact. `tix show` and the TUI detail pane render
/// these strings verbatim (the pane adds its own styling), so the two cannot word
/// the same epic differently โ€” `contracts/surface-parity.md` ยง2 permits a different
/// *look*, never different *content*.
///
/// Every figure is a field of the service's [`crate::epics::EpicRollup`]; nothing
/// here is recomputed (C-008).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicBlockEntry {
    /// `Name (id)` for a resolved epic, or `<id> (missing reference)`.
    pub heading: String,
    /// The context lines, in one canonical order.
    pub detail: Vec<String>,
}

/// One referenced epic, as the service resolved it for one issue (WP04 T017/T019).
///
/// The **single** resolution path every presentation surface reads: `tix show` and
/// the TUI detail pane render [`epic_block_entry`] of each item, and `tix list`
/// renders [`epic_cell`]. One definition, so a surface cannot resolve a reference a
/// second way (C-002) and a missing reference cannot be dropped on one path but
/// diagnosed on another (C-005).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum EpicRefItem {
    /// A reference the registry resolves: the service's own rollup and hierarchy.
    Resolved(
        Box<crate::epics::EpicRollup>,
        Box<crate::epics::EpicHierarchy>,
    ),
    /// A reference that does not resolve, with the service's recorded reason.
    Missing { id: String, reason: String },
}

/// The compact completion figure, read straight from the service's typed value.
pub(crate) fn progress_figure(progress: &crate::epics::EpicProgress) -> String {
    format!("{}/{} done", progress.done, progress.total)
}

/// The compact weight-aware figure, read straight from the service's typed value.
pub(crate) fn weighted_figure(weighted: &crate::epics::WeightedProgress) -> String {
    match weighted.percent {
        Some(percent) => format!(
            "{}/{} ({percent}%)",
            weighted.done_weight, weighted.total_weight
        ),
        None => "none (no weighted children)".to_string(),
    }
}

/// Resolve one issue's epic references against a pre-built snapshot (C-008).
///
/// The index, the targets and the graph are built **once** per snapshot by the
/// callers below, so a listing resolves every row against one read (contract ยง7).
/// The order is the issue's own recorded order, with duplicates collapsed exactly as
/// the service buckets them (T007 step 7).
///
/// A reference that does not resolve carries the index's own recorded reason
/// ([`crate::epics::EpicIndex::missing`]): this function never decides *why* a
/// reference failed, the service already did. The fallback wording copies the
/// service's functions for the one case the index cannot see โ€” an archived issue,
/// which `graph_source` excludes from its snapshot.
pub(crate) fn epic_ref_items(
    config: &crate::config::Config,
    index: &crate::epics::EpicIndex,
    targets: &crate::epics::ReferenceTargets,
    graph: &RelationshipGraph<'_>,
    issue: &Issue,
) -> Result<Vec<EpicRefItem>> {
    let Some(ids) = issue.epics.as_ref().filter(|ids| !ids.is_empty()) else {
        return Ok(Vec::new());
    };
    let holder = crate::epics::ReferenceHolder::Issue(crate::epics::IssueKey::new(issue.number));
    let mut out = Vec::new();
    let mut seen: Vec<&str> = Vec::new();
    for raw in ids {
        if seen.contains(&raw.as_str()) {
            continue;
        }
        seen.push(raw.as_str());
        let resolved = crate::config::EpicId::new(raw)
            .ok()
            .filter(|id| index.epic(id).is_some());
        match resolved {
            Some(id) => {
                let rollup = index
                    .rollup(config, id.as_str(), targets, graph)
                    .map_err(|err| crate::error::TixError::InvalidInput(err.message()))?;
                let hierarchy = index
                    .hierarchy(id.as_str())
                    .map_err(|err| crate::error::TixError::InvalidInput(err.message()))?;
                out.push(EpicRefItem::Resolved(Box::new(rollup), Box::new(hierarchy)));
            }
            None => {
                let reason = index
                    .missing()
                    .iter()
                    .find(|missing| missing.holder == holder && missing.target == raw.as_str())
                    .map(|missing| missing.reason.clone())
                    .unwrap_or_else(|| {
                        if crate::config::EpicId::new(raw).is_ok() {
                            crate::epics::missing_epic_reason(&holder, raw)
                        } else {
                            crate::epics::malformed_epic_reason(issue.number, raw)
                        }
                    });
                out.push(EpicRefItem::Missing {
                    id: raw.clone(),
                    reason,
                });
            }
        }
    }
    Ok(out)
}

/// The presentation rows for one item โ€” the canonical content every surface renders.
fn epic_block_entry(item: &EpicRefItem) -> EpicBlockEntry {
    match item {
        EpicRefItem::Missing { id, reason } => EpicBlockEntry {
            heading: format!("{id} (missing reference)"),
            detail: vec![reason.clone()],
        },
        EpicRefItem::Resolved(rollup, hierarchy) => resolved_entry(rollup, hierarchy),
    }
}

/// The canonical rows for a resolved epic, from the service's own two values.
///
/// The one place the order and the wording are decided, so the issue detail block, the
/// list cell and the TUI epic view cannot reword the same epic.
fn resolved_entry(
    rollup: &crate::epics::EpicRollup,
    hierarchy: &crate::epics::EpicHierarchy,
) -> EpicBlockEntry {
    let mut detail = vec![
        format!("progress: {}", progress_figure(&rollup.progress)),
        format!(
            "weighted progress: {}",
            weighted_figure(&rollup.weighted_progress)
        ),
        format!(
            "weight: {}",
            rollup
                .weighted_progress
                .own_weight
                .map_or_else(|| "unset".to_string(), |weight| weight.to_string())
        ),
        format!("children: {}", rollup.child_count),
        match (&hierarchy.parent, &hierarchy.unresolved) {
            (Some(parent), _) => format!("parent: {}", parent.display),
            (None, Some(unresolved)) => format!(
                "parent: {} (missing reference: {})",
                unresolved.recorded_parent, unresolved.reason
            ),
            (None, None) => "parent: (none)".to_string(),
        },
        format!("depth: {}", hierarchy.depth),
        format!("blocked: {}", rollup.blocked),
    ];
    for member in &rollup.blocked_members {
        detail.push(format!("  {}: {}", member.display, member.reason));
    }
    for missing in &rollup.missing_references {
        detail.push(format!(
            "missing {} reference: {}",
            missing.target_kind.as_str(),
            missing.reason
        ));
    }
    EpicBlockEntry {
        heading: crate::epics::epic_display(&rollup.epic_id, &rollup.name),
        detail,
    }
}

/// The compact list cell for one item (WP04 T018, C-008).
pub(crate) fn epic_cell(item: &EpicRefItem) -> String {
    match item {
        EpicRefItem::Missing { id, .. } => format!("{id} (missing reference)"),
        EpicRefItem::Resolved(rollup, _) => format!(
            "{} {}, weighted {}, blocked {}",
            crate::epics::epic_display(&rollup.epic_id, &rollup.name),
            progress_figure(&rollup.progress),
            weighted_figure(&rollup.weighted_progress),
            rollup.blocked,
        ),
    }
}

/// [`epic_entries`], over a snapshot the caller already holds (WP04 T019, C-008).
///
/// `App::detail_state_for` already has the board snapshot in hand for the graph and
/// the hierarchy rows, so re-reading it here would be a third full directory walk for
/// one pane open. `snapshot` and `done_column` are exactly what
/// [`crate::storage::Store::graph_source`] returns, so the two entry points resolve the
/// same values.
pub(crate) fn epic_entries_over(
    config: &crate::config::Config,
    snapshot: &[Issue],
    done_column: &str,
    issue: &Issue,
) -> Result<Vec<EpicBlockEntry>> {
    let index = crate::epics::EpicIndex::build(config, snapshot);
    let planner = crate::planning::Planner::from_config(config.clone(), std::path::PathBuf::new());
    let targets = crate::epics::ReferenceTargets::from_planner(&planner)?;
    let graph = crate::commands::graph_over(snapshot, done_column);
    let items = epic_ref_items(config, &index, &targets, &graph, issue)?;
    Ok(items.iter().map(epic_block_entry).collect())
}

/// The issue's referenced epics as presentation rows (WP04 T017/T019, FR-003).
///
/// One service read per epic, from the **one** [`crate::epics::EpicIndex`] built
/// over the snapshot, so `tix show` and the TUI detail pane read the same values for
/// the same snapshot.
pub fn epic_entries(store: &Store, issue: &Issue) -> Result<Vec<EpicBlockEntry>> {
    // One snapshot for the index and the graph, so a member's blocked state and the
    // epic's membership cannot describe different reads of the same board.
    let (issues, done_column) = store.graph_source()?;
    epic_entries_over(&store.config, &issues, &done_column, issue)
}

/// Every issue's epic cell, read from the service in one pass (WP04 T018, FR-003).
///
/// The same snapshot shape [`epic_entries`] reads for one issue: the index, the
/// targets and the graph are built once for the whole listing, and each row's cell is
/// the shared [`epic_cell`] of the items [`epic_ref_items`] resolved โ€” so a row can
/// never report a figure that disagrees with `tix show` for the same snapshot
/// (C-008). An issue in no epic has no entry (rendered `-`), and a reference that no
/// longer resolves renders its recorded id and `(missing reference)`, so the two
/// empty-looking cases stay distinguishable.
pub(crate) fn epic_cells(store: &Store, rows: &[Issue]) -> Result<BTreeMap<u32, String>> {
    // The figures are read from the **full** snapshot, not from the listed slice: an
    // epic's progress is a property of the epic, and a `--status`/`--filter`
    // narrowing must not silently reduce it (the rule `project_cells` follows).
    let (snapshot, done_column) = store.graph_source()?;
    let index = crate::epics::EpicIndex::build(&store.config, &snapshot);
    let planner =
        crate::planning::Planner::from_config(store.config.clone(), std::path::PathBuf::new());
    let targets = crate::epics::ReferenceTargets::from_planner(&planner)?;
    let graph = crate::commands::graph_over(&snapshot, &done_column);
    let mut out = BTreeMap::new();
    for issue in rows {
        let items = epic_ref_items(&store.config, &index, &targets, &graph, issue)?;
        if items.is_empty() {
            continue;
        }
        out.insert(
            issue.number,
            items.iter().map(epic_cell).collect::<Vec<_>>().join("; "),
        );
    }
    Ok(out)
}

/// One member of an epic, for the TUI epic view's direct issue navigation (FR-004).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicMemberRef {
    /// The member issue's number, the selector a surface opens it by.
    pub number: u32,
    /// `#<number> <title>`, the service's display label.
    pub display: String,
}

/// One epic as the TUI epic view presents it (WP04 T020, FR-003).
///
/// `epic` is the **same** canonical row `tix show` and the detail pane render, so the
/// three surfaces cannot disagree about one epic's figures (C-008); `members` is the
/// derived membership the service returned, so a member's issue opens directly
/// without the epic layer (FR-004).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicViewEntry {
    /// Heading and context lines, from [`resolved_entry`].
    pub epic: EpicBlockEntry,
    /// The epic's members, in the service's order.
    pub members: Vec<EpicMemberRef>,
}

/// Every epic, with its context lines and its member list (WP04 T020, FR-003/FR-004).
///
/// Built in **declaration order** (the service's [`crate::epics::EpicIndex::epics`]),
/// from one index over one snapshot, so the view's order is deterministic and its
/// figures equal `tix show`'s for the same snapshot. A task-labelled member is a member
/// like any other: the renderer has no task section, because there is no task entity
/// (C-001).
pub fn epic_view(store: &Store) -> Result<Vec<EpicViewEntry>> {
    // The **active** issue set: `graph_source` is `Store::list`, which excludes
    // archived issues. A surface that mirrors `tix epic list` / `tix epic show`
    // (which read `Store::list_all`) must call [`epic_view_over`] with that set
    // instead, or an archived member's count and list would disagree with the CLI.
    let (snapshot, done_column) = store.graph_source()?;
    epic_view_over(&store.config, &snapshot, &done_column)
}

/// [`epic_view`] over a snapshot the caller already holds (WP06).
///
/// Same derivation, same order, same content โ€” the epic index, the targets, the
/// graph and every entry are built from the `issues` and `done_column` handed in, so
/// a caller that mirrors a CLI listing can pass the **same** set that listing reads
/// (`Store::list_all`, archived issues included) and the two cannot disagree about a
/// member count or a member list (C-008). `epic_view` is the `graph_source`
/// (active-only) shorthand for callers with no such constraint.
pub fn epic_view_over(
    config: &crate::config::Config,
    issues: &[Issue],
    done_column: &str,
) -> Result<Vec<EpicViewEntry>> {
    let index = crate::epics::EpicIndex::build(config, issues);
    let planner = crate::planning::Planner::from_config(config.clone(), std::path::PathBuf::new());
    let targets = crate::epics::ReferenceTargets::from_planner(&planner)?;
    let graph = crate::commands::graph_over(issues, done_column);
    let mut out = Vec::new();
    for epic in index.epics() {
        let id = epic.id.clone();
        let rollup = index
            .rollup(config, id.as_str(), &targets, &graph)
            .map_err(|err| crate::error::TixError::InvalidInput(err.message()))?;
        let hierarchy = index
            .hierarchy(id.as_str())
            .map_err(|err| crate::error::TixError::InvalidInput(err.message()))?;
        let members = epic
            .members
            .iter()
            .map(|member| EpicMemberRef {
                number: member.issue.number(),
                display: member.display.clone(),
            })
            .collect();
        out.push(EpicViewEntry {
            epic: resolved_entry(&rollup, &hierarchy),
            members,
        });
    }
    Ok(out)
}

/// The epic block appended to `tix show`'s output (WP04 T017, FR-003, C-005).
///
/// One line per referenced epic, carrying the **id**, the name, and the rollup
/// context. Every figure comes from the service's typed value ([`epic_entries`]) and
/// none is recomputed here (C-008). A reference that no longer resolves is rendered
/// explicitly with the recorded id and the service's reason rather than silently
/// dropped (C-005).
///
/// The heading appears **only** when the issue carries at least one reference: an
/// issue in no epic renders nothing at all, not an empty heading.
pub fn epics_block(store: &Store, issue: &Issue) -> Result<String> {
    let entries = epic_entries(store, issue)?;
    if entries.is_empty() {
        return Ok(String::new());
    }
    let mut out = String::from("\n## Epics\n\n");
    for entry in entries {
        out.push_str(&format!("- {}\n", entry.heading));
        for line in entry.detail {
            out.push_str(&format!("  - {line}\n"));
        }
    }
    Ok(out)
}

/// The project block appended to `tix show`'s output (WP04 T017, C-005).
///
/// One line per association, carrying the **id**, the name, and the health context.
/// Every figure comes from the service's typed value ([`project_reports`]) and none
/// is recomputed here (C-006). An association that no longer resolves is rendered
/// explicitly with the recorded id and the service's reason rather than silently
/// dropped (C-005).
///
/// The heading appears **only** when the issue carries at least one association: an
/// issue in no project renders nothing at all, not an empty heading.
pub fn projects_block(store: &Store, issue: &Issue) -> Result<String> {
    let Some(ids) = issue.projects.as_ref().filter(|ids| !ids.is_empty()) else {
        return Ok(String::new());
    };
    let issues = store.list()?;
    let (_index, reports) = project_reports(store, &issues)?;
    let mut out = String::from("\n## Projects\n\n");
    let mut seen: Vec<&str> = Vec::new();
    for raw in ids {
        if seen.contains(&raw.as_str()) {
            continue;
        }
        seen.push(raw.as_str());
        match ProjectId::new(raw).ok().and_then(|id| reports.get(&id)) {
            Some(report) => out.push_str(&format!(
                "- {} {}/{}{}\n",
                crate::projects::project_display(&report.project_id, &report.name),
                report.progress.done,
                report.progress.total,
                health_suffix(report),
            )),
            None => out.push_str(&format!(
                "- {raw} (missing reference): {}\n",
                crate::projects::missing_reference_reason(issue.number, raw)
            )),
        }
    }
    Ok(out)
}

/// The view core (WP03): resolve `<issue>` and load the [`Issue`] record.
///
/// This is what MCP's `get_issue` tool (WP04) calls. Side-effect policy
/// (C-005): the core never reads `stdin`/writes `stdout`; the CLI printer in
/// [`run`] renders the record. Selector resolution and ambiguity handling
/// reuse `commands/mod.rs` unchanged (Directive 024).
pub fn get(store: &Store, raw: &str) -> Result<Issue> {
    let selector = parse_selector(store, raw)?;
    store.get(selector)
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::model::{Issue, Priority, Status};
    use std::fs;
    use tempfile::TempDir;

    fn make_store() -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(dir.join("alice")).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        config.save(&config_path).unwrap();
        let config = crate::config::Config::load_with_warning(&config_path, |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    fn seed(store: &Store, number: u32, title: &str) -> Issue {
        let mut issue = Issue {
            projects: None,
            id: None,
            number,
            title: title.to_string(),
            status: Status::new("todo"),
            labels: vec![],
            priority: Priority::default(),
            assignee: Some("alice".to_string()),
            estimate: None,
            commit: None,
            gitlab_id: None,
            linear_id: None,
            mission: None,
            task: None,
            relationships: vec![],
            related_issues: vec![],
            files: vec![],
            cycles: None,
            milestones: None,
            reviewer: None,
            start_date: None,
            due_date: None,
            created: "2026-01-01".to_string(),
            type_: None,
            updated: "2026-01-01".to_string(),
            filename: String::new(),
            body: "the body".to_string(),
            history: crate::model::History::new(),
            has_retired_links_key: false,
            time_entries: vec![],
            parent: None,
            series: None,
            health: None,
            epics: None,
            extra_frontmatter: std::collections::BTreeMap::new(),
            archived: false,
            entered_at: None,
            source: None,
        };
        issue.filename = format!("alice/2026-01-01-{}.md", crate::slug::slugify(title));
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();
        issue
    }

    #[test]
    fn get_returns_the_full_record() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let seeded = seed(&store, 1, "Get me");
        let issue = get(&store, &seeded.number.to_string()).unwrap();
        assert_eq!(issue.title, "Get me");
        assert_eq!(issue.body, "the body");
    }

    #[test]
    fn get_selector_miss_is_not_found() {
        let (tmp, store) = make_store();
        let _ = tmp;
        let err = get(&store, "999").unwrap_err();
        assert!(
            matches!(err, crate::error::TixError::NotFound(_)),
            "missing issue must surface as NotFound, got {err}"
        );
    }

    #[test]
    fn get_ambiguous_selector_is_an_error() {
        let (tmp, store) = make_store();
        let _ = tmp;
        seed(&store, 1, "Shared title");
        seed(&store, 2, "Shared title other");
        // A bare filename fragment matches nothing; a title fragment matching
        // two issues is ambiguous per contracts/cli.md.
        let err = get(&store, "Shared").unwrap_err();
        assert!(
            matches!(err, crate::error::TixError::InvalidInput(_)),
            "ambiguous selector must be an InvalidInput error, got {err}"
        );
    }

    // ---- WP03: `--show relationships` --------------------------------

    #[test]
    fn show_relationships_is_off_by_default_so_the_output_is_still_the_file() {
        // The reason the block is behind a flag: `tix view <n> > copy.md` has to
        // keep producing a valid issue file.
        let (tmp, store) = make_store();
        let _ = tmp;
        let seeded = seed(&store, 1, "Plain");
        let on_disk = fs::read_to_string(store.issues_dir.join(&seeded.filename)).unwrap();
        assert_eq!(
            get(&store, "1").unwrap().to_file_contents(),
            on_disk,
            "precondition: the record round-trips to exactly the file's bytes"
        );
        assert!(!link::wants_relationships(None).unwrap());
    }

    #[test]
    fn the_derived_block_shows_an_edge_stored_on_the_other_endpoint() {
        // The regression `Store::relationships_for` was written to prevent: a
        // relationship is stored **once**, in its canonical source's file, so
        // reading this issue's own `relationships` field would show nothing
        // where the service reports one.
        let (tmp, store) = make_store();
        let _ = tmp;
        let source = seed(&store, 1, "Source");
        let target = seed(&store, 2, "Target");
        store
            .link(
                &source.number.to_string(),
                &target.number.to_string(),
                crate::relationships::RelationKind::Blocks,
            )
            .unwrap();

        // The target's own stored field is empty โ€” the edge lives on the source.
        let target_record = get(&store, "2").unwrap();
        assert!(
            target_record.relationships.is_empty(),
            "precondition: the edge is stored once, on the source"
        );

        let (issues, done_column) = store.graph_source().unwrap();
        let views: Vec<IssueView<'_>> = issues.iter().map(Issue::issue_view).collect();
        let graph = RelationshipGraph::new(&views, &done_column);
        let block = link::derived_block(&graph, target_record.number);

        assert!(
            block.contains("Source"),
            "the target must see the edge that names it:\n{block}"
        );
        assert!(
            block.contains("blocked"),
            "and the blocked reason follows from it:\n{block}"
        );
    }
    // ----------------------------------------------------------------------
    // WP08 T036 โ€” the category in issue detail
    // ----------------------------------------------------------------------

    /// A store on a **mapped** board, so a category exists to render.
    fn mapped_store(columns: &[&str], done_column: &str, map: &[(&str, &str)]) -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(dir.join("alice")).unwrap();
        let config = crate::config::Config {
            issues_dir: dir.clone(),
            kanban: crate::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    crate::config::BoardConfiguration {
                        columns: columns.iter().map(|c| (*c).to_string()).collect(),
                        done_column: Some(done_column.to_string()),
                        category_map: map
                            .iter()
                            .map(|(c, k)| ((*c).to_string(), (*k).to_string()))
                            .collect(),
                        ..Default::default()
                    },
                )]),
            },
            ..crate::config::Config::default()
        };
        config.save(&tmp.path().join("tix.toml")).unwrap();
        let config =
            crate::config::Config::load_with_warning(&tmp.path().join("tix.toml"), |_| {}).unwrap();
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    fn five_categories() -> (TempDir, Store) {
        mapped_store(
            &["triage", "wip", "review", "shipped", "abandoned"],
            "shipped",
            &[
                ("triage", "backlog"),
                ("wip", "active"),
                ("review", "active"),
                ("shipped", "completed"),
                ("abandoned", "canceled"),
            ],
        )
    }

    fn write(store: &Store, number: u32, title: &str, column: &str) {
        let slug = crate::slug::slugify(title);
        fs::write(
            store.issues_dir.join(format!("alice/2026-01-01-{slug}.md")),
            format!(
                "---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"{column}\"\n\
                 labels: []\npriority: \"medium\"\ncreated: \"2026-01-01\"\n\
                 updated: \"2026-01-01\"\n---\n\nbody\n"
            ),
        )
        .unwrap();
    }

    #[test]
    fn t036_the_detail_block_carries_the_key_the_label_and_the_completion_context() {
        let (_tmp, store) = five_categories();
        write(&store, 1, "Shipped", "shipped");
        write(&store, 2, "Abandoned", "abandoned");
        write(&store, 3, "Wip", "wip");
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        for (selector, key, label, meaning) in [
            ("1", "completed", "Done", "complete"),
            ("2", "canceled", "Canceled", "terminal, not complete"),
            ("3", "active", "In progress", "in progress"),
        ] {
            let issue = crate::commands::view::get(&store, selector).unwrap();
            let block = crate::commands::view::category_block(&issue, &resolution);
            assert!(
                block.contains(&format!("- category: {key} ({label})")),
                "{selector}: {block}"
            );
            assert!(
                block.contains(&format!("- workflow: {meaning}")),
                "{selector}: {block}"
            );
        }
    }

    #[test]
    fn t036_a_canceled_issue_never_reads_as_complete() {
        // T036 step 2, the reason the second line exists at all. A detail view
        // saying only `Canceled` leaves a reader to guess whether the work was
        // finished, and this is the C-004 rule made visible.
        let (_tmp, store) = five_categories();
        write(&store, 1, "Abandoned", "abandoned");
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let issue = crate::commands::view::get(&store, "1").unwrap();
        let block = crate::commands::view::category_block(&issue, &resolution);
        assert!(block.contains("terminal, not complete"), "{block}");
        assert!(
            !block.contains("workflow: complete"),
            "a canceled issue must never say complete: {block}"
        );
    }

    #[test]
    fn t036_an_unmapped_column_shows_a_label_not_an_error_and_not_a_blank() {
        // Two distinct cases, and the block must not conflate them.
        //  - configured but unmapped โ†’ the safe default's label
        //  - not configured at all    โ†’ `(unmapped)`, spelled as the list column
        //                                 spells it
        let (_tmp, store) = mapped_store(
            &["triage", "wip", "shipped"],
            "shipped",
            &[("wip", "active"), ("shipped", "completed")],
        );
        write(&store, 1, "Defaulted", "triage");
        write(&store, 2, "Orphan", "not-a-column");
        let (_, resolution) = crate::workflow::active_resolution(&store.config);
        let defaulted = crate::commands::view::get(&store, "1").unwrap();
        let block = crate::commands::view::category_block(&defaulted, &resolution);
        assert!(block.contains("unstarted (Not started)"), "{block}");
        let orphan = crate::commands::view::get(&store, "2").unwrap();
        let block = crate::commands::view::category_block(&orphan, &resolution);
        assert!(
            block.contains("category: (unmapped) ((unmapped))"),
            "{block}"
        );
        assert!(
            block.contains("this board configures no category for it"),
            "an unmapped column is stated, not left blank: {block}"
        );
    }

    // ---- WP04 T017/T019: the project block and cross-surface parity ---------

    /// A store whose registry holds `(id, name)` projects and whose default board
    /// is the shipped one.
    fn project_store(projects: &[(&str, &str)]) -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(dir.join("alice")).unwrap();
        let mut config = crate::config::Config {
            issues_dir: dir.clone(),
            ..crate::config::Config::default()
        };
        for (id, name) in projects {
            config.projects.insert(
                (*id).to_string(),
                crate::config::ProjectConfiguration {
                    name: (*name).to_string(),
                    ..crate::config::ProjectConfiguration::default()
                },
            );
        }
        (
            tmp,
            Store {
                issues_dir: dir,
                config,
            },
        )
    }

    /// The issue with its associations and assignee set, written back to disk.
    fn rewrite(store: &Store, mut issue: Issue, projects: &[&str], assignee: Option<&str>) {
        issue.projects = Some(projects.iter().map(|p| (*p).to_string()).collect());
        issue.assignee = assignee.map(str::to_string);
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();
    }

    #[test]
    fn t017_the_project_block_shows_both_projects_with_id_name_and_health() {
        let (_tmp, store) = project_store(&[("p-a", "Platform"), ("p-b", "Docs")]);
        rewrite(
            &store,
            seed(&store, 1, "Shared"),
            &["p-a", "p-b"],
            Some("alice"),
        );
        let loaded = get(&store, "1").unwrap();
        let block = projects_block(&store, &loaded).unwrap();
        assert!(block.contains("## Projects"), "{block}");
        assert!(
            block.contains("- Platform (p-a) 0/1 done, overdue 0, blocked 0, unassigned 0"),
            "the id, the name, and every figure are rendered: {block}"
        );
        assert!(block.contains("- Docs (p-b) 0/1 done"), "{block}");
    }

    #[test]
    fn t017_an_issue_in_no_project_renders_no_project_heading() {
        let (_tmp, store) = project_store(&[("p-a", "Platform")]);
        seed(&store, 1, "None");
        let loaded = get(&store, "1").unwrap();
        assert_eq!(
            projects_block(&store, &loaded).unwrap(),
            "",
            "an empty association list is the empty state, not an empty heading"
        );
    }

    #[test]
    fn t017_a_missing_reference_is_rendered_with_its_id_and_reason() {
        let (_tmp, store) = project_store(&[("p-a", "Platform")]);
        rewrite(
            &store,
            seed(&store, 1, "Dangling"),
            &["p-a", "p-gone"],
            Some("alice"),
        );
        let loaded = get(&store, "1").unwrap();
        let block = projects_block(&store, &loaded).unwrap();
        assert!(
            block.contains("- p-gone (missing reference):"),
            "a dangling association is named, not dropped: {block}"
        );
        assert!(
            block.contains("not in the registry"),
            "the service's reason is rendered: {block}"
        );
        assert!(
            block.contains("Platform (p-a)"),
            "the resolvable association is still shown: {block}"
        );
    }

    #[test]
    fn t019_c006_show_and_list_report_the_same_figures_for_one_snapshot() {
        // What this proves: the two surfaces agree on the figures for one snapshot,
        // because both read the service's typed value. What it cannot prove: the
        // **absence** of a second computation โ€” a test cannot observe that. The
        // review check for that is recorded in the WP04 report.
        let (_tmp, store) = project_store(&[("p-a", "Platform")]);
        let mut done = seed(&store, 1, "Done");
        done.status = crate::model::Status::new("done");
        rewrite(&store, done, &["p-a"], Some("alice"));
        rewrite(&store, seed(&store, 2, "Open"), &["p-a"], None);

        let loaded = get(&store, "1").unwrap();
        let block = projects_block(&store, &loaded).unwrap();
        let issues = store.list().unwrap();
        let cells = crate::commands::list::project_cells(&store, &issues).unwrap();
        let figure = "1/2 done, overdue 0, blocked 0, unassigned 1";
        assert!(block.contains(figure), "`tix show` must report it: {block}");
        let cell = cells.get(&1).expect("issue #1 belongs to a project");
        assert!(
            cell.contains(figure),
            "`tix list --show progress` must report the same value: {cell}"
        );
    }

    // ---- WP04 T017/T021: the epic block, its parity and its determinism ------

    /// A store with an epic registry `(id, name, weight, parent)` and the default board.
    fn epic_store(epics: &[(&str, &str, Option<i64>, Option<&str>)]) -> (TempDir, Store) {
        let (tmp, mut store) = make_store();
        for (id, name, weight, parent) in epics {
            store.config.epics.insert(
                (*id).to_string(),
                crate::config::EpicConfiguration {
                    name: (*name).to_string(),
                    weight: *weight,
                    parent: parent.map(str::to_string),
                    ..crate::config::EpicConfiguration::default()
                },
            );
        }
        (tmp, store)
    }

    /// Write `issue` back with its epic references set.
    fn with_epics(store: &Store, mut issue: Issue, epics: &[&str]) -> Issue {
        issue.epics = Some(epics.iter().map(|id| (*id).to_string()).collect());
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();
        issue
    }

    /// Write `issue` back with its status set.
    fn with_status(store: &Store, mut issue: Issue, status: &str) -> Issue {
        issue.status = crate::model::Status::new(status);
        fs::write(
            store.issues_dir.join(&issue.filename),
            issue.to_file_contents(),
        )
        .unwrap();
        issue
    }

    #[test]
    fn t017_the_epic_block_shows_both_epics_with_id_name_and_rollup() {
        let (_tmp, store) = epic_store(&[
            ("e-aaa111", "Alpha", None, None),
            ("e-bbb222", "Beta", None, None),
        ]);
        let issue = with_epics(&store, seed(&store, 1, "Shared"), &["e-aaa111", "e-bbb222"]);
        let loaded = get(&store, &issue.number.to_string()).unwrap();
        let block = epics_block(&store, &loaded).unwrap();
        assert!(block.contains("## Epics"), "{block}");
        assert!(
            block.contains("- Alpha (e-aaa111)"),
            "the id and the name render: {block}"
        );
        assert!(block.contains("- Beta (e-bbb222)"), "{block}");
        assert!(
            block.contains("progress: 0/1 done"),
            "the rollup figures render: {block}"
        );
        assert!(block.contains("blocked: 0"), "{block}");
        let alpha = block.find("Alpha").unwrap();
        let beta = block.find("Beta").unwrap();
        assert!(
            alpha < beta,
            "the issue's own reference order is kept: {block}"
        );
    }

    #[test]
    fn t017_an_issue_in_no_epic_renders_no_epic_heading() {
        let (_tmp, store) = epic_store(&[("e-aaa111", "Alpha", None, None)]);
        seed(&store, 1, "None");
        let loaded = get(&store, "1").unwrap();
        assert_eq!(
            epics_block(&store, &loaded).unwrap(),
            "",
            "an empty reference list is the empty state, not an empty heading"
        );
    }

    #[test]
    fn t017_a_missing_epic_reference_is_rendered_with_its_id_and_reason() {
        let (_tmp, store) = epic_store(&[("e-aaa111", "Alpha", None, None)]);
        let issue = with_epics(
            &store,
            seed(&store, 1, "Dangling"),
            &["e-aaa111", "e-gone1", "bad.epic"],
        );
        let loaded = get(&store, &issue.number.to_string()).unwrap();
        let block = epics_block(&store, &loaded).unwrap();
        assert!(
            block.contains("- e-gone1 (missing reference)"),
            "a dangling reference is named, not dropped: {block}"
        );
        assert!(
            block.contains("not in the registry"),
            "the service's reason is rendered: {block}"
        );
        assert!(
            block.contains("- bad.epic (missing reference)"),
            "an entry that is not a well-formed id is named too: {block}"
        );
        assert!(block.contains("not a well-formed epic id"), "{block}");
        assert!(
            block.contains("Alpha (e-aaa111)"),
            "the resolvable reference is still shown: {block}"
        );
    }

    #[test]
    fn t017_a_task_labelled_issue_shows_its_epic_like_any_other() {
        // C-001 in the UI, not only in the model: a `task` label changes nothing about
        // the issue's presence as an epic member, and there is no task section anywhere.
        let (_tmp, store) = epic_store(&[("e-aaa111", "Alpha", None, None)]);
        let mut issue = seed(&store, 1, "A task");
        issue.labels = vec!["task".to_string()];
        let issue = with_epics(&store, issue, &["e-aaa111"]);
        let loaded = get(&store, &issue.number.to_string()).unwrap();
        let block = epics_block(&store, &loaded).unwrap();
        assert!(block.contains("Alpha (e-aaa111)"), "{block}");
        assert!(
            !block.contains("task"),
            "no task heading or task section exists (C-001): {block}"
        );
    }

    /// The fixed parity fixture: Alpha (weight 5) has child Beta (weight 2); #1 (done)
    /// references both, and #2 (todo) references Alpha. Alpha therefore reads `1/2`
    /// members done and `2/2 (100%)` weighted, and Beta is complete.
    fn epic_parity_store() -> (TempDir, Store) {
        let (_tmp, store) = epic_store(&[
            ("e-aaa111", "Alpha", Some(5), None),
            ("e-bbb222", "Beta", Some(2), Some("e-aaa111")),
        ]);
        let one = with_epics(&store, seed(&store, 1, "Done"), &["e-aaa111", "e-bbb222"]);
        with_status(&store, one, "done");
        with_epics(&store, seed(&store, 2, "Open"), &["e-aaa111"]);
        (_tmp, store)
    }

    #[test]
    fn t021_c008_the_epic_figures_are_equal_across_show_list_and_the_tui_paths() {
        // What this proves: the CLI block, the listing cell, the TUI-data rows and the
        // epic view agree on one snapshot's figures, because each reads the one service
        // value. What it **cannot** prove: the *absence* of a second computation, or
        // that the pane is fed correctly โ€” a test cannot observe either. The first is a
        // review check (WP04 report); the second lives in
        // `tests/tui_state.rs::t019_c008_the_detail_pane_reads_its_epic_block_through_the_real_app_builder`,
        // which drives the real `App::open_issue_by_filename` and the real pane.
        let (_tmp, store) = epic_parity_store();
        let loaded = get(&store, "2").unwrap();
        let block = epics_block(&store, &loaded).unwrap();
        let issues = store.list().unwrap();
        let cells = epic_cells(&store, &issues).unwrap();
        let cell = cells.get(&2).expect("#2 references Alpha");
        // `epic_entries` is `epics_block`'s own input, so this leg compares the block
        // against its source, not against a separately-populated pane; it says what it
        // proves (the show/list figures are the service's) and no more.
        let entries = epic_entries(&store, &loaded).unwrap();
        let view = crate::commands::view::epic_view(&store).unwrap();

        // The correctness anchor: the exact figures, so the equality below is not
        // satisfied by rendering the same constant everywhere.
        for text in [block.as_str(), cell.as_str()] {
            assert!(text.contains("1/2 done"), "{text}");
            assert!(text.contains("2/2 (100%)"), "{text}");
        }
        assert_eq!(entries.len(), 1, "issue #2 references exactly Alpha");
        assert_eq!(entries[0].heading, "Alpha (e-aaa111)");
        for line in [
            "progress: 1/2 done",
            "weighted progress: 2/2 (100%)",
            "weight: 5",
            "children: 1",
            "blocked: 0",
        ] {
            assert!(
                entries[0].detail.iter().any(|detail| detail == line),
                "the TUI detail path must carry `{line}`: {:?}",
                entries[0].detail
            );
        }

        // The TUI epic view: declaration order, and the same figures for Alpha.
        assert_eq!(
            view.first().map(|entry| entry.epic.heading.as_str()),
            Some("Alpha (e-aaa111)"),
            "epics render in declaration order"
        );
        let alpha = view
            .iter()
            .find(|entry| entry.epic.heading.starts_with("Alpha"))
            .expect("Alpha is declared");
        for line in ["progress: 1/2 done", "weighted progress: 2/2 (100%)"] {
            assert!(
                alpha.epic.detail.iter().any(|detail| detail == line),
                "the epic view must carry `{line}`: {:?}",
                alpha.epic.detail
            );
        }
        // And the widget renders those canonical lines, so the equality reaches the
        // drawn surface rather than only the data behind it.
        let state = crate::ui::planning::EpicViewState::new();
        let lines = crate::ui::planning::epic_lines(&view, &state, 40);
        let text = lines
            .iter()
            .map(|line| {
                line.spans
                    .iter()
                    .map(|span| span.content.as_ref())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n");
        assert!(text.contains("progress: 1/2 done"), "{text}");
        assert!(text.contains("weighted progress: 2/2 (100%)"), "{text}");
    }

    #[test]
    fn t021_the_epic_figures_are_deterministic_and_stable_under_a_no_op() {
        let (_tmp, store) = epic_parity_store();
        let loaded = get(&store, "2").unwrap();
        let first = epic_entries(&store, &loaded).unwrap();
        let first_cells = epic_cells(&store, &store.list().unwrap()).unwrap();
        let first_view = crate::commands::view::epic_view(&store).unwrap();
        // The correctness anchor: determinism is only meaningful if the value is right,
        // so this is asserted before the loop rather than being implied by it.
        assert!(
            first[0]
                .detail
                .iter()
                .any(|line| line == "progress: 1/2 done")
        );
        assert!(
            first[0]
                .detail
                .iter()
                .any(|line| line == "weighted progress: 2/2 (100%)")
        );

        for _ in 0..3 {
            assert_eq!(epic_entries(&store, &loaded).unwrap(), first);
            assert_eq!(
                epic_cells(&store, &store.list().unwrap()).unwrap(),
                first_cells
            );
            assert_eq!(
                crate::commands::view::epic_view(&store).unwrap(),
                first_view
            );
        }

        // A no-op dereference of an absent reference produces no change and no event
        // (contract ยง5), and leaves every rendered figure untouched.
        let issues = store.list().unwrap();
        let change = crate::epics::dereference_epic(&issues, 2, "e-bbb222").unwrap();
        assert!(change.event.is_none(), "an absent reference is a no-op");
        assert_eq!(
            epic_entries(&store, &loaded).unwrap(),
            first,
            "a no-op must not move a figure"
        );
    }
}