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
use std::cell::{Cell, RefCell};
use std::collections::BTreeSet;
use std::io;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEvent, KeyEventKind,
    KeyModifiers, MouseButton, MouseEvent, MouseEventKind,
};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Position, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};

use crate::assignee::{git_identity, resolve_me};
use crate::commands::{self, mv};
use crate::config::{BoardConfiguration, Config};
use crate::error::{Result, TixError};
use crate::keybindings::{EffectiveBindings, InputContext, TuiAction};
use crate::model::{Issue, Priority, Status, today};
use crate::planning::Planner;
use crate::search::{self, Corpus, FilterField};
use crate::storage::{IssueSelector, Store};
use crate::templates::{TemplateInput, TemplateScope, TemplateSelection, resolve};

use crate::edit_problems::{self, EditFix, EditProblem};
use crate::editor;
use crate::ui::action_menu::{ActionGroup, ActionMenu, ActionMenuItem, IssueAction, MenuEvent};
use crate::ui::board::{self, BoardState, HitTarget};
use crate::ui::commandbar;
use crate::ui::date_picker::{DatePicker, DatePickerEvent, DatePickerHit};
use crate::ui::detail::{self, DetailState};
use crate::ui::dialog::{DialogEvent, RolloverDialog};
use crate::ui::form::{self, FormState, NewIssueTarget};
use crate::ui::nav::{NavDisplay, TopMode};
use crate::ui::pickers::{DropdownState, PickerEvent, PickerItem, PickerMode, SelectionModel};
use crate::ui::planning::{
    PlanningForm, PlanningKind, PlanningModal, PlanningPrompt, PlanningRow, PlanningSegment,
};
use crate::ui::settings::{
    ConfigLevel, ConfigSection, SettingsModal, SettingsPrompt, board_rows_len,
};
use crate::ui::tabs::BoardTabs;
use crate::ui::triage::{TriageControl, TriageDropdownKind};
use crate::ui::views::{ViewFeedback, ViewRow, ViewsModal, ViewsPrompt, scope_summary};
use crate::views::divergence::{ActiveViewMarker, ViewDivergence, ViewSurface};
use crate::views::plan::{ViewPlan, ViewVisibility};
use crate::views::registry::{ViewDiagnostic, ViewId, ViewScope, ViewWriteError};
use crate::views::service::{DeleteConfirmed, ViewDefinition, ViewService};
use crate::watcher::FsDelta;

mod bulk;
mod feedback;
mod mentions;
mod mode;
mod state;
mod triage;
pub use feedback::ActionFeedback;
pub use mode::Mode;
pub use state::{Action, LinkStep, MoveTarget};
use state::{
    CandidateAction, CapacityCache, Drag, HelpMetrics, HitRegion, MAX_DETAIL_NAV, MouseDown,
    MouseState, PendingEdit, PendingMove, ViewSession, WHEEL_ROWS,
};

// ---------------------------------------------------------------------------
// WP05: the F7 Stats page's Time tab, and the time-entry form
// ---------------------------------------------------------------------------

/// Append `current` to a picker's options when it is non-empty and not already
/// listed, so a criterion that is already set stays selectable even when nothing
/// currently produces its value.
fn push_current_option(options: &mut Vec<PickerItem>, current: &str) {
    if current.is_empty() || options.iter().any(|option| option.id == current) {
        return;
    }
    options.push(PickerItem {
        id: current.to_string(),
        label: current.to_string(),
    });
}

/// The shared resolver input for the TUI's create form (WP05/T025).
///
/// Every row the form has maps one-for-one onto the resolver's documented create
/// fields, so a template can only ever pre-fill the normal create model. A
/// **blank** row maps to `None` — "not provided" — rather than `Some("")`, so an
/// omitted value does not override a template default; this is the same meaning
/// `tix create` gives a flag that was left off, which is what keeps the two
/// surfaces equivalent. The rows the form does not have (`files`,
/// `related_issues`, `type`) are `None` here and are filled from the template's
/// defaults by the resolver, so no template field is silently dropped.
fn template_input_from_form(form: &FormState) -> TemplateInput {
    fn present(value: &str) -> Option<String> {
        (!value.trim().is_empty()).then(|| value.to_string())
    }
    TemplateInput {
        title: present(&form.title),
        // The body is content, not a whitespace-trimmed flag: only a truly empty
        // body is "not provided", so a Markdown body's blank lines survive.
        body: (!form.body.is_empty()).then(|| form.body.clone()),
        status: present(&form.status),
        priority: present(&form.priority),
        assignee: present(&form.assignee),
        labels: present(&form.labels),
        files: None,
        estimate: present(&form.estimate),
        cycles: present(&form.cycles),
        milestones: present(&form.milestones),
        reviewer: present(&form.reviewer),
        start_date: present(&form.start_date),
        due_date: present(&form.due_date),
        parent: present(&form.parent),
        related_issues: None,
        type_: None,
    }
}

/// Independent toggles are what a TUI session's state *is* — the mode lives in `Mode`,
/// and the flags beside it (archived shown, help line open, one-shot exit) are not
/// states a machine would model, they are switches the user throws. Four is not a
/// design smell here; a struct with a mode enum and a handful of toggles is the shape.
#[allow(clippy::struct_excessive_bools)]
pub struct App {
    pub mode: Mode,
    /// The active top-level mode of the shell (tui-mode-navigation). Session-only:
    /// it is derived from the current [`Mode`] by [`App::sync_top_mode`] and never
    /// persisted.
    pub top_mode: TopMode,
    /// How the vertical mode navigation is displayed (`Off`/`Small`/`Default`).
    /// Session-only, cycled by `toggle_navigation`; never persisted.
    pub nav_display: NavDisplay,
    /// Which rail row owns the keyboard, as an index into [`App::nav_rows`]
    /// (trunks and their limbs in draw order); `None` means the mode's content
    /// owns it. Session-only. Entered with `h`/`Left` when the active mode has
    /// no leftward target, left with `l`/`Right`/`Esc` (see
    /// [`App::handle_nav_key`]).
    nav_focus: Option<usize>,
    /// Whether the Config surface is currently standing in for the F5
    /// **Milestones** mode. The Milestones mode reuses the Config surface pinned
    /// to [`ConfigSection::Milestones`] rather than growing a second view; this
    /// flag is what makes the rail highlight Milestones (not Config), gives the
    /// mode its own [`InputContext::Milestones`] keys, and hides the Config
    /// section rail. Session-only, never persisted.
    pub milestone_mode: bool,
    pub board: BoardState,
    /// Resolved tag/type/milestone colors for this session (tix #1530). Built
    /// once at startup from the tag store and the config; the board and detail
    /// renderers read it.
    pub theme: crate::ui::color::Theme,
    pub detail: Option<DetailState>,
    pub form: Option<FormState>,
    pub confirm_delete_target: Option<String>,
    pub store: Store,
    pub status_msg: Option<String>,
    /// The last advertised action this mode refused, with the remedy that would
    /// make it possible. Cleared when the next key is accepted, so a refusal is
    /// visible on the frame that produced it and never leaks into a later mode.
    pub action_feedback: Option<ActionFeedback>,
    pub quit: bool,
    pub bindings: EffectiveBindings,
    /// The raw bytes of `tix.toml` as last read, so a hand-edit during the
    /// session is adopted instead of linted against a stale configuration.
    config_snapshot: Option<Vec<u8>>,
    /// The active named board configuration index into `Config::configs()`
    /// (session state only — never persisted). `rebuild_board`/`apply_filter`
    /// must not reset it.
    pub active_config: usize,
    /// Persistent tabs bar of all named boards (DM-01M2MH8J01DZHV3JMT76XX38KX).
    pub tabs: BoardTabs,
    filter: Option<String>,
    corpus: Corpus,
    /// A second corpus snapshot that **includes archived** issues, built
    /// lazily the first time a `/` search runs and reused keystroke to
    /// keystroke (tix #1498).
    ///
    /// `corpus` above is the active set, built from [`crate::storage::Store::list`]
    /// so a repository full of archived files opens cheaply (tix #1492). Search
    /// must still find an archived issue — the whole point of "always search
    /// archived" — so it reads this snapshot instead, and only once a query is
    /// non-empty. [`App::refresh_corpus`] drops it, so the next search rebuilds
    /// it from whatever is on disk now. `None` also means "not yet built"; a
    /// build error leaves it `None` and the caller falls back to `corpus`, so a
    /// transient read failure degrades to an archived-blind search rather than
    /// no search at all.
    search_corpus: Option<Corpus>,
    /// Whether the board is showing **archived** issues too (tix #1492).
    ///
    /// Off by default, and that default is the point: the board and the corpus are
    /// built from [`crate::storage::Store::list`], which drops a dot-prefixed file
    /// from the directory entry without opening it, so a repository with thousands of
    /// archived issues costs nothing to open. Toggling this on is the "reload them on
    /// demand" half — `refresh_corpus` re-reads the issue set with the archived files
    /// included and rebuilds the board around it.
    pub show_archived: bool,
    /// Whether the board draws each issue's sub-issues beneath it (tix #1399).
    ///
    /// **On** by default. Session-only, like [`App::show_archived`] — it is a view
    /// preference, not a setting written back to `tix.toml`. The `u` toggle flips it
    /// and rebuilds the board, which reorders each column so a sub-issue follows its
    /// parent offset one ASCII column (see `BoardState::build_with`); no store
    /// re-read is needed because the children are already in the issue set.
    pub show_children: bool,
    /// How many rows the keybindings overlay is scrolled down (tix #1441).
    ///
    /// Reset when the overlay opens, so `?` always starts at the top: a help screen
    /// that reappears halfway down, from a scroll three sessions ago, would hide the
    /// first bindings from exactly the person who needed them.
    help_scroll: u16,
    /// The keybindings overlay's `/` query, and whether the input line has the
    /// keyboard (tix #1496).
    ///
    /// Cleared when the overlay opens, like the scroll offset and for the same reason:
    /// a help screen that reappeared filtered by a query from ten minutes ago would
    /// hide the binding the reader opened it to find.
    help_query: String,
    help_searching: bool,
    /// The overlay's last-rendered geometry, recorded by its own draw (tix #1441).
    ///
    /// A `Cell` for the same reason `frame_hit_regions` is a `RefCell`: the renderer
    /// takes `&App`, and it is the only thing that knows how many rows fit.
    help_metrics: std::cell::Cell<HelpMetrics>,
    /// Cards one screen of the active board column holds, as of the last draw
    /// (tix #1442 follow-up).
    ///
    /// Reported by the board renderer, which is the only thing that knows the column's
    /// height and each card's rendered height; a `Cell` for the same reason
    /// `help_metrics` is one — the renderer holds `&App`.
    board_page: std::cell::Cell<usize>,
    pub filter_modal: Option<crate::ui::filter_modal::FilterModal>,
    /// Config mode state (F12, `s`, `b`): the active section and the dashboards
    /// row cursor. `Some` exactly while [`Mode::Settings`] (and its planning
    /// sub-forms) is active.
    pub settings: Option<SettingsModal>,
    /// Planning cursor: the `m` management surface's list state, and the same
    /// cursor the Config mode's cycles/milestones sections drive (one state, not
    /// two).
    pub planning: Option<PlanningModal>,
    /// Create/edit form for a planning item.
    pub planning_form: Option<PlanningForm>,
    /// Open calendar date picker (overlaid on the form that opened it).
    pub date_picker: Option<DatePicker>,
    /// Committed structured filter (kept when the modal is closed). The live
    /// in-progress criteria come from `filter_modal` while it is open.
    structured: search::StructuredFilter,
    rollover_dialog: Option<RolloverDialog>,
    form_picker: Option<FormPicker>,
    /// The filter modal's open value picker, `Some` exactly while a criterion's
    /// list overlays the modal. Cleared whenever the modal closes.
    filter_picker: Option<FilterPicker>,
    /// One-shot render (`tix render`): suppresses the keyboard hint bar.
    one_shot: bool,
    /// Click targets recorded by widgets during the current draw; cleared at
    /// the start of every draw and resolved by [`App::resolve_region`] when a
    /// pointer event arrives (D3). `RefCell` lets the &-borrowing render pass
    /// record regions while `handle_mouse` resolves them later (D6).
    frame_hit_regions: RefCell<Vec<HitRegion>>,
    /// Mouse click/drag state (D4).
    mouse: MouseState,
    /// The issue action menu: `Some` exactly while `mode` is
    /// [`Mode::ActionMenu`].
    pub action_menu: Option<ActionMenu>,
    /// The move waiting on one of its prompts; the answers survive every
    /// re-entry so no prompt discards another's.
    pending_move: Option<PendingMove>,
    /// Where a time form opened from the action menu returns: the board, not the
    /// Stats page that owns the form's usual entry point.
    time_return: Option<Mode>,
    /// The batch modal (WP07), `Some` exactly while `mode` is
    /// [`Mode::BulkModal`].
    pub bulk: Option<crate::ui::bulk::BulkModal>,
    /// The marked set a content action (comment, health, parent) covers, or
    /// `None` when the action is about the detail pane's single issue. Set when
    /// the action menu opens on a card that is part of a multi-selection, and
    /// cleared when the prompt submits or cancels.
    pub bulk_action_targets: Option<Vec<u32>>,
    /// The saved-views modal (WP05), `Some` exactly while `mode` is
    /// [`Mode::Views`]. Its rows mirror the registry; its cursor, prompt, and
    /// feedback are its own.
    pub views: Option<ViewsModal>,
    /// The saved view the live board is associated with, session-only. `None`
    /// means "no active view" — which the divergence report distinguishes from
    /// "the active view was deleted" (C-006/data-model §5).
    view_session: Option<ViewSession>,
    /// The triage inbox (WP06), `Some` exactly while `mode` is
    /// [`Mode::TriageInbox`]. Its cursor and selection are its own — see the
    /// note on that mode.
    pub triage: Option<crate::ui::triage::TriageState>,
    /// The F3 Cycle mode's cursor (tui-cycle-mode), `Some` exactly while `mode`
    /// is [`Mode::Cycle`]. Its selection is its own, like the triage inbox's.
    pub cycle_state: Option<crate::ui::cycle::CycleState>,
    /// The F6 Repos mode's row cursor (tix #1529). Session-only; reset when the
    /// mode is entered.
    pub repos_cursor: usize,
    /// The due-warning overlay (WP07), `Some` exactly while `mode` is
    /// [`Mode::RecurringWarning`].
    pub recurring_warning: Option<crate::ui::recurring_warning::RecurringWarning>,
    /// The per-issue mention notice, `Some` exactly while it is open.
    pub mentions: Option<crate::ui::mentions::MentionsView>,
    /// The all-issues mentions view, `Some` exactly while it is open.
    pub mentions_view: Option<crate::ui::mentions::MentionsView>,
    /// How many unread mentions the local user holds — the indicator row's figure.
    ///
    /// Cached because counting reads the mention store, and a render pass must not
    /// touch the disk. Recomputed by [`App::refresh_mentions`], which runs at
    /// startup, on every refresh, and after every mention action, so the indicator
    /// cannot disagree with the rows a notice is showing.
    pub unread_mentions: usize,
    /// The mention bodies that address the local user, from git (design D6), cached
    /// beside [`App::unread_mentions`] so the two are always the same snapshot.
    pub mention_candidates: Vec<String>,
    /// The board's WIP state, derived once per refresh (WP05 T025). Empty for a
    /// board with no limits, and rebuilt from the corpus rather than re-read: the
    /// figures a header shows are the ones the policy judged the move against.
    pub wip: crate::wip::WipSnapshot,
    /// The override prompt (WP05 T026), `Some` exactly while `mode` is
    /// [`Mode::WipOverride`].
    pub wip_override: Option<crate::ui::wip_override::WipOverridePrompt>,

    /// The health form being filled in, when one is open.
    pub health_form: Option<HealthForm>,
    /// The `F7` Stats page's active tab (WP05 T026). A tab on a page that already
    /// ships — not a mode — exactly as `crate::ui::roadmap` documents for the `F10`
    /// Portfolio page.
    pub stats_tab: StatsTab,
    /// The Time tab's one read and its session state, `Some` exactly while the tab has
    /// been opened. Rebuilt on entering the tab and after every mutation, so a render
    /// never reads the disk.
    pub stats_time: Option<StatsTimeState>,
    /// The Burndown tab's selections and its one read (WP06 T029–T032), `Some` exactly
    /// while the tab has been opened.
    ///
    /// The document inside it is the shared [`crate::analytics::chart::ChartExport`] the
    /// CLI's verbs read, rebuilt when the tab is opened and after every control — never
    /// during a render, and never from a second fold of its own.
    pub stats_burndown: Option<crate::ui::analytics::BurndownState>,
    /// The time-entry form being filled in, when one is open.
    pub time_form: Option<TimeForm>,
    /// The Time tab's filter editor, when it is open.
    pub time_filter_form: Option<TimeFilterForm>,
    /// The `F7` Stats page's row cursor.
    pub stats_cursor: usize,
    /// The health document for the whole repository (mission
    /// `project-issue-health-status-01M3C8HX`, WP06): the same DTO the CLI renders,
    /// so the card badge, the detail block and the `F7` page cannot describe a
    /// different snapshot from `tix health` (C-007).
    ///
    /// Refreshed wherever the board is rebuilt, and never computed per keystroke: the
    /// document is one pass over the issues, and a render must not read the disk.
    pub health: Option<crate::health::PortableHealth>,
    /// The override the user authorized, while a move is still in flight.
    ///
    /// A confirmed override does not always finish the move: a move into a
    /// completion column still has to ask for a commit hash, and that prompt is a
    /// **separate** writer. Holding the request here is what keeps the two from
    /// drifting — the second writer finds the same authorization rather than a
    /// second evaluation that could disagree with the first.
    pending_wip_override: Option<crate::wip::OverrideRequest>,
    /// The F8 Schedule page's state: the active tab, its cursor and any reason
    /// prompt (tix #1593/#181), `Some` exactly while `mode` is [`Mode::Schedule`].
    pub schedule: Option<crate::ui::schedule::ScheduleState>,
    /// The last read-only cycle-schedule evaluation (WP07 T035), replaced by the
    /// startup pass and by every refresh.
    ///
    /// A **value**, not a writer: [`crate::cycle_schedule::evaluate::evaluate`] is
    /// pure, and the refresh only reads the records and the schedule registry to
    /// build the index. Nothing here closes, generates, or advances a cursor — the
    /// mutation paths are the confirmed requests in
    /// [`App::begin_cycle_schedule_action`]/[`App::generate_selected_cycle_schedule`].
    cycle_schedule_warnings: Option<crate::cycle_schedule::evaluate::CycleEvaluation>,
    /// The capacity read and the display data derived from it (WP06).
    ///
    /// `None` when the project's schedule index could not be read at the last refresh;
    /// the Capacity tab then says so rather than claiming nothing is configured.
    capacity: Option<CapacityCache>,
    /// The F11 Library page's state (tix #1593), `Some` exactly while `mode` is
    /// [`Mode::Library`]: the active tab and its row cursor. Session-only, reset
    /// when the mode is entered.
    pub library: Option<crate::ui::library::LibraryState>,
    /// The F10 Portfolio page's state (WP06), `Some` exactly while `mode` is
    /// [`Mode::Portfolio`]: the active tab and its row cursor. Session-only, reset
    /// when the mode is entered.
    pub portfolio: Option<crate::ui::portfolio::PortfolioState>,
    /// The Portfolio page's project list, cached at mode entry and after every key
    /// (WP06).
    ///
    /// The CLI the page mirrors (`tix project list` / `tix project show`) reads
    /// `store.list_all()`, **archived issues included**, so the page must read the
    /// same set or its member counts would differ from the CLI's and would change
    /// when the board's archive toggle moved. Reading that set per frame is the cost
    /// this cache exists to avoid (the corpus excludes archived issues, so it is not
    /// a substitute); it is dropped with the page's other state when the mode is
    /// left.
    portfolio_projects: Option<Vec<crate::projects::Project>>,
    /// The Portfolio page's typed project health, cached beside the list (WP09).
    ///
    /// The page must render "exactly the data the CLI exposes", so the detail pane
    /// shows the same progress and health figures `tix project show` prints. Those
    /// figures are the service's typed value ([`crate::projects::ProjectHealthReport`]),
    /// read once per refresh from the shared `project_reports` path rather than
    /// recomputed per frame (C-006); `None` (page not open, or no reports) makes the
    /// page render the record alone.
    portfolio_reports: Option<
        std::collections::BTreeMap<crate::config::ProjectId, crate::projects::ProjectHealthReport>,
    >,
    /// The Portfolio page's **Epics** tab rows, cached beside the project list (WP06
    /// T032).
    ///
    /// Read through [`crate::commands::view::epic_view`] — the same service path the
    /// epic view and `tix show` use — over the same `store.list_all()` snapshot as
    /// the project list, so the tab's rows and its detail are the values the CLI
    /// exposes and no surface derives a second one (C-008). Dropped with the page's
    /// other state when the mode is left.
    portfolio_epics: Option<Vec<crate::commands::view::EpicViewEntry>>,
    /// The Portfolio page's **Roadmap** tab projection (WP05), cached beside the
    /// page's other reads.
    ///
    /// The shared [`crate::roadmap::RoadmapProjection`] the CLI's `tix roadmap list`
    /// renders — the same join, predicate and sort — so the tab and the CLI cannot
    /// disagree about a row, a summary value or a diagnostic (C-004, C-007). Rebuilt
    /// per refresh from the snapshot [`Self::refresh_portfolio_projects`] already
    /// read; dropped with the page's other state when the mode is left.
    portfolio_roadmap: Option<crate::roadmap::RoadmapProjection>,
    /// The Roadmap tab's normalized filter (WP05), the **one** DTO the CLI builds
    /// too. Session-only: reset when the page is entered, and never persisted.
    pub roadmap_filter: crate::roadmap::RoadmapFilter,
    /// The Roadmap tab's open overlay (WP05): the filter editor or an initiative
    /// action, `Some` exactly while one is open. Cleared with the page's other state
    /// and on a tab change, so its text never leaks onto another tab.
    pub portfolio_roadmap_overlay: Option<crate::ui::roadmap::RoadmapOverlay>,
    /// The mode the planning-management modal returns to when it closes: the
    /// board when opened with `m` there, the F3 Cycle mode when opened from it
    /// (tui-cycle-mode / planning-management). Session-only.
    planning_return: Mode,
    /// Column currently shown as the drag-drop target while a card is held.
    drag_preview_col: Option<usize>,
    /// The action of the innermost hit region under the pointer as of the last
    /// `Moved` event, so any widget can style itself when hovered (the vertical
    /// mode navigation in every mode, the Config section rail, dropdown rows).
    /// `None` when the pointer is not over a recorded region.
    hover_action: Option<Action>,
    /// The terminal size of the most recent draw, remembered so pointer
    /// coordinates can be mapped onto the board render area (D3).
    frame_size: Cell<Rect>,
    /// The editor round trip currently in flight, if any (tix #1510). `Some` only
    /// between the snapshot taken before the editor is launched and the decision
    /// [`App::after_editor`] makes when it exits, so it is also the signal that a
    /// pre-edit snapshot exists to compare against.
    pending_edit: Option<PendingEdit>,
    /// The detail pane's back stack, bounded (tix #1513).
    ///
    /// A pane is pushed when the reader opens a **related** entry from an open
    /// pane, so `Backspace` can return to where the jump started. Snapshotting the
    /// whole [`DetailState`] rather than a filename is what keeps the stack honest
    /// for a `Path` entry: the previous pane may itself have been an external,
    /// read-only file with no store entry to re-open.
    ///
    /// Bounded because following links is unbounded by nature — a chain of
    /// cross-repo references can be arbitrarily long, and a session that walks a
    /// thousand of them must not grow the stack without limit. The **oldest** entry
    /// is dropped, so the back key always walks back toward what the reader saw
    /// most recently.
    nav_stack: Vec<DetailState>,
    /// The open related-issues picker, `Some` exactly while it overlays the detail
    /// pane (tix #1513). `input_context` reports [`InputContext::RelatedPicker`]
    /// while it is `Some`, exactly as `form_picker` does for the form.
    related_picker: Option<DropdownState>,
    /// The startup tips modal (tix #1632), `Some` exactly while `mode` is
    /// [`Mode::Tips`]. Its index is into the embedded [`crate::tips::all`] slice.
    pub tips: Option<crate::ui::tips::TipsState>,
}

impl App {
    /// Record a disclosure raised by a write, alongside whatever confirmation the
    /// action already produced.
    ///
    /// Cycle-4 F4. The event loop drains at the *top* of the loop body, so a
    /// disclosure raised by `handle_key` at the bottom would overwrite that
    /// action's confirmation message before any frame ever drew it — the user
    /// moved an issue and never saw "Moved #1 to in progress". Composing is the
    /// fix: both facts are true, and both are worth showing.
    ///
    /// The disclosure is appended rather than prepended so the confirmation reads
    /// first, which is the order the user caused them in. The existing message
    /// is left untouched, so this cannot swallow anything either.
    pub fn note_disclosure(&mut self, disclosure: String) {
        // Disclosure first, then the confirmation. Order alone does **not** make
        // it fit: the status area is a single unwrapped row, so at 80 columns a
        // disclosure plus a long filename is cut regardless of order. Cycle 6
        // measured this and found the claim previously recorded here — that
        // reordering made the actionable tail survive — to be false at 80, 100
        // and 120 columns.
        //
        // What actually helps is that the disclosure now *leads with the action*
        // ("remove `links:` by hand to silence"), so the instruction is the part
        // that survives a long filename, plus an ellipsis at the render site so a
        // cut is visible rather than silent. The full text remains in
        // `tix lint`, which is the durable channel for it.
        self.status_msg = Some(match self.status_msg.take() {
            Some(existing) if !existing.is_empty() => format!("{disclosure} — {existing}"),
            _ => disclosure,
        });
    }

    #[allow(clippy::too_many_lines)]
    pub fn new(config: &Config) -> Result<Self> {
        let mut store = Store::open(config)?;
        // A session started from the Repos mode inherits the parent's project
        // root in `TIX_PARENT_REPO` (tix #1529). Adopt it when no explicit
        // `parent_repo` is configured, so the way back exists even in a child
        // that never declared one.
        let started_from_parent = std::env::var_os("TIX_PARENT_REPO").is_some();
        if store.config.parent_repo.is_none() {
            if let Some(parent) = std::env::var_os("TIX_PARENT_REPO") {
                store.config.parent_repo = Some(PathBuf::from(parent));
            }
        }
        // The bytes `tix.toml` had at startup, so a hand-edit made while the TUI
        // is open can be noticed and adopted (see `reload_config_if_changed`).
        let config_snapshot = store
            .config_path()
            .ok()
            .and_then(|path| std::fs::read(path).ok());
        // Resolve the color theme once (tix #1530): tag colors from the tag
        // store, type colors from the config, milestone colors from their files.
        let theme = theme_for(&store.config);
        let tabs = BoardTabs::new(config.configs().map(|(name, _)| name.to_string()).collect());
        // One enumeration for the whole startup (tix #1518). Before this, the
        // board, the corpus and the rollover plan each walked the tree — the
        // board and corpus once each, the rollover plan once per expired cycle
        // — so a cold start read and parsed every issue file three or four
        // times over. All three now build from this single slice.
        let issues = store.list()?;
        let board_config = config.default_config();
        let keybindings_root =
            Config::project_root(&store.issues_dir).unwrap_or_else(|| PathBuf::from("."));
        let bindings = crate::keybindings::KeyBindings::load_effective(&keybindings_root)?;
        let resolution = BoardState::resolution_for(&store, board_config);
        // Sub-issues are nested beneath their parents by default (tix #1399); the
        // `u` toggle flips `show_children` and rebuilds from the same corpus.
        let board =
            BoardState::build_from_issues(&issues, board_config, &store.config, &resolution, true);
        let planner = Planner::from_config(config.clone(), std::path::PathBuf::from("."));
        let rollover_plan = planner.rollover_plan_from(&issues, &today());
        let corpus = Corpus::from_issues(issues);
        // The snapshot is derived from the corpus the board is about to be built
        // from, so a first frame shows the same figures a refresh would (WP05 T025).
        let wip = crate::wip::WipSnapshot::build(config.default_config(), &corpus.issues);
        let rollover_dialog = if rollover_plan.is_empty() {
            None
        } else {
            Some(RolloverDialog::new(
                rollover_plan
                    .into_iter()
                    .map(|p| (p.from_cycle, p.to_cycle, p.issues.len()))
                    .collect(),
            ))
        };
        let mut app = App {
            mode: if rollover_dialog.is_some() {
                Mode::RolloverDialog
            } else {
                Mode::Board
            },
            top_mode: TopMode::default(),
            nav_display: NavDisplay::default(),
            nav_focus: None,
            milestone_mode: false,
            board,
            theme,
            // The default board is the active set; archived issues are read only
            // when the toggle asks for them (tix #1492).
            show_archived: false,
            show_children: true,
            help_scroll: 0,
            help_query: String::new(),
            help_searching: false,
            help_metrics: std::cell::Cell::new(HelpMetrics::default()),
            board_page: std::cell::Cell::new(0),
            detail: None,
            form: None,
            confirm_delete_target: None,
            store,
            // A session spawned from a parent repository says so once, so the
            // user knows F6 goes back (tix #1529).
            status_msg: started_from_parent
                .then(|| "Started from a parent repository — F6 Repos to return".to_string()),
            action_feedback: None,
            quit: false,
            bindings,
            config_snapshot,
            active_config: 0,
            tabs,
            filter: None,
            corpus,
            search_corpus: None,
            filter_modal: None,
            settings: None,
            planning: None,
            planning_form: None,
            date_picker: None,
            structured: search::StructuredFilter::default(),
            rollover_dialog,
            form_picker: None,
            filter_picker: None,
            one_shot: false,
            frame_hit_regions: RefCell::new(Vec::new()),
            mouse: MouseState::default(),
            hover_action: None,
            action_menu: None,
            pending_move: None,
            time_return: None,
            bulk: None,
            bulk_action_targets: None,
            views: None,
            view_session: None,
            triage: None,
            cycle_state: None,
            repos_cursor: 0,
            recurring_warning: None,
            mentions: None,
            mentions_view: None,
            unread_mentions: 0,
            mention_candidates: Vec::new(),
            // The corpus is built just above, and the snapshot is derived from it:
            // a board's first frame shows the same figures a refresh would.
            wip,
            wip_override: None,
            // Read once at startup, so the first detail pane opened has health to
            // show rather than an empty block until the next board rebuild.
            health: crate::commands::export::run_health_core(config).ok(),
            health_form: None,
            stats_tab: StatsTab::default(),
            stats_time: None,
            stats_burndown: None,
            time_form: None,
            time_filter_form: None,
            stats_cursor: 0,
            pending_wip_override: None,
            schedule: None,
            cycle_schedule_warnings: None,
            capacity: None,
            library: None,
            portfolio: None,
            portfolio_projects: None,
            portfolio_reports: None,
            portfolio_epics: None,
            portfolio_roadmap: None,
            roadmap_filter: crate::roadmap::RoadmapFilter::default(),
            portfolio_roadmap_overlay: None,
            planning_return: Mode::Board,
            drag_preview_col: None,
            frame_size: Cell::new(Rect::new(0, 0, 0, 0)),
            pending_edit: None,
            nav_stack: Vec::new(),
            related_picker: None,
            tips: None,
        };
        // Detection on **start** (WP07 T033): the same read-only pass a refresh
        // runs, so the first frame after launch already knows what is due.
        app.refresh_recurring_warnings(false);
        // The mention count, read once at startup so the indicator row is right on
        // the first frame rather than after an `r`. Read-only.
        app.refresh_mentions();
        // Unread mentions put the all-issues modal up first, so what needs attention
        // is seen before the board. Like the recurring warning, it only raises from
        // the board — a rollover prompt or a due warning keeps its place.
        if app.unread_mentions > 0 && matches!(app.mode, Mode::Board) {
            app.open_mentions();
        }
        // The cycle-schedule twin of the pass above (WP07 T035): the same read-only
        // evaluation a refresh runs, so the Cycle schedules tab's warnings are there
        // on the first frame rather than after an `r`.
        app.refresh_cycle_schedule_warnings();
        // The capacity read (WP06): one pass over the shared pair, so the Capacity tab,
        // the board's cycle group headers and every detail pane opened afterwards read
        // the same reading rather than each building another.
        app.refresh_capacity_view();
        Ok(app)
    }

    /// The active `BoardConfiguration` indexed by [`App::active_config`].
    fn active_board_config(&self) -> &BoardConfiguration {
        self.store
            .config
            .configs()
            .nth(self.active_config)
            .map(|(_, board)| board)
            .unwrap_or_else(|| self.store.config.default_config())
    }

    // The pointer handlers below are filled in by their mouse tasks
    // (dialog click targets 5.x); until then they are honest stubs that
    // return a no-op so the dispatch trunk stays live.

    // -- mentions (OpenSpec change `issue-mentions`) -------------------------

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

    fn reload_config_from(&mut self, root: &std::path::Path) -> Result<()> {
        let cfg = Config::load_with_warning(&root.join("tix.toml"), |_| {})?;
        self.bindings = crate::keybindings::KeyBindings::load_effective(root)?;
        self.store.config = cfg;
        Ok(())
    }

    /// Re-read `tix.toml` **when it changed on disk**, so a hand-edit made while
    /// the session is open is honoured without a restart.
    ///
    /// Called before linting an editor round trip, because the lint's job is to
    /// report the project's *current* rules: warning `unknown_key` for a key the
    /// user has just declared in `[custom_attributes]` is a false positive, and a
    /// false positive is what teaches someone to ignore the warning. It also
    /// prevents the declare-fix from rewriting `tix.toml` from a stale in-memory
    /// copy.
    ///
    /// A `tix.toml` that does not load is reported and the previous configuration
    /// is kept, and the snapshot is **not** advanced — a half-saved file is
    /// retried on the next call rather than latched.
    fn reload_config_if_changed(&mut self) -> bool {
        let Ok(path) = self.store.config_path() else {
            return false;
        };
        let Ok(bytes) = std::fs::read(&path) else {
            return false;
        };
        if self.config_snapshot.as_deref() == Some(bytes.as_slice()) {
            return false;
        }
        let root = path
            .parent()
            .map(std::path::Path::to_path_buf)
            .unwrap_or_else(|| std::path::PathBuf::from("."));
        match self.reload_config_from(&root) {
            Ok(()) => {
                self.config_snapshot = Some(bytes);
                self.reload_tabs();
                // The capacity cache holds the index and issue snapshot built
                // under the previous configuration. Re-read both here, before
                // another render can pair the new ceiling with the old
                // conversion table.
                self.refresh_capacity_view();
                self.refresh_cycle_schedule_warnings();
                self.rebuild_board();
                true
            }
            Err(e) => {
                self.status_msg = Some(format!("tix.toml: {e} — kept the previous configuration"));
                false
            }
        }
    }

    // -- saved views (WP05, T024–T027) ------------------------------------
    //
    // The whole section is an **adapter**, like `src/commands/views.rs` is for
    // the CLI: it owns no rule of its own. Ids, scopes, plan validation, apply,
    // CRUD, definition-only delete, the active marker, and divergence all come
    // from WP01–WP03 (`crate::views`); the filter grammar comes from
    // `crate::search`, and the board rebuild from the existing
    // `apply_filter`/`rebuild_board`. What this section decides is only:
    //
    // - **where** a view came from (the live filter state), and
    // - **what** the user sees (the indicator and the feedback panel).
    //
    // Three boundaries are load-bearing and are why the code looks the way it
    // does:
    //
    // - **Applying writes nothing.** [`Self::apply_view`] calls
    //   `ViewService::apply`, which borrows the config and the corpus, and then
    //   installs the returned plan into the live filter state through the
    //   existing `apply_filter`. No issue, comment, relationship, or `tix.toml`
    //   byte changes (C-005).
    // - **The marker is informational** (C-006). [`Self::live_plan`] derives the
    //   live plan from the *current* filter state and the *current* visibility,
    //   so editing the filter after applying a view makes the divergence report
    //   name the difference instead of silently reconciling it.
    // - **Only create/update/duplicate/delete write**, each through the one
    //   audited registry commit, each validated before it (C-008).

    // -----------------------------------------------------------------------
    // WP07 (mission `repeating-cycle-schedules-01M3C7W1`): the cycle schedules on
    // the F8 Schedule page's **Cycle schedules** tab.
    // -----------------------------------------------------------------------

    // -----------------------------------------------------------------------
    // WP06 — the capacity read: the Capacity tab, the board's cells and the
    // issue detail all render this one reading.
    // -----------------------------------------------------------------------
}

mod render;
pub use render::render;
use render::{
    HINT_HEIGHT, HOVER_HEIGHT, HealthRow, RENDER_BOTTOM_MARGIN, RENDER_FALLBACK_HEIGHT,
    RENDER_FALLBACK_WIDTH, TAB_HEIGHT, capacity_cell, capacity_detail, capacity_fields,
    capacity_row, feed_minutes, filter_band_height, issue_estimate_line, mention_row_height,
    open_in_browser, plan_lines, run_child_tix, template_default_lines, template_subtitle,
    theme_for,
};

mod cycle;
mod filter;
mod library;
mod mouse;
mod nav;
mod pickers;
mod planning;
mod portfolio;
mod roadmap;
mod schedule;
mod schedule_capacity;
mod schedule_forms;
mod settings;
mod shell;
mod stats;
mod stats_burndown;
mod stats_health;
mod stats_time;
#[cfg(test)]
mod tests;
mod views;
mod wip;
pub(in crate::app) use filter::FilterPicker;
pub use pickers::FormPickerField;
pub(in crate::app) use pickers::{FormPicker, LEGACY_TEMPLATE_PREFIX, STABLE_TEMPLATE_PREFIX};
mod actions;
mod board_input;
mod confirm;
mod detail_input;
mod editor_input;
mod forms;
mod help;
mod refresh;
mod relationships;
mod repair;
mod session;
#[cfg(test)]
pub(in crate::app) use session::{
    Startup, cells_to_text, render_once_at, render_to_cells, resolve_render_size,
};
pub use session::{drain_disclosures, render_once, run, run_new_issue};
pub(in crate::app) use session::{error_message, io_err, names_backup};
pub use stats::StatsTab;
use stats_health::HealthForm;
pub use stats_time::StatsTimeState;
use stats_time::{TimeBreakdown, TimeFilterForm, TimeForm};