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
#[allow(clippy::wildcard_imports)]
use super::*;

/// The frontmatter key carrying an issue's epic references.
///
/// WP03's field is `epics` (contracts/epic-registry.md §3); named once here so a
/// second spelling has no home.
pub const EPICS_KEY: &str = "epics";

/// A derived reference to another epic, with its display label.
///
/// The label is computed on read and **never stored**: a stored name goes stale
/// the moment the epic is renamed (data-model §2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicRef {
    /// The referenced epic's stable id.
    pub id: EpicId,
    /// The epic's display label at read time.
    pub name: String,
    /// `Name (e-id)`, from [`epic_display`].
    pub display: String,
}

impl EpicRef {
    /// Build a reference, deriving the label from the name.
    #[must_use]
    pub fn new(id: &EpicId, name: &str) -> Self {
        Self {
            id: id.clone(),
            name: name.to_string(),
            display: epic_display(id, name),
        }
    }
}

/// The service-side view of an epic (data-model §2).
///
/// Combines the registry record with the derived members and children.
/// Registry-only operations ([`create_epic`], [`edit_epic`]) return it with an
/// **empty** member list — there is no issue set to derive from — while
/// index-backed operations ([`EpicIndex::resolve`], [`list_epics`]) fill it.
/// Nothing here is stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Epic {
    /// The stable registry key; the identity that survives a rename (C-003).
    pub id: EpicId,
    /// The mutable display label; never the identity.
    pub name: String,
    /// Optional long-form context.
    pub description: Option<String>,
    /// Optional epic status (free-form; not a board column, not a category).
    pub status: Option<String>,
    /// Optional owner identity string.
    pub owner: Option<String>,
    /// Optional start date (`YYYY-MM-DD`).
    pub start_date: Option<String>,
    /// Optional due date (`YYYY-MM-DD`).
    pub due_date: Option<String>,
    /// Optional positive relative size, used by the epic rollup.
    pub weight: Option<i64>,
    /// The recorded parent epic **id**, exactly as stored. Retained even when it
    /// no longer resolves, so the reference can be repaired (contract §3.4).
    pub parent: Option<String>,
    /// Project **ids** this epic concerns, verbatim (FR-002).
    pub projects: Vec<String>,
    /// The recorded milestone **name**, verbatim (FR-002).
    pub milestone: Option<String>,
    /// The recorded cycle **name**, verbatim (FR-002).
    pub cycle: Option<String>,
    /// Derived members, ordered by issue number. Never stored.
    pub members: Vec<MemberRef>,
    /// `members.len()`, carried because listings ask for it constantly.
    pub member_count: usize,
    /// Derived child epics, in registry declaration order. Never stored.
    pub children: Vec<EpicRef>,
    /// `children.len()`.
    pub child_count: usize,
}

impl Epic {
    /// Project a registry record into the service view.
    pub(super) fn from_configuration(
        id: EpicId,
        record: &EpicConfiguration,
        members: Vec<MemberRef>,
        children: Vec<EpicRef>,
    ) -> Self {
        Self {
            id,
            name: record.name.clone(),
            description: record.description.clone(),
            status: record.status.clone(),
            owner: record.owner.clone(),
            start_date: record.start_date.clone(),
            due_date: record.due_date.clone(),
            weight: record.weight,
            parent: record.parent.clone(),
            projects: record.projects.clone(),
            milestone: record.milestone.clone(),
            cycle: record.cycle.clone(),
            member_count: members.len(),
            members,
            child_count: children.len(),
            children,
        }
    }
}

/// The shared display form for an epic: `Harden the sync path (e-7c4a91)`.
///
/// One function, because every listing must show the id beside the name and a
/// second formatting site is how two surfaces end up disagreeing about what an
/// epic is called.
#[must_use]
pub fn epic_display(id: &EpicId, name: &str) -> String {
    format!("{name} ({id})")
}

/// The diagnostic kinds the epic service names, spelled exactly.
///
/// The variants map one-to-one onto [`EpicError`], so a surface prints the named
/// kind without a second classification step (contract `cli-surface.md` §4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum EpicDiagnosticKind {
    /// A name is blank, padded, or already in use.
    DuplicateName,
    /// An epic reference names no stored epic.
    UnknownEpic,
    /// An issue selector names no issue in the snapshot.
    UnknownIssue,
    /// The start/due dates are malformed or inverted.
    InvalidDates,
    /// The weight is not a positive relative size.
    InvalidWeight,
    /// A reference field's value is not a well-formed id.
    InvalidReference,
    /// The proposed parent is the epic itself.
    SelfParent,
    /// The proposed parent chain would close a cycle.
    Cycle,
}

impl EpicDiagnosticKind {
    /// The canonical snake_case spelling a surface prints.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            EpicDiagnosticKind::DuplicateName => "duplicate_name",
            EpicDiagnosticKind::UnknownEpic => "unknown_epic",
            EpicDiagnosticKind::UnknownIssue => "unknown_issue",
            EpicDiagnosticKind::InvalidDates => "invalid_dates",
            EpicDiagnosticKind::InvalidWeight => "invalid_weight",
            EpicDiagnosticKind::InvalidReference => "invalid_reference",
            EpicDiagnosticKind::SelfParent => "self_parent",
            EpicDiagnosticKind::Cycle => "cycle",
        }
    }
}

impl fmt::Display for EpicDiagnosticKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The single wording for an epic reference that names no stored epic.
#[must_use]
pub fn unknown_epic_reason(reference: &str) -> String {
    format!("no epic matches `{reference}`; an epic is selected by its stable id or by name")
}

/// The single wording for an issue selector that names no issue.
#[must_use]
pub fn unknown_issue_reason(selector: impl fmt::Display) -> String {
    format!("issue `{selector}` is not in this store")
}

/// The single wording for an epic date refusal.
///
/// Wraps the shared [`crate::model::validate_issue_dates`] message so the date
/// *rule* keeps its one owner and only the wording lives here.
#[must_use]
pub fn invalid_dates_reason(detail: &str) -> String {
    format!("epic dates are invalid: {detail}")
}

/// The single wording for an epic weight refusal.
#[must_use]
pub fn invalid_weight_reason(value: i64) -> String {
    format!("epic weight must be a positive integer; got {value}")
}

/// The single wording for a reference field whose value is not a well-formed id.
///
/// The write-path half of WP01's load-time shape check: an epic references a
/// project **by id**, so a value that is not one has to be refused rather than
/// stored, or the registry would no longer load. A *dangling* but well-formed id
/// is a different thing and is stored, then diagnosed (C-005).
#[must_use]
pub fn invalid_reference_reason(field: &str, value: &str) -> String {
    format!(
        "`epics.<id>.{field}` entry `{value}` is not a well-formed id; \
         an epic references the target by its stable id"
    )
}

/// The single wording for an epic name refusal.
#[must_use]
pub fn duplicate_name_reason(name: &str) -> String {
    if name.trim().is_empty() {
        "an epic name must not be blank".to_string()
    } else if name.trim() != name {
        format!("epic name `{name}` has leading or trailing whitespace")
    } else {
        format!("epic name `{name}` is already in use; epic names must be unique")
    }
}

/// The single wording for a self-parent refusal.
#[must_use]
pub fn self_parent_reason(epic: &EpicId) -> String {
    format!("epic `{epic}` cannot be its own parent")
}

/// The single wording for a cycle refusal, naming the offending path.
#[must_use]
pub fn cycle_reason(epic: &EpicId, path: &[EpicId]) -> String {
    let rendered: Vec<&str> = path.iter().map(EpicId::as_str).collect();
    format!(
        "parent would close an epic cycle: `{epic}` -> {}",
        rendered.join(" -> ")
    )
}

/// The single wording for an unresolved parent epic (contract §3.4).
#[must_use]
pub fn unresolved_parent_reason(epic: &EpicId, recorded_parent: &str) -> String {
    format!(
        "epic `{epic}` records parent `{recorded_parent}`, which no longer exists \
         (the reference is kept so it can be repaired)"
    )
}

/// The single wording for a reference change's `## History` detail line.
///
/// One renderer, in the service, for every writer, so the CLI, the TUI and MCP
/// cannot word the same change differently.
#[must_use]
pub fn reference_detail(epic_id: &str, referenced: bool) -> String {
    if referenced {
        format!("epic `{epic_id}` referenced")
    } else {
        format!("epic `{epic_id}` dereferenced")
    }
}

/// Why an epic operation was refused.
///
/// The variants map one-to-one onto [`EpicDiagnosticKind`] and carry the
/// contract's names (`contracts/epic-service.md` §1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EpicError {
    /// An epic reference did not resolve.
    UnknownEpic {
        /// The reference exactly as the caller wrote it.
        reference: String,
    },
    /// An issue selector named no issue in the snapshot.
    UnknownIssue {
        /// The selector exactly as the caller wrote it.
        selector: u32,
    },
    /// The name is blank, padded, or already in use.
    DuplicateName {
        /// The name as supplied.
        name: String,
    },
    /// The start/due dates are malformed or inverted.
    InvalidDates {
        /// The shared date rule's message.
        detail: String,
    },
    /// The weight is not a positive relative size.
    InvalidWeight {
        /// The value as supplied.
        value: i64,
    },
    /// A reference field's value is not a well-formed id.
    InvalidReference {
        /// The record field the value belongs to, e.g. `projects`.
        field: &'static str,
        /// The value as supplied.
        value: String,
    },
    /// The proposed parent is the epic itself.
    SelfParent {
        /// The epic that would parent itself.
        epic: EpicId,
    },
    /// The proposed parent chain would close a cycle.
    Cycle {
        /// The epic whose proposed parent closes the loop.
        epic: EpicId,
        /// The offending path, from the epic back to itself.
        path: Vec<EpicId>,
    },
}

impl EpicError {
    /// The named diagnostic kind this refusal reports.
    #[must_use]
    pub fn kind(&self) -> EpicDiagnosticKind {
        match self {
            EpicError::UnknownEpic { .. } => EpicDiagnosticKind::UnknownEpic,
            EpicError::UnknownIssue { .. } => EpicDiagnosticKind::UnknownIssue,
            EpicError::DuplicateName { .. } => EpicDiagnosticKind::DuplicateName,
            EpicError::InvalidDates { .. } => EpicDiagnosticKind::InvalidDates,
            EpicError::InvalidWeight { .. } => EpicDiagnosticKind::InvalidWeight,
            EpicError::InvalidReference { .. } => EpicDiagnosticKind::InvalidReference,
            EpicError::SelfParent { .. } => EpicDiagnosticKind::SelfParent,
            EpicError::Cycle { .. } => EpicDiagnosticKind::Cycle,
        }
    }

    /// The single wording for this refusal, via the kind's helper.
    #[must_use]
    pub fn message(&self) -> String {
        match self {
            EpicError::UnknownEpic { reference } => unknown_epic_reason(reference),
            EpicError::UnknownIssue { selector } => unknown_issue_reason(selector),
            EpicError::DuplicateName { name } => duplicate_name_reason(name),
            EpicError::InvalidDates { detail } => invalid_dates_reason(detail),
            EpicError::InvalidWeight { value } => invalid_weight_reason(*value),
            EpicError::InvalidReference { field, value } => invalid_reference_reason(field, value),
            EpicError::SelfParent { epic } => self_parent_reason(epic),
            EpicError::Cycle { epic, path } => cycle_reason(epic, path),
        }
    }
}

impl fmt::Display for EpicError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.kind(), self.message())
    }
}

impl std::error::Error for EpicError {}

/// An epic refusal becomes user input error, so `?` works at the call site.
///
/// The payload is a single-line diagnostic (`<kind>: <message>`), so it takes the
/// crate's existing `invalid input:` prefix without doubling it — the same
/// boundary every other selector/validation refusal crosses (cli-surface §6).
impl From<EpicError> for TixError {
    fn from(err: EpicError) -> TixError {
        TixError::InvalidInput(err.to_string())
    }
}

/// The spec for a new epic (contract §1: name plus optional metadata).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NewEpic {
    /// Required display label.
    pub name: String,
    /// Optional long-form context.
    pub description: Option<String>,
    /// Optional epic status.
    pub status: Option<String>,
    /// Optional owner identity string.
    pub owner: Option<String>,
    /// Optional start date.
    pub start_date: Option<String>,
    /// Optional due date.
    pub due_date: Option<String>,
    /// Optional positive relative size.
    pub weight: Option<i64>,
    /// Project **ids** this epic concerns (FR-002). Shape is checked; existence is
    /// diagnosed rather than refused, so a dangling reference is repairable.
    pub projects: Vec<String>,
    /// Optional milestone name (the existing name-keyed reference).
    pub milestone: Option<String>,
    /// Optional cycle name (the existing name-keyed reference).
    pub cycle: Option<String>,
}

/// The fields of an epic edit.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EpicEdit {
    /// The display label. A rename is a label change only (C-003, NFR-002).
    pub name: Patch<String>,
    /// Long-form context.
    pub description: Patch<String>,
    /// Epic status.
    pub status: Patch<String>,
    /// Owner identity string.
    pub owner: Patch<String>,
    /// Start date.
    pub start_date: Patch<String>,
    /// Due date.
    pub due_date: Patch<String>,
    /// Weight.
    pub weight: Patch<i64>,
    /// The parent epic reference: `Set` resolves to the parent's id and is
    /// validated against the epic chain, `Clear` detaches the epic.
    pub parent: Patch<String>,
    /// Project **ids** this epic concerns. Each entry is shape-validated and never
    /// resolved, so a dangling-but-well-formed id is stored for repair (C-005).
    pub projects: Patch<Vec<String>>,
    /// Milestone name; `Clear` removes the reference.
    pub milestone: Patch<String>,
    /// Cycle name; `Clear` removes the reference.
    pub cycle: Patch<String>,
}

/// The impact report of an epic deletion (contract §1).
///
/// It **reports**; it does not delete. The affected issues keep their references
/// (which then read as missing references, C-005) and the child epics keep their
/// recorded parent (which then reads as unresolved, contract §3.4), so this type
/// carries them for the caller's notice rather than a cascade (C-006).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EpicDeletion {
    /// The id that was removed from the registry. Never handed out again.
    pub id: EpicId,
    /// The name the record carried, for the notice.
    pub name: String,
    /// The issues that still reference the deleted epic, ordered by number.
    pub affected: Vec<MemberRef>,
    /// The epics that recorded it as their parent, in declaration order.
    pub child_epics: Vec<EpicRef>,
}

/// Normalize an optional text field: a written-but-empty value is absent.
///
/// WP01 refuses a present-but-blank key, so collapsing it here is what keeps a
/// record this service writes loadable. Non-blank values are kept verbatim.
pub(super) fn normalize_optional(value: Option<String>) -> Option<String> {
    value.filter(|v| !v.trim().is_empty())
}

/// Validate a requested display name against the registry.
///
/// Mirrors [`crate::config`]'s rule (`validate_epics`): non-blank, no padding,
/// and unique case-folded, since a user does not tell `Platform` from `platform`.
/// WP01 owns the loader's copy; this is the write-path half, pinned to the same
/// rule by `t006_create_epic_refuses_a_duplicate_name`.
pub(super) fn validate_name(
    registry: &IndexMap<String, EpicConfiguration>,
    name: &str,
    exclude: Option<&EpicId>,
) -> Result<(), EpicError> {
    if name.trim().is_empty() || name.trim() != name {
        return Err(EpicError::DuplicateName {
            name: name.to_string(),
        });
    }
    let normalized = name.to_lowercase();
    let clash = registry.iter().any(|(raw, record)| {
        let is_self = exclude.is_some_and(|id| raw.as_str() == id.as_str());
        !is_self && record.name.to_lowercase() == normalized
    });
    if clash {
        return Err(EpicError::DuplicateName {
            name: name.to_string(),
        });
    }
    Ok(())
}

/// Validate the pair through the shared date rule (WP01 uses the same helper).
pub(super) fn validate_dates(start: Option<&str>, due: Option<&str>) -> Result<(), EpicError> {
    crate::model::validate_issue_dates(start, due).map_err(|err| EpicError::InvalidDates {
        detail: err.to_string(),
    })
}

/// Validate a project-id list: shape only, never resolution.
///
/// Each entry must be a well-formed [`ProjectId`], because that is what a
/// registry must hold to load. A well-formed id the project registry does not
/// hold is **kept** — it is the diagnosable dangling reference C-005 promises —
/// and an exact duplicate collapses to one reference, as a repeated issue-side id
/// does. The caller's order is preserved.
pub(super) fn validate_project_ids(list: &[String]) -> Result<Vec<String>, EpicError> {
    let mut out: Vec<String> = Vec::new();
    for entry in list {
        let id = ProjectId::new(entry).map_err(|_| EpicError::InvalidReference {
            field: "projects",
            value: entry.clone(),
        })?;
        if !out.iter().any(|stored| stored == id.as_str()) {
            out.push(id.to_string());
        }
    }
    Ok(out)
}

/// Validate a weight: a positive relative size, or nothing.
pub(super) fn validate_weight(weight: i64) -> Result<(), EpicError> {
    if weight > 0 {
        return Ok(());
    }
    Err(EpicError::InvalidWeight { value: weight })
}

/// Resolve an epic id from a reference: **id first**, then a name convenience.
///
/// Resolution is by the stable id (C-003). A name is accepted because a human
/// selects epics by name; it resolves to the same epic, and WP01's uniqueness
/// rule guarantees it is unambiguous. An id that also happens to look like
/// another epic's name wins, which is what "id first" means.
pub fn resolve_epic_id(
    registry: &IndexMap<String, EpicConfiguration>,
    reference: &str,
) -> Result<EpicId, EpicError> {
    if let Ok(id) = EpicId::new(reference) {
        if registry.contains_key(id.as_str()) {
            return Ok(id);
        }
    }
    let normalized = reference.trim().to_lowercase();
    if let Some((raw, _)) = registry
        .iter()
        .find(|(_, record)| record.name.to_lowercase() == normalized)
    {
        return EpicId::new(raw).map_err(|_| EpicError::UnknownEpic {
            reference: reference.to_string(),
        });
    }
    Err(EpicError::UnknownEpic {
        reference: reference.to_string(),
    })
}

/// The epics that record `id` as their parent, in declaration order.
pub(super) fn recorded_children(
    registry: &IndexMap<String, EpicConfiguration>,
    id: &EpicId,
) -> Vec<EpicRef> {
    registry
        .iter()
        .filter(|(_, record)| record.parent.as_deref() == Some(id.as_str()))
        .filter_map(|(raw, record)| {
            EpicId::new(raw)
                .ok()
                .map(|child| EpicRef::new(&child, &record.name))
        })
        .collect()
}

/// Create an epic, allocating a fresh stable id (FR-001).
///
/// Validates the name, the dates, and the weight first, so a refusal yields no
/// registry change (contract §4). The record is inserted into the in-memory
/// [`Config`]; the caller persists it with `Config::save`, so the atomic write
/// path has exactly one owner. The returned view carries no members or children —
/// a create has no issue set to derive from.
pub fn create_epic(config: &mut Config, new: &NewEpic) -> Result<Epic, EpicError> {
    validate_name(&config.epics, &new.name, None)?;
    validate_dates(new.start_date.as_deref(), new.due_date.as_deref())?;
    if let Some(weight) = new.weight {
        validate_weight(weight)?;
    }
    let projects = validate_project_ids(&new.projects)?;
    let id = config.allocate_epic_id();
    let record = EpicConfiguration {
        name: new.name.clone(),
        description: normalize_optional(new.description.clone()),
        status: normalize_optional(new.status.clone()),
        owner: normalize_optional(new.owner.clone()),
        start_date: new.start_date.clone(),
        due_date: new.due_date.clone(),
        weight: new.weight,
        projects,
        milestone: normalize_optional(new.milestone.clone()),
        cycle: normalize_optional(new.cycle.clone()),
        ..EpicConfiguration::default()
    };
    config.epics.insert(id.to_string(), record.clone());
    Ok(Epic::from_configuration(
        id,
        &record,
        Vec::new(),
        Vec::new(),
    ))
}

/// Edit an epic's fields by reference.
///
/// A name change is a **label change only**: the registry key is untouched, so
/// every member reference and derived figure stays intact (C-003, NFR-002). A
/// proposed parent is validated — self-parent and cycle — **before** any write,
/// so a rejection leaves the registry byte-unchanged (contract §3, §4). The
/// returned view carries no members — an edit has no issue set to derive from.
pub fn edit_epic(config: &mut Config, reference: &str, edit: &EpicEdit) -> Result<Epic, EpicError> {
    let id = resolve_epic_id(&config.epics, reference)?;
    let mut updated =
        config
            .epics
            .get(id.as_str())
            .cloned()
            .ok_or_else(|| EpicError::UnknownEpic {
                reference: reference.to_string(),
            })?;

    // --- validation first: nothing below this block runs on a refusal --------
    match &edit.name {
        Patch::Unchanged => {}
        Patch::Clear => {
            return Err(EpicError::DuplicateName {
                name: String::new(),
            });
        }
        Patch::Set(name) => {
            validate_name(&config.epics, name, Some(&id))?;
        }
    }
    if let Patch::Set(weight) = &edit.weight {
        validate_weight(*weight)?;
    }
    let proposed_parent = match &edit.parent {
        Patch::Unchanged => None,
        Patch::Clear => Some(None),
        Patch::Set(parent) => Some(Some(validate_epic_parent(&config.epics, &id, parent)?)),
    };
    let proposed_projects = match &edit.projects {
        Patch::Unchanged => None,
        Patch::Clear => Some(Vec::new()),
        Patch::Set(list) => Some(validate_project_ids(list)?),
    };

    // --- apply --------------------------------------------------------------
    if let Patch::Set(name) = &edit.name {
        updated.name.clone_from(name);
    }
    apply_optional(&edit.description, &mut updated.description);
    apply_optional(&edit.status, &mut updated.status);
    apply_optional(&edit.owner, &mut updated.owner);
    apply_date(&edit.start_date, &mut updated.start_date);
    apply_date(&edit.due_date, &mut updated.due_date);
    if let Patch::Set(weight) = &edit.weight {
        updated.weight = Some(*weight);
    }
    if let Patch::Clear = &edit.weight {
        updated.weight = None;
    }
    if let Some(parent) = proposed_parent {
        updated.parent = parent.map(|id| id.to_string());
    }
    if let Some(projects) = proposed_projects {
        updated.projects = projects;
    }
    apply_optional(&edit.milestone, &mut updated.milestone);
    apply_optional(&edit.cycle, &mut updated.cycle);

    validate_dates(updated.start_date.as_deref(), updated.due_date.as_deref())?;

    if let Some(record) = config.epics.get_mut(id.as_str()) {
        *record = updated.clone();
    }
    Ok(Epic::from_configuration(
        id,
        &updated,
        Vec::new(),
        Vec::new(),
    ))
}

/// Apply an optional-text patch.
pub(super) fn apply_optional(patch: &Patch<String>, slot: &mut Option<String>) {
    match patch {
        Patch::Unchanged => {}
        Patch::Clear => *slot = None,
        Patch::Set(value) => *slot = normalize_optional(Some(value.clone())),
    }
}

/// Apply a date patch.
pub(super) fn apply_date(patch: &Patch<String>, slot: &mut Option<String>) {
    match patch {
        Patch::Unchanged => {}
        Patch::Clear => *slot = None,
        Patch::Set(value) => *slot = Some(value.clone()),
    }
}

/// Remove an epic from the registry, reporting what referenced it.
///
/// Removes the registry entry **only**. Every member issue keeps its `epics`
/// entry (which then reads as a missing reference) and every child epic keeps its
/// recorded parent (which then reads as unresolved), so both can be repaired
/// rather than being silently rebound (C-005, C-006). The id is never reused
/// (WP01's allocation carries that guarantee).
pub fn delete_epic<N: EpicNode>(
    config: &mut Config,
    reference: &str,
    issues: &[N],
) -> Result<EpicDeletion, EpicError> {
    let id = resolve_epic_id(&config.epics, reference)?;
    let record = config
        .epics
        .get(id.as_str())
        .cloned()
        .ok_or_else(|| EpicError::UnknownEpic {
            reference: reference.to_string(),
        })?;
    let affected = EpicIndex::build(config, issues)
        .epic(&id)
        .map(|epic| epic.members.clone())
        .unwrap_or_default();
    let child_epics = recorded_children(&config.epics, &id);
    config.epics.shift_remove(id.as_str());
    Ok(EpicDeletion {
        id,
        name: record.name,
        affected,
        child_epics,
    })
}