tix-tracker 0.12.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
#[allow(clippy::wildcard_imports)]
use super::*;

pub(super) fn cycle_schedule_create(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if !opt_bool(args, "confirm")?.unwrap_or(false) {
        return Ok(cycle_schedule_unconfirmed("create"));
    }
    // Every spelling is parsed by the shared registry (`record_for`), so this tool
    // and `tix cycle schedule create` agree on what a cadence family or a unit is
    // by construction (C-008/H4).
    let draft = ScheduleDraft {
        id: req_string(args, "id")?,
        name: req_string(args, "name")?,
        cadence: req_string(args, "cadence")?,
        interval: opt_u32(args, "interval")?,
        unit: opt_string(args, "unit")?,
        duration: req_u32(args, "duration")?,
        duration_unit: req_string(args, "duration_unit")?,
        start_date: req_string(args, "start_date")?,
        timezone: req_string(args, "timezone")?,
        look_ahead: opt_u32(args, "look_ahead")?,
    };
    let (mut config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    // The id-exists refusal, the spent-id guard (a stored record **or** a closed
    // snapshot still claims a deleted id) and the pre-persistence validation all
    // live in the registry, so a create the CLI refuses is refused here with the
    // same sentence — and writes nothing.
    let id = match registry::create(&mut config, &root, &draft) {
        Ok(id) => id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let Some(record) = index.schedule(&id) else {
        return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
            format!("cycle schedule `{id}`"),
        )));
    };
    Ok(success_result(
        format!("created schedule `{id}`\n"),
        cycle_schedule_value(&id, record, &index),
    ))
}

pub(super) fn cycle_schedule_delete(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if !opt_bool(args, "confirm")?.unwrap_or(false) {
        return Ok(cycle_schedule_unconfirmed("delete"));
    }
    let selector = req_string(args, "schedule")?;
    let (mut config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    // The value this reports is read through the shared read model before the
    // removal; the removal itself — the selector resolution, the count of records
    // deliberately left on disk and the save — is the registry's one implementation
    // (C-008/H4). Nothing here re-spends an id, re-folds a name or re-writes a
    // sentence of its own.
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let id = match registry::resolve(&index, &selector) {
        Ok(id) => id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let Some(record) = index.schedule(&id).cloned() else {
        return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
            format!("cycle schedule `{selector}`"),
        )));
    };
    let deleted = cycle_schedule_value(&id, &record, &index);
    let deletion = match registry::delete(&mut config, &root, &selector) {
        Ok(deletion) => deletion,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let generated = deletion.generated_cycles;
    let mut text = format!("deleted schedule `{id}`\n");
    if generated > 0 {
        text.push_str(&format!(
            "note: {generated} generated cycle(s) and their snapshots were left unchanged; they \
             now reference a missing schedule\n"
        ));
    }
    Ok(success_result(
        text,
        json!({
            "deleted": deleted,
            "generated": generated,
        }),
    ))
}

pub(super) fn cycle_schedule_detect(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    let date = opt_string(args, "date")?;
    let timezone = opt_string(args, "timezone")?;
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    // `date` wins; otherwise the boundary resolves today, exactly as
    // `tix cycle schedule detect` does. Nothing below reads a clock.
    let context = match cmd_recurring::context_for(date.as_deref(), timezone.as_deref()) {
        Ok(context) => context,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let evaluation = evaluate_cycle_schedules(&index, &context);
    Ok(success_result(
        cycle_detection_text(&evaluation),
        json!({
            "date": context.today.to_string(),
            "timezone": context.timezone.as_ref().map(ToString::to_string),
            "schedules_examined": evaluation.schedules_examined(),
            "has_failures": evaluation.has_failures(),
            "warnings": evaluation
                .warnings()
                .iter()
                .map(cycle_warning_value)
                .collect::<Vec<_>>(),
        }),
    ))
}

pub(super) fn cycle_schedule_edit(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    if !opt_bool(args, "confirm")?.unwrap_or(false) {
        return Ok(cycle_schedule_unconfirmed("edit"));
    }
    let selector = req_string(args, "schedule")?;
    // Every named field becomes one patch field and the registry changes exactly
    // those, carrying the rest of the record — including its cursor — over. The
    // vocabulary is the registry's, so a `cadence` this tool refuses is refused by
    // the CLI with the same sentence (C-008/H4).
    let patch = ScheduleEdit {
        name: opt_string(args, "name")?,
        cadence: opt_string(args, "cadence")?,
        interval: opt_u32(args, "interval")?,
        unit: opt_string(args, "unit")?,
        duration: opt_u32(args, "duration")?,
        duration_unit: opt_string(args, "duration_unit")?,
        start_date: opt_string(args, "start_date")?,
        timezone: opt_string(args, "timezone")?,
        look_ahead: opt_u32(args, "look_ahead")?,
    };
    let (mut config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let id = match registry::edit(&mut config, &root, &selector, &patch) {
        Ok(id) => id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let Some(record) = index.schedule(&id) else {
        return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
            format!("cycle schedule `{id}`"),
        )));
    };
    Ok(success_result(
        format!("updated schedule `{id}`\n"),
        cycle_schedule_value(&id, record, &index),
    ))
}

pub(super) fn cycle_schedule_generate(
    _config: &Config,
    store: &Store,
    args: &Value,
) -> ToolOutcome {
    if !opt_bool(args, "confirm")?.unwrap_or(false) {
        return Ok(cycle_schedule_unconfirmed("generate"));
    }
    let selector = req_string(args, "schedule")?;
    let through = opt_string(args, "through")?;
    let date = opt_string(args, "date")?;
    let timezone = opt_string(args, "timezone")?;
    let actor = cycle_schedule_actor(args)?;
    let (mut config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let id = match registry::resolve(&index, &selector) {
        Ok(id) => id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let look_ahead = match through.as_deref() {
        Some(through) => match cycle_candidates_through(&index, &id, through) {
            Ok(count) => count,
            Err(error) => return Ok(cycle_schedule_failure(&error)),
        },
        // 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 = match cmd_recurring::context_for(date.as_deref(), timezone.as_deref()) {
        Ok(context) => context,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let request = CycleGenerationRequest::new(id, context, look_ahead, actor).confirm();
    let report = match generate_cycles(&mut config, &root, &index, &request) {
        Ok(report) => report,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let value = cycle_report_value(&report);
    let (text, failures) = cycle_generation_text(&report);
    if !failures.is_empty() {
        return Ok(rejected_result(
            crate::error::render_error(&crate::error::TixError::Refused(failures.join("\n"))),
            value,
        ));
    }
    Ok(success_result(text, value))
}

pub(super) fn cycle_schedule_list(_config: &Config, store: &Store, _args: &Value) -> ToolOutcome {
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let mut text = String::from(
        "id\tname\tstate\tcadence\tduration\tstart_date\tlook_ahead\tnext_sequence\tgenerated\n",
    );
    for (id, record) in index.schedules() {
        text.push_str(&cycle_schedule_row(id, record, &index));
    }
    let (_, diagnostics) = cycle_schedule_diagnostics(&index, None);
    Ok(success_result(
        text,
        json!({
            "schedules": index
                .schedules()
                .map(|(id, record)| cycle_schedule_value(id, record, &index))
                .collect::<Vec<_>>(),
            "schedule_count": index.schedule_count(),
            "generated_count": index.generated_count(),
            "diagnostics": diagnostics,
        }),
    ))
}

pub(super) fn cycle_schedule_show(_config: &Config, store: &Store, args: &Value) -> ToolOutcome {
    let selector = req_string(args, "schedule")?;
    let (config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let id = match registry::resolve(&index, &selector) {
        Ok(id) => id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let Some(record) = index.schedule(&id) else {
        // Unreachable: `registry::resolve` resolves only ids the index holds.
        return Ok(cycle_schedule_failure(&crate::error::TixError::NotFound(
            format!("cycle schedule `{selector}`"),
        )));
    };
    let (_, diagnostics) = cycle_schedule_diagnostics(&index, Some(&id));
    Ok(success_result(
        cycle_schedule_detail(&id, record, &index),
        json!({
            "schedule": cycle_schedule_value(&id, record, &index),
            "cursor": cycle_cursor_value(&index.cursor(&id)),
            "instances": index
                .cycles_of(&id)
                .map(cycle_instance_value)
                .collect::<Vec<_>>(),
            "diagnostics": diagnostics,
        }),
    ))
}

pub(super) fn cycle_snapshot_list(_config: &Config, store: &Store, _args: &Value) -> ToolOutcome {
    let (_, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let snapshots = match CycleSnapshotStore::new(&root).list() {
        Ok(snapshots) => snapshots,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let mut text = String::from(
        "cycle_id\tschedule_id\tsequence\tstart_date\tdue_date\tclosed_at\tclosed_by\tstate\n",
    );
    for snapshot in &snapshots {
        text.push_str(&format!(
            "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
            snapshot.cycle_id,
            snapshot.schedule_id,
            snapshot.sequence,
            snapshot.start_date,
            snapshot.due_date,
            snapshot.closed_at,
            snapshot.closed_by,
            snapshot.state_summary
        ));
    }
    Ok(success_result(
        text,
        json!({
            "directory": "docs/cycle_snapshots",
            "snapshot_count": snapshots.len(),
            "snapshots": snapshots.iter().map(cycle_snapshot_value).collect::<Vec<_>>(),
        }),
    ))
}

pub(super) fn dispatch(
    config: &Config,
    store: &Store,
    name: &str,
    arguments: &Value,
) -> Option<ToolOutcome> {
    match name {
        "cycle_schedule_list" => Some(cycle_schedule_list(config, store, arguments)),
        "cycle_schedule_show" => Some(cycle_schedule_show(config, store, arguments)),
        "cycle_schedule_create" => Some(cycle_schedule_create(config, store, arguments)),
        "cycle_schedule_edit" => Some(cycle_schedule_edit(config, store, arguments)),
        "cycle_schedule_delete" => Some(cycle_schedule_delete(config, store, arguments)),
        "cycle_schedule_detect" => Some(cycle_schedule_detect(config, store, arguments)),
        "cycle_schedule_generate" => Some(cycle_schedule_generate(config, store, arguments)),
        "cycle_schedule_close" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Close,
        )),
        "cycle_schedule_reopen" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Reopen,
        )),
        "cycle_schedule_extend" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Extend,
        )),
        "cycle_schedule_skip" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Skip,
        )),
        "cycle_schedule_pause" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Pause,
        )),
        "cycle_schedule_resume" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Resume,
        )),
        "cycle_schedule_adjust_future" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::AdjustFuture,
        )),
        "cycle_schedule_ignore" => Some(cycle_schedule_lifecycle(
            store,
            arguments,
            CycleLifecycleAction::Ignore,
        )),
        "cycle_snapshot_list" => Some(cycle_snapshot_list(config, store, arguments)),
        _ => None,
    }
}

/// The registry, the project root and the `tix.toml` path one call needs.
///
/// Re-read per call, for the reason the project/epic tools re-read: the server
/// bootstrapped once, so a config snapshot would not see a schedule this session
/// just created — while the CLI, a fresh process each time, always does. The path
/// is found through the issue directory (the same upward walk every command uses),
/// so it is the file the rest of the session reads.
pub(super) fn cycle_schedule_config(
    store: &Store,
) -> TixResult<(Config, std::path::PathBuf, std::path::PathBuf)> {
    let (config, path) = registry_config(store)?;
    let root = path
        .parent()
        .map_or_else(|| std::path::PathBuf::from("."), Path::to_path_buf);
    Ok((config, root, path))
}

/// The read model, built from the configuration and the records on disk — the same
/// one pass the CLI makes, so a stale snapshot can never drive a write (WP02/WP04).
pub(super) fn cycle_schedule_index(config: &Config, root: &Path) -> TixResult<ScheduleIndex> {
    Ok(ScheduleIndex::build(config, &CycleStore::new(root).list()?))
}

/// A domain failure as the FR-014 failure shape, rendered by the one boundary
/// renderer — byte for byte what the CLI prints to stderr.
pub(super) fn cycle_schedule_failure(error: &crate::error::TixError) -> Value {
    error_result(crate::error::render_error(error))
}

/// The refusal for an unconfirmed mutation: the CLI's own sentence, so
/// `tix cycle schedule <action>` without `--confirm` and this tool without
/// `confirm: true` read the same. Nothing is written (C-004).
pub(super) fn cycle_schedule_unconfirmed(action: &str) -> Value {
    cycle_schedule_failure(&registry::refuse(
        "not_confirmed",
        format!(
            "`tix cycle schedule {action}` changes state; pass `--confirm` to proceed — nothing \
             was written"
        ),
    ))
}

/// How many candidates starting on or before `through` the schedule would create.
///
/// A **horizon selector**, not a second generator: it steps through 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 the generator's, under its own
/// count contract (`look_ahead`).
pub(super) fn cycle_candidates_through(
    index: &ScheduleIndex,
    id: &CycleScheduleId,
    through: &str,
) -> TixResult<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) = cmd_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)
}

/// Who a History entry is attributed to: the caller's `actor`, or the boundary's
/// identity — which is what the CLI records when it is not told.
pub(super) fn cycle_schedule_actor(args: &Value) -> std::result::Result<String, ()> {
    Ok(opt_string(args, "actor")?.unwrap_or_else(cmd_recurring::actor))
}

/// The cadence in words, through the shared rule's own summary, or the same
/// placeholder the CLI prints when the record defines no resolvable cadence.
pub(super) fn cycle_cadence_summary(record: &CycleScheduleConfiguration) -> String {
    cadence_rule(record)
        .map(|rule| rule.summary())
        .unwrap_or_else(|| "(no cadence)".to_string())
}

/// The duration as the CLI renders it: `"<count> <unit>"`, or `"<count> (no unit)"`.
pub(super) fn cycle_duration_text(record: &CycleScheduleConfiguration) -> String {
    match record.duration.unit {
        Some(unit) => format!("{} {}", record.duration.count, unit.as_str()),
        None => format!("{} (no unit)", record.duration.count),
    }
}

/// The cursor as values, with the two derived fields a surface shows.
pub(super) fn cycle_cursor_value(cursor: &GenerationCursor) -> Value {
    json!({
        "next_sequence": cursor.next_sequence,
        "next_start": cursor.next_start,
        "last_generated_key": cursor
            .last_generated_key
            .as_ref()
            .map(GeneratedCycleId::as_str),
    })
}

/// One instance as every surface reports it.
pub(super) fn cycle_instance_value(cycle: &GeneratedCycle) -> Value {
    json!({
        "id": cycle.id.as_str(),
        "schedule_id": cycle.schedule_id.as_str(),
        "sequence": cycle.sequence,
        "name": cycle.name,
        "state": cycle.state.as_str(),
        "start_date": cycle.start_date,
        "due_date": cycle.due_date,
    })
}

/// One schedule as values: identity, definition, its *derived* cursor and its
/// instance count — the `ScheduleIndex`'s answer, never a re-derivation.
pub(super) fn cycle_schedule_value(
    id: &CycleScheduleId,
    record: &CycleScheduleConfiguration,
    index: &ScheduleIndex,
) -> Value {
    let cursor = index.cursor(id);
    json!({
        "id": id.as_str(),
        "name": record.name,
        "state": record.state.as_str(),
        "cadence": cycle_cadence_summary(record),
        "cadence_kind": record.cadence.kind.map(RuleKind::as_str),
        "interval": record.cadence.interval,
        "unit": record.cadence.unit.map(IntervalUnit::as_str),
        "duration": {
            "count": record.duration.count,
            "unit": record.duration.unit.map(IntervalUnit::as_str),
        },
        "start_date": record.start_date,
        "timezone": record.timezone.as_ref().map(ToString::to_string),
        "look_ahead": record.look_ahead,
        "next_sequence": cursor.next_sequence,
        "next_start": cursor.next_start,
        "last_generated_key": cursor
            .last_generated_key
            .as_ref()
            .map(GeneratedCycleId::as_str),
        "generated": index.cycles_of(id).count(),
    })
}

/// The CLI's `tix cycle schedule list` row, column for column (`NFR-003`).
pub(super) fn cycle_schedule_row(
    id: &CycleScheduleId,
    record: &CycleScheduleConfiguration,
    index: &ScheduleIndex,
) -> String {
    let cursor = index.cursor(id);
    let next = cursor
        .next_sequence
        .map(|sequence| sequence.to_string())
        .unwrap_or_else(|| "-".to_string());
    format!(
        "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
        id,
        record.name,
        record.state.as_str(),
        cycle_cadence_summary(record),
        cycle_duration_text(record),
        record.start_date,
        record.look_ahead,
        next,
        index.cycles_of(id).count()
    )
}

/// The CLI's `tix cycle schedule show` block, line for line (`NFR-003`).
///
/// The identity findings the CLI prints to stderr are **not** appended: the text
/// channel is the CLI's stdout, and the findings travel in `structuredContent`
/// beside it, which is what keeps the two surfaces byte-comparable.
pub(super) fn cycle_schedule_detail(
    id: &CycleScheduleId,
    record: &CycleScheduleConfiguration,
    index: &ScheduleIndex,
) -> String {
    let cursor = index.cursor(id);
    let last = cursor
        .last_generated_key
        .as_ref()
        .map(GeneratedCycleId::as_str)
        .unwrap_or("-");
    let next = cursor
        .next_sequence
        .map(|sequence| sequence.to_string())
        .unwrap_or_else(|| "-".to_string());
    let mut text = format!(
        "id: {id}\nname: {}\nstate: {}\ncadence: {}\nduration: {}\nstart_date: {}\ntimezone: \
         {}\nlook_ahead: {}\nnext_sequence: {next}\nnext_start: {}\nlast_generated_key: \
         {last}\ngenerated: {}\n",
        record.name,
        record.state.as_str(),
        cycle_cadence_summary(record),
        cycle_duration_text(record),
        record.start_date,
        record
            .timezone
            .as_ref()
            .map(ToString::to_string)
            .unwrap_or_else(|| "(none)".to_string()),
        record.look_ahead,
        cursor.next_start.as_deref().unwrap_or("-"),
        index.cycles_of(id).count()
    );
    for cycle in index.cycles_of(id) {
        text.push_str(&format!(
            "  {}\t{}\t{} -> {}\n",
            cycle.id,
            cycle.state.as_str(),
            cycle.start_date,
            cycle.due_date
        ));
    }
    text
}

/// The index's identity findings, as the block the CLI prints and as values.
///
/// `only` restricts the block to one schedule, exactly as `tix cycle schedule
/// show` filters; `None` reports the whole index, as `list` does.
pub(super) fn cycle_schedule_diagnostics(
    index: &ScheduleIndex,
    only: Option<&CycleScheduleId>,
) -> (String, Value) {
    let wanted: Vec<&crate::cycle_schedule::identity::IdentityDiagnostic> = index
        .diagnostics()
        .iter()
        .filter(|diagnostic| match only {
            Some(id) => diagnostic.schedule_id.as_ref() == Some(id),
            None => true,
        })
        .collect();
    let mut text = String::new();
    for diagnostic in &wanted {
        text.push_str(&diagnostic.render());
        text.push('\n');
    }
    let values: Vec<Value> = wanted
        .iter()
        .map(|diagnostic| {
            json!({
                "kind": diagnostic.kind.as_str(),
                "schedule_id": diagnostic.schedule_id.as_ref().map(CycleScheduleId::as_str),
                "cycle_id": diagnostic.cycle_id.as_ref().map(GeneratedCycleId::as_str),
                "field": diagnostic.field,
                "message": diagnostic.message,
            })
        })
        .collect();
    (text, Value::Array(values))
}

/// One warning as values (T042): the stable schedule/instance identity, the kind,
/// the effective dates, the candidate a confirmed generation would create, the
/// explicit decisions the warning accepts, and the field-aware finding a `failure`
/// carries.
pub(super) fn cycle_warning_value(
    warning: &crate::cycle_schedule::evaluate::ScheduleWarning,
) -> Value {
    json!({
        "kind": warning.kind.as_str(),
        "schedule_id": warning.schedule_id.as_str(),
        "cycle_id": warning.cycle_id.as_ref().map(GeneratedCycleId::as_str),
        "effective_dates": warning.effective_dates.as_ref().map(|dates| json!({
            "start": dates.start,
            "due": dates.due,
        })),
        "next_generation": warning.next_generation.as_ref().map(|key| json!({
            "id": key.id.as_str(),
            "sequence": key.sequence,
            "start_date": key.start_date,
        })),
        "available_actions": warning
            .available_actions
            .iter()
            .map(|action| action.as_str())
            .collect::<Vec<_>>(),
        "diagnostic": warning.diagnostic.as_ref().map(|diagnostic| json!({
            "kind": diagnostic.kind.as_str(),
            "field": diagnostic.field,
            "message": diagnostic.message,
        })),
    })
}

/// The CLI's `tix cycle schedule detect` table, row for row (`NFR-003`).
pub(super) fn cycle_detection_text(
    evaluation: &crate::cycle_schedule::evaluate::CycleEvaluation,
) -> String {
    if evaluation.is_empty() {
        return format!(
            "No cycle-schedule warnings across {} schedule(s).\n",
            evaluation.schedules_examined()
        );
    }
    let mut text = String::from(
        "schedule_id\tkind\tcycle_id\tstart\tdue\tnext_start\tnext_id\tactions\tdetail\n",
    );
    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("-");
        text.push_str(&format!(
            "{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n",
            warning.schedule_id,
            warning.kind.as_str(),
            cycle_id,
            start,
            due,
            next_start,
            next_id,
            actions,
            detail
        ));
    }
    text
}

/// One generation outcome as values, in the service's own vocabulary.
pub(super) fn cycle_generation_outcome_value(outcome: &CycleGenerationOutcome) -> Value {
    match outcome {
        CycleGenerationOutcome::Created { key, cycle, .. } => json!({
            "status": "created",
            "key": key.as_str(),
            "cycle": cycle_instance_value(cycle),
        }),
        CycleGenerationOutcome::NoOp {
            key,
            state,
            message,
            ..
        } => json!({
            "status": "no-op",
            "key": key.as_str(),
            "state": state.as_str(),
            "message": message,
        }),
        CycleGenerationOutcome::Rejected {
            key, diagnostics, ..
        } => json!({
            "status": "rejected",
            "key": key.as_ref().map(GeneratedCycleId::as_str),
            "diagnostics": diagnostics
                .iter()
                .map(|diagnostic| json!({
                    "kind": diagnostic.kind.as_str(),
                    "field": diagnostic.field,
                    "message": diagnostic.message,
                }))
                .collect::<Vec<_>>(),
        }),
    }
}

/// The whole generation pass as values: the audit context, one outcome per
/// requested key, the counts, and the cursor after the pass.
pub(super) fn cycle_report_value(report: &CycleGenerationReport) -> Value {
    json!({
        "actor": report.actor(),
        "as_of": report.as_of().to_string(),
        "schedule_id": report.schedule_id().as_str(),
        "outcomes": report
            .outcomes()
            .iter()
            .map(cycle_generation_outcome_value)
            .collect::<Vec<_>>(),
        "created": report.created().count(),
        "no_ops": report.no_ops().count(),
        "rejected": report.rejected().count(),
        "refused": report.is_refused(),
        "cursor": report.cursor().map(cycle_cursor_value),
    })
}

/// The CLI's generation lines, word for word, split into what it prints and the
/// refusals it raises (`(text, failures)`).
pub(super) fn cycle_generation_text(report: &CycleGenerationReport) -> (String, Vec<String>) {
    let mut text = String::new();
    let mut failures = Vec::new();
    for outcome in report.outcomes() {
        if outcome.is_rejected() {
            failures.push(outcome.render());
        } else {
            text.push_str(&outcome.render());
            text.push('\n');
        }
    }
    if report.is_empty() {
        text.push_str(&report.render());
        text.push('\n');
    }
    (text, failures)
}

/// One lifecycle outcome as values (T042), with the snapshot identity a close
/// captured and the resulting window an action moved.
pub(super) fn cycle_lifecycle_value(outcome: &CycleLifecycleOutcome) -> Value {
    match outcome {
        CycleLifecycleOutcome::Applied {
            action,
            schedule_id,
            cycle_id,
            snapshot_path,
            dates,
            message,
        } => json!({
            "status": "applied",
            "action": action.as_str(),
            "schedule_id": schedule_id.as_str(),
            "cycle_id": cycle_id.as_ref().map(GeneratedCycleId::as_str),
            "snapshot_path": snapshot_path,
            "dates": dates
                .as_ref()
                .map(|(start, due)| json!({ "start": start, "due": due })),
            "message": message,
        }),
        CycleLifecycleOutcome::NoOp {
            action,
            schedule_id,
            cycle_id,
            message,
        } => json!({
            "status": "no-op",
            "action": action.as_str(),
            "schedule_id": schedule_id.as_str(),
            "cycle_id": cycle_id.as_ref().map(GeneratedCycleId::as_str),
            "message": message,
        }),
        CycleLifecycleOutcome::Rejected {
            action,
            schedule_id,
            cycle_id,
            diagnostics,
        } => json!({
            "status": "rejected",
            "action": action.as_str(),
            "schedule_id": schedule_id.as_str(),
            "cycle_id": cycle_id.as_ref().map(GeneratedCycleId::as_str),
            "diagnostics": diagnostics
                .iter()
                .map(|diagnostic| json!({
                    "kind": diagnostic.kind.as_str(),
                    "field": diagnostic.field,
                    "message": diagnostic.message,
                }))
                .collect::<Vec<_>>(),
        }),
    }
}

/// One preserved metadata map as JSON, without dropping an unknown key.
///
/// Named for the *shape* rather than for one feature: a capacity snapshot's
/// `measurements`/`extensions` and a time entry's `extensions` (WP06) are the same
/// conversion, and a second copy is how two payloads come to render one preserved key
/// two ways. A map that cannot be a JSON value keeps the key with a `null` rather than
/// dropping it.
pub(super) fn yaml_map_value(
    metadata: &std::collections::BTreeMap<String, serde_yaml::Value>,
) -> Value {
    let mut map = serde_json::Map::with_capacity(metadata.len());
    for (key, value) in metadata {
        map.insert(
            key.clone(),
            serde_json::to_value(value).unwrap_or(Value::Null),
        );
    }
    Value::Object(map)
}

/// One immutable snapshot as values (T042): the stable identity, the historical
/// dates and the audit context, all read from the snapshot file rather than
/// recomputed from the live schedule (C-007).
pub(super) fn cycle_snapshot_value(snapshot: &CycleSnapshot) -> Value {
    json!({
        "cycle_id": snapshot.cycle_id.as_str(),
        "schedule_id": snapshot.schedule_id.as_str(),
        "sequence": snapshot.sequence,
        "start_date": snapshot.start_date,
        "due_date": snapshot.due_date,
        "closed_at": snapshot.closed_at,
        "closed_by": snapshot.closed_by,
        "state_summary": snapshot.state_summary,
        "measurements": yaml_map_value(&snapshot.measurements),
        "extensions": yaml_map_value(&snapshot.extensions),
    })
}

// -- the handlers ------------------------------------------------------------

/// The instance a lifecycle action names: `cycle` first, then a unique instance by
/// `from` start date, else none — the same precedence and the same refusal as the
/// CLI's own selector.
pub(super) fn cycle_schedule_target(
    index: &ScheduleIndex,
    id: &CycleScheduleId,
    cycle: Option<&str>,
    from: Option<&str>,
) -> TixResult<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"
            ),
        )),
    }
}

/// The seven lifecycle tools are the seven [`CycleLifecycleAction`]s, so the shared
/// lifecycle sees exactly what `tix cycle schedule <action>` sends it (T041).
///
/// Every one is confirmed, and the outcome is the service's own
/// (`applied`/`no-op`/`rejected`); the History entry it wrote is described in the
/// message the outcome carries, and the snapshot it captured by `snapshot_path`.
pub(super) fn cycle_schedule_lifecycle(
    store: &Store,
    args: &Value,
    action: CycleLifecycleAction,
) -> ToolOutcome {
    let selector = req_string(args, "schedule")?;
    if !opt_bool(args, "confirm")?.unwrap_or(false) {
        return Ok(cycle_schedule_unconfirmed(action.as_str()));
    }
    // The shared lifecycle extends by exactly one cadence period per action; this
    // surface refuses any other count rather than re-deriving a multi-period step
    // of its own (the CLI's `--by` check, same kind and sentence).
    if let Some(periods) = opt_u32(args, "by")?
        && periods != 1
    {
        return Ok(cycle_schedule_failure(&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 reason = opt_string(args, "reason")?;
    let cycle = opt_string(args, "cycle")?;
    let from = opt_string(args, "from")?;
    let actor = cycle_schedule_actor(args)?;
    // The explicit instant the action records: the caller's, or the boundary clock
    // — the same source the CLI resolves it from (this crate has no clock below
    // the boundary).
    let timestamp = opt_string(args, "timestamp")?.unwrap_or_else(crate::model::utc_now_rfc3339);
    let (mut config, root, _path) = match cycle_schedule_config(store) {
        Ok(loaded) => loaded,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let index = match cycle_schedule_index(&config, &root) {
        Ok(index) => index,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let id = match registry::resolve(&index, &selector) {
        Ok(id) => id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let cycle_id = match cycle_schedule_target(&index, &id, cycle.as_deref(), from.as_deref()) {
        Ok(cycle_id) => cycle_id,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let mut request = CycleLifecycleRequest::new(action, id, actor).with_timestamp(timestamp);
    if let Some(cycle_id) = cycle_id {
        request = request.for_cycle(cycle_id);
    }
    if let Some(reason) = reason {
        request = request.with_reason(reason);
    }
    let request =
        match crate::commands::capacity::with_close_capacity(request, &config, &root, store) {
            Ok(request) => request,
            Err(error) => return Ok(cycle_schedule_failure(&error)),
        };
    let outcome = match apply_cycle_lifecycle(&mut config, &root, &request.confirm()) {
        Ok(outcome) => outcome,
        Err(error) => return Ok(cycle_schedule_failure(&error)),
    };
    let value = cycle_lifecycle_value(&outcome);
    if outcome.is_rejected() {
        return Ok(rejected_result(
            crate::error::render_error(&crate::error::TixError::Refused(outcome.render())),
            value,
        ));
    }
    Ok(success_result(format!("{}\n", outcome.render()), value))
}