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
//! `tix cycle` and its `tix cycle schedule` namespace (mission
//! `repeating-cycle-schedules-01M3C7W1`, WP06).
//!
//! The legacy `tix cycle create|list|edit|delete` verbs are untouched: they are
//! the hand-written cycle registry, and their behaviour is frozen.
//!
//! # The schedule surface is a thin adapter
//!
//! `tix cycle schedule …` parses, calls **one** service, and prints. The schedule
//! record and its validation live in [`crate::cycle_schedule::config`], the read
//! model in [`crate::cycle_schedule::identity`], detection in
//! [`crate::cycle_schedule::evaluate`], creation in
//! [`crate::cycle_schedule::generate`], the lifecycle in
//! [`crate::cycle_schedule::lifecycle`], and the **registry** — create, edit, delete,
//! the selector and the spent-id guard — in [`crate::cycle_schedule::registry`].
//! This module owns **no** cadence arithmetic, no cursor, no snapshot and no History
//! grammar — a second evaluator here is the exact divergence C-008 forbids.
//!
//! `create`/`edit`/`delete` were implemented here first; they are now the service's,
//! and the TUI's `F8` Schedule page form and the MCP tools call the same functions, so
//! a change to the guard or the vocabulary reaches every surface at once (WP07 review
//! finding H4).
//!
//! # Close and reopen carry the capacity evidence (mission
//! `cycle-capacity-planning-01M3C85C`, WP05)
//!
//! A confirmed `close` hands the shared capacity calculation to the lifecycle as its
//! snapshot's evidence ([`crate::cycle_schedule::lifecycle::LifecycleRequest::capacity`]),
//! computed through `commands::capacity::calculation_for` — a `pub(crate)` seam — because
//! this is where the project configuration and the issue store are owned: the `apply`
//! seam holds neither, by design. `reopen` is that action's own inverse and captures
//! nothing: it restores the record and appends the one `cycle_reopened` event, so the
//! snapshot the close wrote stays the immutable evidence a later reader quotes
//! (C-008/NFR-002). Neither verb derives a total, a rounding or a scope identity of its
//! own.
//!
//! # The one clock, and where it lives
//!
//! `detect` evaluates against an explicit `--date` when one is given, and
//! otherwise against the crate's own boundary clock
//! ([`crate::model::today`]), exactly as `tix recurring detect` does. Nothing in
//! the domain reads a clock. A lifecycle action's audit timestamp is resolved the
//! same way, at the boundary ([`crate::model::utc_now_rfc3339`]), because the
//! service requires an explicit instant and this crate has no clock below the CLI.
//!
//! # Confirmation
//!
//! Every mutating verb requires `--confirm`; without it the command refuses, prints
//! one diagnostic to stderr and exits non-zero, having written nothing. Detection
//! and the read verbs never take the flag and never write.

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

use crate::cli::{
    CycleCommand, CycleScheduleCommand, CycleScheduleCreateArgs, CycleScheduleEditArgs,
    CycleScheduleLifecycleArgs,
};
use crate::config::Config;
use crate::cycle_schedule::config::CycleScheduleId;
use crate::cycle_schedule::evaluate::evaluate;
use crate::cycle_schedule::generate::{GenerationRequest, generate};
use crate::cycle_schedule::identity::{GeneratedCycleId, ScheduleIndex, cadence_rule};
use crate::cycle_schedule::lifecycle::{
    LifecycleAction, LifecycleOutcome, LifecycleRequest, apply,
};
use crate::cycle_schedule::registry::{self, ScheduleDraft, ScheduleEdit};
use crate::error::{Result, TixError};
use crate::planning::Planner;
use crate::recurrence::rule::IntervalUnit;
use crate::storage::Store;

fn root_from_store(store: &Store) -> PathBuf {
    Config::project_root(&store.issues_dir).unwrap_or_else(|| PathBuf::from("."))
}

/// Route the frozen legacy `tix cycle create|list|edit|delete` verbs.
///
/// Called from `commands::dispatch`, so a legacy `tix cycle …` still passes
/// through `run_subcommand` and emits the same rollover advisory it always did.
pub fn run_legacy(config: &Config, store: &Store, cmd: &CycleCommand) -> Result<()> {
    let mut planner = Planner::from_config(config.clone(), root_from_store(store));
    match cmd {
        CycleCommand::Create {
            name,
            description,
            start_date,
            due_date,
        } => create(
            &mut planner,
            name.as_deref(),
            description.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
        ),
        CycleCommand::List => list(&planner, store),
        CycleCommand::Edit {
            name,
            new_name,
            description,
            start_date,
            due_date,
        } => edit(
            &mut planner,
            store,
            name,
            new_name.as_deref(),
            description.as_deref(),
            start_date.as_deref(),
            due_date.as_deref(),
        ),
        CycleCommand::Delete { name, yes } => delete(&mut planner, store, name, *yes),
        // Routed by the process entry, not by `dispatch`; reaching here means the
        // router dropped it.
        CycleCommand::Schedule { .. } => {
            unreachable!("`tix cycle schedule` is routed by `cli::run`, not by `cycle::run_legacy`")
        }
    }
}

fn create(
    planner: &mut Planner,
    name: Option<&str>,
    description: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
) -> Result<()> {
    let name = planner.add_cycle(name.map(str::to_string))?;
    planner.set_cycle_fields(&name, description, start_date, due_date)?;
    let overlaps = planner.overlapping_cycles(&name);
    println!("{name}");
    // The cycle is created either way; an overlapping window is a warning, not
    // a refusal. A cycle with no start date has no window and warns about
    // nothing (tix #1509).
    if !overlaps.is_empty() {
        eprintln!(
            "{}",
            crate::diagnostics::Diagnostic::warning(
                "W-tix-cycle",
                format!(
                    "cycle `{name}` overlaps existing cycle(s): {}",
                    overlaps.join(", ")
                )
            )
            .render_auto()
        );
    }
    Ok(())
}

fn list(planner: &Planner, store: &Store) -> Result<()> {
    for name in planner.cycle_names() {
        let Some(cycle) = planner.cycle(&name) else {
            continue;
        };
        let issues = store
            .list()?
            .into_iter()
            .filter(|issue| {
                issue
                    .cycles
                    .as_ref()
                    .is_some_and(|cycles| cycles.iter().any(|cycle_name| cycle_name == &name))
            })
            .count();
        let description = cycle.description.as_deref().unwrap_or("");
        let start = cycle.start_date.as_deref().unwrap_or("");
        let due = cycle.due_date.as_deref().unwrap_or("");
        println!("{name}\t{description}\t{start}\t{due}\t{issues}");
    }
    Ok(())
}

fn edit(
    planner: &mut Planner,
    store: &Store,
    name: &str,
    new_name: Option<&str>,
    description: Option<&str>,
    start_date: Option<&str>,
    due_date: Option<&str>,
) -> Result<()> {
    let final_name = if let Some(new_name) = new_name {
        let impact = planner.rename_cycle_cascade(store, name, new_name)?;
        println!(
            "renamed cycle `{name}` to `{new_name}`; updated {} issue(s)",
            impact.changed_issue_count
        );
        new_name
    } else {
        name
    };

    if description.is_some() || start_date.is_some() || due_date.is_some() {
        planner.set_cycle_fields(final_name, description, start_date, due_date)?;
    }
    Ok(())
}

fn delete(planner: &mut Planner, store: &Store, name: &str, yes: bool) -> Result<()> {
    let impact = planner.delete_impact(store, name)?;
    if !impact.referencing_issues.is_empty() {
        eprintln!(
            "cycle `{name}` is referenced by {} issue(s): {}",
            impact.referencing_issues.len(),
            impact.referencing_issues.join(", ")
        );
    }

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

    planner.delete_cycle(name)?;
    println!("deleted cycle `{name}`");
    if !impact.referencing_issues.is_empty() {
        println!("note: issue cycle references were left unchanged");
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// `tix cycle schedule …`
// ---------------------------------------------------------------------------

/// Route `tix cycle schedule …` to the one service each verb wraps.
///
/// Called from `cli::run` (the schedule namespace mutates `tix.toml`, so it needs
/// the mutable config only the process entry owns). The legacy verbs stay on
/// [`run_legacy`], reached through `commands::dispatch`, so their behaviour —
/// including `run_subcommand`'s rollover advisory — is exactly as before.
pub fn run_schedule(
    config: &mut Config,
    store: &Store,
    command: &CycleScheduleCommand,
) -> Result<()> {
    let root = root_from_store(store);
    match command {
        CycleScheduleCommand::List => schedule_list(config, &root),
        CycleScheduleCommand::Show { schedule } => schedule_show(config, &root, schedule),
        CycleScheduleCommand::Create(args) => schedule_create(config, &root, args),
        CycleScheduleCommand::Edit {
            schedule,
            args,
            confirm,
        } => schedule_edit(config, &root, schedule, args, *confirm),
        CycleScheduleCommand::Delete { schedule, confirm } => {
            schedule_delete(config, &root, schedule, *confirm)
        }
        CycleScheduleCommand::Detect { date } => schedule_detect(config, &root, date.as_deref()),
        CycleScheduleCommand::Generate {
            schedule,
            through,
            confirm,
        } => schedule_generate(config, &root, schedule, through.as_deref(), *confirm),
        CycleScheduleCommand::Close { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Close,
            &args.lifecycle,
            args.reason.as_deref(),
            None,
        ),
        CycleScheduleCommand::Reopen { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Reopen,
            &args.lifecycle,
            args.reason.as_deref(),
            None,
        ),
        CycleScheduleCommand::Extend { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Extend,
            &args.reason.lifecycle,
            args.reason.reason.as_deref(),
            args.by,
        ),
        CycleScheduleCommand::Skip { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Skip,
            &args.lifecycle,
            args.reason.as_deref(),
            None,
        ),
        CycleScheduleCommand::Pause { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Pause,
            args,
            None,
            None,
        ),
        CycleScheduleCommand::Resume { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Resume,
            args,
            None,
            None,
        ),
        CycleScheduleCommand::AdjustFuture { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::AdjustFuture,
            &args.lifecycle,
            args.reason.as_deref(),
            None,
        ),
        CycleScheduleCommand::Ignore { schedule, args } => lifecycle(
            config,
            store,
            &root,
            schedule,
            LifecycleAction::Ignore,
            args,
            None,
            None,
        ),
    }
}

// -- config: list, show, create, edit, delete --------------------------------

fn schedule_list(config: &Config, root: &Path) -> Result<()> {
    let index = registry::load_index(config, root)?;
    println!(
        "id\tname\tstate\tcadence\tduration\tstart_date\tlook_ahead\tnext_sequence\tgenerated"
    );
    for (id, record) in index.schedules() {
        let cadence = cadence_rule(record)
            .map(|rule| rule.summary())
            .unwrap_or_else(|| "(no cadence)".to_string());
        let duration = match record.duration.unit {
            Some(unit) => format!("{} {}", record.duration.count, unit.as_str()),
            None => format!("{} (no unit)", record.duration.count),
        };
        let cursor = index.cursor(id);
        let next = cursor
            .next_sequence
            .map(|sequence| sequence.to_string())
            .unwrap_or_else(|| "-".to_string());
        println!(
            "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
            id,
            record.name,
            record.state.as_str(),
            cadence,
            duration,
            record.start_date,
            record.look_ahead,
            next,
            index.cycles_of(id).count()
        );
    }
    Ok(())
}

fn schedule_show(config: &Config, root: &Path, selector: &str) -> Result<()> {
    let index = registry::load_index(config, root)?;
    let id = registry::resolve(&index, selector)?;
    let record = index
        .schedule(&id)
        .expect("resolved schedule exists in the index");
    println!("id: {id}");
    println!("name: {}", record.name);
    println!("state: {}", record.state.as_str());
    println!(
        "cadence: {}",
        cadence_rule(record)
            .map(|rule| rule.summary())
            .unwrap_or_else(|| "(no cadence)".to_string())
    );
    println!(
        "duration: {} {}",
        record.duration.count,
        record
            .duration
            .unit
            .map_or("(no unit)", IntervalUnit::as_str)
    );
    println!("start_date: {}", record.start_date);
    println!(
        "timezone: {}",
        record
            .timezone
            .as_ref()
            .map(ToString::to_string)
            .unwrap_or_else(|| "(none)".to_string())
    );
    println!("look_ahead: {}", record.look_ahead);
    let cursor = index.cursor(&id);
    println!(
        "next_sequence: {}",
        cursor
            .next_sequence
            .map(|sequence| sequence.to_string())
            .unwrap_or_else(|| "-".to_string())
    );
    println!(
        "next_start: {}",
        cursor.next_start.as_deref().unwrap_or("-")
    );
    println!(
        "last_generated_key: {}",
        cursor
            .last_generated_key
            .as_ref()
            .map(GeneratedCycleId::as_str)
            .unwrap_or("-")
    );
    println!("generated: {}", index.cycles_of(&id).count());
    for cycle in index.cycles_of(&id) {
        println!(
            "  {}\t{}\t{} -> {}",
            cycle.id,
            cycle.state.as_str(),
            cycle.start_date,
            cycle.due_date
        );
    }
    for diagnostic in index
        .diagnostics()
        .iter()
        .filter(|d| d.schedule_id.as_ref() == Some(&id))
    {
        eprintln!("{}", diagnostic.render());
    }
    Ok(())
}

/// `tix cycle schedule create`: parse the flags into a draft, hand it to the shared
/// registry, print.
///
/// The name-exists check, the spent-id guard, the vocabulary and the write all live in
/// [`crate::cycle_schedule::registry`], so this function and the TUI's form and the
/// MCP tool cannot drift apart (WP07 finding H4). `--confirm` stays here: it is a
/// flag, and the caller's consent is the CLI's business, not the registry's.
fn schedule_create(config: &mut Config, root: &Path, args: &CycleScheduleCreateArgs) -> Result<()> {
    require_confirm("create", args.confirm)?;
    let id = registry::create(
        config,
        root,
        &ScheduleDraft {
            id: args.id.clone(),
            name: args.name.clone(),
            cadence: args.cadence.clone(),
            interval: args.interval,
            unit: args.unit.clone(),
            duration: args.duration,
            duration_unit: args.duration_unit.clone(),
            start_date: args.start_date.clone(),
            timezone: args.timezone.clone(),
            look_ahead: args.look_ahead,
        },
    )?;
    println!("created schedule `{id}`");
    Ok(())
}

/// `tix cycle schedule edit`: every flag the user named becomes one patch field, and
/// the registry changes exactly those.
fn schedule_edit(
    config: &mut Config,
    root: &Path,
    selector: &str,
    args: &CycleScheduleEditArgs,
    confirm: bool,
) -> Result<()> {
    require_confirm("edit", confirm)?;
    let id = registry::edit(
        config,
        root,
        selector,
        &ScheduleEdit {
            name: args.name.clone(),
            cadence: args.cadence.clone(),
            interval: args.interval,
            unit: args.unit.clone(),
            duration: args.duration,
            duration_unit: args.duration_unit.clone(),
            start_date: args.start_date.clone(),
            timezone: args.timezone.clone(),
            look_ahead: args.look_ahead,
        },
    )?;
    println!("updated schedule `{id}`");
    Ok(())
}

/// `tix cycle schedule delete`: remove the definition, and report the records it
/// deliberately left behind.
fn schedule_delete(config: &mut Config, root: &Path, selector: &str, confirm: bool) -> Result<()> {
    require_confirm("delete", confirm)?;
    let deletion = registry::delete(config, root, selector)?;
    let id = deletion.id;
    println!("deleted schedule `{id}`");
    if deletion.generated_cycles > 0 {
        println!(
            "note: {} generated cycle(s) and their snapshots were left unchanged; they now \
             reference a missing schedule",
            deletion.generated_cycles
        );
    }
    Ok(())
}

// -- read-only detection -----------------------------------------------------

fn schedule_detect(config: &Config, root: &Path, date: Option<&str>) -> Result<()> {
    // `--date` wins; otherwise the boundary resolves today, exactly as
    // `tix recurring detect` does. Nothing below reads a clock.
    let context = crate::commands::recurring::context_for(date, None)?;
    let index = registry::load_index(config, root)?;
    let evaluation = evaluate(&index, &context);
    if evaluation.is_empty() {
        println!(
            "No cycle-schedule warnings across {} schedule(s).",
            evaluation.schedules_examined()
        );
        return Ok(());
    }
    println!("schedule_id\tkind\tcycle_id\tstart\tdue\tnext_start\tnext_id\tactions\tdetail");
    for warning in evaluation.warnings() {
        let start = warning
            .effective_dates
            .as_ref()
            .map(|dates| dates.start.as_str())
            .unwrap_or("-");
        let due = warning
            .effective_dates
            .as_ref()
            .map(|dates| dates.due.as_str())
            .unwrap_or("-");
        let next_start = warning
            .next_generation
            .as_ref()
            .and_then(|key| key.start_date.as_deref())
            .unwrap_or("-");
        let next_id = warning
            .next_generation
            .as_ref()
            .map(|key| key.id.as_str())
            .unwrap_or("-");
        let actions = if warning.available_actions.is_empty() {
            "-".to_string()
        } else {
            warning
                .available_actions
                .iter()
                .map(|action| action.as_str())
                .collect::<Vec<_>>()
                .join(",")
        };
        let detail = warning
            .diagnostic
            .as_ref()
            .map(|diagnostic| diagnostic.message.as_str())
            .unwrap_or("-");
        let cycle_id = warning
            .cycle_id
            .as_ref()
            .map(GeneratedCycleId::as_str)
            .unwrap_or("-");
        println!(
            "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}",
            warning.schedule_id,
            warning.kind.as_str(),
            cycle_id,
            start,
            due,
            next_start,
            next_id,
            actions,
            detail
        );
    }
    Ok(())
}

// -- confirmed generation ----------------------------------------------------

fn schedule_generate(
    config: &mut Config,
    root: &Path,
    selector: &str,
    through: Option<&str>,
    confirm: bool,
) -> Result<()> {
    require_confirm("generate", confirm)?;
    let index = registry::load_index(config, root)?;
    let id = registry::resolve(&index, selector)?;
    let look_ahead = match through {
        Some(through) => candidates_through(&index, &id, through)?,
        // No `--through`: the schedule's own configured look-ahead is the horizon,
        // exactly as a confirmation of what detection showed.
        None => index.schedule(&id).map_or(0, |record| record.look_ahead),
    };
    let context = crate::commands::recurring::context_for(None, None)?;
    let request = GenerationRequest::new(id, context, look_ahead, actor()).confirm();
    let report = generate(config, root, &index, &request)?;

    let mut failures: Vec<String> = Vec::new();
    for outcome in report.outcomes() {
        if outcome.is_rejected() {
            failures.push(outcome.render());
        } else {
            println!("{}", outcome.render());
        }
    }
    if report.is_empty() {
        println!("{}", report.render());
    }
    if !failures.is_empty() {
        return Err(TixError::Refused(failures.join("\n")));
    }
    Ok(())
}

/// How many candidates starting on or before `through` the schedule would create.
///
/// This is a **horizon selector**, not a second generator: it steps through
/// [`crate::recurrence::rule::RecurrenceRule::next_occurrence`] — the shared
/// arithmetic owner the generator itself uses — starting at the same
/// [`ScheduleIndex::next_key`] the generator starts at, and counts how many land on
/// or before the date. The creation itself is still [`generate`]'s, under its own
/// count contract (`look_ahead`).
fn candidates_through(index: &ScheduleIndex, id: &CycleScheduleId, through: &str) -> Result<u32> {
    let through = registry::canonical_date(through)?;
    let Some(first) = index.next_key(id) else {
        return Ok(0);
    };
    let Some(record) = index.schedule(id) else {
        return Ok(0);
    };
    let Some(rule) = cadence_rule(record) else {
        return Ok(0);
    };
    let mut count: u32 = 0;
    let mut date = first.start_date.clone();
    while let Some(start) = date {
        if start.as_str() > through.as_str() {
            break;
        }
        count = count.saturating_add(1);
        if count == u32::MAX {
            break;
        }
        let Ok(context) = crate::commands::recurring::context_for(Some(start.as_str()), None)
        else {
            break;
        };
        match rule.next_occurrence(&context) {
            Ok(next) => date = Some(next.as_str().to_string()),
            Err(_) => break,
        }
    }
    Ok(count)
}

// -- confirmed lifecycle -----------------------------------------------------

#[allow(clippy::too_many_arguments)]
fn lifecycle(
    config: &mut Config,
    store: &Store,
    root: &Path,
    selector: &str,
    action: LifecycleAction,
    args: &CycleScheduleLifecycleArgs,
    reason: Option<&str>,
    by: Option<u32>,
) -> Result<()> {
    require_confirm(action.as_str(), args.confirm)?;
    if let Some(periods) = by
        && periods != 1
    {
        return Err(registry::refuse(
            "invalid_input",
            format!(
                "`--by {periods}` is not supported: the shared lifecycle extends an instance by \
                 exactly one cadence period per action, and this surface will not re-derive a \
                 multi-period step of its own. Extend once per period."
            ),
        ));
    }
    let index = registry::load_index(config, root)?;
    let id = registry::resolve(&index, selector)?;
    let cycle_id = select_cycle(&index, &id, args.cycle.as_deref(), args.from.as_deref())?;

    let mut request =
        LifecycleRequest::new(action, id.clone(), actor()).with_timestamp(now_timestamp());
    if let Some(cycle_id) = cycle_id.clone() {
        request = request.for_cycle(cycle_id);
    }
    if let Some(reason) = reason {
        request = request.with_reason(reason);
    }
    // WP05 (T028): a confirmed close records the capacity evidence the mission promised
    // (FR-005/C-008). The seam computes it — this site owns the configuration and the
    // issue store, and the lifecycle's `apply` owns neither — and it is the same seam
    // the TUI's and MCP's close sites call, so three surfaces record one payload.
    let request = crate::commands::capacity::with_close_capacity(request, config, root, store)?;
    let request = request.confirm();

    let outcome = apply(config, root, &request)?;
    print_outcome(&outcome)
}

/// Resolve the instance a lifecycle action names: `--cycle` first, then a unique
/// instance by `--from` start date, else none.
fn select_cycle(
    index: &ScheduleIndex,
    id: &CycleScheduleId,
    cycle: Option<&str>,
    from: Option<&str>,
) -> Result<Option<GeneratedCycleId>> {
    if let Some(raw) = cycle {
        return Ok(Some(GeneratedCycleId::parse(raw)?));
    }
    let Some(raw) = from else {
        return Ok(None);
    };
    let wanted = registry::canonical_date(raw)?;
    match index
        .cycles_of(id)
        .find(|cycle| cycle.start_date == wanted)
        .map(|cycle| cycle.id.clone())
    {
        Some(cycle_id) => Ok(Some(cycle_id)),
        None => Err(registry::refuse(
            "unknown_cycle",
            format!(
                "no instance of schedule `{id}` starts on `{wanted}`; pass `--cycle \
                 <schedule-id>:<sequence>` to name one"
            ),
        )),
    }
}

fn print_outcome(outcome: &LifecycleOutcome) -> Result<()> {
    if outcome.is_rejected() {
        return Err(TixError::Refused(outcome.render()));
    }
    println!("{}", outcome.render());
    Ok(())
}

// -- shared helpers ----------------------------------------------------------

/// The actor recorded in History: the git identity when there is one, else the
/// environment's user, else a stable placeholder (shared with `tix recurring`).
fn actor() -> String {
    crate::commands::recurring::actor()
}

/// The explicit instant a lifecycle action records: resolved at the boundary,
/// because the crate has no clock below it (the same clock `created`/`updated`
/// use).
fn now_timestamp() -> String {
    crate::model::utc_now_rfc3339()
}

/// Refuse a mutation that was not confirmed, writing nothing.
fn require_confirm(action: &str, confirm: bool) -> Result<()> {
    if confirm {
        return Ok(());
    }
    Err(crate::cycle_schedule::registry::refuse(
        "not_confirmed",
        format!(
            "`tix cycle schedule {action}` changes state; pass `--confirm` to proceed — nothing \
             was written"
        ),
    ))
}