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
//! Immutable capacity evidence captured at an explicit cycle close (WP04, T019–T024).
//!
//! # One trigger, one file, one payload
//!
//! The mission allows **one** snapshot trigger: a confirmed cycle **close** (C-008). The
//! immutable file it writes already exists and is issue-181's:
//! [`CycleSnapshotStore`] writes one [`CycleSnapshot`] per generated cycle into
//! `docs/cycle_snapshots/`, refuses to overwrite a path (so a closed cycle's evidence is
//! immutable by construction), and tells "this cycle's own snapshot" from "someone
//! else's file" through [`SnapshotOccupant`]. This module does **not** add a store, a
//! file, a directory or a second format: it is the *producer and reader of the payload*
//! that rides in [`CycleSnapshot::measurements`].
//!
//! That payload is [`CapacitySnapshot`] — the capacity half of the close's evidence
//! (`data-model.md` §6): the stable snapshot identity, the cycle identity, the close
//! actor and time, the [`CapacityCalculation`] the close ran, the optional breakdown, and
//! any metadata a build this one has never heard of.
//!
//! # The close hook is one line, and this is why
//!
//! `CycleSnapshot`'s `measurements` is the free-form
//! [`CycleSnapshotMetadata`] map the issue-181 snapshot already carries for exactly this
//! purpose, so the close path fills it by calling [`CapacitySnapshot::to_measurements`]
//! instead of `CycleSnapshotMetadata::new()`. Nothing else in the close path changes:
//! the snapshot is still written first, the record second, and a failed record write
//! still discards the snapshot and the directory it created. Because a repeat close is
//! already a no-op there, "one snapshot, one event" is a property of the existing seam
//! rather than something this module has to re-establish.
//!
//! # What "immutable" means here, precisely
//!
//! * **The bytes.** Nothing in this module writes, renames or deletes anything.
//!   [`CapacitySnapshot::read`] is a pure read, and the store under it refuses to
//!   overwrite a path (`a_second_capture_cannot_rewrite_a_captured_snapshot`).
//! * **The meaning.** [`CapacitySnapshot::from_cycle_snapshot`] cross-checks the
//!   payload's identity, close time and actor against the file it was read from, so the
//!   evidence can never disagree with the snapshot that carries it
//!   (`evidence_that_disagrees_with_its_file_is_refused`).
//! * **The calculation.** Every derived value is the value the DTO held at close; nothing
//!   is recomputed from the live schedule or the current `tix.toml`, which are exactly
//!   what a later edit is allowed to change. A reopen or a capacity edit produces a *new
//!   current* calculation and never touches this payload; a re-close after a reopen finds
//!   the path occupied and writes no snapshot at all.
//!
//! # Reopen/edit are History events, not snapshots
//!
//! [`reopen_event`] and [`capacity_edit_event`] build the **`## History` vocabulary** for
//! a closed-cycle change ([`HistoryEventKind::CycleReopened`] and
//! [`HistoryEventKind::CycleCapacityEdited`]): the kind and the one `detail` line the
//! append-only log stores. They go to the **cycle record's own Markdown body** — the same
//! log `cycle_closed` goes to, and the only log a cycle has — never to an issue's
//! `## History`. The lifecycle's existing `append_event` appends the line, so one applied
//! action appends exactly one entry, and [`History::append`] never rewrites or removes an
//! existing line.
//!
//! [`History::append`]: crate::model::History::append
//!
//! # The optional breakdown: a carrier, not an invented schema
//!
//! `data-model.md` §6 lists `scope_breakdown` as optional "team/assignee values" without
//! fixing its shape, and the discipline this mission follows is *prefer omission over
//! invention*. The breakdown is therefore a caller-supplied [`CycleSnapshotMetadata`] map
//! persisted verbatim — enough for a producer that has one to store it, and no invented
//! field list for a calculation to depend on. **This build computes none**: the
//! calculation is one scope's numbers, and picking which teams/assignees to break a cycle
//! into is a scope-selection decision this mission has not approved. A snapshot captured
//! here carries no breakdown, and one that carries a breakdown this build does not
//! interpret reads back verbatim and stays queryable.
//!
//! # No clock, no store, no writer
//!
//! Nothing here reads `SystemTime`: `closed_at` and `closed_by` are the explicit values
//! the close request carries. The module holds no `Store`, no `Planner` and no writer —
//! [`CapacitySnapshot::capture`] is a pure conversion from a DTO that already exists, and
//! every field is either supplied or derived from one. Unknown metadata on a payload is
//! preserved verbatim rather than dropped, so a `tix` that does not know about a key
//! still round-trips it.

use serde_yaml::{Mapping, Value};

use super::calculate::{CapacityCalculation, CapacityScope, CapacitySource, CapacityState};
use super::config::CapacityScopeKind;
use super::scope::ScopeDiagnosticKind;
use super::warning::{CapacityWarning, CapacityWarningKind};
use crate::cycle_schedule::identity::GeneratedCycleId;
use crate::cycle_schedule::snapshot::{CycleSnapshot, CycleSnapshotMetadata, CycleSnapshotStore};
use crate::error::{Result, TixError};
use crate::model::HistoryEventKind;
use crate::wip::WipDiagnosticKind;

// ---------------------------------------------------------------------------
// The payload's keys
// ---------------------------------------------------------------------------

/// The key that marks a payload as a capacity payload: `data-model.md` §6 makes
/// `snapshot_id` a required field, so its presence is the marker and its absence means
/// "no capacity evidence" rather than "corrupt evidence".
pub const SNAPSHOT_ID_KEY: &str = "snapshot_id";
const CYCLE_ID_KEY: &str = "cycle_id";
const CLOSED_AT_KEY: &str = "closed_at";
const CLOSED_BY_KEY: &str = "closed_by";
const SCOPE_KIND_KEY: &str = "scope_kind";
const SCOPE_REFERENCE_KEY: &str = "scope_reference";
const SCOPE_DISPLAY_KEY: &str = "scope_display";
const STATE_KEY: &str = "state";
const CAPACITY_KEY: &str = "capacity";
const UNIT_KEY: &str = "unit";
const COMMITTED_KEY: &str = "committed";
const COMPLETED_KEY: &str = "completed";
const REMAINING_KEY: &str = "remaining";
const OVERFLOW_KEY: &str = "overflow";
const UTILIZATION_KEY: &str = "utilization";
const COUNTED_ISSUES_KEY: &str = "counted_issues";
const UNCOUNTED_ISSUES_KEY: &str = "uncounted_issues";
const UNESTIMATED_ISSUES_KEY: &str = "unestimated_issues";
const SOURCE_ISSUES_KEY: &str = "source_issues";
const SOURCE_UNITS_KEY: &str = "source_units";
const DIAGNOSTICS_KEY: &str = "diagnostics";
const BREAKDOWN_KEY: &str = "breakdown";
const KIND_KEY: &str = "kind";
const ISSUES_KEY: &str = "issues";
const CURRENT_KEY: &str = "current";
const LIMIT_KEY: &str = "limit";
const REASON_KEY: &str = "reason";
const REMEDY_KEY: &str = "remedy";

/// Every key [`CapacitySnapshot::to_measurements`] writes.
///
/// Any other key found on the map is **unknown metadata**: it is carried on
/// [`CapacitySnapshot::extensions`] and written back unchanged, so a payload a newer
/// `tix` extended round-trips instead of being trimmed to what this build understands.
pub const SNAPSHOT_MEASUREMENT_KEYS: [&str; 22] = [
    SNAPSHOT_ID_KEY,
    CYCLE_ID_KEY,
    CLOSED_AT_KEY,
    CLOSED_BY_KEY,
    SCOPE_KIND_KEY,
    SCOPE_REFERENCE_KEY,
    SCOPE_DISPLAY_KEY,
    STATE_KEY,
    CAPACITY_KEY,
    UNIT_KEY,
    COMMITTED_KEY,
    COMPLETED_KEY,
    REMAINING_KEY,
    OVERFLOW_KEY,
    UTILIZATION_KEY,
    COUNTED_ISSUES_KEY,
    UNCOUNTED_ISSUES_KEY,
    UNESTIMATED_ISSUES_KEY,
    SOURCE_ISSUES_KEY,
    SOURCE_UNITS_KEY,
    DIAGNOSTICS_KEY,
    BREAKDOWN_KEY,
];

// ---------------------------------------------------------------------------
// The entity
// ---------------------------------------------------------------------------

/// The immutable capacity evidence one cycle close captured (`data-model.md` §6).
///
/// Every field is the value the close held. Nothing here is recomputed: a later schedule
/// edit, a capacity configuration change, or a reopen changes what *today* calculates
/// and leaves this value exactly as it was.
///
/// The identity fields (`snapshot_id`, `cycle_id`, `closed_at`, `closed_by`) are carried
/// in the payload as well as on the [`CycleSnapshot`] around it, so the payload is
/// **self-describing**: a portable or MCP surface that quotes one snapshot without the
/// file it lives in still knows which snapshot it is quoting. [`Self::from_cycle_snapshot`]
/// cross-checks the two so they cannot drift.
#[derive(Debug, Clone, PartialEq)]
pub struct CapacitySnapshot {
    /// The stable snapshot identity: the generated cycle id and the explicit close time.
    ///
    /// Stable because both halves are written once and never rewritten; see
    /// [`snapshot_id`]. Deliberately not a random or clock-derived value — this build
    /// reads no clock.
    pub snapshot_id: String,
    /// The generated cycle this evidence belongs to, by its stable id.
    pub cycle_id: String,
    /// The explicit close time, RFC 3339 `YYYY-MM-DDTHH:MM:SSZ`.
    pub closed_at: String,
    /// The audit actor who closed the cycle.
    pub closed_by: String,
    /// The scope the calculation ran for.
    pub scope: CapacityScope,
    /// Whether the scope had a ceiling it could count against at close.
    pub state: CapacityState,
    /// The ceiling in force, or `None` when the scope was unconfigured.
    pub capacity: Option<u64>,
    /// The unit every number is counted in, or `None` when the scope was unconfigured.
    pub unit: Option<String>,
    /// The committed total at close.
    pub committed: Option<u64>,
    /// The completed part of it at close.
    pub completed: Option<u64>,
    /// `committed - completed` at close.
    pub remaining: Option<u64>,
    /// `max(committed - capacity, 0)` at close.
    pub overflow: Option<u64>,
    /// The floored utilization percentage at close.
    pub utilization: Option<u32>,
    /// How many issues were counted into `committed`.
    pub counted_issues: Option<u32>,
    /// How many issues stated an estimate that could not be counted.
    pub uncounted_issues: Option<u32>,
    /// How many issues stated no estimate at all.
    pub unestimated_issues: Option<u32>,
    /// The reading the numbers came from.
    pub source: CapacitySource,
    /// The findings the calculation raised, in derivation order.
    pub diagnostics: Vec<CapacityWarning>,
    /// The optional team/assignee breakdown, persisted verbatim; `None` when no producer
    /// supplied one (see the module docs — this build computes none).
    pub breakdown: Option<CycleSnapshotMetadata>,
    /// Metadata this build does not interpret, preserved verbatim.
    pub extensions: CycleSnapshotMetadata,
}

impl CapacitySnapshot {
    /// Capture the evidence a confirmed close records (`T019`).
    ///
    /// A pure conversion: every field comes from `calculation` or from the explicit
    /// identity/actor/time the close request carries. Nothing is read from the store, the
    /// clock or the configuration, so the evidence is exactly the DTO the close ran —
    /// there is no second formula and no recomputation to drift.
    #[must_use]
    pub fn capture(
        cycle_id: &GeneratedCycleId,
        closed_at: &str,
        closed_by: &str,
        calculation: &CapacityCalculation,
    ) -> Self {
        Self {
            snapshot_id: snapshot_id(cycle_id, closed_at),
            cycle_id: cycle_id.as_str().to_string(),
            closed_at: closed_at.trim().to_string(),
            closed_by: closed_by.trim().to_string(),
            scope: calculation.scope.clone(),
            state: calculation.state(),
            capacity: calculation.capacity,
            unit: calculation.unit.clone(),
            committed: calculation.committed,
            completed: calculation.completed,
            remaining: calculation.remaining,
            overflow: calculation.overflow,
            utilization: calculation.utilization,
            counted_issues: calculation.counted_issues,
            uncounted_issues: calculation.uncounted_issues,
            unestimated_issues: calculation.unestimated_issues,
            source: calculation.source.clone(),
            diagnostics: calculation.diagnostics.clone(),
            breakdown: None,
            extensions: CycleSnapshotMetadata::new(),
        }
    }

    /// Attach a team/assignee breakdown, persisted verbatim.
    ///
    /// An **empty** map is not a breakdown: it is omitted, so a snapshot with no
    /// breakdown and a snapshot with an empty one are the same file (the round trip a
    /// caller cannot accidentally alter by passing `BTreeMap::new()`).
    #[must_use]
    pub fn with_breakdown(mut self, breakdown: CycleSnapshotMetadata) -> Self {
        self.breakdown = (!breakdown.is_empty()).then_some(breakdown);
        self
    }

    /// The one-line auditable summary of the evidence, as the `## History` detail quotes
    /// it: state, and the four numbers a reader compares.
    #[must_use]
    pub fn summary(&self) -> String {
        evidence_summary(
            self.state,
            self.committed,
            self.completed,
            self.capacity,
            self.unit.as_deref(),
        )
    }

    /// Render the evidence into a cycle snapshot's `measurements` map (`T019/T022`).
    ///
    /// Deterministic and total: the same value always renders to the same map, an absent
    /// optional field is **omitted** rather than written as a null (so a legacy snapshot
    /// stays byte-identical and "unconfigured" is not spelled as "zero"), and every
    /// unknown key on [`Self::extensions`] is written back unchanged.
    #[must_use]
    pub fn to_measurements(&self) -> CycleSnapshotMetadata {
        let mut map = CycleSnapshotMetadata::new();
        let mut put = |key: &str, value: Value| {
            map.insert(key.to_string(), value);
        };
        put(SNAPSHOT_ID_KEY, Value::String(self.snapshot_id.clone()));
        put(CYCLE_ID_KEY, Value::String(self.cycle_id.clone()));
        put(CLOSED_AT_KEY, Value::String(self.closed_at.clone()));
        put(CLOSED_BY_KEY, Value::String(self.closed_by.clone()));
        put(
            SCOPE_KIND_KEY,
            Value::String(self.scope.kind.as_str().to_string()),
        );
        put(
            SCOPE_REFERENCE_KEY,
            Value::String(self.scope.reference.clone()),
        );
        put(SCOPE_DISPLAY_KEY, Value::String(self.scope.display.clone()));
        put(STATE_KEY, Value::String(self.state.as_str().to_string()));
        for (key, value) in [
            (CAPACITY_KEY, self.capacity),
            (COMMITTED_KEY, self.committed),
            (COMPLETED_KEY, self.completed),
            (REMAINING_KEY, self.remaining),
            (OVERFLOW_KEY, self.overflow),
        ] {
            if let Some(value) = value {
                put(key, Value::Number(value.into()));
            }
        }
        if let Some(unit) = self.unit.as_deref() {
            put(UNIT_KEY, Value::String(unit.to_string()));
        }
        for (key, value) in [
            (UTILIZATION_KEY, self.utilization),
            (COUNTED_ISSUES_KEY, self.counted_issues),
            (UNCOUNTED_ISSUES_KEY, self.uncounted_issues),
            (UNESTIMATED_ISSUES_KEY, self.unestimated_issues),
        ] {
            if let Some(value) = value {
                put(key, Value::Number(value.into()));
            }
        }
        put(
            SOURCE_ISSUES_KEY,
            Value::Number(u64::try_from(self.source.issues).unwrap_or(u64::MAX).into()),
        );
        put(
            SOURCE_UNITS_KEY,
            Value::Sequence(
                self.source
                    .units
                    .iter()
                    .map(|unit| Value::String(unit.clone()))
                    .collect(),
            ),
        );
        put(
            DIAGNOSTICS_KEY,
            Value::Sequence(self.diagnostics.iter().map(warning_to_value).collect()),
        );
        if let Some(breakdown) = &self.breakdown {
            put(BREAKDOWN_KEY, metadata_to_value(breakdown));
        }
        for (key, value) in &self.extensions {
            map.insert(key.clone(), value.clone());
        }
        map
    }

    /// Read the evidence a payload carries, or `None` when it carries none (`T020/T023`).
    ///
    /// `None` is the answer for **every** snapshot that is not this mission's evidence:
    /// an issue-181 snapshot whose `measurements` are empty, a snapshot whose map holds
    /// only metadata this build does not interpret, and a snapshot a future build wrote
    /// without the identity key. That is deliberate — a legacy record must keep loading
    /// and stay queryable, so "no capacity evidence" is a value and never an error, and
    /// nothing is migrated or upgraded in place.
    ///
    /// Once the identity key *is* present the payload claims to be this build's, so a
    /// missing required field or a value of the wrong type is a field-aware error naming
    /// the key rather than a silently half-filled value.
    pub fn from_measurements(measurements: &CycleSnapshotMetadata) -> Result<Option<Self>> {
        if !measurements.contains_key(SNAPSHOT_ID_KEY) {
            return Ok(None);
        }
        let scope = CapacityScope {
            kind: scope_kind(&required_string(measurements, SCOPE_KIND_KEY)?)?,
            reference: required_string(measurements, SCOPE_REFERENCE_KEY)?,
            display: required_string(measurements, SCOPE_DISPLAY_KEY)?,
        };
        let snapshot = Self {
            snapshot_id: required_string(measurements, SNAPSHOT_ID_KEY)?,
            cycle_id: required_string(measurements, CYCLE_ID_KEY)?,
            closed_at: required_string(measurements, CLOSED_AT_KEY)?,
            closed_by: required_string(measurements, CLOSED_BY_KEY)?,
            scope,
            state: state_of(&required_string(measurements, STATE_KEY)?)?,
            capacity: optional_u64(measurements, CAPACITY_KEY)?,
            unit: optional_string(measurements, UNIT_KEY)?,
            committed: optional_u64(measurements, COMMITTED_KEY)?,
            completed: optional_u64(measurements, COMPLETED_KEY)?,
            remaining: optional_u64(measurements, REMAINING_KEY)?,
            overflow: optional_u64(measurements, OVERFLOW_KEY)?,
            utilization: optional_u32(measurements, UTILIZATION_KEY)?,
            counted_issues: optional_u32(measurements, COUNTED_ISSUES_KEY)?,
            uncounted_issues: optional_u32(measurements, UNCOUNTED_ISSUES_KEY)?,
            unestimated_issues: optional_u32(measurements, UNESTIMATED_ISSUES_KEY)?,
            source: CapacitySource {
                issues: usize::try_from(required_u64(measurements, SOURCE_ISSUES_KEY)?)
                    .map_err(|_| type_error(SOURCE_ISSUES_KEY, "a count that fits in a usize"))?,
                units: string_list(measurements, SOURCE_UNITS_KEY)?,
            },
            diagnostics: diagnostic_list(measurements, DIAGNOSTICS_KEY)?,
            breakdown: optional_metadata(measurements, BREAKDOWN_KEY)?,
            extensions: unknown_metadata(measurements),
        };
        Ok(Some(snapshot))
    }

    /// Read the evidence out of a stored [`CycleSnapshot`] (`T020`).
    ///
    /// Beyond parsing, this is the **integrity** seam: a payload that names a different
    /// cycle, close time or actor than the file it was read from is refused, so the
    /// evidence can never be quoted against the wrong snapshot. A snapshot with no
    /// capacity payload is `None`, never an error and never an upgrade.
    pub fn from_cycle_snapshot(snapshot: &CycleSnapshot) -> Result<Option<Self>> {
        let Some(evidence) = Self::from_measurements(&snapshot.measurements)? else {
            return Ok(None);
        };
        let file = snapshot.cycle_id.as_str();
        if evidence.cycle_id != file
            || evidence.closed_at != snapshot.closed_at
            || evidence.closed_by != snapshot.closed_by
        {
            return Err(TixError::Parse(format!(
                "capacity evidence in `docs/cycle_snapshots/{}` names `{}` closed at `{}` by \
                 `{}`, but the snapshot is {} closed at `{}` by `{}`; the evidence is refused \
                 rather than quoted against the wrong snapshot",
                CycleSnapshotStore::filename_for(&snapshot.cycle_id),
                evidence.cycle_id,
                evidence.closed_at,
                evidence.closed_by,
                file,
                snapshot.closed_at,
                snapshot.closed_by,
            )));
        }
        Ok(Some(evidence))
    }

    /// Read a closed cycle's capacity evidence from its snapshot file (`T020`).
    ///
    /// A pure read through the existing immutable store: `None` when the cycle has no
    /// snapshot, when its snapshot predates this mission (empty `measurements`), or when
    /// the path is occupied by a file that is not this cycle's snapshot — a foreign
    /// occupant is never overwritten and never parsed as one of ours.
    pub fn read(store: &CycleSnapshotStore, cycle_id: &GeneratedCycleId) -> Result<Option<Self>> {
        match store.read(cycle_id)? {
            Some(snapshot) => Self::from_cycle_snapshot(&snapshot),
            None => Ok(None),
        }
    }
}

// ---------------------------------------------------------------------------
// T021 — the append-only History vocabulary for a closed-cycle change
// ---------------------------------------------------------------------------

/// The one `## History` event an applied **reopen** appends (`T021`, C-008).
///
/// Returns the kind and the single `detail` line the append-only log stores; the
/// lifecycle's existing `append_event` appends it to the **cycle record's** body, beside
/// `cycle_closed`, and one applied reopen appends exactly one entry. The prior snapshot
/// and every prior event are untouched: this is a value, and nothing here writes.
///
/// The detail reads `reason: <why>; state: reopened; snapshot: <identity|none>`. The
/// `snapshot` field is the **capacity evidence's** stable identity, not the snapshot
/// file's path: `none` means the closed cycle recorded no capacity evidence (a snapshot
/// written before this mission, or a close whose request carried no calculation), which
/// is why `prior` is an `Option` rather than a required value. A reopen is auditable
/// either way — the entry never invents an identity it does not have.
///
/// A **blank** reason is refused here as well as by the request gate, because "why" is
/// the whole content of the entry: an un-reasoned reopen is not an audit record.
pub fn reopen_event(
    reason: &str,
    prior: Option<&CapacitySnapshot>,
) -> Result<(HistoryEventKind, String)> {
    let reason = audited_reason(reason)?;
    Ok((
        HistoryEventKind::CycleReopened,
        format!(
            "reason: {reason}; state: reopened; snapshot: {}",
            prior.map_or("none", |evidence| evidence.snapshot_id.as_str())
        ),
    ))
}

/// The one `## History` event an applied **closed-cycle capacity edit** appends (`T021`).
///
/// Same shape as [`reopen_event`]: one kind, one line, appended to the cycle record's own
/// log. The detail names the prior snapshot identity and the before/after summaries the
/// data model asks for (`data-model.md` §7), so the entry explains *what changed* without
/// the reader having to reconstruct it. `before` is the immutable evidence; `after` is the
/// new *current* calculation — the edit never rewrites the prior snapshot, and never
/// becomes one.
pub fn capacity_edit_event(
    reason: &str,
    before: Option<&CapacitySnapshot>,
    after: &CapacityCalculation,
) -> Result<(HistoryEventKind, String)> {
    let reason = audited_reason(reason)?;
    Ok((
        HistoryEventKind::CycleCapacityEdited,
        format!(
            "reason: {reason}; snapshot: {snapshot}; before: {before}; after: {after}",
            snapshot = before.map_or("none", |evidence| evidence.snapshot_id.as_str()),
            before = before.map_or_else(|| "none".to_string(), CapacitySnapshot::summary),
            after = evidence_summary(
                after.state(),
                after.committed,
                after.completed,
                after.capacity,
                after.unit.as_deref(),
            ),
        ),
    ))
}

/// The stable snapshot identity for a cycle close (`T019`).
///
/// `<cycle-id>@<close-time>`. Both halves are written once, so the identity is stable;
/// nothing is random, nothing is read from a clock, and no counter is kept. It is
/// deliberately not a display label — see the issue-181 snapshot module's note on why a
/// mutable name must not become an identity.
#[must_use]
pub fn snapshot_id(cycle_id: &GeneratedCycleId, closed_at: &str) -> String {
    format!("{}@{}", cycle_id.as_str(), closed_at.trim())
}

/// A reason an auditable event may carry; a blank one is refused.
///
/// The **single-line** rule a `## History` entry needs — no line break, and no U+2014 in
/// the reason — is deliberately *not* enforced here. It is enforced at the two places an
/// event can enter a cycle record's log: the lifecycle's audit gate
/// (`src/cycle_schedule/lifecycle.rs`, `history_text_hazard`) and
/// [`crate::cycle_schedule::lifecycle::append_cycle_event`]. One place owns the
/// character policy, so a builder and a writer cannot drift apart about it; this
/// function owns only the half a builder can judge alone, which is that a reason exists.
fn audited_reason(reason: &str) -> Result<&str> {
    let trimmed = reason.trim();
    if trimmed.is_empty() {
        return Err(TixError::InvalidInput(
            "a reopen or a closed-cycle capacity edit is auditable: a non-blank reason is \
             required and is stored with the append-only `History` event"
                .into(),
        ));
    }
    Ok(trimmed)
}

/// The one-line summary both the evidence and the new current calculation render.
fn evidence_summary(
    state: CapacityState,
    committed: Option<u64>,
    completed: Option<u64>,
    capacity: Option<u64>,
    unit: Option<&str>,
) -> String {
    format!(
        "state={state}, committed={committed}, completed={completed}, capacity={capacity}, \
         unit={unit}",
        state = state.as_str(),
        committed = number_or_none(committed),
        completed = number_or_none(completed),
        capacity = number_or_none(capacity),
        unit = unit.unwrap_or("none"),
    )
}

fn number_or_none(value: Option<u64>) -> String {
    value.map_or_else(|| "none".to_string(), |value| value.to_string())
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

fn warning_to_value(warning: &CapacityWarning) -> Value {
    let mut map = Mapping::new();
    let mut put = |key: &str, value: Value| {
        map.insert(Value::String(key.to_string()), value);
    };
    put(KIND_KEY, Value::String(warning.kind.as_str().to_string()));
    put(
        SCOPE_KIND_KEY,
        Value::String(warning.scope.kind.as_str().to_string()),
    );
    put(
        SCOPE_REFERENCE_KEY,
        Value::String(warning.scope.reference.clone()),
    );
    put(
        SCOPE_DISPLAY_KEY,
        Value::String(warning.scope.display.clone()),
    );
    if !warning.issues.is_empty() {
        put(
            ISSUES_KEY,
            Value::Sequence(
                warning
                    .issues
                    .iter()
                    .map(|issue| Value::Number(u64::from(*issue).into()))
                    .collect(),
            ),
        );
    }
    for (key, value) in [
        (CURRENT_KEY, warning.current),
        (LIMIT_KEY, warning.limit),
        (OVERFLOW_KEY, warning.overflow),
    ] {
        if let Some(value) = value {
            put(key, Value::Number(value.into()));
        }
    }
    if let Some(unit) = warning.unit.as_deref() {
        put(UNIT_KEY, Value::String(unit.to_string()));
    }
    put(REASON_KEY, Value::String(warning.reason.clone()));
    if let Some(remedy) = warning.remedy.as_deref() {
        put(REMEDY_KEY, Value::String(remedy.to_string()));
    }
    Value::Mapping(map)
}

fn metadata_to_value(metadata: &CycleSnapshotMetadata) -> Value {
    let mut map = Mapping::new();
    for (key, value) in metadata {
        map.insert(Value::String(key.clone()), value.clone());
    }
    Value::Mapping(map)
}

// ---------------------------------------------------------------------------
// Parsing
// ---------------------------------------------------------------------------

/// Every key this build does not know about, preserved verbatim.
fn unknown_metadata(measurements: &CycleSnapshotMetadata) -> CycleSnapshotMetadata {
    measurements
        .iter()
        .filter(|(key, _)| !SNAPSHOT_MEASUREMENT_KEYS.contains(&key.as_str()))
        .map(|(key, value)| (key.clone(), value.clone()))
        .collect()
}

fn required_string(fields: &CycleSnapshotMetadata, key: &str) -> Result<String> {
    match fields.get(key) {
        Some(Value::String(value)) => Ok(value.clone()),
        Some(other) => Err(type_error(
            key,
            &format!("a string, found {}", kind_of(other)),
        )),
        None => Err(missing(key)),
    }
}

fn optional_string(fields: &CycleSnapshotMetadata, key: &str) -> Result<Option<String>> {
    match fields.get(key) {
        Some(Value::String(value)) => Ok(Some(value.clone())),
        Some(other) => Err(type_error(
            key,
            &format!("a string, found {}", kind_of(other)),
        )),
        None => Ok(None),
    }
}

fn required_u64(fields: &CycleSnapshotMetadata, key: &str) -> Result<u64> {
    match fields.get(key) {
        Some(Value::Number(value)) => value
            .as_u64()
            .ok_or_else(|| type_error(key, "a whole number at or above zero")),
        Some(other) => Err(type_error(
            key,
            &format!("a number, found {}", kind_of(other)),
        )),
        None => Err(missing(key)),
    }
}

fn optional_u64(fields: &CycleSnapshotMetadata, key: &str) -> Result<Option<u64>> {
    match fields.get(key) {
        Some(Value::Number(value)) => value
            .as_u64()
            .map(Some)
            .ok_or_else(|| type_error(key, "a whole number at or above zero")),
        Some(other) => Err(type_error(
            key,
            &format!("a number, found {}", kind_of(other)),
        )),
        None => Ok(None),
    }
}

fn optional_u32(fields: &CycleSnapshotMetadata, key: &str) -> Result<Option<u32>> {
    let Some(value) = optional_u64(fields, key)? else {
        return Ok(None);
    };
    u32::try_from(value)
        .map(Some)
        .map_err(|_| type_error(key, "a number that fits in 32 bits"))
}

fn string_list(fields: &CycleSnapshotMetadata, key: &str) -> Result<Vec<String>> {
    let Some(Value::Sequence(items)) = fields.get(key) else {
        return Err(match fields.get(key) {
            Some(other) => type_error(key, &format!("a list, found {}", kind_of(other))),
            None => missing(key),
        });
    };
    items
        .iter()
        .map(|item| match item {
            Value::String(value) => Ok(value.clone()),
            other => Err(type_error(
                key,
                &format!("a list of strings, found {}", kind_of(other)),
            )),
        })
        .collect()
}

fn diagnostic_list(fields: &CycleSnapshotMetadata, key: &str) -> Result<Vec<CapacityWarning>> {
    let Some(Value::Sequence(items)) = fields.get(key) else {
        return Err(match fields.get(key) {
            Some(other) => type_error(key, &format!("a list, found {}", kind_of(other))),
            None => missing(key),
        });
    };
    items
        .iter()
        .map(|item| diagnostic_from_value(item, key))
        .collect()
}

fn diagnostic_from_value(value: &Value, key: &str) -> Result<CapacityWarning> {
    let fields = value_to_metadata(value, key)?;
    let scope = CapacityScope {
        kind: scope_kind(&required_string(&fields, SCOPE_KIND_KEY)?)?,
        reference: required_string(&fields, SCOPE_REFERENCE_KEY)?,
        display: required_string(&fields, SCOPE_DISPLAY_KEY)?,
    };
    let kind = warning_kind(&required_string(&fields, KIND_KEY)?)?;
    let mut warning = CapacityWarning::new(kind, scope, required_string(&fields, REASON_KEY)?);
    warning.issues = match fields.get(ISSUES_KEY) {
        None => Vec::new(),
        Some(Value::Sequence(items)) => items
            .iter()
            .map(|item| match item {
                Value::Number(value) => value
                    .as_u64()
                    .and_then(|value| u32::try_from(value).ok())
                    .ok_or_else(|| type_error(ISSUES_KEY, "a list of issue numbers")),
                other => Err(type_error(
                    ISSUES_KEY,
                    &format!("a list, found {}", kind_of(other)),
                )),
            })
            .collect::<Result<Vec<u32>>>()?,
        Some(other) => {
            return Err(type_error(
                ISSUES_KEY,
                &format!("a list, found {}", kind_of(other)),
            ));
        }
    };
    warning.current = optional_u64(&fields, CURRENT_KEY)?;
    warning.limit = optional_u64(&fields, LIMIT_KEY)?;
    warning.overflow = optional_u64(&fields, OVERFLOW_KEY)?;
    warning.unit = optional_string(&fields, UNIT_KEY)?;
    warning.remedy = optional_string(&fields, REMEDY_KEY)?;
    Ok(warning)
}

fn optional_metadata(
    fields: &CycleSnapshotMetadata,
    key: &str,
) -> Result<Option<CycleSnapshotMetadata>> {
    match fields.get(key) {
        Some(value) => Ok(Some(value_to_metadata(value, key)?)),
        None => Ok(None),
    }
}

fn value_to_metadata(value: &Value, key: &str) -> Result<CycleSnapshotMetadata> {
    let Some(mapping) = value.as_mapping() else {
        return Err(type_error(key, &format!("a map, found {}", kind_of(value))));
    };
    let mut metadata = CycleSnapshotMetadata::new();
    for (field, value) in mapping {
        let Some(field) = field.as_str() else {
            return Err(type_error(key, "a map with string keys"));
        };
        metadata.insert(field.to_string(), value.clone());
    }
    Ok(metadata)
}

/// The scope kind a payload spelling names. Unknown spellings are refused rather than
/// coerced, for the reason the whole payload is: a misread identity is worse than an
/// error.
fn scope_kind(spelling: &str) -> Result<CapacityScopeKind> {
    match spelling {
        "cycle" => Ok(CapacityScopeKind::Cycle),
        "team" => Ok(CapacityScopeKind::Team),
        "assignee" => Ok(CapacityScopeKind::Assignee),
        other => Err(TixError::Parse(format!(
            "`{other}` is not a capacity scope kind; expected `cycle`, `team` or `assignee`"
        ))),
    }
}

/// The calculation state a payload spelling names.
fn state_of(spelling: &str) -> Result<CapacityState> {
    match spelling {
        "unconfigured" => Ok(CapacityState::Unconfigured),
        "uncountable" => Ok(CapacityState::Uncountable),
        "configured" => Ok(CapacityState::Configured),
        other => Err(TixError::Parse(format!(
            "`{other}` is not a capacity state; expected `unconfigured`, `uncountable` or \
             `configured`"
        ))),
    }
}

/// The finding kind a payload spelling names.
///
/// The spellings are the registries' own ([`CapacityWarningKind::as_str`] delegates to
/// the WIP and scope vocabularies), so this is a wire parser for **this** payload rather
/// than a second vocabulary: nothing here is printed anywhere, and the values it returns
/// are the registries'.
fn warning_kind(spelling: &str) -> Result<CapacityWarningKind> {
    Ok(match spelling {
        "capacity_overflow" => CapacityWarningKind::Overflow,
        "malformed_estimate" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::MalformedEstimate)
        }
        "missing_conversion" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::MissingConversion)
        }
        "ambiguous_conversion" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::AmbiguousConversion)
        }
        "unknown_unit" => CapacityWarningKind::Conversion(WipDiagnosticKind::UnknownUnit),
        "over_limit" => CapacityWarningKind::Conversion(WipDiagnosticKind::OverLimit),
        "override_applied" => CapacityWarningKind::Conversion(WipDiagnosticKind::OverrideApplied),
        "override_required" => CapacityWarningKind::Conversion(WipDiagnosticKind::OverrideRequired),
        "unconfirmed_override" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::UnconfirmedOverride)
        }
        "missing_override_field" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::MissingOverrideField)
        }
        "stale_override_limit" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::StaleOverrideLimit)
        }
        "rejected_transition" => {
            CapacityWarningKind::Conversion(WipDiagnosticKind::RejectedTransition)
        }
        "unknown_scope" => CapacityWarningKind::Scope(ScopeDiagnosticKind::UnknownScope),
        "ambiguous_scope" => CapacityWarningKind::Scope(ScopeDiagnosticKind::AmbiguousScope),
        other => {
            return Err(TixError::Parse(format!(
                "`{other}` is not a capacity warning kind this build records"
            )));
        }
    })
}

fn missing(key: &str) -> TixError {
    TixError::Parse(format!(
        "capacity evidence is missing `{key}`; the payload claims to be a capacity snapshot, so \
         a required field is never defaulted"
    ))
}

fn type_error(key: &str, expected: &str) -> TixError {
    TixError::Parse(format!("capacity evidence `{key}` must be {expected}"))
}

fn kind_of(value: &Value) -> &'static str {
    match value {
        Value::Null => "null",
        Value::Bool(_) => "a boolean",
        Value::Number(_) => "a number",
        Value::String(_) => "a string",
        Value::Sequence(_) => "a list",
        Value::Mapping(_) => "a map",
        Value::Tagged(_) => "a tagged value",
    }
}