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

impl App {
    /// The Schedule page's pointer handling (WP06): a left-click on the tab strip
    /// switches to that tab, so the page's tabs are reachable by pointer as well as by
    /// `Tab`.
    ///
    /// The strip is the page's own geometry ([`crate::ui::schedule::tab_rects`], the
    /// same widths [`crate::ui::schedule::render`] draws), so a click lands on the tab
    /// it looks like it lands on. The state change happens **here** rather than through
    /// the recorded-region fallback: it needs no action the event loop must perform,
    /// and a click that only switched a tab is not something the terminal has to do
    /// anything about. A form or reason prompt owns every key while it is open, and it
    /// owns the pointer too — a click must not switch tabs out from under a half-typed
    /// reason.
    pub(in crate::app) fn handle_schedule_mouse(&mut self, mouse: MouseEvent) -> Result<Action> {
        if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) {
            return Ok(Action::None);
        }
        let busy = self
            .schedule
            .as_ref()
            .is_some_and(|state| state.form.is_some() || state.prompt.is_some());
        if busy {
            return Ok(Action::None);
        }
        let hit = crate::ui::schedule::tab_rects(self.frame_size.get())
            .into_iter()
            .find(|(_, rect)| rect.contains(Position::new(mouse.column, mouse.row)))
            .map(|(tab, _)| tab);
        if let Some(tab) = hit
            && let Some(state) = self.schedule.as_mut()
            && state.tab != tab
        {
            state.tab = tab;
            state.selected = 0;
        }
        Ok(Action::None)
    }

    /// The Schedule page's raw key layer (WP07 T036/T037): tab switching, its action
    /// keys, and the reason prompt.
    ///
    /// Returns whether the key was consumed. It runs ahead of the binding layer (see
    /// [`App::handle_key`]) because the page's `[schedule]` table binds
    /// the Series tab's actions only: `Tab`/`Shift+Tab` have no binding there, and
    /// `c`/`e`/`a` are unbound, so without this layer they would arrive as the inert
    /// sentinel.
    pub(in crate::app) fn handle_schedule_raw_key(&mut self, key: KeyEvent) -> Result<bool> {
        use crate::ui::schedule::ScheduleTab;
        if !matches!(self.mode, Mode::Schedule) {
            return Ok(false);
        }
        // The create/edit form is the outermost text surface: while it is up it owns
        // every key, so `q` is a letter and `Tab` moves a field rather than a tab.
        // The Series tab's create form is the same kind of surface; only one of the
        // two is ever open.
        if self
            .schedule
            .as_ref()
            .is_some_and(|state| state.series_form.is_some())
        {
            return self.handle_series_form_key(key);
        }
        if self
            .schedule
            .as_ref()
            .is_some_and(|state| state.form.is_some())
        {
            return self.handle_cycle_schedule_form_key(key);
        }
        // The reason prompt is a text surface for the same reason: every key belongs
        // to it, exactly as the Roadmap tab's overlay owns its keys.
        if self
            .schedule
            .as_ref()
            .is_some_and(|state| state.prompt.is_some())
        {
            return self.handle_cycle_reason_key(key);
        }
        match key.code {
            KeyCode::Tab => {
                if let Some(state) = self.schedule.as_mut() {
                    state.switch_tab(1);
                }
                return Ok(true);
            }
            KeyCode::BackTab => {
                if let Some(state) = self.schedule.as_mut() {
                    state.switch_tab(-1);
                }
                return Ok(true);
            }
            _ => {}
        }
        if self.schedule_state().tab != ScheduleTab::Cycles {
            return Ok(false);
        }
        match key.code {
            // Defining a schedule (`n`) and editing one (`E` — the lowercase is the
            // lifecycle's extend) are the tab's own keys, read raw for the same reason
            // `c`/`e`/`a` are: the page's binding section names the Series actions.
            KeyCode::Char('n') => {
                self.open_cycle_schedule_create_form();
                Ok(true)
            }
            KeyCode::Char('E') => {
                self.open_cycle_schedule_edit_form();
                Ok(true)
            }
            KeyCode::Char('c') => {
                self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Close,
                )?;
                Ok(true)
            }
            // The uppercase `R` is the reopen route: `r` resumes a *paused schedule*,
            // so the instance action takes the shifted key — the same reason `E` edits
            // a schedule while `e` extends an instance.
            KeyCode::Char('R') => {
                self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Reopen,
                )?;
                Ok(true)
            }
            KeyCode::Char('e') => {
                self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Extend,
                )?;
                Ok(true)
            }
            KeyCode::Char('a') => {
                self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::AdjustFuture,
                )?;
                Ok(true)
            }
            _ => Ok(false),
        }
    }

    /// The create/edit form's keys, read raw (T036).
    ///
    /// `tab`/`↓` and `shift+tab`/`↑` walk the fields, `enter` saves through the shared
    /// registry (**the** explicit, confirmed save — the same service the CLI's
    /// `--confirm` reaches), and `esc` cancels and writes nothing. A refusal keeps the
    /// form open with the message and everything typed on it.
    pub(in crate::app) fn handle_cycle_schedule_form_key(&mut self, key: KeyEvent) -> Result<bool> {
        match key.code {
            KeyCode::Esc => {
                if let Some(state) = self.schedule.as_mut() {
                    state.form = None;
                }
                self.status_msg = Some("create/edit cancelled: nothing was written".to_string());
            }
            KeyCode::Enter => self.save_cycle_schedule_form()?,
            KeyCode::Tab | KeyCode::Down => {
                if let Some(form) = self.schedule.as_mut().and_then(|state| state.form.as_mut()) {
                    form.focus_next();
                }
            }
            KeyCode::BackTab | KeyCode::Up => {
                if let Some(form) = self.schedule.as_mut().and_then(|state| state.form.as_mut()) {
                    form.focus_prev();
                }
            }
            KeyCode::Backspace => {
                if let Some(form) = self.schedule.as_mut().and_then(|state| state.form.as_mut()) {
                    form.delete_char();
                }
            }
            // `delete` empties the focused field: a name or a date being *replaced* is
            // the common edit, and backspacing a whole value is not a keyboard
            // shortcut. The date picker binds `delete` to its own Reset, so this is the
            // same key meaning the same thing.
            KeyCode::Delete => {
                if let Some(form) = self.schedule.as_mut().and_then(|state| state.form.as_mut()) {
                    form.clear_field();
                }
            }
            KeyCode::Char(c) => {
                if let Some(form) = self.schedule.as_mut().and_then(|state| state.form.as_mut()) {
                    form.insert_char(c);
                }
            }
            _ => {}
        }
        Ok(true)
    }

    /// Open the form that defines a new schedule (T036).
    pub(in crate::app) fn open_cycle_schedule_create_form(&mut self) {
        if let Some(state) = self.schedule.as_mut() {
            state.form = Some(crate::ui::schedule::ScheduleForm::create());
            state.prompt = None;
        }
    }

    /// Open the form that defines a new recurring series (the Series tab's `n`).
    ///
    /// The form collects the three fields `tix recurring create` requires; the save
    /// reaches the same service the CLI runs. Nothing is written here — the explicit,
    /// confirmed `enter` is what writes.
    pub(in crate::app) fn open_series_create_form(&mut self) {
        if let Some(state) = self.schedule.as_mut() {
            state.series_form = Some(crate::ui::schedule::SeriesForm::create());
            state.form = None;
            state.prompt = None;
        }
    }

    /// The Series form's keys, read raw.
    ///
    /// `tab`/`↓` and `shift+tab`/`↑` walk the fields, `enter` saves through the shared
    /// create service, and `esc` cancels and writes nothing. A refusal keeps the form
    /// open with the message and everything typed on it — the same contract the Cycle
    /// schedules form honours.
    pub(in crate::app) fn handle_series_form_key(&mut self, key: KeyEvent) -> Result<bool> {
        match key.code {
            KeyCode::Esc => {
                if let Some(state) = self.schedule.as_mut() {
                    state.series_form = None;
                }
                self.status_msg = Some("create cancelled: nothing was written".to_string());
            }
            KeyCode::Enter => self.save_series_form()?,
            KeyCode::Tab | KeyCode::Down => {
                if let Some(form) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.series_form.as_mut())
                {
                    form.focus_next();
                }
            }
            KeyCode::BackTab | KeyCode::Up => {
                if let Some(form) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.series_form.as_mut())
                {
                    form.focus_prev();
                }
            }
            KeyCode::Backspace => {
                if let Some(form) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.series_form.as_mut())
                {
                    form.delete_char();
                }
            }
            // `delete` empties the focused field, as it does on every other form.
            KeyCode::Delete => {
                if let Some(form) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.series_form.as_mut())
                {
                    form.clear_field();
                }
            }
            KeyCode::Char(c) => {
                if let Some(form) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.series_form.as_mut())
                {
                    form.insert_char(c);
                }
            }
            _ => {}
        }
        Ok(true)
    }

    /// Save the open Series form through the shared create service.
    ///
    /// The form's three fields become the CLI's own flags — `--title`, `--rule`,
    /// `--anchor` — and nothing else is set, so the issue's status, priority, labels
    /// and `--name` keep exactly the CLI defaults. The rule and anchor are passed
    /// through **verbatim**: what they may be is the service's answer, and a blank
    /// title, an unknown rule or a malformed anchor is refused by the same validation
    /// the command line runs, with the same wording, having written nothing. The form
    /// then stays open with everything typed.
    pub(in crate::app) fn save_series_form(&mut self) -> Result<()> {
        use crate::ui::schedule::SeriesField;

        let Some(form) = self
            .schedule
            .as_ref()
            .and_then(|state| state.series_form.clone())
        else {
            return Ok(());
        };
        let args = crate::cli::RecurringCreateArgs {
            title: form.value(SeriesField::Title).trim().to_string(),
            body: None,
            status: None,
            priority: None,
            labels: None,
            assignee: None,
            name: None,
            id: None,
            rule: crate::cli::RecurringRuleArgs {
                rule: Some(form.value(SeriesField::Rule).trim().to_string()),
                anchor: Some(form.value(SeriesField::Anchor).trim().to_string()),
                interval: None,
                unit: None,
                expression: None,
                timezone: None,
            },
        };
        let result =
            crate::commands::recurring::create_series(&self.store.config, &self.store, &args)
                .map(|created| {
                    format!(
                        "created series `{}` (issue #{}, rule {})",
                        created.id, created.issue_number, created.rule
                    )
                })
                .map_err(|error| error.to_string());
        match result {
            Ok(line) => {
                if let Some(state) = self.schedule.as_mut() {
                    state.series_form = None;
                }
                self.status_msg = Some(line);
                // The service wrote an issue file: re-read the corpus, so the Series
                // tab lists the new series and the board has it.
                self.refresh_corpus()?;
            }
            Err(message) => {
                self.status_msg = Some(message.clone());
                if let Some(active) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.series_form.as_mut())
                {
                    crate::ui::schedule::SeriesForm::set_error(active, message);
                }
            }
        }
        Ok(())
    }

    /// Open the form that edits the selected schedule (T036), pre-filled from the
    /// record the read model holds.
    ///
    /// The values are read **by field**, in [`ScheduleField::EDIT`] order, so the form
    /// and the record cannot drift: a field the form gains and this match does not
    /// fill is the empty string, and a cursor is carried as-is (an edit does not touch
    /// the generation position).
    pub(in crate::app) fn open_cycle_schedule_edit_form(&mut self) {
        use crate::ui::schedule::ScheduleField;

        let Some(id) = self.selected_cycle_schedule_id() else {
            self.status_msg = Some("No cycle schedule selected".to_string());
            return;
        };
        let Ok(index) = self.cycle_schedule_index() else {
            self.status_msg = Some("could not read the cycle schedule registry".to_string());
            return;
        };
        let Some(record) = index.schedule(&id) else {
            self.status_msg = Some(format!("no cycle schedule `{id}` is defined"));
            return;
        };
        let values: Vec<String> = ScheduleField::EDIT
            .iter()
            .map(|field| match field {
                ScheduleField::Name => record.name.clone(),
                ScheduleField::Cadence => record
                    .cadence
                    .kind
                    .map(|kind| kind.as_str().to_string())
                    .unwrap_or_default(),
                ScheduleField::Interval => record
                    .cadence
                    .interval
                    .map(|interval| interval.to_string())
                    .unwrap_or_default(),
                ScheduleField::Unit => record
                    .cadence
                    .unit
                    .map(|unit| unit.as_str().to_string())
                    .unwrap_or_default(),
                ScheduleField::Duration => record.duration.count.to_string(),
                ScheduleField::DurationUnit => record
                    .duration
                    .unit
                    .map(|unit| unit.as_str().to_string())
                    .unwrap_or_default(),
                ScheduleField::StartDate => record.start_date.clone(),
                ScheduleField::Timezone => record
                    .timezone
                    .as_ref()
                    .map(ToString::to_string)
                    .unwrap_or_default(),
                // `0` is the record's "no look-ahead"; the field is blank then, so a
                // save that leaves it blank keeps the absent value rather than
                // writing a literal zero the user did not type.
                ScheduleField::LookAhead => {
                    if record.look_ahead > 0 {
                        record.look_ahead.to_string()
                    } else {
                        String::new()
                    }
                }
                ScheduleField::Id => id.as_str().to_string(),
            })
            .collect();
        if let Some(state) = self.schedule.as_mut() {
            state.form = Some(crate::ui::schedule::ScheduleForm::edit(
                id.as_str().to_string(),
                values,
            ));
            state.prompt = None;
        }
    }

    /// The draft the create form describes, or a field-named refusal.
    ///
    /// Only the two things a text field can get wrong *by itself* are decided here —
    /// a value that is not a whole number. Everything else (an unknown cadence family,
    /// a date that is not a date, an id already spent, a duration of zero) is the
    /// shared registry's refusal, with the same wording the CLI and MCP see.
    pub(in crate::app) fn cycle_schedule_draft(
        form: &crate::ui::schedule::ScheduleForm,
    ) -> std::result::Result<crate::cycle_schedule::registry::ScheduleDraft, String> {
        use crate::ui::schedule::ScheduleField as Field;

        let text = |field: Field| form.value(field).trim().to_string();
        Ok(crate::cycle_schedule::registry::ScheduleDraft {
            id: text(Field::Id),
            name: text(Field::Name),
            cadence: text(Field::Cadence),
            interval: Self::form_number(form, Field::Interval)?,
            unit: Some(text(Field::Unit)).filter(|unit| !unit.is_empty()),
            duration: Self::form_number(form, Field::Duration)?.unwrap_or_default(),
            duration_unit: text(Field::DurationUnit),
            start_date: text(Field::StartDate),
            timezone: text(Field::Timezone),
            look_ahead: Self::form_number(form, Field::LookAhead)?,
        })
    }

    /// The patch the edit form describes, or a field-named refusal.
    ///
    /// Every field the form shows is named, and an empty optional field is `None` —
    /// "leave it as it is", the CLI's own flag semantics, so the form cannot invent a
    /// value the user did not type.
    pub(in crate::app) fn cycle_schedule_patch(
        form: &crate::ui::schedule::ScheduleForm,
    ) -> std::result::Result<crate::cycle_schedule::registry::ScheduleEdit, String> {
        use crate::ui::schedule::ScheduleField as Field;

        let text = |field: Field| form.value(field).trim().to_string();
        Ok(crate::cycle_schedule::registry::ScheduleEdit {
            name: Some(text(Field::Name)),
            cadence: Some(text(Field::Cadence)).filter(|kind| !kind.is_empty()),
            interval: Self::form_number(form, Field::Interval)?,
            unit: Some(text(Field::Unit)).filter(|unit| !unit.is_empty()),
            duration: Self::form_number(form, Field::Duration)?,
            duration_unit: Some(text(Field::DurationUnit)).filter(|unit| !unit.is_empty()),
            start_date: Some(text(Field::StartDate)),
            timezone: Some(text(Field::Timezone)),
            look_ahead: Self::form_number(form, Field::LookAhead)?,
        })
    }

    /// A whole number from the form's `field`: `None` when it is empty, and a refusal
    /// naming the field when it is not a number.
    pub(in crate::app) fn form_number(
        form: &crate::ui::schedule::ScheduleForm,
        field: crate::ui::schedule::ScheduleField,
    ) -> std::result::Result<Option<u32>, String> {
        let raw = form.value(field).trim();
        if raw.is_empty() {
            return Ok(None);
        }
        raw.parse::<u32>()
            .map(Some)
            .map_err(|_| format!("`{raw}` is not a whole number for `{}`", field.label()))
    }

    /// Save the open form through the shared registry service (T036/T037).
    ///
    /// Create and edit are the *same* call the CLI makes, so the name-exists check,
    /// the spent-id guard (records **and** snapshots) and the validator are one
    /// implementation. A refusal — local (a field that is not a number) or from the
    /// registry — keeps the form open with everything typed, and writes nothing.
    pub(in crate::app) fn save_cycle_schedule_form(&mut self) -> Result<()> {
        use crate::cycle_schedule::registry;
        use crate::ui::schedule::ScheduleForm;

        let Some(form) = self.schedule.as_ref().and_then(|state| state.form.clone()) else {
            return Ok(());
        };
        let root = self.project_root();
        let result: std::result::Result<String, String> = match &form.editing {
            None => match Self::cycle_schedule_draft(&form) {
                Err(message) => Err(message),
                Ok(draft) => registry::create(&mut self.store.config, &root, &draft)
                    .map(|id| format!("created schedule `{id}`"))
                    .map_err(|error| error.to_string()),
            },
            Some(id) => match Self::cycle_schedule_patch(&form) {
                Err(message) => Err(message),
                Ok(patch) => registry::edit(&mut self.store.config, &root, id, &patch)
                    .map(|id| format!("updated schedule `{id}`"))
                    .map_err(|error| error.to_string()),
            },
        };
        match result {
            Ok(line) => {
                if let Some(state) = self.schedule.as_mut() {
                    state.form = None;
                }
                self.status_msg = Some(line);
                // The registry wrote `tix.toml`: re-read and re-evaluate, so the rows,
                // the detail and the warnings come from what is on disk now.
                self.refresh_corpus()?;
            }
            Err(message) => {
                self.status_msg = Some(message.clone());
                if let Some(active) = self.schedule.as_mut().and_then(|state| state.form.as_mut()) {
                    ScheduleForm::set_error(active, message);
                }
            }
        }
        Ok(())
    }

    /// The reason prompt's keys, read raw (T037).
    ///
    /// `enter` applies the captured action through WP05's service with the typed
    /// reason; `esc` cancels and writes nothing. An empty reason is refused here with
    /// the same word the service uses, rather than sent as a request the service
    /// would reject — either way nothing is written.
    pub(in crate::app) fn handle_cycle_reason_key(&mut self, key: KeyEvent) -> Result<bool> {
        let Some(prompt) = self
            .schedule
            .as_ref()
            .and_then(|state| state.prompt.clone())
        else {
            return Ok(false);
        };
        match key.code {
            KeyCode::Esc => {
                if let Some(state) = self.schedule.as_mut() {
                    state.prompt = None;
                }
                self.status_msg = Some(format!(
                    "{} cancelled: nothing was written",
                    prompt.action.as_str()
                ));
            }
            KeyCode::Enter => {
                let reason = prompt.buffer.trim().to_string();
                if let Some(state) = self.schedule.as_mut() {
                    state.prompt = None;
                }
                if reason.is_empty() {
                    self.status_msg = Some(format!(
                        "{} records a reason; supply one — nothing was written",
                        prompt.action.as_str()
                    ));
                    return Ok(true);
                }
                self.apply_cycle_schedule_action(
                    &prompt.schedule,
                    prompt.action,
                    prompt.cycle.clone(),
                    Some(reason),
                )?;
            }
            KeyCode::Backspace => {
                if let Some(active) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.prompt.as_mut())
                {
                    active.buffer.pop();
                }
            }
            KeyCode::Char(c) => {
                if let Some(active) = self
                    .schedule
                    .as_mut()
                    .and_then(|state| state.prompt.as_mut())
                {
                    active.buffer.push(c);
                }
            }
            _ => {}
        }
        Ok(true)
    }

    /// Begin one lifecycle action on the selected cycle schedule (T037).
    ///
    /// An action that records a reason opens the prompt first; the four that need no
    /// reason go straight through, confirmed. Naming a row is never consent — this
    /// method only ever *builds* a confirmed request, and it is only reached from an
    /// explicit key press.
    pub(in crate::app) fn begin_cycle_schedule_action(
        &mut self,
        action: crate::cycle_schedule::lifecycle::LifecycleAction,
    ) -> Result<()> {
        let Some(schedule_id) = self.selected_cycle_schedule_id() else {
            self.status_msg = Some("No cycle schedule selected".to_string());
            return Ok(());
        };
        if action.requires_reason() {
            // The three actions about *an instance* target the schedule's current
            // cycle; `adjust-future` is about the schedule's own definition, so it
            // names no instance — exactly the request the CLI builds when neither
            // `--cycle` nor `--from` is given.
            let cycle = match action {
                crate::cycle_schedule::lifecycle::LifecycleAction::Close
                | crate::cycle_schedule::lifecycle::LifecycleAction::Extend
                | crate::cycle_schedule::lifecycle::LifecycleAction::Skip => {
                    self.current_cycle_id(&schedule_id)
                }
                // `reopen` is `close`'s inverse, and a closed instance is terminal:
                // it is therefore never the schedule's *current* instance, so the
                // instance selector is the schedule's closed instance instead. As
                // with the siblings, a schedule with nothing to act on names no
                // instance and the shared service answers with its own refusal
                // rather than this surface inventing a target.
                crate::cycle_schedule::lifecycle::LifecycleAction::Reopen => {
                    self.reopenable_cycle_id(&schedule_id)
                }
                _ => None,
            };
            if let Some(state) = self.schedule.as_mut() {
                state.prompt = Some(crate::ui::schedule::CycleReasonPrompt {
                    schedule: schedule_id,
                    action,
                    cycle,
                    buffer: String::new(),
                });
            }
            return Ok(());
        }
        self.apply_cycle_schedule_action(&schedule_id, action, None, None)
    }

    /// Put one confirmed lifecycle action through WP05's shared service, and show the
    /// outcome **it** returned (T037).
    ///
    /// The actor, the reason and the instant come from the same boundary sources the
    /// CLI's `tix cycle schedule …` uses — the configured identity, the caller's
    /// typed reason, and [`crate::model::utc_now_rfc3339`], the crate's one clock
    /// read. This surface owns no second lifecycle, snapshot writer or History
    /// grammar: the service decides, writes or refuses, and its word (`applied`,
    /// `no-op`, `rejected`) is what the user sees.
    pub(in crate::app) fn apply_cycle_schedule_action(
        &mut self,
        schedule_id: &crate::cycle_schedule::config::CycleScheduleId,
        action: crate::cycle_schedule::lifecycle::LifecycleAction,
        cycle: Option<crate::cycle_schedule::identity::GeneratedCycleId>,
        reason: Option<String>,
    ) -> Result<()> {
        use crate::cycle_schedule::lifecycle::LifecycleOutcome;

        let root = self.project_root();
        let mut request = crate::cycle_schedule::lifecycle::LifecycleRequest::new(
            action,
            schedule_id.clone(),
            crate::commands::recurring::actor(),
        )
        .with_timestamp(crate::model::utc_now_rfc3339());
        if let Some(cycle) = cycle {
            request = request.for_cycle(cycle);
        }
        if let Some(reason) = reason {
            request = request.with_reason(reason);
        }
        let request = crate::commands::capacity::with_close_capacity(
            request,
            &self.store.config,
            &root,
            &self.store,
        )?;
        let request = request.confirm();

        let outcome =
            crate::cycle_schedule::lifecycle::apply(&mut self.store.config, &root, &request)?;
        self.status_msg = Some(match &outcome {
            LifecycleOutcome::Rejected { .. } => format!("rejected: {}", outcome.render()),
            _ => outcome.render(),
        });
        // The action wrote files: re-read the corpus and re-evaluate, so the board,
        // the rows and the warnings are all derived from what is on disk now.
        self.refresh_corpus()?;
        Ok(())
    }

    /// Generate the selected schedule's look-ahead through WP04's confirmed
    /// generator, and report the report's own figures (T037).
    ///
    /// The horizon is the schedule's configured `look_ahead` — the same value the
    /// CLI uses when `--through` is absent — so the page and
    /// `tix cycle schedule generate <id> --confirm` ask the service for the same
    /// pass. The one thing this does not do is pick stages: `generate` is
    /// idempotent, so a second press is the same stable keys, and the surface reports
    /// `created`/`no-op`/`rejected` per the report.
    pub(in crate::app) fn generate_selected_cycle_schedule(&mut self) -> Result<()> {
        let Some(schedule_id) = self.selected_cycle_schedule_id() else {
            self.status_msg = Some("No cycle schedule selected".to_string());
            return Ok(());
        };
        let Ok(index) = self.cycle_schedule_index() else {
            self.status_msg = Some("could not read the cycle schedule registry".to_string());
            return Ok(());
        };
        let Some(context) = Self::cycle_schedule_context() else {
            self.status_msg = Some("no date context is available".to_string());
            return Ok(());
        };
        let look_ahead = index
            .schedule(&schedule_id)
            .map_or(0, |record| record.look_ahead);
        let request = crate::cycle_schedule::generate::GenerationRequest::new(
            schedule_id.clone(),
            context,
            look_ahead,
            crate::commands::recurring::actor(),
        )
        .confirm();

        let root = self.project_root();
        let report = crate::cycle_schedule::generate::generate(
            &mut self.store.config,
            &root,
            &index,
            &request,
        )?;
        let mut line = format!(
            "generate `{schedule_id}`: {} created, {} no-op, {} rejected",
            report.created().count(),
            report.no_ops().count(),
            report.rejected().count()
        );
        if report.is_empty() {
            line.push_str(" (the schedule's look-ahead is 0: nothing to generate)");
        }
        if let Some(first) = report.rejected().next() {
            line.push_str(&format!(" — {}", first.render()));
        }
        self.status_msg = Some(line);
        self.refresh_corpus()?;
        Ok(())
    }

    /// The Schedule page's keys (T036): move, then act through the shared services.
    ///
    /// Every action goes to the service the CLI uses, with the due candidate the
    /// detector reports — never an event date this surface invented. A series with
    /// nothing due says so instead of guessing one.
    ///
    /// The active **tab** decides what a letter means. The Series tab keeps its
    /// keys, plus `n` (its own bound `series_new`, which opens the create form);
    /// the Cycle schedules tab maps the same letters onto
    /// the cycle-schedule services (`g`enerate/`p`ause/`r`esume/`s`kip/`i`gnore),
    /// and the three letters it adds — `c`lose, `e`xtend, adjust-`f`uture's `a` —
    /// arrive raw through [`App::handle_schedule_raw_key`] because the page's
    /// binding section does not name them. `x` and `d` mean nothing on the Cycle
    /// tab and are inert rather than silently aliased to something else.
    pub(in crate::app) fn handle_schedule_key(&mut self, key: KeyEvent) -> Result<Action> {
        use crate::ui::schedule::ScheduleTab;

        if !matches!(self.mode, Mode::Schedule) {
            return Ok(Action::None);
        }
        let tab = self.schedule_state().tab;
        let rows = match tab {
            ScheduleTab::Series => self.schedule_entries().len(),
            ScheduleTab::Cycles => self.cycle_schedule_entries().len(),
            ScheduleTab::Capacity => self.capacity_rows().len(),
        };
        if let Some(state) = self.schedule.as_mut() {
            state.clamp_selected(rows);
        }
        match key.code {
            KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('Q') => {
                self.schedule = None;
                // Schedule actions report through `status_msg`, which this page now
                // renders. Clear it on the way out so a refusal cannot reappear as a
                // stale board message.
                self.status_msg = None;
                self.mode = Mode::Board;
            }
            KeyCode::Up | KeyCode::Char('k') => {
                if let Some(state) = self.schedule.as_mut() {
                    state.move_selected(-1, rows);
                }
            }
            KeyCode::Down | KeyCode::Char('j') => {
                if let Some(state) = self.schedule.as_mut() {
                    state.move_selected(1, rows);
                }
            }
            // The Series tab's create key. On the Cycle schedules tab `n` is claimed
            // by the raw layer (it defines a schedule), so it never reaches here.
            KeyCode::Char('n') => {
                if tab == ScheduleTab::Series {
                    self.open_series_create_form();
                }
            }
            KeyCode::Char('p') => match tab {
                ScheduleTab::Series => {
                    self.act_on_series(crate::recurrence::lifecycle::LifecycleAction::Pause)?
                }
                ScheduleTab::Cycles => self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Pause,
                )?,
                // The Capacity tab is read-only: `p`/`r`/`g`/`s`/`i` act on a series or
                // a schedule and mean nothing here, so they are inert rather than
                // silently aliased.
                ScheduleTab::Capacity => {}
            },
            KeyCode::Char('r') => match tab {
                ScheduleTab::Series => {
                    self.act_on_series(crate::recurrence::lifecycle::LifecycleAction::Resume)?
                }
                ScheduleTab::Cycles => self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Resume,
                )?,
                ScheduleTab::Capacity => {}
            },
            KeyCode::Char('x') => {
                if tab == ScheduleTab::Series {
                    self.act_on_series(crate::recurrence::lifecycle::LifecycleAction::End)?;
                }
            }
            KeyCode::Char('g') => match tab {
                ScheduleTab::Series => self.act_on_selected_candidate(CandidateAction::Generate)?,
                ScheduleTab::Cycles => self.generate_selected_cycle_schedule()?,
                ScheduleTab::Capacity => {}
            },
            KeyCode::Char('s') => match tab {
                ScheduleTab::Series => self.act_on_selected_candidate(CandidateAction::Skip)?,
                ScheduleTab::Cycles => self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Skip,
                )?,
                ScheduleTab::Capacity => {}
            },
            KeyCode::Char('d') => {
                if tab == ScheduleTab::Series {
                    self.act_on_selected_candidate(CandidateAction::Defer)?;
                }
            }
            KeyCode::Char('i') => match tab {
                ScheduleTab::Series => self.act_on_selected_candidate(CandidateAction::Ignore)?,
                ScheduleTab::Cycles => self.begin_cycle_schedule_action(
                    crate::cycle_schedule::lifecycle::LifecycleAction::Ignore,
                )?,
                ScheduleTab::Capacity => {}
            },
            KeyCode::Char('?') => self.open_help(Mode::Schedule),
            _ => {}
        }
        Ok(Action::None)
    }

    /// Apply a state action to the selected series.
    pub(in crate::app) fn act_on_series(
        &mut self,
        action: crate::recurrence::lifecycle::LifecycleAction,
    ) -> Result<()> {
        let Some(series_id) = self.selected_series_id() else {
            self.status_msg = Some("No series selected".to_string());
            return Ok(());
        };
        let request = crate::recurrence::lifecycle::LifecycleRequest::new(
            series_id.clone(),
            action,
            crate::commands::recurring::actor(),
        )
        .confirm();
        let outcome = crate::recurrence::lifecycle::apply(&self.store, &request)?;
        self.status_msg = Some(format!("{}: {}", action.as_str(), outcome.render()));
        Ok(())
    }

    /// Act on the selected series\' due candidate — the one the detector reports.
    ///
    /// A series with nothing due says so rather than acting on a date this surface
    /// invented.
    pub(in crate::app) fn act_on_selected_candidate(
        &mut self,
        action: CandidateAction,
    ) -> Result<()> {
        let Some(series_id) = self.selected_series_id() else {
            self.status_msg = Some("No series selected".to_string());
            return Ok(());
        };
        let index = self.series_index()?;
        let Some(series) = index.series_by_id(&series_id).cloned() else {
            return Ok(());
        };
        let Some(warning) = Self::due_candidate(&index, &series) else {
            self.status_msg = Some(format!(
                "Series `{series_id}` has nothing due; generation and the occurrence \
                 actions need a due candidate"
            ));
            return Ok(());
        };
        self.status_msg = Some(self.apply_candidate(&warning, action)?);
        Ok(())
    }
}