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
//! `tix capacity`: the CLI adapter over the shared capacity service (mission
//! `cycle-capacity-planning-01M3C85C`, WP05, T025–T029).
//!
//! Parse, call, print. Nothing here computes a total, rounds a percentage, folds a scope
//! identity, or writes a file. The section and its refusals are
//! [`crate::capacity::config`]'s (`set_capacity`, `validate`, `validate_cycle_references`,
//! `ensure_cycle_editable`), the one-pass index and a scope's membership are
//! [`crate::capacity::scope`]'s, the only formula and the only rounding policy are
//! [`crate::capacity::calculate`]'s, the findings are [`crate::capacity::warning`]'s, and
//! the close evidence is [`crate::capacity::snapshot`]'s. A number this module prints is a
//! number the DTO held — C-007's one-DTO rule, and the reason `calculate` has no
//! arithmetic in it at all.
//!
//! # The commands
//!
//! * `tix capacity list` — one tab-separated row per configured entry.
//! * `tix capacity show <REFERENCE> [--scope <KIND>]` — one entry, by the reference it
//!   names (a cycle's name or stable id, a team label, an assignee identity).
//! * `tix capacity set --scope <KIND> --id <REFERENCE> --value <N> --unit <UNIT>
//!   [--disabled]` — configure one scope's ceiling, through [`set_capacity`].
//! * `tix capacity delete --scope <KIND> --id <REFERENCE>` — remove one entry.
//! * `tix capacity calculate --scope <KIND> --id <REFERENCE> [--warnings]` — the shared
//!   [`CapacityCalculation`], every field of it.
//! * `tix capacity snapshot <CYCLE> [--warnings]` — read back a closed cycle's immutable
//!   evidence.
//!
//! # stdout is the result, stderr is the diagnostic
//!
//! The values go to stdout, one `key: value` per line (the shape `tix cycle schedule
//! show` uses), because that is the text a script reads. Findings render through
//! [`CapacityWarning::render`] to **stderr**, the way `tix wip show` renders its own
//! snapshot diagnostics: a diagnostic interleaved into the value lines would be a parse
//! error rather than a warning.
//!
//! A finding about one issue's estimate or about a reference that did not resolve means
//! the numbers are **incomplete** — an issue that could not be counted in the scope's
//! unit contributes nothing and is not a zero (C-004) — so it always renders. The
//! overflow report is a report about a complete calculation, so it renders only when
//! `--warnings` is given (FR-003; the `overflow:` value itself is always on stdout).
//!
//! # The entry handle, and the identity it is derived from
//!
//! An entry's `[capacity.<id>]` key is derived from the **identity** its scope resolves
//! to: `<kind>-<slug(identity)>`, where the identity is the label
//! [`CapacityScope::new`] yields (a generated instance's *name* for its stable id, an
//! assignee's canonical handle, a team label, a hand-written cycle's name). The crate's
//! one [`crate::slug::slugify`] turns that into a key, so the two spellings of one
//! generated cycle — its stable id and its name — derive one handle, and re-running
//! `set` for that scope updates that entry rather than adding a second one.
//!
//! The handle is a **naming** choice, never an identity: nothing reads a scope back
//! through it. `show` and `delete` match on the resolved label itself, so a hand-written
//! entry whose key this CLI never derived is reachable by the scope it declares, and a
//! generated instance is readable and removable under either spelling. Two *different*
//! labels can still slug to one key (`Platform` and `platform`); `set` refuses that case
//! naming the scope it would have replaced, so the collision can never silently destroy
//! a ceiling.
//!
//! # Nothing is written when a command is refused
//!
//! `set` goes through [`set_capacity`], which stages the change on a copy, runs the
//! closed-cycle gate and both validation halves, and commits only once they pass — so a
//! refusal leaves `tix.toml` byte-identical. `delete` mirrors that shape (gate, stage,
//! validate, save, commit) with the same [`CapacityEdit::Configure`] authorization, so
//! deleting a closed cycle's ceiling is refused exactly as setting one is. A `set` whose
//! derived handle is already another scope's is refused before anything is staged. No
//! command here opens a snapshot or an issue for writing: `calculate` and `snapshot` are
//! reads, and an overflow is a report, never a mutation (C-006).
//!
//! # The close seam
//!
//! `with_close_capacity` is the other half of this file's job (T028): the one rule a
//! **close** passes its lifecycle request through. The calculation is computed there —
//! a close site owns the project configuration and the issue store, while the
//! lifecycle's `apply` deliberately owns neither
//! ([`LifecycleRequest::capacity`] is the caller's) — and it is never recomputed inside
//! the store. Routing every surface's close through that one seam is what keeps the
//! CLI, the TUI and MCP capturing one payload (NFR-003) rather than three.

use std::path::{Path, PathBuf};

use crate::capacity::calculate::{CapacityCalculation, CapacityScope};
use crate::capacity::config::{
    CapacityEdit, CapacityEntry, CapacityExtensions, CapacityScopeKind, ensure_cycle_editable,
    set_capacity, validate, validate_cycle_references,
};
use crate::capacity::scope::IssueSnapshot;
use crate::capacity::snapshot::CapacitySnapshot;
use crate::capacity::warning::{CapacityWarning, CapacityWarningKind};
use crate::capacity::{resolve_cycle, schedule_index};
use crate::cli::CapacityCommand;
use crate::config::Config;
use crate::cycle_schedule::identity::{CycleReference, ScheduleIndex};
use crate::cycle_schedule::lifecycle::{LifecycleAction, LifecycleRequest};
use crate::cycle_schedule::snapshot::CycleSnapshotStore;
use crate::cycle_store::CycleStore;
use crate::error::{Result, TixError};
use crate::storage::Store;

/// Route one `tix capacity` subcommand.
pub fn run(config: &mut Config, store: &Store, command: &CapacityCommand) -> Result<()> {
    let root = root_from_store(store);
    match command {
        CapacityCommand::List => list(config, &root),
        CapacityCommand::Show { reference, scope } => {
            show(config, &root, scope.as_deref(), reference)
        }
        CapacityCommand::Set {
            scope,
            id,
            value,
            unit,
            disabled,
        } => set(config, &root, scope, id, *value, unit, *disabled),
        CapacityCommand::Delete { scope, id } => delete(config, &root, scope, id),
        CapacityCommand::Calculate {
            scope,
            id,
            warnings,
        } => calculate(config, store, &root, scope, id, *warnings),
        CapacityCommand::Snapshot { cycle, warnings } => {
            read_snapshot(config, &root, cycle, *warnings)
        }
    }
}

/// The project root the cycle records, the snapshots and `tix.toml` resolve against —
/// the same walk `commands::cycle` and `commands::views` do, so a subcommand writes the
/// file every other command reads.
fn root_from_store(store: &Store) -> PathBuf {
    Config::project_root(&store.issues_dir).unwrap_or_else(|| PathBuf::from("."))
}

// ---------------------------------------------------------------------------
// The snapshot + index pair every calculation reads (WP02/WP03)
// ---------------------------------------------------------------------------

/// The schedule index and the one-pass issue snapshot a capacity calculation reads.
///
/// The snapshot is built **with** the index that produced it, so the pair a caller hands
/// to [`CapacityCalculation::for_scope`] is the reading the numbers were indexed
/// against — never a second pass that could count a different membership (NFR-001).
pub(crate) fn snapshot_for(
    config: &Config,
    root: &Path,
    store: &Store,
) -> Result<(ScheduleIndex, IssueSnapshot)> {
    let index = schedule_index(config, root)?;
    let snapshot = IssueSnapshot::build(config, &index, &store.list()?);
    Ok((index, snapshot))
}

/// The shared calculation for one scope — the single entry point both `tix capacity
/// calculate` and the cycle-close site call, so the two cannot run different arithmetic.
pub(crate) fn calculation_for(
    config: &Config,
    root: &Path,
    store: &Store,
    kind: CapacityScopeKind,
    reference: &str,
) -> Result<CapacityCalculation> {
    let (index, snapshot) = snapshot_for(config, root, store)?;
    let scope = CapacityScope::new(kind, reference, &index);
    Ok(CapacityCalculation::for_scope(
        &snapshot, &index, config, scope,
    ))
}

/// Attach the capacity evidence a **close** records — the one seam every surface's
/// close site passes its request through (WP05, T028).
///
/// The calculation is computed here because the close sites own the project
/// configuration and the issue store, while the lifecycle's `apply` deliberately owns
/// neither ([`LifecycleRequest::capacity`]). The rule lives in **one** place so the CLI,
/// the TUI and the MCP tool cannot drift into capturing three different payloads
/// (NFR-003), which is why the signature needs nothing a close site does not already
/// hold. The scope is the instance's own name, which the identity adapter folds with its
/// stable id — a ceiling declared under either spelling is the one this close captures.
///
/// Nothing is read for any other action, and a close that named no instance, or named
/// one no record answers to, is returned unchanged — the lifecycle refuses both before
/// writing anything.
pub(crate) fn with_close_capacity(
    request: LifecycleRequest,
    config: &Config,
    root: &Path,
    store: &Store,
) -> Result<LifecycleRequest> {
    if request.action != LifecycleAction::Close {
        return Ok(request);
    }
    let Some(cycle_id) = request.cycle_id.clone() else {
        return Ok(request);
    };
    let (index, snapshot) = snapshot_for(config, root, store)?;
    let Some(cycle) = index.cycle(&cycle_id) else {
        return Ok(request);
    };
    let scope = CapacityScope::new(CapacityScopeKind::Cycle, &cycle.name, &index);
    Ok(request.with_capacity(CapacityCalculation::for_scope(
        &snapshot, &index, config, scope,
    )))
}

// ---------------------------------------------------------------------------
// T025/T026 — list, show, set, delete
// ---------------------------------------------------------------------------

/// `tix capacity list`: every configured entry, in declaration order.
///
/// The `display` column is the label the reference resolves to
/// ([`CapacityScope::new`]) — the same resolution the calculation matches a ceiling by,
/// so a reader can see that a stable id and a name are one scope.
fn list(config: &Config, root: &Path) -> Result<()> {
    let index = schedule_index(config, root)?;
    println!("id\tscope\treference\tdisplay\tcapacity\tunit\tenabled");
    for (id, entry) in config.capacity.iter() {
        // A loaded section is validated, so every entry names exactly one scope.
        let Some(kind) = entry.scope_kind() else {
            continue;
        };
        let reference = entry.scope_id().unwrap_or_default();
        let display = scope_label(kind, reference, &index);
        println!(
            "{id}\t{kind}\t{reference}\t{display}\t{ceiling}\t{unit}\t{enabled}",
            kind = kind.as_str(),
            ceiling = number(entry.capacity),
            unit = entry.unit.as_deref().unwrap_or("-"),
            enabled = entry.enabled,
        );
    }
    Ok(())
}

/// `tix capacity show <REFERENCE>`: one entry, by the scope the reference resolves to.
fn show(config: &Config, root: &Path, scope: Option<&str>, reference: &str) -> Result<()> {
    let wanted = scope.map(parse_scope_kind).transpose()?;
    let index = schedule_index(config, root)?;
    let (id, kind, entry) = one_entry(config, wanted, reference, &index)?;
    let display = scope_label(kind, entry.scope_id().unwrap_or_default(), &index);
    println!("id: {id}");
    println!("scope: {}", kind.as_str());
    println!("reference: {}", entry.scope_id().unwrap_or_default());
    println!("display: {display}");
    println!("capacity: {}", number(entry.capacity));
    println!("unit: {}", entry.unit.as_deref().unwrap_or("-"));
    println!("enabled: {}", entry.enabled);
    Ok(())
}

/// `tix capacity set`: configure one scope's ceiling through the shared write path.
///
/// The entry's handle is derived from the **identity** the reference resolves to, its
/// unknown metadata is carried over from an entry already under that handle, and
/// everything else — the scope's resolution, the unit's declaration, the one-ceiling
/// rule, the closed-cycle refusal — is [`set_capacity`]'s. A handle already held by a
/// *different* scope is refused before anything is staged: two labels can slug to one
/// handle (`Platform` and `platform`), and one scope's ceiling must never silently
/// become another's.
fn set(
    config: &mut Config,
    root: &Path,
    scope: &str,
    id: &str,
    value: i64,
    unit: &str,
    disabled: bool,
) -> Result<()> {
    let kind = parse_scope_kind(scope)?;
    let reference = required("--id", id)?;
    let unit = required("--unit", unit)?;
    let index = schedule_index(config, root)?;
    let label = scope_label(kind, reference, &index);
    let key = capacity_key(kind, &label);
    // The handle is a naming choice, so a collision is this surface's to refuse: the
    // library's one-ceiling rule keys on identity and would not see two *different*
    // scopes that slug alike — nor a hand-written entry of another kind that happens to
    // sit on this handle.
    let occupied = config.capacity.get(&key).map(|entry| {
        (
            entry.scope_kind(),
            entry.scope_id().unwrap_or_default().to_string(),
        )
    });
    if let Some((occupied_kind, occupied_scope)) = occupied {
        let same_scope =
            occupied_kind == Some(kind) && scope_label(kind, &occupied_scope, &index) == label;
        if !same_scope {
            let occupied = occupied_kind.map_or_else(
                || format!("an entry naming no single scope (`{occupied_scope}`)"),
                |occupied_kind| format!("{kind} `{occupied_scope}`", kind = occupied_kind.as_str()),
            );
            let remedy = occupied_kind.map_or_else(
                || "Remove that entry first".to_string(),
                |occupied_kind| {
                    format!(
                        "Update the configured scope by naming it exactly (`--id \
                         {occupied_scope}`), or remove it first (`tix capacity delete --scope \
                         {kind} --id {occupied_scope}`)",
                        kind = occupied_kind.as_str(),
                    )
                },
            );
            return Err(TixError::Config(format!(
                "`capacity.{key}` already configures {occupied}, which resolves to the same entry \
                 handle as `--id {reference}`; writing it would replace that ceiling. {remedy}"
            )));
        }
    }
    let mut entry = CapacityEntry {
        capacity: Some(value),
        unit: Some(unit.to_string()),
        enabled: !disabled,
        // A key this section already uses keeps its unknown metadata: the section's
        // promise is that a key a newer `tix` added survives an edit, and this edit is
        // no exception. The value is read by handle, never re-derived from the scope.
        extensions: config
            .capacity
            .get(&key)
            .map_or_else(CapacityExtensions::default, |entry| {
                entry.extensions.clone()
            }),
        ..CapacityEntry::default()
    };
    match kind {
        CapacityScopeKind::Cycle => entry.cycle = Some(reference.to_string()),
        CapacityScopeKind::Team => entry.team = Some(reference.to_string()),
        CapacityScopeKind::Assignee => entry.assignee = Some(reference.to_string()),
    }
    set_capacity(config, &key, entry, &CapacityEdit::Configure, root)?;
    println!(
        "Set capacity for {kind} `{reference}`: {value}{unit}{disabled}",
        kind = kind.as_str(),
        disabled = if disabled { " (disabled)" } else { "" },
    );
    Ok(())
}

/// `tix capacity delete`: remove one entry, through the same boundary a set passes.
fn delete(config: &mut Config, root: &Path, scope: &str, id: &str) -> Result<()> {
    let kind = parse_scope_kind(scope)?;
    let reference = required("--id", id)?;
    let index = schedule_index(config, root)?;
    let (key, _, target) = one_entry(config, Some(kind), reference, &index)?;
    // C-008: a closed cycle's capacity is the historical record, and removing its
    // ceiling is an ordinary configuration change, so it passes the same gate a `set`
    // does — before anything is staged.
    if kind == CapacityScopeKind::Cycle
        && let Some(reference) = target.scope_id()
    {
        ensure_cycle_editable_for(config, root, reference)?;
    }
    let key = key.to_string();
    // The shape `set_capacity` uses: stage on a copy, validate both halves, commit only
    // once they pass, so a refusal cannot leave a half-applied section behind.
    let mut candidate = config.clone();
    candidate.capacity.entries_mut().shift_remove(&key);
    validate(&candidate.capacity, &candidate)?;
    validate_cycle_references(&candidate.capacity, &candidate, root)?;
    candidate.save(&root.join("tix.toml"))?;
    *config = candidate;
    println!("Removed capacity for {kind} `{reference}`");
    Ok(())
}

// ---------------------------------------------------------------------------
// T027 — calculate, and the one warning policy
// ---------------------------------------------------------------------------

/// `tix capacity calculate`: the shared DTO, every field of it, and the findings.
///
/// There is no arithmetic here: `committed`, `completed`, `remaining`, `overflow` and
/// `utilization` are the values [`CapacityCalculation::for_scope`] derived, and an
/// absent one prints as `-` rather than as a zero (an unconfigured scope is not a scope
/// with zero capacity, and an uncountable one is not a zero total).
fn calculate(
    config: &Config,
    store: &Store,
    root: &Path,
    scope: &str,
    id: &str,
    warnings: bool,
) -> Result<()> {
    let kind = parse_scope_kind(scope)?;
    let reference = required("--id", id)?;
    let calculation = calculation_for(config, root, store, kind, reference)?;
    print_calculation(&calculation);
    render_findings(&calculation.diagnostics, warnings);
    Ok(())
}

/// The DTO's own fields as one text block, in the shape `tix cycle schedule show` prints
/// — the exact bytes [`print_calculation`] writes to stdout, and the text the MCP surface
/// returns, so the two cannot word one calculation two ways (C-007/NFR-003). A number
/// this prints is a number the DTO held.
pub(crate) fn calculation_text(calculation: &CapacityCalculation) -> String {
    format!(
        "scope: {scope}\nreference: {reference}\ndisplay: {display}\nstate: {state}\n\
         capacity: {capacity}\nunit: {unit}\ncommitted: {committed}\ncompleted: {completed}\n\
         remaining: {remaining}\noverflow: {overflow}\nutilization: {utilization}\n\
         counted_issues: {counted}\nuncounted_issues: {uncounted}\n\
         unestimated_issues: {unestimated}\nsource_issues: {source_issues}\n\
         source_units: {source_units}\ndiagnostics: {diagnostics}\n",
        scope = calculation.scope.kind.as_str(),
        reference = calculation.scope.reference,
        display = calculation.scope.display,
        state = calculation.state().as_str(),
        capacity = number(calculation.capacity),
        unit = calculation.unit.as_deref().unwrap_or("-"),
        committed = number(calculation.committed),
        completed = number(calculation.completed),
        remaining = number(calculation.remaining),
        overflow = number(calculation.overflow),
        utilization = utilization(calculation.utilization),
        counted = number(calculation.counted_issues),
        uncounted = number(calculation.uncounted_issues),
        unestimated = number(calculation.unestimated_issues),
        source_issues = calculation.source.issues,
        source_units = joined(&calculation.source.units),
        diagnostics = calculation.diagnostics.len(),
    )
}

/// The DTO's own fields, in the shape `tix cycle schedule show` prints.
fn print_calculation(calculation: &CapacityCalculation) {
    print!("{}", calculation_text(calculation));
}

/// Render the findings, through the shared [`CapacityWarning::render`].
///
/// A finding about an estimate or a reference explains why a total is short, so it is
/// always printed; the overflow report is the opt-in half of the same set, and carries
/// the scope, the committed value, the ceiling, the excess and the unit (C-006).
fn render_findings(diagnostics: &[CapacityWarning], overflow: bool) {
    for warning in diagnostics {
        if overflow || !matches!(warning.kind, CapacityWarningKind::Overflow) {
            eprintln!("{}", warning.render());
        }
    }
}

// ---------------------------------------------------------------------------
// T028 — the close evidence, read back
// ---------------------------------------------------------------------------

/// `tix capacity snapshot <CYCLE>`: a closed cycle's immutable capacity evidence.
///
/// A pure read through the existing snapshot store and the WP04 reader. A cycle with no
/// snapshot at all is a `not_found` (the command asked for something that is not there);
/// a snapshot that carries no capacity payload — written before this mission, or by a
/// close whose request carried no calculation — is `evidence: none`, a value and never
/// an error, so a legacy record stays readable.
fn read_snapshot(config: &Config, root: &Path, cycle: &str, warnings: bool) -> Result<()> {
    let index = schedule_index(config, root)?;
    let cycle_id = match resolve_cycle(&index, cycle) {
        CycleReference::Generated { id, .. } => id,
        CycleReference::Legacy { .. } => {
            return Err(TixError::NotFound(format!(
                "cycle `{cycle}` is a hand-written cycle and has no generated snapshot; \
                 `tix capacity snapshot` reads the evidence a generated cycle's close captured"
            )));
        }
        CycleReference::Unknown { .. } => {
            return Err(TixError::NotFound(format!(
                "no cycle `{cycle}` resolves to a record, so there is no snapshot to read"
            )));
        }
    };
    let store = CycleSnapshotStore::new(root);
    let Some(stored) = store.read(&cycle_id)? else {
        return Err(TixError::NotFound(format!(
            "cycle `{cycle_id}` has no snapshot: it has not been closed, or its snapshot was \
             removed"
        )));
    };
    println!("cycle: {cycle_id}");
    println!(
        "snapshot: docs/cycle_snapshots/{filename}",
        filename = CycleSnapshotStore::filename_for(&cycle_id)
    );
    match CapacitySnapshot::from_cycle_snapshot(&stored)? {
        None => {
            println!("evidence: none");
            eprintln!(
                "note: this snapshot carries no capacity payload; it was written before capacity \
                 evidence was captured, and it is not an error — nothing is migrated in place"
            );
        }
        Some(evidence) => {
            println!("evidence: present");
            print_evidence(&evidence);
            render_findings(&evidence.diagnostics, warnings);
        }
    }
    Ok(())
}

/// The stored evidence's own fields as one text block, exactly as the close wrote them —
/// the bytes [`print_evidence`] appends to stdout, and the text the MCP surface returns,
/// so the two cannot word one snapshot two ways (C-007/NFR-003).
pub(crate) fn evidence_text(evidence: &CapacitySnapshot) -> String {
    format!(
        "snapshot_id: {snapshot_id}\nclosed_at: {closed_at}\nclosed_by: {closed_by}\n\
         scope: {scope}\nreference: {reference}\ndisplay: {display}\nstate: {state}\n\
         capacity: {capacity}\nunit: {unit}\ncommitted: {committed}\ncompleted: {completed}\n\
         remaining: {remaining}\noverflow: {overflow}\nutilization: {utilization}\n\
         counted_issues: {counted}\nuncounted_issues: {uncounted}\n\
         unestimated_issues: {unestimated}\nsource_issues: {source_issues}\n\
         source_units: {source_units}\ndiagnostics: {diagnostics}\n",
        snapshot_id = evidence.snapshot_id,
        closed_at = evidence.closed_at,
        closed_by = evidence.closed_by,
        scope = evidence.scope.kind.as_str(),
        reference = evidence.scope.reference,
        display = evidence.scope.display,
        state = evidence.state.as_str(),
        capacity = number(evidence.capacity),
        unit = evidence.unit.as_deref().unwrap_or("-"),
        committed = number(evidence.committed),
        completed = number(evidence.completed),
        remaining = number(evidence.remaining),
        overflow = number(evidence.overflow),
        utilization = utilization(evidence.utilization),
        counted = number(evidence.counted_issues),
        uncounted = number(evidence.uncounted_issues),
        unestimated = number(evidence.unestimated_issues),
        source_issues = evidence.source.issues,
        source_units = joined(&evidence.source.units),
        diagnostics = evidence.diagnostics.len(),
    )
}

/// The stored evidence's own fields, exactly as the close wrote them.
fn print_evidence(evidence: &CapacitySnapshot) {
    print!("{}", evidence_text(evidence));
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

/// Parse `--scope`. A well-formed but unknown word is a refusal naming the vocabulary,
/// not a guess (the shape `commands::views::parse_scope_kind` uses).
pub(crate) fn parse_scope_kind(raw: &str) -> Result<CapacityScopeKind> {
    match raw {
        "cycle" => Ok(CapacityScopeKind::Cycle),
        "team" => Ok(CapacityScopeKind::Team),
        "assignee" => Ok(CapacityScopeKind::Assignee),
        other => Err(TixError::InvalidInput(format!(
            "`{other}` is not a capacity scope; expected one of `{}`",
            CapacityScopeKind::all()
                .iter()
                .map(|kind| kind.as_str())
                .collect::<Vec<_>>()
                .join("`, `")
        ))),
    }
}

/// A flag value that must be present and non-blank, named as the user typed it.
pub(crate) fn required<'a>(flag: &str, value: &'a str) -> Result<&'a str> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err(TixError::InvalidInput(format!(
            "`{flag}` must not be blank"
        )));
    }
    if trimmed != value {
        return Err(TixError::InvalidInput(format!(
            "`{flag}` (`{value}`) has leading or trailing whitespace"
        )));
    }
    Ok(value)
}

/// The identity label a scope reference resolves to — **the library's own resolution**.
///
/// [`CapacityScope::new`] is the crate's reference-to-scope adapter for a capacity scope:
/// a generated cycle's stable id resolves to the instance's name, an assignee handle is
/// canonicalised by the model's own parser, a team label and a hand-written cycle name
/// stay themselves, and a reference nothing answers to keeps the text the caller wrote.
/// Two spellings of one scope therefore yield one label here, which is what makes a
/// ceiling configured under a stable id readable, updatable and removable under the
/// instance's name (C-003's "a legacy cycle name and generated stable cycle ID are
/// resolved through one adapter"), while two genuinely unresolvable names stay distinct.
pub(crate) fn scope_label(
    kind: CapacityScopeKind,
    reference: &str,
    index: &ScheduleIndex,
) -> String {
    CapacityScope::new(kind, reference, index).display
}

/// The `[capacity.<id>]` handle a scope's **resolved identity** derives.
///
/// Derived, never resolved: nothing reads a scope back through the handle
/// ([`CapacityCalculation::for_scope`] folds the reference itself), so this is a naming
/// choice that exists to make `set` idempotent for one scope across its spellings — the
/// instance's stable id and its name derive one handle, because they resolve to one
/// label. [`crate::slug::slugify`] is the crate's one slug, so two *different* labels can
/// still collide on one handle (`Platform` and `platform`); `set` refuses that case
/// rather than letting one scope's ceiling become another's.
fn capacity_key(kind: CapacityScopeKind, label: &str) -> String {
    format!(
        "{kind}-{slug}",
        kind = kind.as_str(),
        slug = crate::slug::slugify(label)
    )
}

/// Every entry that answers to `reference`, by the **identity** its scope resolves to,
/// optionally restricted to one scope kind. The entry's kind and reference are resolved
/// here, so a caller never has to ask a validated section's entry again.
///
/// Matching on the resolved label — not on the entry's key and not on its scope text — is
/// what lets a generated instance's id and its name select one ceiling, and it keeps a
/// hand-written entry (whose key this CLI never derived) reachable by the scope it
/// declares.
pub(crate) fn entries_matching<'a>(
    config: &'a Config,
    kind: Option<CapacityScopeKind>,
    reference: &str,
    index: &ScheduleIndex,
) -> Vec<(&'a str, CapacityScopeKind, &'a CapacityEntry)> {
    config
        .capacity
        .iter()
        .filter_map(|(id, entry)| {
            let entry_kind = entry.scope_kind()?;
            if kind.is_some_and(|wanted| wanted != entry_kind) {
                return None;
            }
            let entry_label = scope_label(entry_kind, entry.scope_id()?, index);
            (entry_label == scope_label(entry_kind, reference, index))
                .then_some((id, entry_kind, entry))
        })
        .collect()
}

/// The one entry a reference names, or the refusal saying why it is none or several.
pub(crate) fn one_entry<'a>(
    config: &'a Config,
    kind: Option<CapacityScopeKind>,
    reference: &str,
    index: &ScheduleIndex,
) -> Result<(&'a str, CapacityScopeKind, &'a CapacityEntry)> {
    let matches = entries_matching(config, kind, reference, index);
    match matches.as_slice() {
        [] => Err(TixError::NotFound(match kind {
            Some(kind) => format!(
                "no capacity entry for {kind} `{reference}`; configure one with `tix capacity \
                 set --scope {kind} --id {reference} --value <N> --unit <UNIT>`"
            ),
            None => format!(
                "no capacity entry names `{reference}`; `tix capacity list` shows the configured \
                 scopes"
            ),
        })),
        [(id, kind, entry)] => Ok((*id, *kind, *entry)),
        many => {
            let listed = many
                .iter()
                .map(|(id, kind, entry)| {
                    format!(
                        "`{id}` ({kind} `{scope}`)",
                        kind = kind.as_str(),
                        scope = entry.scope_id().unwrap_or_default()
                    )
                })
                .collect::<Vec<_>>()
                .join(", ");
            Err(TixError::InvalidInput(format!(
                "`{reference}` matches {} capacity entries: {listed}; pass `--scope` to name one",
                many.len()
            )))
        }
    }
}

/// The closed-cycle boundary for a delete, through the library's own resolution.
///
/// [`set_capacity`] gates a `set` on its own; a `delete` is the other ordinary
/// configuration change, so it consults the same [`ensure_cycle_editable`] with the same
/// [`CapacityEdit::Configure`]. The record is found by the identity
/// [`resolve_cycle`] answers with — the reference is never re-folded here. A reference
/// no record answers to has no lifecycle state to consult, which is the same answer
/// [`set_capacity`] reaches.
fn ensure_cycle_editable_for(config: &Config, root: &Path, reference: &str) -> Result<()> {
    let records = CycleStore::new(root).list()?;
    let index = ScheduleIndex::build(config, &records);
    let name = match resolve_cycle(&index, reference) {
        CycleReference::Generated { name, .. } | CycleReference::Legacy { name } => name,
        CycleReference::Unknown { .. } => return Ok(()),
    };
    if let Some(record) = records.iter().find(|record| record.name == name) {
        ensure_cycle_editable(record, &CapacityEdit::Configure)?;
    }
    Ok(())
}

/// An absent number as `-`, the crate's convention for "no value" (never a zero).
pub(crate) fn number<T: std::fmt::Display>(value: Option<T>) -> String {
    value.map_or_else(|| "-".to_string(), |value| value.to_string())
}

/// A utilization percentage as the DTO's `u32` — `-` when the ceiling was zero or absent.
pub(crate) fn utilization(value: Option<u32>) -> String {
    value.map_or_else(|| "-".to_string(), |value| format!("{value}%"))
}

/// A unit list as one cell; an empty list is `-`.
pub(crate) fn joined(units: &[String]) -> String {
    if units.is_empty() {
        "-".to_string()
    } else {
        units.join(", ")
    }
}