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
//! The `F10` **Portfolio** page's **Roadmap** tab (WP05): the shared
//! [`RoadmapProjection`] the CLI renders, as a tab on the page `#1593` gives the
//! project registry.
//!
//! # A tab, not a mode
//!
//! The mission's earlier planning sketch described the roadmap as a top-level
//! page; the surface that actually shipped is an **additional tab on the `F10`
//! Portfolio page** (`switch_to_portfolio`), exactly as the Epics tab is. So there
//! is no new function key, no new [`crate::keybindings::InputContext`] and no new
//! `TopMode`: `Tab`/`Shift+Tab` cycle `Projects -> Epics -> Roadmap`, `j`/`k` walk
//! the rows, and `q`/`esc` close the page. `F9` stays reserved for `#1593`'s Data
//! page.
//!
//! # Exactly the CLI's rows
//!
//! Nothing here re-renders a figure. The list headline and the detail pane are the
//! CLI's own [`crate::commands::roadmap::roadmap_row_lines`] (the same lines
//! `tix roadmap show` prints, contributions and diagnostics included), the empty
//! state is [`crate::commands::roadmap::roadmap_list_lines`]'s own sentence, and
//! the active criteria line is
//! [`crate::commands::roadmap::roadmap_filter_line`]. The projection itself is the
//! shared [`crate::roadmap::projection::project`] over a once-per-refresh source
//! snapshot ([`projection_over`]); this module owns no progress, risk or ownership
//! rule, so the tab cannot disagree with the CLI about one (C-004, C-007).
//!
//! # Filters are the one DTO
//!
//! The filter editor ([`RoadmapOverlay::Filter`]) edits a [`FilterDraft`] and
//! normalizes it into the **same** [`RoadmapFilter`] the CLI builds; the predicate
//! and the ordering stay in [`crate::roadmap`]. There is no second filter grammar.
//!
//! # Actions go through the registry
//!
//! `c`/`e`/`a`/`x` open the create, rename, associate and dereference overlays.
//! Applying one calls [`crate::roadmap::registry`]'s own atomic boundary with the
//! live `tix.toml` path — the same writer `tix initiative …` uses — so a refusal
//! leaves the file byte-identical and no second writer exists (C-008).

use std::collections::HashSet;

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

use crate::app::App;
use crate::config::Config;
use crate::error::Result;
use crate::model::Issue;
use crate::roadmap::registry::{AssociationKind, InitiativeEdit, NewInitiative};
use crate::roadmap::{
    RoadmapConsumed, RoadmapFilter, RoadmapProjection, RoadmapRow, RoadmapSources,
};
use crate::storage::Store;

// ---------------------------------------------------------------------------
// Tab registration (read by `crate::ui::portfolio`)
// ---------------------------------------------------------------------------

/// The tab's label in the Portfolio strip.
pub const TAB_LABEL: &str = "Roadmap";

/// The registry the tab reads, as `tix.toml` spells it.
///
/// The roadmap is a **projection** over `[initiatives.<id>]`, so this names the
/// section the tab's data is declared in rather than a section of its own.
pub const TAB_SECTION: &str = "initiatives";

/// The tab's noun, for a detail pane with nothing to describe.
pub const TAB_NOUN: &str = "initiative";

/// What to say when the initiative registry is empty.
pub const TAB_EMPTY_HINT: &str =
    "No initiatives yet — run `tix initiative create <name>`, or press `c` to add one here.";

/// The one-line hint under the strip: the tab's keys, matching what the handler
/// reads.
pub const TAB_HINT: &str =
    "j/k row · c create · e rename · a associate · x dereference · f filter · Tab tabs · q close";

// ---------------------------------------------------------------------------
// The read adapter (T022)
// ---------------------------------------------------------------------------

/// The shared projection for `filter`, over an already-read issue snapshot.
///
/// This is the TUI's counterpart of the CLI's `build_sources` + `projection::project`
/// pair: the **consumed** facts (assigned, overdue, blocked, reference targets) are
/// gathered from their owning services — never derived here — and the join, the
/// predicate and the sort all stay in [`crate::roadmap`]. `issues` is passed in so
/// the page can reuse the `store.list_all()` read it already made for the Projects
/// and Epics tabs instead of reading the tree a second time (NFR-001).
pub fn projection_over(
    config: &Config,
    store: &Store,
    issues: &[Issue],
    filter: &RoadmapFilter,
) -> Result<RoadmapProjection> {
    filter.validate()?;
    let policy = config.health.policy()?;
    let root = Config::project_root(&store.issues_dir).unwrap_or_else(|| store.issues_dir.clone());
    let planner = crate::planning::Planner::from_config(config.clone(), root);
    let targets = crate::epics::ReferenceTargets::from_planner(&planner)?;
    let overdue: HashSet<u32> = planner
        .overdue_batch(store, &crate::model::today())
        .iter()
        .map(|issue| issue.number)
        .collect();
    let assigned = crate::projects::assigned_keys(issues);
    let (graph_issues, done_column) = store.graph_source()?;
    let views: Vec<crate::relationships::IssueView<'_>> =
        graph_issues.iter().map(Issue::issue_view).collect();
    let graph = crate::relationships::RelationshipGraph::new(&views, &done_column);
    let blocked: HashSet<u32> = graph_issues
        .iter()
        .filter(|issue| graph.blocked_state(issue.number).is_blocked)
        .map(|issue| issue.number)
        .collect();
    let consumed = RoadmapConsumed {
        targets,
        done_column,
        assigned,
        overdue,
        blocked,
    };
    let sources = RoadmapSources::new(config, issues, &policy, consumed);
    crate::roadmap::projection::project(config, &sources, filter)
}

// ---------------------------------------------------------------------------
// Pure render data (T022, T025)
// ---------------------------------------------------------------------------

/// One row's headline: the **CLI's own** header line, its tab separators spaced so
/// the TUI list reads as columns.
///
/// The content is [`crate::commands::roadmap::roadmap_row_lines`]'s first line
/// verbatim (`id`, name, target date or `undated`, summary state); replacing the
/// separator with spaces is presentation only.
#[must_use]
pub fn headline(row: &RoadmapRow) -> String {
    crate::commands::roadmap::roadmap_row_lines(row)
        .into_iter()
        .next()
        .unwrap_or_default()
        .replace('\t', "  ")
}

/// One row's detail lines: the CLI's `roadmap show` output, **verbatim**.
///
/// Every provenance, resolution (`[missing]`), progress, risk, policy version,
/// empty-summary sentence and diagnostic the CLI prints is here, because it is the
/// CLI's string.
#[must_use]
pub fn detail_lines(row: &RoadmapRow) -> Vec<String> {
    crate::commands::roadmap::roadmap_row_lines(row)
}

/// The CLI's explicit empty state for a projection that selected nothing.
#[must_use]
pub fn empty_state_lines(projection: &RoadmapProjection) -> Vec<String> {
    crate::commands::roadmap::roadmap_list_lines(projection)
}

/// The active normalized criteria, exactly as `tix roadmap list` prints them, or
/// `None` when the filter narrows nothing.
#[must_use]
pub fn filter_context(filter: &RoadmapFilter) -> Option<String> {
    crate::commands::roadmap::roadmap_filter_line(filter)
}

// ---------------------------------------------------------------------------
// Overlays: the filter editor and the initiative actions (T023, T024)
// ---------------------------------------------------------------------------

/// The verb an association overlay applies.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssocVerb {
    /// Record the target on the selected initiative.
    Associate,
    /// Drop the target from the selected initiative.
    Dereference,
}

/// The overlay open over the Roadmap tab: the filter editor, or one initiative
/// action. All are text surfaces, so the page assigns them raw keys ahead of the
/// binding layer (`j` typed into an owner name must stay a letter).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RoadmapOverlay {
    /// The normalized filter editor (T023).
    Filter(FilterDraft),
    /// Create an initiative; `c`.
    Create(NameDraft),
    /// Rename the selected initiative; `e`.
    Rename(NameDraft),
    /// Associate or dereference a reference on the selected initiative; `a`/`x`.
    Associate(AssociationDraft),
}

impl RoadmapOverlay {
    /// The overlay's title.
    #[must_use]
    pub fn title(&self) -> &'static str {
        match self {
            Self::Filter(_) => "Roadmap filter",
            Self::Create(_) => "New initiative",
            Self::Rename(_) => "Rename initiative",
            Self::Associate(draft) => match draft.verb {
                AssocVerb::Associate => "Associate reference",
                AssocVerb::Dereference => "Dereference reference",
            },
        }
    }

    /// The overlay's footer hint.
    #[must_use]
    pub fn hint(&self) -> &'static str {
        match self {
            Self::Filter(_) => "type to edit · tab/↑↓ field · enter apply · esc cancel",
            Self::Create(_) => "type a name · enter create · esc cancel",
            Self::Rename(_) => "type a name · enter rename · esc cancel",
            Self::Associate(_) => "type a target · ←/→ kind · enter apply · esc cancel",
        }
    }

    /// Move the focused field by `delta`, wrapping.
    pub fn focus(&mut self, delta: isize) {
        match self {
            Self::Filter(draft) => draft.focus(delta),
            Self::Associate(draft) => draft.focus(delta),
            Self::Create(_) | Self::Rename(_) => {}
        }
    }

    /// Cycle the association **kind** by `delta` (a no-op on every other overlay).
    pub fn cycle_kind(&mut self, delta: isize) {
        if let Self::Associate(draft) = self {
            draft.cycle_kind(delta);
        }
    }

    /// Append `ch` to the focused text field.
    pub fn push(&mut self, ch: char) {
        if let Some(field) = self.field_mut() {
            field.push(ch);
        }
    }

    /// Delete the focused field's last character.
    pub fn backspace(&mut self) {
        if let Some(field) = self.field_mut() {
            field.pop();
        }
    }

    /// The focused text field, or `None` when the overlay has none.
    fn field_mut(&mut self) -> Option<&mut String> {
        match self {
            Self::Filter(draft) => Some(draft.field_mut()),
            Self::Create(draft) | Self::Rename(draft) => Some(&mut draft.value),
            Self::Associate(draft) => draft.field_mut(),
        }
    }
}

/// A single text field — the create and rename overlays.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NameDraft {
    /// The typed value.
    pub value: String,
}

/// The normalized filter editor: one text row per criterion, in the DTO's own
/// field order.
///
/// The DTO the draft normalizes into is [`RoadmapFilter`]; the labels are a
/// comma-separated list in **this** control only, normalized to the DTO's
/// `Vec<String>` on apply.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FilterDraft {
    /// The `period_from` row.
    pub from: String,
    /// The `period_to` row.
    pub to: String,
    /// The `owner` row.
    pub owner: String,
    /// The `status` row.
    pub status: String,
    /// The `labels` row, comma-separated.
    pub labels: String,
    /// The `query` row.
    pub query: String,
    /// The focused row.
    pub field: usize,
}

impl FilterDraft {
    /// The rows in display order; index is [`Self::field`].
    pub const ROWS: [&'static str; 6] = ["from", "to", "owner", "status", "labels", "query"];

    /// Seed the editor from an installed filter.
    #[must_use]
    pub fn from_filter(filter: &RoadmapFilter) -> Self {
        Self {
            from: filter.period_from.clone().unwrap_or_default(),
            to: filter.period_to.clone().unwrap_or_default(),
            owner: filter.owner.clone().unwrap_or_default(),
            status: filter.status.clone().unwrap_or_default(),
            labels: filter.labels.join(","),
            query: filter.query.clone().unwrap_or_default(),
            field: 0,
        }
    }

    /// Normalize the draft into **the one** filter DTO (contract §Normalized
    /// filter). A blank row is `None`/empty; `labels` splits on `,` and trims.
    #[must_use]
    pub fn to_filter(&self) -> RoadmapFilter {
        let opt = |value: &str| {
            let trimmed = value.trim();
            (!trimmed.is_empty()).then(|| trimmed.to_string())
        };
        RoadmapFilter {
            period_from: opt(&self.from),
            period_to: opt(&self.to),
            owner: opt(&self.owner),
            status: opt(&self.status),
            labels: self
                .labels
                .split(',')
                .map(str::trim)
                .filter(|label| !label.is_empty())
                .map(ToString::to_string)
                .collect(),
            query: opt(&self.query),
        }
    }

    /// The focused row's value.
    #[must_use]
    pub fn value(&self) -> &str {
        self.value_at(self.field)
    }

    /// The `index`-th row's value.
    #[must_use]
    pub fn value_at(&self, index: usize) -> &str {
        match index % Self::ROWS.len() {
            0 => &self.from,
            1 => &self.to,
            2 => &self.owner,
            3 => &self.status,
            4 => &self.labels,
            _ => &self.query,
        }
    }

    /// Move the focused row by `delta`, wrapping.
    pub fn focus(&mut self, delta: isize) {
        let len = Self::ROWS.len() as isize;
        self.field = (self.field as isize + delta).rem_euclid(len) as usize;
    }

    fn field_mut(&mut self) -> &mut String {
        match self.field % Self::ROWS.len() {
            0 => &mut self.from,
            1 => &mut self.to,
            2 => &mut self.owner,
            3 => &mut self.status,
            4 => &mut self.labels,
            _ => &mut self.query,
        }
    }
}

/// The association overlay's draft: the verb, the kind and the target.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssociationDraft {
    /// Whether applying the overlay associates or dereferences.
    pub verb: AssocVerb,
    /// The reference kind; cycled with `←`/`→`.
    pub kind: AssociationKind,
    /// The typed target.
    pub target: String,
    /// The focused field (`0` = kind, `1` = target).
    pub field: usize,
}

impl AssociationDraft {
    /// The kinds in cycle order.
    pub const KINDS: [AssociationKind; 3] = [
        AssociationKind::Project,
        AssociationKind::Epic,
        AssociationKind::Milestone,
    ];

    /// A fresh draft for `verb`.
    #[must_use]
    pub fn new(verb: AssocVerb) -> Self {
        Self {
            verb,
            kind: AssociationKind::Project,
            target: String::new(),
            field: 1,
        }
    }

    /// Cycle the kind by `delta`, wrapping.
    pub fn cycle_kind(&mut self, delta: isize) {
        let current = Self::KINDS
            .iter()
            .position(|kind| *kind == self.kind)
            .unwrap_or(0);
        let len = Self::KINDS.len() as isize;
        self.kind = Self::KINDS[(current as isize + delta).rem_euclid(len) as usize];
    }

    /// The kind's label in the overlay.
    #[must_use]
    pub fn kind_label(&self) -> &'static str {
        self.kind.field()
    }

    fn focus(&mut self, delta: isize) {
        let len = 2isize;
        self.field = (self.field as isize + delta).rem_euclid(len) as usize;
    }

    fn field_mut(&mut self) -> Option<&mut String> {
        (self.field % 2 == 1).then_some(&mut self.target)
    }
}

/// The initiative the create overlay builds: a name; every other field is the
/// CLI's own default and is edited later (or from `tix initiative edit`).
#[must_use]
pub fn new_initiative(draft: &NameDraft) -> NewInitiative {
    NewInitiative {
        name: draft.value.trim().to_string(),
        ..NewInitiative::default()
    }
}

/// The rename edit a [`RoadmapOverlay::Rename`] draft applies: a **label** change
/// only, so the stable id — and every association — survives (C-002).
#[must_use]
pub fn rename_edit(draft: &NameDraft) -> InitiativeEdit {
    InitiativeEdit {
        name: crate::projects::Patch::Set(draft.value.trim().to_string()),
        ..InitiativeEdit::default()
    }
}

// ---------------------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------------------

/// The style of everything secondary.
fn dim() -> Style {
    Style::default().fg(Color::DarkGray)
}

/// Draw the Roadmap tab into `area`: the active criteria line, then the ordered
/// rows beside the selected row's CLI detail.
///
/// The whole tab is one function so the Portfolio page's renderer only has to
/// dispatch to it — the tab cannot drift from the page's other tabs, and the
/// page's own layout code stays untouched beyond the dispatch.
pub fn render_tab(app: &App, f: &mut Frame, area: Rect, selected: usize) {
    let split = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(1)])
        .split(area);

    let criteria = filter_context(app.roadmap_filter());
    let line = match criteria {
        Some(text) => Line::from(Span::styled(text, Style::default().fg(Color::Cyan))),
        None => Line::from(Span::styled(
            "filter: none (no criterion set) · f to edit",
            dim(),
        )),
    };
    f.render_widget(Paragraph::new(line), split[0]);

    let body = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([Constraint::Percentage(55), Constraint::Min(24)])
        .split(split[1]);

    let projection = app.portfolio_roadmap();
    let rows: &[RoadmapRow] =
        projection.map_or(&[], |projection| projection.initiatives.as_slice());

    let list_title = format!("{} ({})", TAB_LABEL, rows.len());
    let list_block = Block::default().borders(Borders::ALL).title(list_title);
    if rows.is_empty() {
        // Two distinct empty states, never one blank pane: a registry with no
        // initiatives names how to fill it, a filter that selected nothing prints
        // the CLI's own sentence for that case, and a projection that could not be
        // built says so rather than panicking on a missing value.
        let text = if app.roadmap_registry_is_empty() {
            TAB_EMPTY_HINT.to_string()
        } else {
            match projection {
                Some(projection) => empty_state_lines(projection).join("\n"),
                None => "The roadmap could not be read — check the filter and the registries."
                    .to_string(),
            }
        };
        f.render_widget(
            Paragraph::new(text)
                .block(list_block)
                .wrap(Wrap { trim: true })
                .style(dim()),
            body[0],
        );
    } else {
        let lines: Vec<Line<'static>> = rows
            .iter()
            .enumerate()
            .map(|(index, row)| {
                let selected = index == selected;
                let style = if selected {
                    Style::default().add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                };
                Line::from(vec![
                    Span::raw(if selected { "> " } else { "  " }),
                    Span::styled(headline(row), style),
                ])
            })
            .collect();
        f.render_widget(Paragraph::new(lines).block(list_block), body[0]);
    }

    let detail_block = Block::default()
        .borders(Borders::ALL)
        .title(format!("{} detail", TAB_NOUN));
    match rows.get(selected) {
        Some(row) => {
            let lines: Vec<Line<'static>> = detail_lines(row)
                .into_iter()
                .map(|line| Line::from(line.replace('\t', "  ")))
                .collect();
            f.render_widget(
                Paragraph::new(lines)
                    .block(detail_block)
                    .wrap(Wrap { trim: false }),
                body[1],
            );
        }
        None => f.render_widget(
            Paragraph::new(Span::styled(
                "Nothing selected. An initiative has to exist before the page can describe it.",
                dim(),
            ))
            .block(detail_block)
            .wrap(Wrap { trim: true }),
            body[1],
        ),
    }

    render_overlay(app, f, area);
}

/// Draw the open overlay, if any, centered over `area`.
pub fn render_overlay(app: &App, f: &mut Frame, area: Rect) {
    let Some(overlay) = app.roadmap_overlay() else {
        return;
    };
    let rect = crate::ui::modal::modal_rect(area);
    f.render_widget(Clear, rect);

    let mut lines: Vec<Line<'static>> = Vec::new();
    let row = |focused: bool, key: &str, value: &str| {
        let marker = if focused { "> " } else { "  " };
        let style = if focused {
            Style::default().add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };
        Line::from(vec![
            Span::styled(format!("{marker}{key}: "), dim()),
            Span::styled(value.to_string(), style),
        ])
    };
    match overlay {
        RoadmapOverlay::Filter(draft) => {
            for (index, key) in FilterDraft::ROWS.iter().enumerate() {
                let focused = index == draft.field % FilterDraft::ROWS.len();
                let value = if focused {
                    format!("{}_", draft.value())
                } else {
                    draft.value_at(index).to_string()
                };
                lines.push(row(focused, key, &value));
            }
        }
        RoadmapOverlay::Create(draft) | RoadmapOverlay::Rename(draft) => {
            lines.push(row(true, "name", &format!("{}_", draft.value)));
        }
        RoadmapOverlay::Associate(draft) => {
            let kind = draft.kind_label().to_string();
            lines.push(row(draft.field % 2 == 0, "kind", &kind));
            let target = if draft.field % 2 == 1 {
                format!("{}_", draft.target)
            } else {
                draft.target.clone()
            };
            lines.push(row(draft.field % 2 == 1, "target", &target));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(overlay.hint(), dim())));

    f.render_widget(
        Paragraph::new(lines)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(overlay.title()),
            )
            .wrap(Wrap { trim: false }),
        rect,
    );
}

#[cfg(test)]
mod tests {
    #[allow(clippy::wildcard_imports)]
    use super::*;

    #[test]
    fn the_filter_draft_normalizes_into_the_one_shared_dto() {
        let mut draft = FilterDraft::from_filter(&RoadmapFilter::default());
        assert_eq!(draft.to_filter(), RoadmapFilter::default());
        draft.from = " 2026-01-01 ".to_string();
        draft.owner = "alice".to_string();
        draft.labels = "one, two ,, three".to_string();
        draft.query = "  ".to_string();
        let filter = draft.to_filter();
        assert_eq!(filter.period_from.as_deref(), Some("2026-01-01"));
        assert_eq!(filter.owner.as_deref(), Some("alice"));
        assert_eq!(filter.labels, vec!["one", "two", "three"]);
        assert_eq!(filter.query, None, "a blank row narrows nothing");
        // The DTO's own validator owns the syntax rule.
        assert!(filter.validate().is_ok());
        let mut bad = FilterDraft::from_filter(&RoadmapFilter::default());
        bad.from = "not-a-date".to_string();
        assert!(bad.to_filter().validate().is_err());
    }

    #[test]
    fn the_filter_draft_seeds_from_an_installed_filter() {
        let filter = RoadmapFilter {
            period_to: Some("2026-12-31".to_string()),
            status: Some("active".to_string()),
            labels: vec!["a".to_string(), "b".to_string()],
            ..RoadmapFilter::default()
        };
        let draft = FilterDraft::from_filter(&filter);
        assert_eq!(draft.to, "2026-12-31");
        assert_eq!(draft.status, "active");
        assert_eq!(draft.labels, "a,b");
        assert_eq!(draft.to_filter(), filter, "a round trip through the editor");
        // The rows are the DTO's own field order.
        assert_eq!(
            FilterDraft::ROWS,
            ["from", "to", "owner", "status", "labels", "query"]
        );
    }

    #[test]
    fn focus_wraps_and_the_association_kind_cycles() {
        let mut draft = FilterDraft::from_filter(&RoadmapFilter::default());
        draft.focus(-1);
        assert_eq!(draft.field, FilterDraft::ROWS.len() - 1, "backward wraps");
        draft.focus(1);
        assert_eq!(draft.field, 0, "forward wraps");

        let mut association = AssociationDraft::new(AssocVerb::Associate);
        assert_eq!(association.kind, AssociationKind::Project);
        association.cycle_kind(1);
        assert_eq!(association.kind, AssociationKind::Epic);
        association.cycle_kind(1);
        assert_eq!(association.kind, AssociationKind::Milestone);
        association.cycle_kind(1);
        assert_eq!(association.kind, AssociationKind::Project, "forward wraps");
        association.cycle_kind(-1);
        assert_eq!(
            association.kind,
            AssociationKind::Milestone,
            "backward wraps"
        );
        // Only the target row takes text; the overlay routes characters to it.
        let mut association = AssociationDraft::new(AssocVerb::Associate);
        let mut overlay = RoadmapOverlay::Associate(association.clone());
        overlay.push('p');
        let RoadmapOverlay::Associate(focused_target) = &overlay else {
            unreachable!("the overlay is an association");
        };
        assert_eq!(focused_target.target, "p");
        overlay.backspace();
        let RoadmapOverlay::Associate(cleared) = &overlay else {
            unreachable!("the overlay is an association");
        };
        assert_eq!(cleared.target, "");
        // The kind row is not a text row: a character typed there is dropped.
        association.field = 0;
        overlay = RoadmapOverlay::Associate(association);
        overlay.push('p');
        let RoadmapOverlay::Associate(kind_row) = &overlay else {
            unreachable!("the overlay is an association");
        };
        assert!(kind_row.target.is_empty(), "the kind row takes no text");
    }

    #[test]
    fn the_action_drafts_build_the_services_own_specs() {
        let new = new_initiative(&NameDraft {
            value: "  Alpha  ".to_string(),
        });
        assert_eq!(
            new.name, "Alpha",
            "the name is trimmed, nothing else is invented"
        );
        assert!(new.outcome.is_none() && new.projects.is_empty());

        let edit = rename_edit(&NameDraft {
            value: "Renamed".to_string(),
        });
        assert_eq!(
            edit,
            InitiativeEdit {
                name: crate::projects::Patch::Set("Renamed".to_string()),
                ..InitiativeEdit::default()
            },
            "a rename touches the label only, never the stable id (C-002)"
        );
    }

    #[test]
    fn the_tab_registration_names_how_to_fill_an_empty_registry() {
        assert_eq!(TAB_LABEL, "Roadmap");
        assert_eq!(TAB_SECTION, "initiatives");
        assert_eq!(TAB_NOUN, "initiative");
        assert!(TAB_EMPTY_HINT.contains("tix initiative create"));
        for key in [
            "c create",
            "e rename",
            "a associate",
            "x dereference",
            "f filter",
        ] {
            assert!(TAB_HINT.contains(key), "the hint advertises `{key}`");
        }
    }

    #[test]
    fn the_overlay_titles_and_hints_are_stable() {
        assert_eq!(
            RoadmapOverlay::Create(NameDraft::default()).title(),
            "New initiative"
        );
        assert_eq!(
            RoadmapOverlay::Associate(AssociationDraft::new(AssocVerb::Dereference)).title(),
            "Dereference reference"
        );
        assert_eq!(
            RoadmapOverlay::Filter(FilterDraft::default()).hint(),
            "type to edit · tab/↑↓ field · enter apply · esc cancel"
        );
    }
}