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

impl App {
    /// Persist the cards whose positions differ from the automatic ordering so
    /// a drag-reordered column survives rebuilds/restarts without storing a
    /// full column snapshot.
    pub(in crate::app) fn persist_card_order(&mut self) -> bool {
        let board_name = self.active_board_name().to_string();
        let mut order = Vec::new();
        let active_config = self.active_board_config().clone();
        order.extend(
            self.board
                .columns
                .iter()
                .flat_map(|col| board::sparse_card_order(&active_config, &col.cards)),
        );
        order.extend(
            self.board
                .hidden
                .iter()
                .flat_map(|col| board::sparse_card_order(&active_config, &col.cards)),
        );
        order.extend(board::sparse_card_order(
            &active_config,
            &self.board.mismatch.cards,
        ));
        let Some(board_config) = self.store.config.kanban.configurations.get_mut(&board_name)
        else {
            return false;
        };
        board_config.card_order = order;
        self.persist_config()
    }

    pub(in crate::app) fn reorder_selected_within_column(
        &mut self,
        col: usize,
        from_row: usize,
        to_row: usize,
    ) -> Result<Action> {
        let (filename, number, column_name) = {
            let Some(column) = self.board.columns.get_mut(col) else {
                return Ok(Action::None);
            };
            if from_row >= column.cards.len() || to_row >= column.cards.len() || from_row == to_row
            {
                return Ok(Action::None);
            }
            let card = column.cards.remove(from_row);
            let filename = card.filename.clone();
            let number = card.number;
            let insert_at = to_row;
            column.cards.insert(insert_at, card);
            (filename, number, column.name.clone())
        };

        if !self.persist_card_order() {
            return Ok(Action::None);
        }
        self.rebuild_board();
        self.select_card_by_filename(&filename);
        self.status_msg = Some(format!("Reordered #{} in {}", number, column_name));
        Ok(Action::None)
    }

    /// Move the selected card within the active column by `delta` slots.
    pub(in crate::app) fn move_selected_within_column(&mut self, delta: isize) -> Result<Action> {
        let col = self.board.active_col;
        let column_name = if col < self.board.columns.len() {
            self.board.columns[col].name.clone()
        } else if col == self.board.columns.len() && self.board.show_mismatch {
            self.board.mismatch.name.clone()
        } else {
            return Ok(Action::None);
        };
        let (filename, number) = {
            let cards = if col < self.board.columns.len() {
                &mut self.board.columns[col].cards
            } else {
                &mut self.board.mismatch.cards
            };
            let len = cards.len();
            if len < 2 {
                return Ok(Action::None);
            }
            let from_row = self.board.selected;
            if from_row >= len {
                return Ok(Action::None);
            }
            let to_row = if delta < 0 {
                from_row.saturating_sub(delta.unsigned_abs())
            } else {
                usize::min(from_row + delta as usize, len - 1)
            };
            if to_row == from_row {
                return Ok(Action::None);
            }
            let card = cards.remove(from_row);
            let filename = card.filename.clone();
            let number = card.number;
            let insert_at = to_row;
            cards.insert(insert_at, card);
            (filename, number)
        };
        if !self.persist_card_order() {
            return Ok(Action::None);
        }
        self.rebuild_board();
        self.select_card_by_filename(&filename);
        self.status_msg = Some(format!(
            "Moved #{} {} in {}",
            number,
            if delta < 0 { "up" } else { "down" },
            column_name
        ));
        Ok(Action::None)
    }

    /// Open the action menu for the card the board is displaying, or for the
    /// selected card (tix #1744).
    ///
    /// When exactly one card is displayed, `Enter` targets **it** wherever the
    /// cursor happens to be — a `/` search that narrows the board to a single
    /// issue lands the cursor on an empty column, and requiring a navigation step
    /// before `Enter` does anything is the bug this fixes. With zero or several
    /// cards the cursor still decides, exactly as before.
    pub(in crate::app) fn open_card_action_menu(&mut self) -> Result<Action> {
        let (col, row) = self
            .board
            .sole_visible_card()
            .unwrap_or((self.board.active_col, self.board.selected));
        self.mouse.last_down = None;
        self.open_action_menu(Some(HitTarget::Card { col, row }), false)
    }

    #[allow(clippy::too_many_lines)]
    pub(in crate::app) fn handle_board_key(&mut self, key: KeyEvent) -> Result<Action> {
        if key
            .modifiers
            .contains(crossterm::event::KeyModifiers::CONTROL)
        {
            match key.code {
                KeyCode::Up => return self.move_selected_within_column(-1),
                KeyCode::Down => return self.move_selected_within_column(1),
                _ => {}
            }
        }
        match key.code {
            KeyCode::Char('q') | KeyCode::Char('Q') | KeyCode::Esc => {
                self.quit = true;
                Ok(Action::Quit)
            }
            KeyCode::Tab => {
                self.tabs.next();
                self.active_config = self.tabs.selected;
                self.switch_config();
                Ok(Action::None)
            }
            KeyCode::BackTab => {
                self.tabs.previous();
                self.active_config = self.tabs.selected;
                self.switch_config();
                Ok(Action::None)
            }
            KeyCode::Left | KeyCode::Char('h') => {
                self.board.move_left();
                Ok(Action::None)
            }
            KeyCode::Right | KeyCode::Char('l') => {
                self.board.move_right();
                Ok(Action::None)
            }
            KeyCode::Up | KeyCode::Char('k') => {
                self.board.move_up();
                Ok(Action::None)
            }
            KeyCode::Down | KeyCode::Char('j') => {
                self.board.move_down();
                Ok(Action::None)
            }
            KeyCode::Enter => self.open_card_action_menu(),
            KeyCode::Char('e') => {
                if let Some(card) = self.board.get_selected_card() {
                    Ok(Action::OpenEditor(card.filename.clone()))
                } else {
                    Ok(Action::None)
                }
            }
            // The mentions view (OpenSpec change `issue-mentions`). `i` is the
            // canonical event of `TuiAction::OpenMentions`, so a rebound chord
            // arrives here as `i`; the indicator row reads the chord back out of the
            // effective bindings and advertises whichever one is in force.
            KeyCode::Char('i') => {
                self.open_mentions();
                Ok(Action::None)
            }
            // The board's read-only viewer (#1507) is the **shifted** letter: the
            // plain `v` opens the saved-views modal (WP05) in the arm below, and
            // the Detail context keeps `v` for the viewer. See the board defaults
            // in `keybindings.rs` for why `v` went to saved views.
            KeyCode::Char('V') => {
                if let Some(card) = self.board.get_selected_card() {
                    Ok(Action::OpenViewer(card.filename.clone()))
                } else {
                    Ok(Action::None)
                }
            }
            KeyCode::Char('A') => {
                if let Some(card) = self.board.get_selected_card() {
                    Ok(Action::OpenAgent(card.filename.clone()))
                } else {
                    Ok(Action::None)
                }
            }
            KeyCode::Char('c') => {
                self.toggle_column_visibility();
                Ok(Action::None)
            }
            KeyCode::Char('f') => {
                self.open_filter_modal();
                Ok(Action::None)
            }
            // WP07 T031: `space` marks a card, `x` unmarks it, `X` empties the
            // selection. The **board** owns these, not the modal, because the
            // selection is made by standing on cards; a modal that swallowed the
            // board's keys would break every existing binding, which T031 forbids.
            //
            // Marking deliberately does **not** open the modal: the first `space`
            // used to raise the batch-edit modal, which made every later mark a
            // keystroke inside a surface the user did not ask for. The status line
            // carries the running count instead, and `B` opens the modal when the
            // user actually wants to act on the set.
            KeyCode::Char(' ') => {
                self.toggle_mark_selected();
                Ok(Action::None)
            }
            KeyCode::Char('x') => {
                self.unmark_selected_card();
                Ok(Action::None)
            }
            KeyCode::Char('X') => {
                self.clear_marks();
                Ok(Action::None)
            }
            KeyCode::Char('B') => {
                let action = self
                    .bulk
                    .as_ref()
                    .map(|m| m.action)
                    .unwrap_or(crate::ui::bulk::BatchAction::Edit);
                self.open_bulk_modal(action);
                Ok(Action::None)
            }
            KeyCode::Char('<') => {
                let real_cols = self.board.real_cols();
                if real_cols > 0 {
                    let target = if self.board.active_col == 0 || self.board.active_col >= real_cols
                    {
                        real_cols - 1
                    } else {
                        self.board.active_col - 1
                    };
                    self.move_selected_to(target)
                } else {
                    Ok(Action::None)
                }
            }
            KeyCode::Char('>') => {
                let real_cols = self.board.real_cols();
                if real_cols > 0 {
                    let target = if self.board.active_col >= real_cols {
                        0
                    } else {
                        (self.board.active_col + 1) % real_cols
                    };
                    self.move_selected_to(target)
                } else {
                    Ok(Action::None)
                }
            }
            KeyCode::Char('n') => {
                self.open_new_issue_form();
                Ok(Action::None)
            }
            KeyCode::Char('C') => {
                self.clone_selected_into_form();
                Ok(Action::None)
            }
            // #1492: show the archived issues too, or hide them again. Off by
            // default and *reloaded* rather than filtered on demand: the archived
            // files are not in the corpus until this is on, which is what keeps
            // opening a board in a repository full of them cheap.
            KeyCode::Char('a') => {
                self.show_archived = !self.show_archived;
                self.refresh_corpus()?;
                self.status_msg = Some(
                    if self.show_archived {
                        "Showing archived issues"
                    } else {
                        "Hiding archived issues"
                    }
                    .to_string(),
                );
                Ok(Action::None)
            }
            // #1399: show each issue's sub-issues beneath it, or hide them again.
            // Display-only: the children are already in the board state, so this
            // reorders the columns (one level deep) on a rebuild rather than
            // re-reading the store — the archive toggle's reload would be wasted work.
            KeyCode::Char('u') => {
                self.show_children = !self.show_children;
                self.rebuild_board();
                self.status_msg = Some(
                    if self.show_children {
                        "Showing sub-issues"
                    } else {
                        "Hiding sub-issues"
                    }
                    .to_string(),
                );
                Ok(Action::None)
            }
            // tix #1442 (follow-up): a page of cards. The column scrolls itself to keep
            // the selection visible — the `List` does that — so a page step is a
            // selection jump by one screen, measured by the renderer.
            //
            // These keys were **unbound** on the board until now, and an unbound key in
            // a non-text context is rewritten to `F(12)` before the handler sees it, so
            // `PgUp`/`PgDn` did nothing at all while the wheel next to them worked. A
            // key that silently disappears is worse than one that is not advertised.
            KeyCode::PageDown => {
                self.move_selection_by_page(1);
                Ok(Action::None)
            }
            KeyCode::PageUp => {
                self.move_selection_by_page(-1);
                Ok(Action::None)
            }
            KeyCode::Char('d') => {
                if let Some(card) = self.board.get_selected_card().cloned() {
                    self.confirm_delete_target = Some(card.filename);
                    self.mode = Mode::ConfirmDelete;
                }
                Ok(Action::None)
            }
            KeyCode::Char('r') => {
                self.refresh_corpus()?;
                self.status_msg = Some("Refreshed".to_string());
                Ok(Action::None)
            }
            KeyCode::Char('s') => {
                self.open_settings(None);
                Ok(Action::None)
            }
            // WP06, T029. `t` was unbound, so this adds a key rather than
            // changing what an existing one means — the escalation this
            // mission is told to avoid is an *unrelated* navigation change,
            // and this one is the triage surface's own entry point.
            KeyCode::Char('t') => self.open_triage_inbox(),
            // WP05. `v` was unbound, so this adds a key rather than changing what
            // an existing one means (T024), and it is rebound through
            // `keybindings.board.views` like every other board key.
            KeyCode::Char('v') => {
                self.open_views();
                Ok(Action::None)
            }
            KeyCode::Char('m') | KeyCode::Char('M') => {
                self.open_planning_modal();
                Ok(Action::None)
            }
            KeyCode::Char('b') => {
                self.open_settings(Some(SettingsPrompt::NewBoard(String::new())));
                Ok(Action::None)
            }
            KeyCode::Char('?') => {
                self.open_help(Mode::Board);
                Ok(Action::None)
            }
            KeyCode::Char('/') => {
                let buffer = self.filter.clone().unwrap_or_default();
                self.mode = Mode::Filter { buffer };
                Ok(Action::None)
            }
            _ => Ok(Action::None),
        }
    }

    /// Duplicate the selected issue into the create-issue form, prefilled
    /// (tix #1484). The source is resolved through the same selector path the CLI
    /// uses, so fields the card projection does not carry are copied too.
    pub(in crate::app) fn clone_selected_into_form(&mut self) {
        let Some(card) = self.board.get_selected_card().cloned() else {
            self.status_msg = Some("No issue selected to clone".to_string());
            return;
        };
        match crate::commands::view::get(&self.store, &card.filename) {
            Ok(issue) => {
                self.status_msg = Some(format!("Cloning #{}", issue.number));
                let entry = self.new_issue_target_status(NewIssueTarget::Triage);
                let mut form = FormState::from_issue(&issue);
                if issue.status.to_string().trim() == entry {
                    form.target = NewIssueTarget::Triage;
                }
                self.enter_form(form);
            }
            Err(err) => self.status_msg = Some(format!("Cannot clone: {err}")),
        }
    }

    /// The single entry point for a visible-column move (`<`/`>`, drag-and-drop).
    pub(in crate::app) fn move_selected_to(&mut self, target_col: usize) -> Result<Action> {
        self.start_move(MoveTarget::Visible(target_col))
    }

    /// Start a move to a named configured column (the action dialog's path).
    ///
    /// When the card under the cursor is part of a multi-selection, the move
    /// covers **every** marked issue; otherwise it is the single card. The batch
    /// keeps the selection afterwards, so a user can move a set and then apply
    /// the next action to the same set.
    pub(in crate::app) fn start_move(&mut self, target: MoveTarget) -> Result<Action> {
        let Some(card) = self.board.get_selected_card().cloned() else {
            return Ok(Action::None);
        };
        let target_name = target.name(&self.board);
        let numbers = self.move_numbers(card.number);
        self.pending_move = Some(PendingMove {
            numbers,
            target,
            target_name,
            reason: None,
            acknowledged: false,
            commit: None,
        });
        self.advance_move()
    }

    /// The issues a move started on `anchor` should cover: the whole marked set
    /// when the anchor is marked and the set has more than one issue, otherwise
    /// just the anchor.
    fn move_numbers(&self, anchor: u32) -> Vec<u32> {
        match &self.bulk {
            Some(modal) if modal.selection.len() > 1 && modal.selection.contains(anchor) => {
                modal.selection.numbers().to_vec()
            }
            _ => vec![anchor],
        }
    }

    /// Run the shared move with the answers collected so far.
    ///
    /// The order is the documented one and matches `commands::mv::run`: the
    /// blocked-move guard first (an acknowledgement must not be asked for after
    /// a reason or a commit hash), then the transition policy, then the WIP
    /// policy, then the commit prompt. Every prompt stores its answer in
    /// [`App::pending_move`] and calls back here, so no prompt discards another
    /// prompt's answer.
    ///
    /// A batch asks each question **once** and applies the answer to the whole
    /// set: all items move to the same column, so they share that column's limit
    /// and one reason/acknowledgement/commit is the same decision for each. The
    /// per-item outcomes are collected and reported together; a refused item
    /// never rolls back the ones already applied.
    #[allow(clippy::too_many_lines)]
    pub(in crate::app) fn advance_move(&mut self) -> Result<Action> {
        use crate::wip::WipOutcome;
        use crate::workflow::{TransitionOutcome, WorkflowCategory};

        let Some(pending) = self.pending_move.clone() else {
            return Ok(Action::None);
        };
        if pending.numbers.is_empty() {
            self.finish_move();
            return Ok(Action::None);
        }

        let target_name = pending.target_name.clone();
        let (_, resolution) = crate::workflow::active_resolution(&self.store.config);
        let is_done_target = resolution
            .resolve(&target_name)
            .is_some_and(WorkflowCategory::is_complete);

        // Resolve the batch once. A number that no longer resolves is dropped and
        // reported; the rest still move, which is the same partial-batch rule the
        // CLI and the batch modal use.
        let mut issues = Vec::with_capacity(pending.numbers.len());
        let mut missing = 0usize;
        for number in &pending.numbers {
            match self.store.get(IssueSelector::Number(*number)) {
                Ok(issue) => issues.push(issue),
                Err(_) => missing += 1,
            }
        }
        if issues.is_empty() {
            self.finish_move();
            self.status_msg = Some("Move: none of the selected issues still exist".to_string());
            return Ok(Action::None);
        }

        // 1. Blocked-move guard. One acknowledgement covers the batch; the
        //    decision is recorded per issue by the shared apply.
        if !pending.acknowledged {
            let mut blocked = Vec::new();
            for issue in &issues {
                let guard =
                    mv::blocked_move_guard(&self.store.config, &self.store, issue, &target_name)?;
                if guard.needs_acknowledgement() {
                    blocked.push(guard.warning().unwrap_or_default());
                }
            }
            if let Some(first) = blocked.first() {
                let warning = if issues.len() > 1 {
                    format!(
                        "{} of {} selected issues are blocked. {first}",
                        blocked.len(),
                        issues.len()
                    )
                } else {
                    first.clone()
                };
                self.mode = Mode::ConfirmBlockedMove { warning };
                return Ok(Action::None);
            }
        }

        // 2. Transition policy. One reason covers the batch.
        if pending.reason.is_none() {
            for issue in &issues {
                if let TransitionOutcome::Rejected(diagnostic) =
                    crate::workflow::validate_transition(
                        issue,
                        &target_name,
                        &resolution,
                        &self.store.config,
                        None,
                    )
                {
                    self.mode = Mode::TransitionReason {
                        reason: diagnostic.to_string(),
                        buffer: String::new(),
                    };
                    return Ok(Action::None);
                }
            }
        }

        // 3. WIP policy. Every item targets one column, so one override reason
        //    authorizes the same limit; asking once is the same decision.
        if self.pending_wip_override.is_none() {
            for issue in &issues {
                if let Some(decision) =
                    self.wip_decision(issue.number, &target_name, pending.reason.as_deref(), None)
                    && decision.outcome == WipOutcome::Block
                {
                    self.wip_override = Some(crate::ui::wip_override::WipOverridePrompt {
                        number: issue.number,
                        count: issues.len(),
                        target_move: pending.target.clone(),
                        target: target_name.clone(),
                        decision,
                    });
                    self.mode = Mode::WipOverride {
                        buffer: String::new(),
                    };
                    return Ok(Action::None);
                }
            }
        }

        // 4. Commit prompt. Answered once for the batch; an empty answer records
        //    no hash on the items that reach completion.
        if is_done_target && pending.commit.is_none() {
            let needs_commit = issues.iter().any(|issue| {
                let was_done = resolution
                    .resolve(&issue.status.to_string())
                    .is_some_and(WorkflowCategory::is_complete);
                !was_done && issue.commit.is_none()
            });
            if needs_commit {
                self.mode = Mode::MoveIntoDone {
                    buffer: String::new(),
                };
                return Ok(Action::None);
            }
        }

        // 5. Apply each item with the collected answers.
        let mut moved = Vec::new();
        let mut refusals: Vec<(u32, String)> = Vec::new();
        let mut wip_note: Option<String> = None;
        for issue in &issues {
            let was_done = resolution
                .resolve(&issue.status.to_string())
                .is_some_and(WorkflowCategory::is_complete);
            let commit = if was_done {
                None
            } else {
                match &pending.commit {
                    Some(answered) => answered.clone(),
                    None => issue.commit.clone(),
                }
            };

            let (wip_event, item_note) = match self.wip_decision(
                issue.number,
                &target_name,
                pending.reason.as_deref(),
                self.pending_wip_override.as_ref(),
            ) {
                Some(decision) => match decision.outcome {
                    WipOutcome::Allow => (None, None),
                    WipOutcome::Warn => (None, Some(crate::wip::render_decision(&decision))),
                    WipOutcome::Override => (decision.history.clone(), None),
                    WipOutcome::Rejected
                        if decision.diagnostics.first().is_some_and(|diagnostic| {
                            diagnostic.kind == crate::wip::WipDiagnosticKind::RejectedTransition
                        }) =>
                    {
                        (None, None)
                    }
                    WipOutcome::Block | WipOutcome::Rejected => {
                        refusals.push((issue.number, crate::wip::render_decision(&decision)));
                        continue;
                    }
                },
                None => (None, None),
            };
            if wip_note.is_none() {
                wip_note = item_note;
            }

            match mv::apply_guarded(
                &self.store.config,
                &self.store,
                &issue.filename,
                &target_name,
                commit.as_deref(),
                pending.reason.as_deref(),
                pending.acknowledged,
                wip_event.as_ref(),
            ) {
                Ok(outcome) => {
                    moved.push((issue.number, outcome.acknowledged));
                    // The next item's WIP decision counts the column occupancy
                    // **after** this write. Without the refresh, a batch could
                    // authorize two items against the same free slot.
                    self.refresh_corpus()?;
                }
                Err(error) => refusals.push((issue.number, error.to_string())),
            }
        }

        self.finish_move();
        self.refresh_corpus()?;
        if let Some(index) = pending.target.visible_index() {
            self.board.select_column(index);
        }

        if pending.numbers.len() == 1 && refusals.is_empty() && missing == 0 {
            let (number, acknowledged) = moved.first().copied().unwrap_or((0, false));
            let ack = if acknowledged {
                ", blocked move acknowledged"
            } else {
                ""
            };
            let commit_note = match &pending.commit {
                Some(Some(hash)) => format!(" (commit: {hash}{ack})"),
                Some(None) => format!(" (no commit recorded{ack})"),
                None => String::new(),
            };
            self.status_msg = Some(match wip_note {
                Some(note) => format!("{note}\nMoved #{number} to {target_name}{commit_note}"),
                None => format!("Moved #{number} to {target_name}{commit_note}"),
            });
        } else {
            let mut message = format!(
                "Moved {} of {} to {target_name}",
                moved.len(),
                pending.numbers.len()
            );
            if let Some((number, reason)) = refusals.first() {
                let head = reason.lines().next().unwrap_or_default();
                message.push_str(&format!("; {} refused (#{number}: {head})", refusals.len()));
            }
            if missing > 0 {
                message.push_str(&format!("; {missing} missing"));
            }
            self.status_msg = Some(message);
        }
        Ok(Action::None)
    }

    /// Drop a move that is finished or cancelled, and the WIP authorization it
    /// may have carried.
    pub(in crate::app) fn finish_move(&mut self) {
        self.pending_move = None;
        self.pending_wip_override = None;
    }

    /// The reasoned-override prompt's key handler.
    ///
    /// Enter accepts a **non-blank** reason; Esc cancels. A blank reason is refused
    /// rather than accepted, because a whitespace-only string is not a reason and the
    /// service trims it away — accepting it here would show the user a move that
    /// then fails at the seam, having already closed the prompt.
    ///
    /// Cancelling returns to the board with **nothing** written: no file, no
    /// `updated` bump, no History entry. The move was never applied, so there is
    /// nothing to undo.
    pub(in crate::app) fn handle_transition_reason_key(&mut self, key: KeyEvent) -> Result<Action> {
        match key.code {
            KeyCode::Enter => {
                let reason = match &self.mode {
                    Mode::TransitionReason { buffer, .. } => buffer.clone(),
                    _ => String::new(),
                };
                if reason.trim().is_empty() {
                    self.status_msg = Some(
                        "A reason is required: the decision is recorded in the issue's \
                         history and has to say why"
                            .to_string(),
                    );
                    return Ok(Action::None);
                }
                // Store the reason and resume the shared move: the guard, the
                // policy check, the commit prompt and the write run again, and the
                // answers collected by the other prompts are still there.
                if let Some(pending) = self.pending_move.as_mut() {
                    pending.reason = Some(reason);
                }
                self.mode = Mode::Board;
                self.advance_move()
            }
            KeyCode::Esc => {
                self.finish_move();
                self.mode = Mode::Board;
                Ok(Action::None)
            }
            KeyCode::Char(c) => {
                if let Mode::TransitionReason { ref mut buffer, .. } = self.mode {
                    buffer.push(c);
                }
                Ok(Action::None)
            }
            KeyCode::Backspace => {
                if let Mode::TransitionReason { ref mut buffer, .. } = self.mode {
                    buffer.pop();
                }
                Ok(Action::None)
            }
            _ => Ok(Action::None),
        }
    }

    /// The optional commit prompt for a move into a completion column.
    ///
    /// The answer is stored on [`App::pending_move`] and the shared move resumes;
    /// it no longer writes on its own, which is what dropped the transition reason
    /// and hard-coded the acknowledgement before.
    pub(in crate::app) fn handle_move_into_done_key(&mut self, key: KeyEvent) -> Result<Action> {
        match key.code {
            KeyCode::Enter => {
                let buffer = match &self.mode {
                    Mode::MoveIntoDone { buffer, .. } => buffer.clone(),
                    _ => String::new(),
                };
                let trimmed = buffer.trim();
                if let Some(pending) = self.pending_move.as_mut() {
                    pending.commit = Some(if trimmed.is_empty() {
                        None
                    } else {
                        Some(trimmed.to_string())
                    });
                }
                self.mode = Mode::Board;
                self.advance_move()
            }
            KeyCode::Esc => {
                // The move is abandoned, so the override it may have been authorized
                // with is abandoned with it: leaving it pending would authorize the
                // *next* move to that column.
                self.finish_move();
                self.mode = Mode::Board;
                Ok(Action::None)
            }
            KeyCode::Char(c) => {
                if let Mode::MoveIntoDone { ref mut buffer, .. } = self.mode {
                    buffer.push(c);
                }
                Ok(Action::None)
            }
            KeyCode::Backspace => {
                if let Mode::MoveIntoDone { ref mut buffer, .. } = self.mode {
                    buffer.pop();
                }
                Ok(Action::None)
            }
            _ => Ok(Action::None),
        }
    }

    /// Move the board selection by one screen of cards (tix #1442 follow-up).
    ///
    /// A no-op before the first draw (nothing has reported a page yet) and in an empty
    /// column (the renderer reports zero, because there is nothing to page).
    pub(in crate::app) fn move_selection_by_page(&mut self, direction: i32) {
        let page = self.board_page.get();
        if page == 0 {
            return;
        }
        let step = i32::try_from(page).unwrap_or(i32::MAX);
        self.board.move_selection_by(step * direction);
    }

    /// Toggle column visibility on the active column (FR-005/FR-006/NFR-004/
    /// SC-003). Updates the in-memory config and persists atomically.
    pub(in crate::app) fn toggle_column_visibility(&mut self) {
        let col_name = self.board.active_column_name().to_string();
        let config_name = self.tabs.names[self.active_config].clone();
        let board_config = self
            .store
            .config
            .kanban
            .configurations
            .get_mut(&config_name);
        let board_config = match board_config {
            Some(bc) => bc,
            None => {
                self.status_msg = Some("toggle: config not found".into());
                return;
            }
        };
        let now_hidden = if let Some(pos) = board_config
            .hidden_columns
            .iter()
            .position(|h| h == &col_name)
        {
            board_config.hidden_columns.remove(pos);
            false
        } else {
            board_config.hidden_columns.push(col_name.clone());
            true
        };
        match self.store.config_path() {
            Ok(path) => {
                if let Err(e) = self.store.config.save(&path) {
                    self.status_msg = Some(format!("toggle save: {e}"));
                    return;
                }
            }
            Err(e) => {
                self.status_msg = Some(format!("toggle path: {e}"));
                return;
            }
        }
        // The user changed visibility by hand, so the applied view's visibility
        // snapshot stops being the live board's visibility (WP05, T025/C-006) —
        // dropped **before** the rebuild, because a rebuild that re-applied the
        // snapshot would make the toggle look like it did nothing. The **marker**
        // stays: the board is still associated with that view, and the divergence
        // report now names the difference instead of hiding it.
        if let Some(session) = self.view_session.as_mut() {
            session.visibility = false;
        }
        self.rebuild_board();
        // Keep the cursor logically on the toggled column so a second `c`
        // press re-shows it: visible index when shown, hidden-region index
        // while hidden. Navigation keys still skip hidden columns (T014).
        let visible = self.board.columns.len();
        self.board.active_col = if now_hidden {
            visible
                + self
                    .board
                    .hidden
                    .iter()
                    .position(|c| c.name == col_name)
                    .unwrap_or_default()
        } else {
            self.board
                .columns
                .iter()
                .position(|c| c.name == col_name)
                .unwrap_or_default()
        };
        self.board.clamp_selection();
        self.status_msg = Some(format!("Toggled '{col_name}' visibility"));
    }

    /// Switch the active board configuration (Tab/BackTab). Rebuilds the
    /// board through the same path as `rebuild_board` so filters re-apply to
    /// the new config's visible columns, resetting `active_col` to the first
    /// visible column while keeping the selected card if it is still visible.
    /// Switch to the named board at tab index `i` — the exact Tab/BackTab
    /// path (set `selected`, then `active_config`, then rebuild via
    /// [`App::switch_config`]). Used by the mouse-hit `Action::SwitchBoard`
    /// and the run loop; tabs need a single shared transition.
    pub(in crate::app) fn switch_board(&mut self, index: usize) {
        if index < self.tabs.len() {
            self.tabs.selected = index;
            self.tabs.hovered = None;
            self.active_config = index;
            self.switch_config();
        }
    }

    pub(in crate::app) fn switch_config(&mut self) {
        let selected_filename = self.board.get_selected_card().map(|c| c.filename.clone());
        self.rebuild_board();
        self.board.active_col = 0;
        if let Some(filename) = selected_filename
            && self
                .board
                .column_cards(0)
                .iter()
                .any(|c| c.filename == filename)
        {
            self.board.selected = self
                .board
                .column_cards(0)
                .iter()
                .position(|c| c.filename == filename)
                .unwrap_or(0);
        } else {
            self.board.selected = 0;
        }
        self.board.clamp_selection();
        self.status_msg = Some("Switched board".to_string());
    }

    /// Activate a rail **branch**: switch the shell to the branch's target,
    /// resolved by the same paths the mode's own controls use.
    ///
    /// One method per [`Action`] arm, so a branch click and a branch-only
    /// keyboard activation (there is none today; branches are pointer-only per
    /// the open-question-3 decision) share a single transition.
    pub fn activate_branch(&mut self, action: &Action) -> Result<Action> {
        match action {
            Action::SelectBoard(name) => self.select_board_branch(name),
            Action::SelectCycle(name) => self.select_cycle_branch(name),
            Action::SelectMilestone(name) => self.select_milestone_branch(name),
            Action::NewFromTemplate(name) => self.new_from_template(name),
            _ => Ok(Action::None),
        }
    }

    /// Switch the active board to the named configuration and show the Board
    /// mode (open question 2: the branch switches the mode too, so the result of
    /// the switch is what the user sees rather than a board changing off-screen).
    pub(in crate::app) fn select_board_branch(&mut self, name: &str) -> Result<Action> {
        let index = self
            .store
            .config
            .configs()
            .position(|(candidate, _)| candidate == name);
        let Some(index) = index else {
            self.status_msg = Some(format!("Board '{name}' not found"));
            return Ok(Action::None);
        };
        self.switch_top_mode(TopMode::Board)?;
        self.switch_board(index);
        Ok(Action::None)
    }

    /// Enter the Cycle mode with its cursor on the named cycle.
    ///
    /// The index is a position in the mode's **rendered** flat order, the same
    /// space [`crate::ui::cycle::flat_entries`] and every other cursor write
    /// use; a position in the config's insertion order would land on a
    /// different cycle whenever the two disagree, which is most of the time.
    pub(in crate::app) fn select_cycle_branch(&mut self, name: &str) -> Result<Action> {
        self.switch_top_mode(TopMode::Cycle)?;
        let groups = self.cycle_groups();
        let index = crate::ui::cycle::flat_entries(&groups)
            .iter()
            .position(|entry| entry.name == name);
        if let (Some(index), Some(state)) = (index, self.cycle_state.as_mut()) {
            state.selected = index;
        }
        Ok(Action::None)
    }

    /// Enter the Milestones mode with its cursor on the named milestone.
    pub(in crate::app) fn select_milestone_branch(&mut self, name: &str) -> Result<Action> {
        self.switch_top_mode(TopMode::Milestones)?;
        let (_cycles, milestones) = self.planning_rows();
        let index = milestones
            .iter()
            .position(|row| row.name == name)
            .unwrap_or(0);
        if let Some(modal) = self.planning.as_mut() {
            modal.segment = PlanningSegment::Milestones;
            modal.selected = index;
            modal.prompt = None;
        }
        Ok(Action::None)
    }

    /// Open the New Issue form seeded from the named `[templates.<name>]`
    /// record, entering the New Issue mode first (the form is that mode's
    /// content).
    pub(in crate::app) fn new_from_template(&mut self, name: &str) -> Result<Action> {
        self.switch_top_mode(TopMode::NewIssue)?;
        self.select_template(name);
        Ok(Action::None)
    }
}