tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
//! `tix epic`: the epic lifecycle and association surface (mission
//! `epics-work-items-01M3BYW4`, WP05; FR-001, FR-002, FR-004, C-003, C-006).
//!
//! This module is a **thin adapter**. Every rule it appears to enforce is one
//! [`crate::epics`] already owns and [`crate::storage`] already applies:
//!
//! | concern | owner | how this module reaches it |
//! |---|---|---|
//! | identity, resolution (id first, name second) | `crate::epics` | [`epics::resolve_epic_id`], [`epics::resolve`] |
//! | lifecycle and validation | `crate::epics` | [`epics::create_epic`], [`epics::edit_epic`], [`epics::delete_epic`] |
//! | hierarchy navigation (parent, children, ancestors, depth) | `crate::epics` | [`epics::hierarchy`] |
//! | membership, child counts, progress, weight, blocked | `crate::epics` | [`epics::list_epics`], [`epics::EpicIndex::rollup`] |
//! | association mutations + History | `crate::storage` | [`Store::reference_epic`], [`Store::dereference_epic`], [`Store::bulk_reference`] |
//! | the wording of a refusal | `crate::epics` | [`EpicError`] rendered through `TixError` |
//!
//! Four properties are deliberate and are the ones a surface loses most easily:
//!
//! - **Every listing shows the id.** [`epics::epic_display`] is the one formatter,
//!   and `list` prints the id and the name in separate columns, so a rename can
//!   never be mistaken for a new epic (C-003).
//! - **Delete never deletes an issue or a child epic.** [`epics::delete_epic`]
//!   removes the registry entry and *reports* the affected issues and child epics;
//!   this module prints that report and adds no cascade and no `--cascade` flag
//!   (C-006).
//! - **Bulk is per-issue.** `add`, `remove` and `bulk-add` report one outcome per
//!   selector, and a rejection on one neither aborts nor rolls back the rest. There
//!   is no bulk-edit engine here: the scope is epic reference only, riding the
//!   existing service seams.
//! - **A task is an ordinary issue.** There is no task entity, file, or frontmatter
//!   key: `--labels task` plus a reference is a label and a reference, nothing more
//!   (C-001), and direct issue navigation stays available from every view.
//!
//! `tix epic` mutates `tix.toml` for its lifecycle verbs, so it is routed by
//! [`crate::cli::run`] — the process boundary that owns the mutable config —
//! exactly as `tix project` and `tix wip` are. The batch verbs return a **status**
//! rather than an error, so a partly-successful batch exits non-zero while every
//! outcome stays reported.

use std::io::IsTerminal;

use crate::cli::{EpicCommand, ExitCode};
use crate::config::{Config, EpicId};
use crate::epics::{
    self, Epic, EpicEdit, EpicHierarchy, EpicRollup, NewEpic, Patch, WeightedProgress,
};
use crate::error::{Result, TixError};
use crate::model::Issue;
use crate::relationships::{IssueView, RelationshipGraph};
use crate::storage::{BulkReferenceOutcome, Store};

/// Run one `tix epic` subcommand.
///
/// Returns an [`ExitCode`] rather than `()` because the batch verbs (`add`,
/// `remove`, `bulk-add`) carry a **status**: each selector is independent, so a
/// run where one selector failed is a completed command reporting non-zero, not an
/// error that discarded the rest.
pub fn run(config: &mut Config, store: &Store, command: &EpicCommand) -> Result<ExitCode> {
    match command {
        EpicCommand::Create {
            name,
            description,
            status,
            owner,
            start_date,
            due_date,
            weight,
            projects,
            milestone,
            cycle,
        } => create(
            config,
            store,
            name,
            description.as_deref(),
            status.as_deref(),
            owner.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
            weight.as_deref(),
            projects.as_deref(),
            milestone.as_deref(),
            cycle.as_deref(),
        ),
        EpicCommand::Edit {
            reference,
            name,
            description,
            status,
            owner,
            start_date,
            due_date,
            weight,
            parent,
            projects,
            milestone,
            cycle,
        } => edit(
            config,
            store,
            reference,
            name.as_deref(),
            description.as_deref(),
            status.as_deref(),
            owner.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
            weight.as_deref(),
            parent.as_deref(),
            projects.as_deref(),
            milestone.as_deref(),
            cycle.as_deref(),
        ),
        EpicCommand::List => list(config, store),
        EpicCommand::Show { reference } => show(config, store, reference),
        EpicCommand::Navigate { reference } => navigate(config, store, reference),
        EpicCommand::Delete { reference, yes } => delete(config, store, reference, *yes),
        // `add` and `bulk-add` are the same operation under two spellings: the
        // single-issue form and the explicitly batch form process every selector
        // independently, and separating their behaviour would give one of them a
        // second set of rules.
        EpicCommand::Add { reference, issues } | EpicCommand::BulkAdd { reference, issues } => {
            reference_from_epic(config, store, reference, issues)
        }
        EpicCommand::Remove { reference, issues } => {
            dereference_from_epic(config, store, reference, issues)
        }
    }
}

// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------

/// Persist the registry after an accepted lifecycle change.
///
/// `Config::validate` runs first, so a change that would make `tix.toml`
/// unloadable is refused before it is written rather than discovered by the next
/// command. The path is the shared [`crate::commands::views::config_path`], so
/// registry writes go through the one atomic-save path rather than a second copy
/// of it.
fn save(config: &mut Config, store: &Store) -> Result<()> {
    config.validate()?;
    let path = crate::commands::views::config_path(store);
    config
        .save(&path)
        .map_err(|error| TixError::Config(format!("could not save `{}`: {error}", path.display())))
}

/// `tix epic create <name> [flags]`.
#[allow(clippy::too_many_arguments)]
fn create(
    config: &mut Config,
    store: &Store,
    name: &str,
    description: Option<&str>,
    status: Option<&str>,
    owner: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
    weight: Option<&str>,
    projects: Option<&str>,
    milestone: Option<&str>,
    cycle: Option<&str>,
) -> Result<ExitCode> {
    let new = NewEpic {
        name: name.to_string(),
        description: description.map(String::from),
        status: status.map(String::from),
        owner: owner.map(String::from),
        start_date: trim_optional(start_date),
        due_date: trim_optional(due_date),
        weight: create_weight(weight)?,
        // Shape only, never resolution: the service validates each id's shape and
        // keeps a dangling-but-well-formed one for repair (C-005).
        projects: projects
            .map(crate::commands::parse_csv_list)
            .unwrap_or_default(),
        milestone: trim_optional(milestone),
        cycle: trim_optional(cycle),
    };
    // The service allocates the id and validates name, dates and weight, so an
    // invalid request refuses here with the registry untouched (nothing to persist).
    let epic = epics::create_epic(config, &new)?;
    save(config, store)?;
    println!("Created {}", epics::epic_display(&epic.id, &epic.name));
    Ok(ExitCode::Success)
}

/// `tix epic edit <id> [--field …]`.
///
/// A `--name` change is a **label change only**: [`epics::edit_epic`] touches the
/// record, never the registry key, so nothing is re-keyed and every reference and
/// derived figure survives (C-003). A `--parent` change is validated by the
/// service's cycle walk before any write (contract §3).
#[allow(clippy::too_many_arguments)]
fn edit(
    config: &mut Config,
    store: &Store,
    reference: &str,
    name: Option<&str>,
    description: Option<&str>,
    status: Option<&str>,
    owner: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
    weight: Option<&str>,
    parent: Option<&str>,
    projects: Option<&str>,
    milestone: Option<&str>,
    cycle: Option<&str>,
) -> Result<ExitCode> {
    let edit = EpicEdit {
        name: name.map_or(Patch::Unchanged, |value| Patch::Set(value.to_string())),
        description: text_patch(description),
        status: text_patch(status),
        owner: text_patch(owner),
        start_date: date_patch(start_date),
        due_date: date_patch(due_date),
        weight: weight_patch(weight)?,
        parent: text_patch(parent),
        // `--projects` on an epic **sets the full list**; an empty value clears it.
        projects: match projects {
            None => Patch::Unchanged,
            Some(value) if value.trim().is_empty() => Patch::Clear,
            Some(value) => Patch::Set(crate::commands::parse_csv_list(value)),
        },
        milestone: text_patch(milestone),
        cycle: text_patch(cycle),
    };
    if edit.name.is_unchanged()
        && edit.description.is_unchanged()
        && edit.status.is_unchanged()
        && edit.owner.is_unchanged()
        && edit.start_date.is_unchanged()
        && edit.due_date.is_unchanged()
        && edit.weight.is_unchanged()
        && edit.parent.is_unchanged()
        && edit.projects.is_unchanged()
        && edit.milestone.is_unchanged()
        && edit.cycle.is_unchanged()
    {
        return Err(epic_edit_requires_a_field());
    }
    let epic = epics::edit_epic(config, reference, &edit)?;
    save(config, store)?;
    println!("Updated {}", epics::epic_display(&epic.id, &epic.name));
    Ok(ExitCode::Success)
}

/// `tix epic list` — declaration order, `id<TAB>name<TAB>members<TAB>children`.
///
/// The id is a column of its own rather than a decoration, because selecting by id
/// is the contract and a listing that hides the id makes a rename look like a new
/// epic (C-003). One tab-separated row per epic is greppable and deterministic.
fn list(config: &Config, store: &Store) -> Result<ExitCode> {
    for line in listing_lines(config, &store.list_all()?) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// One tab-separated row per epic: `id<TAB>name<TAB>member count<TAB>child count`.
///
/// A pure function so the id-alongside-name property (C-003) is assertable without
/// capturing a process's stdout.
pub fn listing_lines(config: &Config, issues: &[Issue]) -> Vec<String> {
    epics::list_epics(config, issues)
        .iter()
        .map(|epic| {
            format!(
                "{}\t{}\t{}\t{}",
                epic.id, epic.name, epic.member_count, epic.child_count
            )
        })
        .collect()
}

/// `tix epic show <id>` — the record, its figures, its hierarchy and its members.
///
/// Every figure is the service's typed value ([`epics::EpicIndex::rollup`]) — one
/// call, no second computation (C-008). A member is printed through the shared
/// `MemberRef` renderer (`#<number> <title>`), so a member never shows a stale
/// title: the label is derived on read and never stored. Ids are shown everywhere,
/// because without them the output is not actionable.
fn show(config: &Config, store: &Store, reference: &str) -> Result<ExitCode> {
    let issues = store.list_all()?;
    let index = epics::EpicIndex::build(config, &issues);
    let epic = index.resolve(reference)?.clone();
    // The graph is built here from the **existing** derived reads (the relationship
    // service owns blocked state), and the targets from the existing planner
    // lookups; this module computes no figure of its own.
    let targets = reference_targets(config, store)?;
    let (graph_issues, done_column) = store.graph_source()?;
    let views: Vec<IssueView<'_>> = graph_issues.iter().map(Issue::issue_view).collect();
    let graph = RelationshipGraph::new(&views, &done_column);
    let rollup = index.rollup(config, reference, &targets, &graph)?;
    for line in record_lines(&epic, Some(&rollup)) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// One `key: value` line per record field, then the derived figures, then one line
/// per child epic and one per member.
///
/// Pure, so the record/member rendering is assertable without capturing stdout. The
/// figure lines are emitted only when the service's rollup is supplied: a caller
/// with no snapshot renders the record alone rather than inventing zeros, the same
/// distinction the `-`-for-absent spelling draws for the optional fields.
pub fn record_lines(epic: &Epic, rollup: Option<&EpicRollup>) -> Vec<String> {
    let mut lines = vec![
        format!("id: {}", epic.id),
        format!("name: {}", epic.name),
        format!(
            "description: {}",
            epic.description.as_deref().unwrap_or("-")
        ),
        format!("status: {}", epic.status.as_deref().unwrap_or("-")),
        format!("owner: {}", epic.owner.as_deref().unwrap_or("-")),
        format!("start-date: {}", epic.start_date.as_deref().unwrap_or("-")),
        format!("due-date: {}", epic.due_date.as_deref().unwrap_or("-")),
        format!(
            "weight: {}",
            epic.weight
                .map_or_else(|| "-".to_string(), |w| w.to_string())
        ),
        format!("parent: {}", epic.parent.as_deref().unwrap_or("-")),
        format!("projects: {}", join_or_dash(&epic.projects)),
        format!("milestone: {}", epic.milestone.as_deref().unwrap_or("-")),
        format!("cycle: {}", epic.cycle.as_deref().unwrap_or("-")),
        format!("children: {}", epic.child_count),
        format!("members: {}", epic.member_count),
    ];
    if let Some(rollup) = rollup {
        lines.push(format!(
            "progress: {}/{}",
            rollup.progress.done, rollup.progress.total
        ));
        lines.push(format!(
            "weighted: {}",
            weighted_summary(&rollup.weighted_progress)
        ));
        lines.push(format!("blocked: {}", rollup.blocked));
        lines.push(format!(
            "missing-references: {}",
            rollup.missing_references.len()
        ));
    }
    lines.extend(
        epic.children
            .iter()
            .map(|child| format!("  child: {}", child.display)),
    );
    lines.extend(
        epic.members
            .iter()
            .map(|member| format!("  {}", member.display)),
    );
    lines
}

/// The one spelling of the weight-aware figure.
fn weighted_summary(weighted: &WeightedProgress) -> String {
    let percent = weighted
        .percent
        .map_or_else(|| "-".to_string(), |p| format!("{p}%"));
    format!(
        "{}/{} ({percent}; {} weighted, {} unweighted child epic(s))",
        weighted.done_weight,
        weighted.total_weight,
        weighted.weighted_children,
        weighted.unweighted_children
    )
}

/// `tix epic navigate <id>` — parent, children, ancestors and depth, parent-first.
///
/// The layout is stable and **parent-first**: the ancestors root-first, then the
/// epic itself, then its children, then its members. The member list is followed by
/// an explicit note that a member is an ordinary issue reachable with `tix show`,
/// so FR-004's "direct issue navigation stays available" is visible rather than
/// merely implied.
fn navigate(config: &Config, store: &Store, reference: &str) -> Result<ExitCode> {
    let issues = store.list_all()?;
    let index = epics::EpicIndex::build(config, &issues);
    let hierarchy = index.hierarchy(reference)?;
    let epic = index.resolve(reference)?.clone();
    for line in navigation_lines(&hierarchy, &epic) {
        println!("{line}");
    }
    Ok(ExitCode::Success)
}

/// The parent-first navigation rendering.
///
/// Pure, so ordering and depth are assertable without capturing stdout. A recorded
/// parent that no longer exists is rendered explicitly (contract §3.4) rather than
/// silently dropped.
pub fn navigation_lines(hierarchy: &EpicHierarchy, epic: &Epic) -> Vec<String> {
    let mut lines = vec!["ancestors:".to_string()];
    if hierarchy.ancestors.is_empty() {
        lines.push("  -".to_string());
    }
    for ancestor in &hierarchy.ancestors {
        lines.push(format!("  {}", ancestor.display));
    }
    match &hierarchy.parent {
        Some(parent) => lines.push(format!("parent: {}", parent.display)),
        None => lines.push("parent: -".to_string()),
    }
    if let Some(unresolved) = &hierarchy.unresolved {
        lines.push(format!("unresolved-parent: {}", unresolved.reason));
    }
    lines.push(format!(
        "epic: {}",
        epics::epic_display(&epic.id, &epic.name)
    ));
    lines.push(format!("depth: {}", hierarchy.depth));
    lines.push(format!("children: {}", hierarchy.child_count));
    for child in &hierarchy.children {
        lines.push(format!("  {}", child.display));
    }
    lines.push(format!("issues: {}", epic.member_count));
    for member in &epic.members {
        lines.push(format!("  {}", member.display));
    }
    lines.push(
        "note: members are ordinary issues; navigate one directly with `tix show <number>`"
            .to_string(),
    );
    lines
}

/// `tix epic delete <id> [--yes]`.
///
/// Removes the registry entry **only**. The affected issues are reported — number
/// and title — and their references are retained as diagnosable missing
/// references, and the child epics keep their recorded parent, which then reads as
/// an unresolved parent. There is no cascade and no `--cascade` flag: deleting an
/// epic must never delete a member issue or a child epic (C-006).
///
/// Confirmation follows [`crate::commands::delete`] and `tix project delete`:
/// `--yes` skips the prompt and a non-TTY stdin deletes immediately, so the command
/// is scriptable and TTY-free.
fn delete(config: &mut Config, store: &Store, reference: &str, yes: bool) -> Result<ExitCode> {
    let issues = store.list_all()?;
    // Resolved before the prompt so an unknown id refuses with nothing written and
    // nothing asked.
    let epic = epics::resolve(config, &issues, reference)?;

    let mut confirmed = yes || !std::io::stdin().is_terminal();
    if !confirmed {
        eprint!(
            "Delete epic '{}'? [y/N] ",
            epics::epic_display(&epic.id, &epic.name)
        );
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .map_err(TixError::Io)?;
        confirmed = line.trim().eq_ignore_ascii_case("y");
        if !confirmed {
            eprintln!("aborted");
        }
    }
    if !confirmed {
        return Ok(ExitCode::Success);
    }

    // The impact notice, printed **before** the deletion so it is on screen
    // alongside the confirmation — the convention `tix delete` follows. `eprint!`
    // because it is a warning about what is about to happen, not data.
    eprint!("{}", impact_notice(&epic));

    let deletion = epics::delete_epic(config, reference, &issues)?;
    save(config, store)?;
    println!(
        "Deleted epic {}",
        epics::epic_display(&deletion.id, &deletion.name)
    );
    Ok(ExitCode::Success)
}

/// The delete-time impact notice, or the empty string when nothing references the
/// epic.
///
/// One `tix epic delete` removes **exactly one registry entry**. The issues that
/// referenced the epic keep their references, and the child epics keep their
/// recorded parent; both read as repairable diagnostics afterwards, which `tix
/// lint` names. Neither is deleted or modified.
pub fn impact_notice(epic: &Epic) -> String {
    let mut out = String::new();
    if !epic.members.is_empty() {
        let count = epic.members.len();
        // The verb and the pronoun agree with the noun, chosen by the same `len()`
        // test: "1 issue still references … It is not deleted" vs "N issues still
        // reference … They are not deleted".
        if count == 1 {
            out.push_str(
                "Note: 1 issue still references this epic and keeps the reference as a missing \
                 epic reference.\nIt is not deleted or modified; `tix lint` reports the dangling \
                 reference until it is repaired.\n",
            );
        } else {
            out.push_str(&format!(
                "Note: {count} issues still reference this epic and keep the reference as a \
                 missing epic reference.\nThey are not deleted or modified; `tix lint` reports \
                 the dangling reference until it is repaired.\n"
            ));
        }
        for member in &epic.members {
            out.push_str(&format!("  {}\n", member.display));
        }
    }
    if !epic.children.is_empty() {
        let count = epic.children.len();
        if count == 1 {
            out.push_str(
                "Note: 1 child epic records this epic as its parent and keeps the reference as \
                 an unresolved parent.\nIt is not deleted or modified.\n",
            );
        } else {
            out.push_str(&format!(
                "Note: {count} child epics record this epic as their parent and keep the \
                 reference as an unresolved parent.\nThey are not deleted or modified.\n"
            ));
        }
        for child in &epic.children {
            out.push_str(&format!("  {}\n", child.display));
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Association from the epic side
// ---------------------------------------------------------------------------

/// `tix epic add|bulk-add <id> <sel…>`.
///
/// Each selector is processed independently through [`Store::bulk_reference`],
/// which is the service-backed batch seam: one rejection is reported beside the
/// rest rather than aborting them, and each accepted change appends exactly one
/// History entry. The epic reference is resolved **once**, up front, so an unknown
/// epic refuses before any write.
fn reference_from_epic(
    config: &Config,
    store: &Store,
    reference: &str,
    selectors: &[String],
) -> Result<ExitCode> {
    let id = epics::resolve_epic_id(&config.epics, reference)?;
    let display = display_for(config, &id);
    let outcomes = store.bulk_reference(id.as_str(), selectors)?;
    report(&display, "referenced", outcomes)
}

/// `tix epic remove <id> <sel…>`.
///
/// Drops only the reference (never the issue). The reference is resolved when it
/// names a live epic and otherwise used **verbatim**, which is the repair path
/// C-005 promises: a stale stored id can still be removed. Each selector is
/// independent.
fn dereference_from_epic(
    config: &Config,
    store: &Store,
    reference: &str,
    selectors: &[String],
) -> Result<ExitCode> {
    // The resolve-or-keep-verbatim rule is the service's one classifier (WP09 item B).
    let needle = epics::dereference_needle(&config.epics, reference);
    let display = match epics::resolve_epic_id(&config.epics, reference) {
        Ok(id) => display_for(config, &id),
        Err(_) => format!("`{reference}`"),
    };
    let mut code = ExitCode::Success;
    let mut changed = 0usize;
    let mut unchanged = 0usize;
    let mut failed = 0usize;
    for selector in selectors {
        match store.dereference_epic(selector, &needle) {
            Ok(applied) if applied.changed => {
                changed += 1;
                println!("dereferenced {selector}");
            }
            Ok(_) => {
                unchanged += 1;
                println!("dereferenced {selector} (was not referenced)");
            }
            Err(error) => {
                failed += 1;
                eprintln!("{}", crate::error::render_error(&error));
                if code == ExitCode::Success {
                    code = crate::cli::exit_code_for(&error);
                }
            }
        }
    }
    println!(
        "dereferenced {changed} of {} issue(s) from {display}{}{}",
        selectors.len(),
        unchanged_note(unchanged),
        failure_note(failed)
    );
    Ok(code)
}

/// Report a batch of reference outcomes: one line per issue, then a summary.
///
/// Successes and idempotent no-ops go to stdout (they are the data the user asked
/// about); a refusal goes to stderr, because a consumer redirecting stdout must not
/// find a diagnostic in it. The returned code is the **first** failure's mapped
/// code, so a partly-successful batch exits non-zero while every outcome stays
/// reported.
fn report(display: &str, verb: &str, outcomes: Vec<BulkReferenceOutcome>) -> Result<ExitCode> {
    let total = outcomes.len();
    let mut code = ExitCode::Success;
    let mut changed = 0usize;
    let mut unchanged = 0usize;
    let mut failed = 0usize;
    for outcome in outcomes {
        match outcome.outcome {
            Ok(applied) if applied.changed => {
                changed += 1;
                println!("{verb} {}", outcome.selector);
            }
            Ok(_) => {
                unchanged += 1;
                println!("{verb} {} (already {verb})", outcome.selector);
            }
            Err(error) => {
                failed += 1;
                eprintln!("{}", crate::error::render_error(&error));
                if code == ExitCode::Success {
                    code = crate::cli::exit_code_for(&error);
                }
            }
        }
    }
    println!(
        "{verb} {changed} of {total} issue(s) with {display}{}{}",
        unchanged_note(unchanged),
        failure_note(failed)
    );
    Ok(code)
}

/// ` (N unchanged)`, or nothing when every outcome changed something.
fn unchanged_note(unchanged: usize) -> String {
    if unchanged == 0 {
        String::new()
    } else {
        format!(" ({unchanged} unchanged)")
    }
}

/// `; N failed`, or nothing when the batch had no failure.
fn failure_note(failed: usize) -> String {
    if failed == 0 {
        String::new()
    } else {
        format!("; {failed} failed")
    }
}

/// The display form for a resolved id: the registry name beside the id.
fn display_for(config: &Config, id: &EpicId) -> String {
    match config.epics.get(id.as_str()) {
        Some(record) => epics::epic_display(id, &record.name),
        None => format!("`{id}`"),
    }
}

// ---------------------------------------------------------------------------
// Shared helpers for the create/edit cores
// ---------------------------------------------------------------------------

/// Resolve and validate a comma-separated `--epics` value, in first-seen order.
///
/// Every reference is resolved through the service **before** the caller writes
/// anything, so an unknown id refuses the whole operation rather than leaving a
/// half-referenced issue. Resolution also collapses duplicates: `e-1,e-1` and
/// `Harden,e-1` both name one epic, and one reference is what gets written.
pub fn resolve_epics(config: &Config, raw: &str) -> Result<Vec<String>> {
    let mut out: Vec<String> = Vec::new();
    for reference in crate::commands::parse_csv_list(raw) {
        let id = epics::resolve_epic_id(&config.epics, &reference)?.to_string();
        if !out.contains(&id) {
            out.push(id);
        }
    }
    Ok(out)
}

/// Reference a freshly created issue from the resolved epic ids.
///
/// One [`Store::reference_epic`] per id, so the History entry and the idempotence
/// rule are the service's, not a second implementation here. The ids were resolved
/// before the issue existed, so a refusal cannot leave a half-referenced create.
pub fn reference_created(store: &Store, issue: &Issue, ids: &[String]) -> Result<()> {
    for id in ids {
        store.reference_epic(&issue.number.to_string(), id)?;
    }
    Ok(())
}

/// The validated reference inputs of one `tix edit`, ready to apply.
///
/// Produced by [`plan_edit_epics`] **before** any write, so a refusal leaves every
/// file byte-identical (T025 step 5).
#[derive(Debug)]
pub struct EpicEditPlan {
    add_ids: Vec<String>,
    remove_ids: Vec<String>,
    clear: bool,
}

/// Resolve the `tix edit` epic-reference inputs without writing anything.
///
/// `clear` is `--epics ""`; an absent flag is an empty plan that changes nothing.
/// An unresolvable `--remove-epic` reference is refused as `unknown_epic` **unless**
/// the issue still carries it verbatim — removing a stale id is the repair path,
/// and refusing it would strand the reference. A `--remove-epic` that resolves to a
/// live epic the issue does not carry is an idempotent no-op, exactly as
/// `--remove-project` is.
pub fn plan_edit_epics(
    config: &Config,
    store: &Store,
    selector: &str,
    add: &[String],
    remove: &[String],
    clear: bool,
) -> Result<EpicEditPlan> {
    let mut add_ids: Vec<String> = Vec::new();
    for reference in add {
        let id = epics::resolve_epic_id(&config.epics, reference)?.to_string();
        if !add_ids.contains(&id) {
            add_ids.push(id);
        }
    }
    let remove_ids: Vec<String> = remove
        .iter()
        .map(|reference| epics::dereference_needle(&config.epics, reference))
        .collect();
    let stored = store.resolve_issue(selector)?.epics.unwrap_or_default();
    for reference in &remove_ids {
        // A reference the registry resolves to a live epic is always acceptable (a
        // no-op if absent). One it does not resolve is only acceptable when the
        // issue still carries it verbatim.
        let known = epics::resolve_epic_id(&config.epics, reference).is_ok();
        if !known && !stored.iter().any(|id| id == reference) {
            return Err(epics::EpicError::UnknownEpic {
                reference: reference.clone(),
            }
            .into());
        }
    }
    Ok(EpicEditPlan {
        add_ids,
        remove_ids,
        clear,
    })
}

/// Apply a validated epic-reference plan through the store, reporting whether
/// anything was actually applied.
///
/// Order is clear → remove → add, so `tix edit <n> --epics "" --add-epic e-1` ends
/// with exactly the added reference. Every mutation goes through
/// [`Store::reference_epic`]/[`Store::dereference_epic`], so `updated` is bumped and
/// the History entry appended in the one place that owns both.
///
/// The `bool` is `true` when at least one mutation changed something, so the
/// caller's success line does not claim a write that never happened.
pub fn apply_edit_epics(store: &Store, selector: &str, plan: &EpicEditPlan) -> Result<bool> {
    let mut changed = false;
    if plan.clear {
        let stored = store.resolve_issue(selector)?.epics.unwrap_or_default();
        for id in &stored {
            changed |= store.dereference_epic(selector, id)?.changed;
        }
    }
    for id in &plan.remove_ids {
        changed |= store.dereference_epic(selector, id)?.changed;
    }
    for id in &plan.add_ids {
        changed |= store.reference_epic(selector, id)?.changed;
    }
    Ok(changed)
}

/// The refusal `tix epic edit` prints when no field flag was given.
fn epic_edit_requires_a_field() -> TixError {
    TixError::InvalidInput(
        "no fields to change; pass at least one of --name, --description, --status, \
         --owner, --start-date, --due-date, --weight, --parent, --projects, \
         --milestone or --cycle"
            .to_string(),
    )
}

/// A blank value clears an optional text field; a written one sets it.
fn text_patch(value: Option<&str>) -> Patch<String> {
    match value {
        None => Patch::Unchanged,
        Some(text) if text.trim().is_empty() => Patch::Clear,
        Some(text) => Patch::Set(text.to_string()),
    }
}

/// A blank value clears a date field; a written one is passed through trimmed.
fn date_patch(value: Option<&str>) -> Patch<String> {
    match value {
        None => Patch::Unchanged,
        Some(text) if text.trim().is_empty() => Patch::Clear,
        Some(text) => Patch::Set(text.trim().to_string()),
    }
}

/// A weight patch: absent keeps it, blank clears it, a written value is parsed.
fn weight_patch(value: Option<&str>) -> Result<Patch<i64>> {
    match value {
        None => Ok(Patch::Unchanged),
        Some(text) if text.trim().is_empty() => Ok(Patch::Clear),
        Some(text) => Ok(Patch::Set(parse_weight(text)?)),
    }
}

/// A create-time weight: absent or blank means unset.
fn create_weight(value: Option<&str>) -> Result<Option<i64>> {
    match value {
        None => Ok(None),
        Some(text) if text.trim().is_empty() => Ok(None),
        Some(text) => Ok(Some(parse_weight(text)?)),
    }
}

/// Parse a `--weight` integer, naming the service's diagnostic kind.
///
/// A non-integer is a command-level parse refusal, so it cannot come from the
/// service; it is worded with the same `invalid_weight` kind so the user sees one
/// name for one problem. The **positivity** rule stays the service's.
fn parse_weight(text: &str) -> Result<i64> {
    text.trim().parse::<i64>().map_err(|_| {
        TixError::InvalidInput(format!(
            "{}: epic weight must be an integer; got `{text}`",
            epics::EpicDiagnosticKind::InvalidWeight
        ))
    })
}

/// A trimmed, non-blank optional string, or `None`.
fn trim_optional(value: Option<&str>) -> Option<String> {
    value
        .map(str::trim)
        .filter(|text| !text.is_empty())
        .map(String::from)
}

/// The elements joined by `, `, or `-` when the list is empty.
fn join_or_dash(values: &[String]) -> String {
    if values.is_empty() {
        "-".to_string()
    } else {
        values.join(", ")
    }
}

/// The reference targets for one snapshot, consumed from their owners.
///
/// The milestone and cycle names come from the existing [`crate::planning::Planner`]
/// lookups and the project ids from the project registry — no second milestone,
/// cycle, or project store (research R2, R6).
fn reference_targets(config: &Config, store: &Store) -> Result<epics::ReferenceTargets> {
    let root = Config::project_root(&store.issues_dir).unwrap_or_else(|| store.issues_dir.clone());
    let planner = crate::planning::Planner::from_config(config.clone(), root);
    epics::ReferenceTargets::from_planner(&planner)
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;
    use crate::config::EpicConfiguration;
    use std::fs;
    use tempfile::TempDir;

    /// A store over a temp dir whose persisted registry declares `epics`, with
    /// `issues` issues (numbers `1..=issues`) titled `Issue N`.
    ///
    /// The registry is written to `tix.toml`, not merely held in memory, so a test
    /// that removes an epic can compare a real registry file before and after.
    fn store_with(epics: &[(&str, &str)], issues: usize) -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let mut config = Config {
            issues_dir: dir.clone(),
            ..Config::default()
        };
        config.layout.directory = "{assignee}".to_string();
        config.layout.move_on_change = false;
        for (id, name) in epics {
            config.epics.insert(
                (*id).to_string(),
                EpicConfiguration {
                    name: (*name).to_string(),
                    ..EpicConfiguration::default()
                },
            );
        }
        config.save(&config_path).unwrap();
        let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
        let store = Store {
            issues_dir: dir.clone(),
            config,
        };
        for number in 1..=issues {
            write_issue(
                &store,
                u32::try_from(number).unwrap(),
                &format!("Issue {number}"),
                &[],
            );
        }
        (tmp, store)
    }

    /// A store whose epic `e-1` records a parent id that is not in the registry.
    fn store_with_unresolved_parent() -> (TempDir, Store) {
        let tmp = TempDir::new().unwrap();
        let dir = tmp.path().join("issues");
        fs::create_dir_all(&dir).unwrap();
        let config_path = tmp.path().join("tix.toml");
        let mut config = Config {
            issues_dir: dir.clone(),
            ..Config::default()
        };
        config.layout.directory = "{assignee}".to_string();
        config.layout.move_on_change = false;
        config.epics.insert(
            "e-1".to_string(),
            EpicConfiguration {
                name: "Orphan".to_string(),
                parent: Some("e-gone".to_string()),
                ..EpicConfiguration::default()
            },
        );
        config.save(&config_path).unwrap();
        let config = Config::load_with_warning(&config_path, |_| {}).unwrap();
        let store = Store {
            issues_dir: dir,
            config,
        };
        (tmp, store)
    }

    /// Write one issue file with an optional `epics` list.
    fn write_issue(store: &Store, number: u32, title: &str, epics: &[&str]) {
        let mut frontmatter =
            format!("---\nnumber: {number}\ntitle: \"{title}\"\nstatus: \"todo\"\nlabels: []\n");
        if !epics.is_empty() {
            frontmatter.push_str("epics:\n");
            for id in epics {
                frontmatter.push_str(&format!("- {id}\n"));
            }
        }
        frontmatter.push_str("---\n");
        fs::write(
            store
                .issues_dir
                .join(format!("2026-01-{number:02}-issue-{number}.md")),
            frontmatter,
        )
        .unwrap();
    }

    /// The registry file's bytes, for a "nothing else changed" assertion.
    fn registry(store: &Store) -> String {
        fs::read_to_string(registry_path(store)).unwrap()
    }

    /// The registry file beside the store's issues dir.
    fn registry_path(store: &Store) -> std::path::PathBuf {
        Config::project_root(&store.issues_dir)
            .unwrap()
            .join("tix.toml")
    }

    fn issue_bytes(store: &Store, number: u32) -> String {
        fs::read_to_string(
            store
                .issues_dir
                .join(format!("2026-01-{number:02}-issue-{number}.md")),
        )
        .unwrap()
    }

    // -- T022 — lifecycle ---------------------------------------------------

    #[test]
    fn the_listing_shows_each_epic_id_and_name_alongside_its_counts() {
        let (_tmp, store) = store_with(&[("e-1", "Harden"), ("e-2", "Docs")], 0);
        // e-2 is a child of e-1, so its child count is derived.
        let mut config = store.config.clone();
        config.epics.get_mut("e-2").unwrap().parent = Some("e-1".to_string());
        let lines = listing_lines(&config, &store.list_all().unwrap());
        assert_eq!(lines[0], "e-1\tHarden\t0\t1");
        assert_eq!(lines[1], "e-2\tDocs\t0\t0");
        // The id is present as a field of its own, not decoration (C-003).
        assert!(lines[0].contains("e-1"));
        assert!(lines[0].contains("Harden"));
    }

    #[test]
    fn create_allocates_an_id_and_refuses_a_duplicate_name() {
        let (_tmp, store) = store_with(&[], 0);
        let mut config = store.config.clone();
        create(
            &mut config,
            &store,
            "Harden",
            None,
            None,
            Some("alice"),
            None,
            None,
            Some("3"),
            Some("p-1"),
            None,
            None,
        )
        .unwrap();
        assert_eq!(config.epics.len(), 1);
        let (id, record) = config.epics.iter().next().unwrap();
        assert_eq!(record.name, "Harden");
        assert_eq!(record.owner.as_deref(), Some("alice"));
        assert_eq!(record.weight, Some(3));
        // A well-formed project id that names nothing is stored, not refused.
        assert_eq!(record.projects, vec!["p-1".to_string()]);
        assert!(id.starts_with("e-"), "an allocated id: {id}");

        // The same name (case-folded) is refused, and the registry is unchanged.
        let before = registry(&store);
        let error = create(
            &mut config,
            &store,
            "harden",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .expect_err("a duplicate name is refused");
        assert!(
            error.to_string().contains("duplicate_name"),
            "the named diagnostic: {error}"
        );
        assert_eq!(config.epics.len(), 1);
        assert_eq!(registry(&store), before, "nothing written");
    }

    #[test]
    fn edit_renames_the_label_and_keeps_the_id() {
        let (_tmp, store) = store_with(&[("e-1", "Harden")], 1);
        write_issue(&store, 1, "Issue 1", &["e-1"]);
        let mut config = store.config.clone();
        edit(
            &mut config,
            &store,
            "e-1",
            Some("Harden the sync path"),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        // The registry key is untouched — nothing is re-keyed (C-003).
        assert!(config.epics.contains_key("e-1"));
        assert_eq!(config.epics["e-1"].name, "Harden the sync path");
        // The reference resolves through the same id after the rename.
        let epic = epics::resolve(&config, &store.list_all().unwrap(), "e-1").unwrap();
        assert_eq!(epic.name, "Harden the sync path");
        assert_eq!(epic.member_count, 1);
    }

    #[test]
    fn edit_refuses_a_self_parent_and_a_cycle_without_writing() {
        let (_tmp, store) = store_with(&[("e-1", "A"), ("e-2", "B")], 0);
        let mut config = store.config.clone();
        // e-2 under e-1 is fine.
        edit(
            &mut config,
            &store,
            "e-2",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("e-1"),
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(config.epics["e-2"].parent.as_deref(), Some("e-1"));

        // Self-parent is refused.
        let before = registry(&store);
        let error = edit(
            &mut config,
            &store,
            "e-1",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("e-1"),
            None,
            None,
            None,
        )
        .expect_err("self-parent");
        assert!(error.to_string().contains("self_parent"), "{error}");

        // Closing the loop (e-1 under e-2) is refused.
        let error = edit(
            &mut config,
            &store,
            "e-1",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            Some("e-2"),
            None,
            None,
            None,
        )
        .expect_err("cycle");
        assert!(error.to_string().contains("cycle"), "{error}");
        assert_eq!(registry(&store), before, "nothing written on a refusal");
    }

    #[test]
    fn edit_with_no_fields_is_a_usage_error() {
        let (_tmp, store) = store_with(&[("e-1", "A")], 0);
        let mut config = store.config.clone();
        let error = edit(
            &mut config,
            &store,
            "e-1",
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .expect_err("a fieldless edit is refused");
        assert!(error.to_string().contains("no fields to change"), "{error}");
    }

    // -- T023 — delete retains issues and child epics -----------------------

    #[test]
    fn delete_removes_only_the_registry_entry_and_reports_members_and_children() {
        let (_tmp, store) = store_with(&[("e-1", "Parent"), ("e-2", "Child")], 1);
        write_issue(&store, 1, "Issue 1", &["e-1"]);
        let mut config = store.config.clone();
        config.epics.get_mut("e-2").unwrap().parent = Some("e-1".to_string());
        // The notice names the member and the child and states nothing is deleted.
        let epic = epics::resolve(&config, &store.list_all().unwrap(), "e-1").unwrap();
        let notice = impact_notice(&epic);
        assert!(
            notice.contains("Issue 1"),
            "the notice names the issue: {notice}"
        );
        assert!(
            notice.contains("Child"),
            "the notice names the child: {notice}"
        );
        assert!(notice.contains("not deleted"));

        let issue_before = issue_bytes(&store, 1);
        delete(&mut config, &store, "e-1", true).unwrap();

        // The registry entry is gone; the child epic survives.
        assert!(!config.epics.contains_key("e-1"));
        assert!(config.epics.contains_key("e-2"));
        assert!(!registry(&store).contains("[epics.e-1]"));
        // The issue is untouched: still present, still carrying its reference.
        assert_eq!(issue_bytes(&store, 1), issue_before);
        assert!(issue_bytes(&store, 1).contains("e-1"));
        // The child keeps its recorded parent (now unresolved, C-006).
        assert_eq!(config.epics["e-2"].parent.as_deref(), Some("e-1"));
    }

    #[test]
    fn delete_refuses_an_unknown_id_and_writes_nothing() {
        let (_tmp, store) = store_with(&[("e-1", "A")], 0);
        let mut config = store.config.clone();
        let before = registry(&store);
        let error = delete(&mut config, &store, "bogus", true).expect_err("unknown id");
        assert!(error.to_string().contains("unknown_epic"), "{error}");
        assert!(config.epics.contains_key("e-1"));
        assert_eq!(registry(&store), before);
    }

    // -- T024/T025 — the shared create/edit inputs ---------------------------

    #[test]
    fn resolve_epics_collapses_duplicates_and_refuses_an_unknown_id() {
        let (_tmp, store) = store_with(&[("e-1", "Harden")], 0);
        let ids = resolve_epics(&store.config, "Harden,e-1").unwrap();
        assert_eq!(
            ids,
            vec!["e-1".to_string()],
            "a name and an id are one epic"
        );
        let error = resolve_epics(&store.config, "e-1,bogus").expect_err("unknown id");
        assert!(error.to_string().contains("unknown_epic"), "{error}");
    }

    #[test]
    fn reference_created_writes_one_entry_per_epic() {
        let (_tmp, store) = store_with(&[("e-1", "A"), ("e-2", "B")], 1);
        let issue = store.resolve_issue("1").unwrap();
        reference_created(&store, &issue, &["e-1".to_string(), "e-2".to_string()]).unwrap();
        let after = store.resolve_issue("1").unwrap();
        assert_eq!(
            after.epics,
            Some(vec!["e-1".to_string(), "e-2".to_string()])
        );
        assert_eq!(after.history.events().len(), 2, "one entry per reference");
    }

    #[test]
    fn a_plan_refuses_an_unknown_remove_reference_that_is_not_stored() {
        let (_tmp, store) = store_with(&[("e-1", "A")], 1);
        let error = plan_edit_epics(
            &store.config,
            &store,
            "1",
            &[],
            &["bogus".to_string()],
            false,
        )
        .expect_err("an unresolvable, unstored reference is a typo");
        assert!(error.to_string().contains("unknown_epic"), "{error}");
    }

    #[test]
    fn a_plan_accepts_removing_a_stale_stored_id() {
        let (_tmp, store) = store_with(&[], 1);
        write_issue(&store, 1, "Issue 1", &["e-gone"]);
        let plan = plan_edit_epics(
            &store.config,
            &store,
            "1",
            &[],
            &["e-gone".to_string()],
            false,
        )
        .unwrap();
        assert!(
            apply_edit_epics(&store, "1", &plan).unwrap(),
            "removing a stored id changed the issue"
        );
        assert_eq!(store.resolve_issue("1").unwrap().epics, None);
    }

    #[test]
    fn clearing_removes_every_reference_and_keeps_the_issue() {
        let (_tmp, store) = store_with(&[("e-1", "A"), ("e-2", "B")], 1);
        write_issue(&store, 1, "Issue 1", &["e-1", "e-2"]);
        let plan = plan_edit_epics(&store.config, &store, "1", &[], &[], true).unwrap();
        assert!(apply_edit_epics(&store, "1", &plan).unwrap());
        let issue = store.resolve_issue("1").unwrap();
        assert_eq!(issue.epics, None);
        assert_eq!(issue.history.events().len(), 2, "one entry per removal");
        assert!(
            store.issues_dir.join(&issue.filename).is_file(),
            "the issue itself is kept"
        );
    }

    #[test]
    fn a_noop_epic_plan_reports_no_change() {
        let (_tmp, store) = store_with(&[("e-1", "A"), ("e-2", "B")], 1);
        write_issue(&store, 1, "Issue 1", &["e-1"]);
        // An already-present reference.
        let plan =
            plan_edit_epics(&store.config, &store, "1", &["e-1".to_string()], &[], false).unwrap();
        assert!(
            !apply_edit_epics(&store, "1", &plan).unwrap(),
            "adding an existing reference is a no-op"
        );
        // Removing a reference the registry knows but the issue does not carry is a
        // no-op too.
        let plan =
            plan_edit_epics(&store.config, &store, "1", &[], &["e-2".to_string()], false).unwrap();
        assert!(
            !apply_edit_epics(&store, "1", &plan).unwrap(),
            "removing a reference that is not there is a no-op"
        );
    }

    // -- T026 — association from the epic side and navigation ----------------

    #[test]
    fn bulk_reference_reports_each_selector_independently() {
        let (_tmp, store) = store_with(&[("e-1", "A")], 2);
        let code = reference_from_epic(
            &store.config,
            &store,
            "e-1",
            &["1".to_string(), "99".to_string()],
        )
        .unwrap();
        assert_ne!(code, ExitCode::Success, "a partial batch exits non-zero");
        // The good selector was written and the bad one did not abort it.
        assert!(issue_bytes(&store, 1).contains("e-1"));
        assert_eq!(
            store.resolve_issue("1").unwrap().history.events().len(),
            1,
            "exactly one History entry for the accepted change"
        );
    }

    #[test]
    fn associate_refuses_an_unknown_epic_before_writing_anything() {
        let (_tmp, store) = store_with(&[("e-1", "A")], 1);
        let before = issue_bytes(&store, 1);
        let error = reference_from_epic(&store.config, &store, "bogus", &["1".to_string()])
            .expect_err("an unknown epic refuses up front");
        assert!(error.to_string().contains("unknown_epic"), "{error}");
        assert_eq!(issue_bytes(&store, 1), before, "nothing written");
    }

    #[test]
    fn navigation_lines_are_parent_first_with_ancestors_and_depth() {
        // Chain e-3 -> e-2 -> e-1 (root).
        let (_tmp, store) = store_with(&[("e-1", "Root"), ("e-2", "Mid"), ("e-3", "Leaf")], 0);
        let mut config = store.config.clone();
        config.epics.get_mut("e-2").unwrap().parent = Some("e-1".to_string());
        config.epics.get_mut("e-3").unwrap().parent = Some("e-2".to_string());
        let issues = store.list_all().unwrap();
        let index = epics::EpicIndex::build(&config, &issues);
        let hierarchy = index.hierarchy("e-3").unwrap();
        let epic = index.resolve("e-3").unwrap().clone();
        let lines = navigation_lines(&hierarchy, &epic);
        let pos = |needle: &str| lines.iter().position(|l| l.contains(needle));
        // Parent-first: the ancestor Root precedes the parent Mid, which precedes
        // the epic Leaf.
        assert!(
            pos("Root") < pos("Mid") && pos("Mid") < pos("Leaf"),
            "parent-first order: {lines:?}"
        );
        assert!(lines.contains(&"depth: 2".to_string()), "{lines:?}");
        assert!(
            lines.iter().any(|l| l.contains("navigate one directly")),
            "direct issue navigation is advertised: {lines:?}"
        );
    }

    #[test]
    fn navigation_reports_an_unresolved_parent() {
        let (_tmp, store) = store_with_unresolved_parent();
        let issues = store.list_all().unwrap();
        let index = epics::EpicIndex::build(&store.config, &issues);
        let hierarchy = index.hierarchy("e-1").unwrap();
        let epic = index.resolve("e-1").unwrap().clone();
        let lines = navigation_lines(&hierarchy, &epic);
        assert!(
            lines.iter().any(|l| l.starts_with("unresolved-parent:")),
            "the unresolved parent is reported: {lines:?}"
        );
        assert!(lines.contains(&"parent: -".to_string()), "{lines:?}");
    }

    #[test]
    fn impact_notice_agrees_with_its_subject() {
        // One member and one child epic: singular verbs, "its parent".
        let (_tmp, store) = store_with(&[("e-1", "Parent"), ("e-2", "Child")], 1);
        write_issue(&store, 1, "Issue 1", &["e-1"]);
        let mut config = store.config.clone();
        config.epics.get_mut("e-2").unwrap().parent = Some("e-1".to_string());
        let epic = epics::resolve(&config, &store.list_all().unwrap(), "e-1").unwrap();
        let notice = impact_notice(&epic);
        assert!(
            notice.contains("1 issue still references this epic"),
            "{notice}"
        );
        assert!(
            notice.contains("1 child epic records this epic as its parent"),
            "{notice}"
        );

        // Two members and two children: plural verbs.
        let (_tmp2, store2) = store_with(
            &[("e-1", "Parent"), ("e-2", "Child A"), ("e-3", "Child B")],
            2,
        );
        write_issue(&store2, 1, "Issue 1", &["e-1"]);
        write_issue(&store2, 2, "Issue 2", &["e-1"]);
        let mut config2 = store2.config.clone();
        config2.epics.get_mut("e-2").unwrap().parent = Some("e-1".to_string());
        config2.epics.get_mut("e-3").unwrap().parent = Some("e-1".to_string());
        let epic2 = epics::resolve(&config2, &store2.list_all().unwrap(), "e-1").unwrap();
        let notice2 = impact_notice(&epic2);
        assert!(
            notice2.contains("2 issues still reference this epic"),
            "{notice2}"
        );
        assert!(
            notice2.contains("2 child epics record this epic as their parent"),
            "{notice2}"
        );
    }
}