tix-tracker 0.11.0

A terminal issue tracker: markdown + YAML frontmatter issues with a kanban TUI and CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
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
//! The TUI batch surface (WP07).
//!
//! Everything here is a **state machine over shared services**. It builds no patch
//! and writes no file: the selection goes through `bulk::Selection::from_issues`
//! (WP01's constructor, built for exactly this), the preview through
//! `bulk::plan::build_plan`, the apply through `bulk::apply`/`bulk::pair`/
//! `bulk::archive`, and the text through `commands::bulk`'s **same** renderers the
//! CLI uses.
//!
//! ## Why the TUI holds `PatchFlags` and not an `IssuePatch`
//!
//! T032 says to "reject TUI-local patch construction or direct writes". A TUI that
//! built its own `IssuePatch` would be a second mapping from user input to a typed
//! patch, free to drift from the CLI's — and the drift would show up as a TUI
//! accepting a blank field as `Clear` while the CLI treats it as absent, which is
//! precisely the bug WP06 found in the CLI.
//!
//! So the modal holds `commands::bulk::PatchFlags` — the **same** struct the CLI
//! parses into — and the conversion happens in one place. The TUI's only job is to
//! set flags and press apply.
//!
//! ## The board cursor is untouched
//!
//! T031 requires the existing single-card cursor and navigation semantics to stay
//! intact. So the multi-selection is a **separate** ordered set, and the board's
//! `(active_col, selected)` pair is never written by anything in this module. That is
//! also what makes cancelling safe: the modal is a value, and dropping it restores
//! the board exactly.
//!
//! ## Why there is a focus, and not one key channel
//!
//! A first draft had `p` preview, `y` confirm, `c` clear **and** bare characters as
//! field text, all on one channel. That is not a shortcut, it is a bug: typing `p`
//! into the status field previews instead of typing. Any single-channel design has
//! this — the union of "characters a field may contain" and "keys that are commands"
//! is the whole ASCII range.
//!
//! So the modal has [`BulkFocus`], the same two-state shape the settings prompt already
//! uses (`InputContext::SettingsPrompt`). On a **row** the keys are commands; in
//! **edit** they are text. `enter` moves between them, and the two never overlap.
//!
//! ## The same text as the CLI
//!
//! `render_preview` and `render_result` call `commands::bulk::render_plan` and
//! `render_report`. `contracts/surface-parity.md` requires the same decision and the
//! same message on every surface, and the cheapest way to guarantee that is not to
//! have two renderers.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, List, ListItem, Paragraph};

use crate::bulk::plan::BatchPlan;
use crate::bulk::{
    self, ApplyReport, ArchiveRequest, Confirmation, IssuePatch, RelationshipOp, Selection,
};
use crate::commands::bulk::{self as cli_bulk, Mode, PatchFlags};
use crate::error::{Result, TixError};
use crate::storage::Store;

/// Which batch action a modal is for.
///
/// **Not** `cli::BulkAction`. That enum carries every flag as struct fields — the
/// flags are the clap surface, and the modal *is* the flags. Storing it would put
/// each flag in two places and let them disagree, which is the T032 prohibition
/// ("reject TUI-local patch construction") in a different guise. Four words, and the
/// `From` impl is the only conversion.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BatchAction {
    Edit,
    Link,
    Unlink,
    Archive,
}

impl BatchAction {
    /// The word a user reads.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Edit => "edit",
            Self::Link => "link",
            Self::Unlink => "unlink",
            Self::Archive => "archive",
        }
    }

    /// Whether this action takes field flags, as opposed to a target and a kind.
    pub fn takes_fields(self) -> bool {
        matches!(self, Self::Edit)
    }

    /// Whether this action is a pair.
    pub fn is_pair(self) -> bool {
        matches!(self, Self::Link | Self::Unlink)
    }

    /// The next action, for the cycle key.
    ///
    /// A fixed order — edit, link, unlink, archive — so `a` twice returns to where
    /// it started. A cycle whose order depended on the board would make `a` a
    /// non-repeatable key, and a non-repeatable cycle is a key nobody uses twice.
    pub fn next(self) -> Self {
        match self {
            Self::Edit => Self::Link,
            Self::Link => Self::Unlink,
            Self::Unlink => Self::Archive,
            Self::Archive => Self::Edit,
        }
    }
}

impl From<&crate::cli::BulkAction> for BatchAction {
    fn from(action: &crate::cli::BulkAction) -> Self {
        match action {
            crate::cli::BulkAction::Edit { .. } => Self::Edit,
            crate::cli::BulkAction::Link { .. } => Self::Link,
            crate::cli::BulkAction::Unlink { .. } => Self::Unlink,
            crate::cli::BulkAction::Archive { .. } => Self::Archive,
        }
    }
}

/// The largest a batch selection may be.
///
/// A bound, and stated, because a TUI selection is built by **toggling cards** and
/// there is no "press enter to start" moment at which a user has said "all of these".
/// A board of 1200 issues would let a user mark 1200 of them with 1200 keystrokes
/// and then be asked to confirm a 1200-item write with a `y`.
///
/// So the selection is bounded, `toggle` **refuses** past the bound rather than
/// silently dropping, and the refusal says the bound. A bound the user cannot reach
/// is worse than no bound, so it is a refusal with a number in it — and the number is
/// this constant, not a literal at the call site.
pub const MAX_BATCH_SELECTION: usize = 200;

/// Why a selection operation was refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SelectionProblem {
    /// The bound above.
    TooLarge,
    /// The same issue twice.
    AlreadySelected,
}

impl SelectionProblem {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::TooLarge => "selection_full",
            Self::AlreadySelected => "already_selected",
        }
    }
}

impl std::fmt::Display for SelectionProblem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TooLarge => write!(
                f,
                "a batch selection holds at most {MAX_BATCH_SELECTION} issues — \
                 clear some first, or narrow the filter"
            ),
            Self::AlreadySelected => {
                write!(f, "that issue is already selected — press `x` to remove it")
            }
        }
    }
}

/// The multi-selection: an ordered, de-duplicated set of issue numbers.
///
/// **Order is the order the user marked them**, not the board's column order, and not
/// numeric order. A user marks what they can see, and a plan that reorders what they
/// marked is a plan they did not read.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BulkSelection {
    numbers: Vec<u32>,
}

impl BulkSelection {
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an issue, refusing a duplicate and refusing past the bound.
    ///
    /// Both refusals are `Err` rather than a silent `false`, because a silent `false`
    /// for "too many" is a keystroke that appeared to do nothing, and a user
    /// counting their selection has no way to know which press was dropped.
    pub fn toggle(&mut self, number: u32) -> std::result::Result<bool, SelectionProblem> {
        if self.numbers.contains(&number) {
            return Err(SelectionProblem::AlreadySelected);
        }
        if self.numbers.len() >= MAX_BATCH_SELECTION {
            return Err(SelectionProblem::TooLarge);
        }
        self.numbers.push(number);
        Ok(true)
    }

    /// Remove an issue, reporting whether it was there.
    ///
    /// `bool` rather than `Result`: removing something that is not selected is the
    /// *desired* end state, and a user pressing `x` twice means "not selected", not
    /// "something went wrong".
    pub fn remove(&mut self, number: u32) -> bool {
        let before = self.numbers.len();
        self.numbers.retain(|n| *n != number);
        self.numbers.len() != before
    }

    /// Remove everything.
    pub fn clear(&mut self) {
        self.numbers.clear();
    }

    pub fn contains(&self, number: u32) -> bool {
        self.numbers.contains(&number)
    }

    /// The numbers, in the order the user marked them.
    pub fn numbers(&self) -> &[u32] {
        &self.numbers
    }

    pub fn len(&self) -> usize {
        self.numbers.len()
    }

    pub fn is_empty(&self) -> bool {
        self.numbers.is_empty()
    }

    /// The one-line header a surface shows.
    ///
    /// The count **and** the bound, so a user who hit the ceiling can see where they
    /// are without counting the marks themselves.
    pub fn summary(&self) -> String {
        if self.numbers.is_empty() {
            return "no issues selected — press `space` on a card, `X` to clear".to_string();
        }
        let list: Vec<String> = self.numbers.iter().map(u32::to_string).collect();
        format!(
            "{} selected (#{}) of at most {MAX_BATCH_SELECTION}",
            self.numbers.len(),
            list.join(", ")
        )
    }

    /// The `Selection` a plan is built from, in the marked order.
    ///
    /// Takes the issues rather than a store, because the TUI already has them: it
    /// has read the board to draw the cards. Re-resolving through selectors would be
    /// a second selection path, and it would produce a *different* order.
    ///
    /// Issues whose number is not in `issues` are **dropped** rather than refused.
    /// The board may have been filtered between marking and previewing, and a
    /// preview that refuses because a card went out of view is a preview the user
    /// cannot get at all. The dropped number is reported in the note, so "3 of your
    /// 5 are still visible" is visible rather than inferred.
    pub fn to_selection(&self, issues: &[(u32, crate::model::Issue)]) -> (Selection, Vec<u32>) {
        let mut kept = Vec::new();
        let mut dropped = Vec::new();
        for number in &self.numbers {
            if issues.iter().any(|(n, _)| n == number) {
                kept.push(*number);
            } else {
                dropped.push(*number);
            }
        }
        let selection = Selection::from_issues(
            kept.iter().filter_map(|number| {
                issues
                    .iter()
                    .find(|(n, _)| n == number)
                    .map(|(_, issue)| issue.clone())
            }),
            bulk::SelectionSource::Explicit,
            bulk::SelectionScope::Active,
        );
        (selection, dropped)
    }
}

/// Where the modal is in its own cycle.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BulkState {
    /// Choosing issues.
    Selecting,
    /// A plan is built and shown. Cancelling here changes nothing — it never has.
    Preview(Box<BatchPlan>),
    /// The plan is shown and awaiting an explicit confirm. **Separate** from
    /// `Preview` so the modal can render a different affordance, and so "I saw it" and
    /// "I approved it" are two different states in the record rather than one.
    Confirming(Box<BatchPlan>),
    /// The batch ran. Per-item outcomes are in the report.
    Done(Box<ApplyReport>, String),
    /// The batch was refused before or during the apply.
    Refused(String),
    /// An action needs something the user has not given (a pair's target).
    NeedsInput(&'static str),
}

/// Which channel the keys belong to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BulkFocus {
    /// The key is a command (`p`, `y`, `a`, `x`, `X`, `c`).
    Row,
    /// The key is text for the row under the cursor.
    Edit,
}

/// The batch modal.
#[derive(Debug, Clone)]
pub struct BulkModal {
    pub action: BatchAction,
    /// The **CLI's** flag struct, not a locally built patch (see the module docs).
    pub flags: PatchFlags,
    /// The other end of a pair.
    pub target: Option<String>,
    /// The relationship kind, as the user will set it.
    pub kind: Option<String>,
    /// Which row the cursor is on.
    pub cursor: usize,
    pub focus: BulkFocus,
    /// The text being typed, while `focus` is [`BulkFocus::Edit`].
    ///
    /// A draft is **discarded** on `esc`, never committed. An earlier draft of this
    /// modal snapshotted the row on `begin_edit` and restored it on `esc`; the
    /// snapshot was dead — `commit_edit` is the only thing that writes a row, so the
    /// restore and a clear were indistinguishable from outside. The revert-and-red
    /// run is what proved it: a mutation replacing the restore with a clear left all
    /// 141 cases green.
    pub draft: String,
    pub selection: BulkSelection,
    pub state: BulkState,
    /// The last message, for the status bar.
    pub note: Option<String>,
    /// Whether the plan no longer matches the screen.
    ///
    /// Set on the first preview and on **any** change to the selection or the flags,
    /// so a confirm can never apply a plan the user has not looked at.
    pub plan_stale: bool,
}

impl BulkModal {
    /// A fresh modal for `action`.
    pub fn new(action: BatchAction) -> Self {
        Self {
            action,
            flags: PatchFlags::default(),
            target: None,
            kind: None,
            cursor: 0,
            focus: BulkFocus::Row,
            draft: String::new(),
            selection: BulkSelection::new(),
            state: BulkState::Selecting,
            note: None,
            plan_stale: true,
        }
    }

    /// The row names, in the order `tab` walks them.
    ///
    /// Depends on the action, and that is the point: an archive has **no** rows,
    /// because `ArchiveRequest::archive()` names no target status and inventing a
    /// field for one would be offering a restore that #190's C-003 does not allow.
    /// A pair has no field rows either — it has a target and a kind.
    pub fn row_names(&self) -> Vec<&'static str> {
        let mut names: Vec<&'static str> = if self.action.takes_fields() {
            PatchFlags::field_rows().to_vec()
        } else {
            Vec::new()
        };
        if self.action.is_pair() {
            names.push("target");
            names.push("kind");
        }
        names
    }

    /// The name of the row at `index`, for the render.
    pub fn row_name(&self, index: usize) -> &'static str {
        self.row_names()
            .into_iter()
            .nth(index)
            .unwrap_or("selection")
    }

    /// The value of the row at `index`.
    ///
    /// An absent value is the em dash, not an empty string, so a blank row is
    /// visibly blank rather than looking like a field set to `""`. The distinction is
    /// the whole WP06 finding: a blank `--estimate ""` is `Unchanged`.
    pub fn row_value(&self, index: usize) -> String {
        let flags = &self.flags;
        match self.row_name(index) {
            "status" => flags.status.clone(),
            "priority" => flags.priority.clone(),
            "assignee" => flags.assignee.clone(),
            "labels" => flags.labels.clone(),
            "start-date" => flags.start_date.clone(),
            "due-date" => flags.due_date.clone(),
            "estimate" => flags.estimate.clone(),
            "cycles" => flags.cycles.clone(),
            "milestones" => flags.milestones.clone(),
            "clear" => (!flags.clear.is_empty()).then(|| flags.clear.join(" ")),
            "target" => self.target.clone(),
            "kind" => self.kind.clone(),
            _ => None,
        }
        .unwrap_or_else(|| "—".to_string())
    }

    /// Store `value` on the row at `index`, or say why it cannot be stored.
    ///
    /// A blank value is stored as **absent** (`None`), which is what makes "the user
    /// cleared the field" and "the user never touched it" the same request — the
    /// contract's `Unchanged`. The `clear` row is the *explicit* way to empty
    /// something, and it is the only row that may name a field `clear` does not own.
    pub fn set_row(&mut self, index: usize, value: String) -> Result<()> {
        let value = value.trim().to_string();
        let name = self.row_name(index);
        let flags = &mut self.flags;
        let slot = match name {
            "status" => &mut flags.status,
            "priority" => &mut flags.priority,
            "assignee" => &mut flags.assignee,
            "labels" => &mut flags.labels,
            "start-date" => &mut flags.start_date,
            "due-date" => &mut flags.due_date,
            "estimate" => &mut flags.estimate,
            "cycles" => &mut flags.cycles,
            "milestones" => &mut flags.milestones,
            "clear" => {
                if value.is_empty() {
                    flags.clear.clear();
                    self.mark_stale();
                    return Ok(());
                }
                if !PatchFlags::is_clearable(&value) {
                    return Err(TixError::InvalidInput(format!(
                        "cannot clear '{value}' — clearable fields: {}",
                        PatchFlags::clearable().join(", ")
                    )));
                }
                // One `--clear` per invocation, exactly as the CLI carries it. A second
                // field is **refused**, not appended and not dropped — a `--clear a
                // --clear b` that silently honoured only `a` is a request half-met.
                if !flags.clear.is_empty() && !flags.clear.contains(&value) {
                    return Err(TixError::InvalidInput(format!(
                        "one batch clears one field — '{value}' is clearable, and '{}' is \
                         already named; clear them one run at a time",
                        flags.clear[0]
                    )));
                }
                flags.clear = vec![value];
                self.mark_stale();
                return Ok(());
            }
            "target" => {
                let slot = &mut self.target;
                *slot = (!value.is_empty()).then_some(value);
                self.mark_stale();
                return Ok(());
            }
            "kind" => {
                let slot = &mut self.kind;
                *slot = (!value.is_empty()).then_some(value);
                self.mark_stale();
                return Ok(());
            }
            _ => return Ok(()),
        };
        *slot = (!value.is_empty()).then_some(value);
        self.mark_stale();
        Ok(())
    }

    /// Mark that the plan no longer matches the screen.
    ///
    /// `contracts/patch-plan.md` §4: "Apply requires the exact confirmed plan … any
    /// change to selection or patch requires a new preview." So a confirm is refused
    /// while stale, and the refusal says *why* rather than silently re-previewing — a
    /// silent re-preview would apply something the user did not look at.
    pub fn mark_stale(&mut self) {
        self.plan_stale = true;
    }

    /// Begin editing the row under the cursor.
    pub fn begin_edit(&mut self) {
        let row = self.cursor;
        self.draft = self.row_value(row);
        // A row that was never set starts empty, not showing the em dash the user
        // would then have to delete before typing.
        if self.draft == "—" {
            self.draft.clear();
        }
        self.focus = BulkFocus::Edit;
    }

    /// Commit the draft, or report why it cannot be committed.
    pub fn commit_edit(&mut self) -> Result<()> {
        let row = self.cursor;
        let draft = std::mem::take(&mut self.draft);
        self.focus = BulkFocus::Row;
        self.set_row(row, draft)
    }

    /// Abandon the draft. The row keeps whatever it had.
    ///
    /// Discarding rather than committing is the point: an abandoned edit that still
    /// wrote the half-typed value is an abandoned edit that changed state. The draft
    /// is thrown away rather than left in place, because `begin_edit` rebuilds it
    /// from the row every time — so a leftover draft is a draft nothing can read.
    pub fn abort_edit(&mut self) {
        self.draft.clear();
        self.focus = BulkFocus::Row;
    }

    /// Move the cursor, wrapping. A no-op when the action has no rows (an archive).
    pub fn move_cursor(&mut self, delta: isize) {
        let count = self.row_names().len();
        if count == 0 {
            self.cursor = 0;
            return;
        }
        let len = count as isize;
        let next = (self.cursor as isize + delta).rem_euclid(len);
        self.cursor = next as usize;
    }

    /// The typed patch for a **field** action, or say why it cannot be built.
    ///
    /// Delegates to the CLI's own conversion, so a TUI field and a CLI flag mean the
    /// same thing — including the "a blank field is `Unchanged`, not `Clear`" rule
    /// WP06 found. A TUI that built its own patch would have its own blank rule.
    pub fn patch(&self) -> Result<IssuePatch> {
        self.flags.to_patch()
    }

    /// The typed patch for **this** action, or say why it cannot be built.
    ///
    /// One method, because the preview and the confirm both need it, and two
    /// `match self.action` blocks are two places for an action to be handled
    /// differently.
    pub fn patch_for(&self) -> Result<IssuePatch> {
        Ok(match self.action {
            BatchAction::Edit => self.patch()?,
            BatchAction::Link | BatchAction::Unlink => IssuePatch {
                relationship: Some(self.relationship_for(&[], None)?),
                ..IssuePatch::default()
            },
            BatchAction::Archive => IssuePatch {
                archive: Some(self.archive_request()),
                ..IssuePatch::default()
            },
        })
    }

    /// Build a plan for the current selection. Read-only by construction: it
    /// resolves, validates and renders a preview, and writes nothing.
    pub fn preview(&mut self, store: &Store, issues: &[(u32, crate::model::Issue)]) -> Result<()> {
        if self.selection.is_empty() {
            self.state = BulkState::NeedsInput("select at least one issue with `space`");
            return Ok(());
        }
        // A request the modal cannot turn into a plan is a **refusal**, not an `Err`.
        // WP06 froze that rule for the CLI — "a refusal is a completed command that
        // reports non-zero, its reasons go to stdout" — and the TUI is a surface of
        // the same command, so it gets the same rule. An `Err` out of `preview` would
        // leave the event loop with a `Result` to do something about, and the only
        // sensible thing it could do is quit: a user who pressed `p` with no field set
        // would lose their board.
        let patch = match self.patch_for() {
            Ok(patch) => patch,
            Err(e) => {
                self.state = BulkState::Refused(e.to_string());
                self.note = Some(e.to_string());
                return Ok(());
            }
        };
        let (selection, dropped) = self.selection.to_selection(issues);
        if selection.is_empty() {
            self.state = BulkState::NeedsInput("none of the selected issues are on the board");
            return Ok(());
        }
        let plan = match bulk::plan::build_plan(
            &store.config,
            &store.issues_dir,
            selection,
            patch,
            |op: &RelationshipOp| bulk::pair::plan_for(store, op),
        )
        .map(|mut plan| {
            // WP07 T035: the modal's preview shows the same WIP decisions the apply
            // will, from the **store's** issues (a column counts every card in it,
            // not only the selected ones).
            crate::wip::bulk::annotate_plan(
                &mut plan,
                &store.config,
                &store.list().unwrap_or_default(),
            );
            plan
        }) {
            Ok(plan) => plan,
            Err(e) => {
                self.state = BulkState::Refused(e.to_string());
                self.note = Some(e.to_string());
                return Ok(());
            }
        };
        self.note = (!dropped.is_empty()).then(|| {
            format!(
                "{} selected issue(s) are no longer on the board and were left out: #{}",
                dropped.len(),
                dropped
                    .iter()
                    .map(u32::to_string)
                    .collect::<Vec<_>>()
                    .join(", #")
            )
        });
        self.state = BulkState::Preview(Box::new(plan));
        self.plan_stale = false;
        Ok(())
    }

    /// The relationship operation for `numbers`, or the field the user has not filled
    /// in.
    ///
    /// A pair's `from` is **per selected issue**, not the whole selection: `from` is a
    /// single issue in the relationship vocabulary, and the batch is the set of
    /// edges. Passing the whole selection as `from` would build a plan for an edge
    /// that does not exist.
    pub fn relationship_for(
        &self,
        numbers: &[u32],
        kind_override: Option<String>,
    ) -> Result<RelationshipOp> {
        let target = self
            .target
            .as_deref()
            .map(str::trim)
            .filter(|t| !t.is_empty())
            .ok_or_else(|| {
                TixError::InvalidInput("a pair needs a target — edit the `target` row".to_string())
            })?;
        // The kind is the **service's** vocabulary, through its own parser, so a TUI
        // kind is a value `tix link --type` would accept.
        let kind = match kind_override {
            Some(raw) => crate::commands::link::require_kind(Some(raw.as_str()))?,
            None => crate::commands::link::require_kind(self.kind.as_deref())?,
        };
        // A preview of a whole selection has no single `from`; the caller pairs each
        // issue separately. An empty `numbers` means "the caller is previewing the
        // shape", and the pair's target and kind are all it needs.
        let from = numbers.first().map(u32::to_string).unwrap_or_default();
        Ok(if self.action == BatchAction::Unlink {
            RelationshipOp::unlink(from, target, kind)
        } else {
            RelationshipOp::link(from, target, kind)
        })
    }

    /// The archive request.
    ///
    /// The TUI's archive action is **archive only** — there is no restore verb on
    /// this modal, because a restore needs an explicit target status (#190's C-003)
    /// and there is no row for one. A modal that offered a restore with no target
    /// would be offering the request #190 rejects.
    pub fn archive_request(&self) -> ArchiveRequest {
        ArchiveRequest::archive()
    }

    /// Go from a shown plan to the confirming state.
    ///
    /// Two steps rather than one, because "I saw it" and "I approved it" are two
    /// different decisions and a single `y` conflates them. The confirming state
    /// renders a different affordance, so the user can see which one they are in.
    pub fn arm(&mut self) {
        if let BulkState::Preview(plan) = &self.state {
            self.state = BulkState::Confirming(plan.clone());
        }
    }

    /// Whether the modal is armed — the state in which `y` writes.
    pub fn is_armed(&self) -> bool {
        matches!(self.state, BulkState::Confirming(_))
    }

    /// Confirm the plan that is on screen and apply it.
    ///
    /// Refuses while the plan is **stale**, and the refusal says why. That is
    /// contract §4's "any change to selection or patch requires a new preview", and
    /// it is checked here rather than inside the apply so a TUI user gets a TUI
    /// message.
    pub fn confirm(&mut self, store: &Store) -> Result<()> {
        if self.plan_stale {
            return Err(TixError::InvalidInput(
                "the selection or the fields changed since the preview — press `p` \
                 again to see what would happen now"
                    .to_string(),
            ));
        }
        let (BulkState::Confirming(plan) | BulkState::Preview(plan)) = &self.state else {
            return Err(TixError::InvalidInput(
                "nothing to confirm — press `p` to preview first".to_string(),
            ));
        };
        let mut confirmed = (**plan).clone();
        confirmed.confirmation = Some(Confirmation::issue(plan));
        let text = match self.action {
            BatchAction::Edit => {
                let report =
                    bulk::apply_fields(store, &confirmed, &crate::storage::actor_identity(), None)?;
                let text = cli_bulk::render_report(&report, &confirmed, Mode::Apply);
                self.state = BulkState::Done(Box::new(report), text.clone());
                text
            }
            BatchAction::Link | BatchAction::Unlink => {
                let text = self.apply_pairs(store, &confirmed);
                self.state = BulkState::Refused(text.clone());
                text
            }
            BatchAction::Archive => {
                // The archive direction, through the **same** `apply_archive` the CLI
                // and MCP use: the store's archive service renames each selected file
                // in place and appends one History event, and the per-item outcomes are
                // the shared vocabulary. A stale-plan check already ran above, and the
                // confirmation is set for the same reason the edit branch sets it.
                //
                // The result is a `Done` report, exactly as an edit batch: the user
                // pressed `y` to apply, so the honest answer is what each issue became,
                // not a refusal screen.
                let report = bulk::apply_archive(store, &confirmed)?;
                let text = cli_bulk::render_report(&report, &confirmed, Mode::Apply);
                self.state = BulkState::Done(Box::new(report), text.clone());
                text
            }
        };
        self.note = text.lines().next().map(str::to_string);
        Ok(())
    }

    /// One plan and one apply per selected issue, for a pair.
    ///
    /// Per issue rather than one batched pair because `from` is a single issue in the
    /// relationship vocabulary. Each issue goes through the same `build_plan` +
    /// `apply_pair` the CLI uses, so a mixed result is a per-issue line and a
    /// refusal names the issue it refused.
    fn apply_pairs(&self, store: &Store, plan: &BatchPlan) -> String {
        let mut lines = Vec::new();
        let mut applied = 0usize;
        let mut refused = 0usize;
        for issue in plan.selection.issues() {
            let numbers = [issue.number];
            let outcome = match self.relationship_for(&numbers, None) {
                Ok(op) => {
                    let per_issue = bulk::plan::build_plan(
                        &store.config,
                        &store.issues_dir,
                        Selection::from_issues(
                            vec![issue.clone()],
                            bulk::SelectionSource::Explicit,
                            bulk::SelectionScope::Active,
                        ),
                        IssuePatch {
                            relationship: Some(op.clone()),
                            ..IssuePatch::default()
                        },
                        |o: &RelationshipOp| bulk::pair::plan_for(store, o),
                    );
                    match per_issue {
                        Ok(mut per_issue) => {
                            per_issue.confirmation = Some(Confirmation::issue(&per_issue));
                            match bulk::apply_pair(store, &per_issue) {
                                Ok(outcome) => {
                                    if outcome.is_applied() {
                                        applied += 1;
                                    } else {
                                        refused += 1;
                                    }
                                    outcome.as_line()
                                }
                                Err(e) => {
                                    refused += 1;
                                    format!("refused: {e}")
                                }
                            }
                        }
                        Err(e) => {
                            refused += 1;
                            format!("refused: {e}")
                        }
                    }
                }
                Err(e) => {
                    refused += 1;
                    format!("refused: {e}")
                }
            };
            lines.push(format!("#{} {} — {outcome}", issue.number, issue.title));
        }
        lines.push(String::new());
        lines.push(format!(
            "{applied} relationship operation{} applied, {refused} refused",
            if applied == 1 { "" } else { "s" }
        ));
        lines.join("\n")
    }

    /// Back to choosing, from any state.
    ///
    /// **`confirm` is the only method here that writes**, so cancelling from any other
    /// state cannot have changed a file. The confirm state keeps its plan so a
    /// mis-aimed `esc` does not throw away a preview the user wanted to look at
    /// again.
    pub fn cancel(&mut self) {
        self.state = BulkState::Selecting;
        self.focus = BulkFocus::Row;
        self.draft.clear();
        self.plan_stale = true;
    }

    /// The state, in the words a user reads.
    pub fn state_label(&self) -> &'static str {
        match self.state {
            BulkState::Selecting => "choosing",
            BulkState::Preview(_) => "preview — nothing written",
            BulkState::Confirming(_) => "confirming — y writes",
            BulkState::Done(..) => "done",
            BulkState::Refused(_) => "refused",
            BulkState::NeedsInput(_) => "needs input",
        }
    }

    /// The rows, as the modal shows them: a cursor, a name and a value.
    pub fn rows(&self) -> Vec<(bool, String, String)> {
        self.row_names()
            .into_iter()
            .enumerate()
            .map(|(index, name)| {
                let value = if self.focus == BulkFocus::Edit && index == self.cursor {
                    format!("{}█", self.draft)
                } else {
                    self.row_value(index)
                };
                (index == self.cursor, name.to_string(), value)
            })
            .collect()
    }

    /// The footer, naming the keys that mean something **right now**.
    ///
    /// The list is per-focus and per-state, because a footer that names `y` while `y`
    /// types a letter is a footer that teaches the wrong thing.
    pub fn footer(&self) -> String {
        if self.focus == BulkFocus::Edit {
            return "enter commit · esc revert".to_string();
        }
        match (&self.state, self.action) {
            (BulkState::Preview(_), _) => {
                "y to confirm · p to re-preview · esc to cancel".to_string()
            }
            (BulkState::Confirming(_), _) => "y APPLIES THIS WRITE · esc to cancel".to_string(),
            (_, BatchAction::Edit) => {
                "space mark · x unmark · X clear · c clear field · enter edit · a action · p preview · esc cancel"
                    .to_string()
            }
            _ => "enter edit · a action · p preview · esc cancel".to_string(),
        }
    }

    /// The text a surface shows for the current state, from the **CLI's** renderers.
    pub fn body(&self) -> String {
        match &self.state {
            BulkState::Selecting => {
                let mut out = self.selection.summary();
                let rows = self.rows();
                if rows.is_empty() {
                    out.push_str(&format!(
                        "\nno fields to fill in for {} — the selection is the whole request\n",
                        self.action.as_str()
                    ));
                } else {
                    out.push_str("\nfields (enter to edit):\n");
                    for (on, name, value) in rows {
                        let cursor = if on { ">" } else { " " };
                        out.push_str(&format!("{cursor} {name}: {value}\n"));
                    }
                }
                if let Some(note) = &self.note {
                    out.push_str(&format!("\nnote: {note}\n"));
                }
                out.push_str(&format!("\n{}", self.footer()));
                out
            }
            BulkState::Preview(plan) => {
                let mut out = cli_bulk::render_plan(plan, Mode::Preview);
                if let Some(note) = &self.note {
                    out.push_str(&format!("\nnote: {note}"));
                }
                out.push('\n');
                out.push_str(&self.footer());
                out
            }
            BulkState::Confirming(plan) => {
                let mut out = cli_bulk::render_plan(plan, Mode::Preview);
                out.push('\n');
                out.push_str(&self.footer());
                out
            }
            BulkState::Done(_, text) | BulkState::Refused(text) => text.clone(),
            BulkState::NeedsInput(what) => format!("{what}\n\n{}", self.footer()),
        }
    }
}

/// Render the modal. Never asserts on pixels — a test reads the buffer.
pub fn render(frame: &mut Frame, area: Rect, modal: &BulkModal) {
    let rect = crate::ui::modal::modal_rect(area);
    frame.render_widget(Clear, rect);
    let block = Block::default()
        .borders(Borders::ALL)
        .title(format!(" batch {} ", modal.action.as_str()))
        .border_style(Style::default().fg(ratatui::style::Color::Cyan));
    let inner = block.inner(rect);
    frame.render_widget(block, rect);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(3), Constraint::Min(1)])
        .split(inner);
    let header = format!("{}  [{}]", modal.selection.summary(), modal.state_label());
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(
            header,
            Style::default().add_modifier(Modifier::BOLD),
        ))),
        chunks[0],
    );
    frame.render_widget(
        Paragraph::new(modal.body()).block(Block::default().borders(Borders::TOP)),
        chunks[1],
    );
}

/// The issues a board shows, as `(number, Issue)`, in the order the cards are drawn.
///
/// A function over the board rather than a `store.list()`, because "visible" is the
/// whole point: with a filter applied, `store.list()` returns issues the user cannot
/// see, and marking those would produce a plan for cards that are not on screen.
pub fn visible_issues(
    board: &crate::ui::board::BoardState,
    store: &Store,
) -> Result<Vec<(u32, crate::model::Issue)>> {
    let mut out = Vec::new();
    let mut numbers = Vec::new();
    for index in 0..=board.columns.len() {
        for card in board.column_cards(index) {
            numbers.push(card.number);
        }
    }
    for issue in store.list()? {
        if numbers.contains(&issue.number) {
            out.push((issue.number, issue));
        }
    }
    // Board order, not store order: the plan reads in the order the cards do.
    Ok(numbers
        .into_iter()
        .filter_map(|number| {
            out.iter()
                .find(|(n, _)| *n == number)
                .map(|(n, issue)| (*n, issue.clone()))
        })
        .collect())
}

/// The selection as a list, for the board's own "N selected" popover.
pub fn selection_items(
    selection: &BulkSelection,
    issues: &[(u32, crate::model::Issue)],
) -> Vec<ListItem<'static>> {
    selection
        .numbers()
        .iter()
        .map(|number| {
            let title = issues
                .iter()
                .find(|(n, _)| n == number)
                .map(|(_, i)| i.title.clone())
                .unwrap_or_else(|| "(not on the board)".to_string());
            ListItem::new(format!("#{number} {title}"))
        })
        .collect()
}

/// Render the selection list, for a caller that wants it on screen.
pub fn render_selection_list(
    frame: &mut Frame,
    area: Rect,
    selection: &BulkSelection,
    issues: &[(u32, crate::model::Issue)],
) {
    let list = List::new(selection_items(selection, issues)).block(
        Block::default()
            .borders(Borders::ALL)
            .title(" batch selection "),
    );
    frame.render_widget(list, area);
}