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
use super::filter::{epic_bucket_label, nest_children, project_bucket_label, sort_cards};
#[allow(clippy::wildcard_imports)]
use super::*;

#[derive(Debug, Clone)]
pub(super) struct GroupSection {
    pub(super) name: String,
    pub(super) start: usize,
    pub(super) end: usize,
    pub(super) done: usize,
    pub(super) total: usize,
}

/// The grouped board's direct-navigation affordance (WP06 T030 step 5, FR-004).
///
/// A grouped board must still open an issue's own detail and edit without passing
/// through the epic layer, so the footer states it rather than leaving it implied by
/// the card text. One constant, so the render and any test that names it cannot
/// drift.
pub(super) const GROUP_OPEN_AFFORDANCE: &str = "Enter: open issue";

/// One badge per issue that records health, keyed by number (WP06 T030).
///
/// Built once per board build, like `blocked_reasons` and `child_markers`: the badge
/// comes from the shared index and rollup, and an issue with neither a recorded value
/// nor contributors gets no entry at all.
pub(super) fn health_badges(issues: &[Issue]) -> BTreeMap<u32, String> {
    let policy = crate::health::HealthPolicy::v1();
    let index = crate::health::HealthIndex::build(issues, &[], &[], &policy);
    let mut out = BTreeMap::new();
    for issue in issues {
        let scope = crate::health::HealthScope::of_issue(issue.number);
        let Some((state, recorded)) = index.state_of(issue.number) else {
            continue;
        };
        let derived = crate::health::rollup(&index, &scope, &policy);
        // Nothing recorded and nobody contributing: nothing to say. A legacy issue is
        // reported as `unknown` by the detail view and by the CLI, which is where a
        // reader who asked about it is looking.
        if recorded.is_none() && derived.contributions.is_empty() {
            continue;
        }
        let current = state.as_str();
        let badge = if derived.is_derived() && derived.state.as_str() != current {
            format!("{current}\u{2192}{}", derived.state.as_str())
        } else {
            current.to_string()
        };
        out.insert(issue.number, badge);
    }
    out
}

#[derive(Debug, Clone)]
pub struct Card {
    /// Canonical identity of the issue this card displays.
    pub reference: crate::id::IssueRef,
    pub number: u32,
    pub title: String,
    pub priority: Priority,
    pub labels: Vec<String>,
    pub assignee: Option<String>,
    pub filename: String,
    pub commit: Option<String>,
    pub created: String,
    pub due_date: Option<String>,
    pub status: String,
    /// The issue's resolved category label, from the service's own `label()`
    /// (WP05 T022, FR-004).
    ///
    /// `Some` for a column the board configures, `None` for one it does not — a
    /// configuration error the user should be able to *see*, rather than a
    /// transition-policy default silently applied to a display. The renderer shows
    /// `(unmapped)` for `None`.
    ///
    /// **The label carries the meaning, not the color.** A board or terminal with no
    /// color must still convey the category, so the label is always rendered and the
    /// `color_hint` only ever tints it (T022 step 3, research R6).
    pub category: Option<String>,
    /// The category's color hint, for tinting. Advisory only: dropping it changes
    /// the display's color and nothing else.
    pub category_color: Option<crate::workflow::ColorHint>,
    /// Whether the service considers this issue **complete** (WP05, C-004).
    ///
    /// Was `issue.status.is(done_column)` — a column-*name* comparison. On a board
    /// whose `category_map` puts `completed` somewhere other than its `done_column`
    /// that is a different question from the one the service answers, and this flag
    /// drives the card's completion styling and the group's rollup.
    pub done: bool,
    pub cycle: Option<String>,
    pub milestone: Option<String>,
    /// The issue's blocked reason, from the relationship service, or `None`.
    ///
    /// Derived, never stored (data-model §4, C-003): recomputed from the graph
    /// on every board build, so a card cannot show a stale blocked state after
    /// its blocker moved.
    pub blocked: Option<String>,
    /// The issue's hierarchy marker: `3` for three children, `3 1/3` when one is
    /// complete, or `None` for a leaf.
    ///
    /// `None` for a leaf rather than `Some("0")`, so a card cannot show a child
    /// count for an issue that is not a parent. Built from the service's
    /// [`crate::commands::parent::HierarchyFacts`] on every board build, so it
    /// cannot go stale when a child is created or moved — the same discipline
    /// `blocked` follows.
    pub children: Option<String>,
    /// The issue's decomposition parent, when it has one (tix #1399).
    ///
    /// Carried on the card rather than looked up at render time, so the board can
    /// place a sub-issue beneath its parent without a second pass over the issues.
    pub parent: Option<crate::id::IssueRef>,
    /// How deeply the card is nested in the board's tree rendering (tix #1399).
    ///
    /// `0` for a top-level card, `1` for a sub-issue shown directly under its
    /// parent. Never above `1`: only one level is rendered, so a grandchild stays
    /// at `0` and is drawn as a normal top-level card.
    pub depth: u8,
    /// Whether this issue is **archived** — its file is dot-prefixed (issue #1492).
    ///
    /// A card only ever carries `true` on a board built with archived issues
    /// included (the TUI's archive toggle); the default board is enumerated from
    /// the active set and never sees one. Rendered as the `[archived]` token, in the
    /// same bracketed language as `[~]` and `[N]`.
    pub archived: bool,

    /// The issue's compact health badge (mission `project-issue-health-status-01M3C8HX`,
    /// WP06 T030): the state the issue records, and the derived value beside it when
    /// the two differ (`at_risk->needs_attention`).
    ///
    /// Built from the **shared** index and rollup — never from a surface-local reading
    /// of the `health:` block, and never from a comparison of statuses (C-006). The
    /// spelling is the state's stable `as_str()`, the same word the CLI's
    /// `--columns health` cell prints, so the two surfaces cannot diverge. `None` when
    /// the issue records no health at all: a legacy card carries no badge, exactly as
    /// a leaf carries no child marker, so the board stays scannable.
    pub health: Option<String>,
    /// How many `related_issues` entries the issue carries (tix #1513).
    ///
    /// A plain count, computed from the issue set the board was built over, so the
    /// card cannot go stale when the field is edited — the same discipline `blocked`
    /// and `children` follow. `0` means no marker at all, which keeps a column of
    /// cards scannable.
    pub related: usize,
    /// The issue's **resolved project ids**, in registry declaration order
    /// (WP06 T028).
    ///
    /// Resolved once per board build from the shared membership index
    /// ([`crate::projects::ProjectIndex::build`]), so the board cannot disagree with
    /// `tix project list` about who is a member, and an association the registry does
    /// not know is not a project here either. Empty means the issue is in no project,
    /// which is the bucket the partition labels `(no project)`.
    ///
    /// Carried on the card rather than looked up at render time for the same reason
    /// `blocked`, `children` and `related` are: the renderer has no store, and a
    /// second read of the issue set per frame is work the build already did.
    pub projects: Vec<String>,
    /// The issue's **resolved epic ids**, in registry declaration order (WP06
    /// T030).
    ///
    /// Resolved once per board build from the shared membership index
    /// ([`crate::epics::EpicIndex::build`]) — only references the registry can
    /// resolve — so the board cannot disagree with `tix epic list` about who is a
    /// member, and a reference the registry does not know is not an epic here
    /// either. Empty means the issue is in no epic, which is the bucket the
    /// partition labels `(no epic)`.
    ///
    /// Carried on the card rather than looked up at render time for the same reason
    /// `projects` is: the renderer has no store, and a second read of the issue set
    /// per frame is work the build already did.
    pub epics: Vec<String>,
}

/// The project partition of one board build (WP06 T028).
///
/// Built once from the **shared** membership index
/// ([`crate::projects::ProjectIndex::build`]), so the board cannot disagree with
/// `tix project list` about who is a member: the resolved ids are the registry's,
/// and an association the registry does not know is not a project here either — it
/// is reported by `tix lint` instead, and its issue is bucketed `(no project)`.
///
/// That last point is a **chosen asymmetry** with the criterion rather than a
/// disagreement to be papered over: `StructuredFilter::project_matches` matches a
/// stored association **verbatim**, so `project:<stale-id>` still *finds* the issues
/// carrying a deleted project's id (the repair affordance `tix project remove`
/// needs), while this partition — which answers "which project owns this issue?" —
/// has no bucket for an id nothing resolves to. See `project_matches`'s doc.
///
/// The bucket rules are the design decision T027 step 4 records:
///
/// - an issue in **no** project is its own clearly labelled `(no project)` bucket;
/// - an issue in exactly **one** project sits in that project's bucket;
/// - an issue in **several** projects sits in a single `(multiple projects)`
///   bucket rather than being duplicated into each project's section.
///
/// Duplication is the road not taken, and deliberately: one issue would become two
/// cards, and the board's cursor, hit-testing and per-column counts are all
/// index-into-one-list arithmetic — a card that appeared twice would need a second
/// identity the renderer does not have. The **filter** still matches an issue in
/// two projects under either id (that is [`crate::search::StructuredFilter::project_matches`]),
/// so the union semantics are not lost where they matter.
pub(super) struct ProjectPartition {
    /// Issue number -> its resolved project ids, registry declaration order.
    pub(super) memberships: HashMap<u32, Vec<String>>,
    /// Project id -> its declaration index, for the sort rank.
    pub(super) order: HashMap<String, usize>,
}

#[derive(Debug, Clone)]
pub struct BoardColumn {
    pub name: String,
    pub cards: Vec<Card>,
}

/// What a pointer position over the board resolves to (D3). `row` is the
/// card's index inside its column — the same index [`BoardState::selected`]
/// uses — so the caller can compare it directly against the selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HitTarget {
    Card { col: usize, row: usize },
    Column { col: usize },
}

/// Compact capacity cells the board's cycle group headers append (WP06 T032).
///
/// One already-rendered cell per configured cycle scope, keyed by **both** the cycle
/// reference a card names and the scope's resolved display label, so either spelling
/// of one scope finds it. Built by [`crate::app::App`] from the shared calculation —
/// never here, and never from a second pass over the issues.
pub type CapacitySummaries = std::collections::BTreeMap<String, String>;

#[derive(Debug, Clone)]
pub struct BoardState {
    /// Visible columns only — configured columns not listed in the active
    pub columns: Vec<BoardColumn>,
    /// Columns hidden from the active board configuration. Their cards stay
    /// in board state (keyed by column name) and remain reachable via
    /// filters/search (DM-01M2MHJB884WCTVCDHPD2T3GE7); they never render.
    pub hidden: Vec<BoardColumn>,
    pub mismatch: BoardColumn,
    /// Whether the computed "Mismatched" pseudo-column is part of the
    /// navigation/render surface (C-002 / FR-003). Cards in unknown statuses
    /// are always collected into [`BoardState::mismatch`]; the column is only
    /// shown when the effective configuration sets `show_mismatch`.
    pub show_mismatch: bool,
    pub active_col: usize,
    pub selected: usize,
    /// The `(col, card index)` the pointer is hovering (D8), set by `Moved`
    /// events and cleared on `Up` / when the pointer leaves the board.
    /// Rendered as a highlight only — it never changes the selection.
    pub hover: Option<(usize, usize)>,
    /// The column the pointer is over, set for **any** position inside a column —
    /// including empty space below the last card, where `hover` is `None`. The
    /// renderer marks the hovered column from this, so an empty column lights up
    /// too. Cleared with `hover`.
    pub hover_col: Option<usize>,
    pub filter: Option<String>,
}

/// Shorten `msg` to at most `budget` **display cells**, appending an ellipsis
/// when anything was dropped.
///
/// The marker is appended *within* the budget rather than after it, so the result
/// is never wider than the area it is rendered into. A combining mark or a
/// zero-width control contributes no width, so it is kept without consuming
/// budget rather than being dropped.
pub fn truncate_to_cells(msg: &str, budget: usize) -> String {
    use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

    const ELLIPSIS: char = '\u{2026}';
    if budget == 0 {
        return String::new();
    }
    if UnicodeWidthStr::width(msg) <= budget {
        return msg.to_string();
    }

    // Reserve one cell for the marker. A double-width character cannot fit in
    // the last cell, so the loop stops on a width overflow rather than on a
    // character count.
    let marker_width = UnicodeWidthChar::width(ELLIPSIS).unwrap_or(1);
    let mut out = String::new();
    let mut used = 0usize;
    for ch in msg.chars() {
        let w = UnicodeWidthChar::width(ch).unwrap_or(0);
        if used + w + marker_width > budget {
            break;
        }
        out.push(ch);
        used += w;
    }
    out.push(ELLIPSIS);
    out
}

/// The blocked reason for every issue, read from the relationship service.
///
/// One graph over the **whole** set, so the answer does not depend on which
/// issues the board happens to be showing (see [`BoardState::blocked`]).
pub(super) fn blocked_reasons(
    issues: &[crate::model::Issue],
    done_column: &str,
) -> std::collections::BTreeMap<u32, String> {
    let views: Vec<crate::relationships::IssueView<'_>> =
        issues.iter().map(crate::model::Issue::issue_view).collect();
    let graph = crate::relationships::RelationshipGraph::new(&views, done_column);
    issues
        .iter()
        .filter_map(|issue| {
            crate::commands::blocked_note(&graph.blocked_state(issue.number))
                .map(|note| (issue.number, note))
        })
        .collect()
}

/// The child-count marker for every issue that has children, keyed by number.
///
/// One index over the whole set, so the marker does not depend on which issues the
/// board is showing. The text comes from the shared `HierarchyFacts`, which is what
/// `tix parent show`, `tix show` and `tix list --show progress` read, so the four
/// surfaces cannot report different figures.
pub(super) fn child_markers(
    issues: &[crate::model::Issue],
    done_column: &str,
) -> std::collections::BTreeMap<u32, String> {
    let views: Vec<crate::relationships::IssueView<'_>> =
        issues.iter().map(crate::model::Issue::issue_view).collect();
    let index = crate::hierarchy::HierarchyIndex::build(&views);
    issues
        .iter()
        .filter_map(|issue| {
            let facts =
                crate::commands::parent::facts_for(&index, issues, issue.number, done_column);
            facts.has_children().then(|| {
                (
                    issue.number,
                    format!(
                        "{} {}/{}",
                        facts.rollup.direct_children,
                        facts.rollup.completed_children,
                        facts.rollup.progress.total
                    ),
                )
            })
        })
        .collect()
}

impl BoardState {
    /// WP05: the resolution must be for the board this call is building, not for
    /// whichever board happens to be `default`.
    ///
    /// `board_config` can be any of the configured boards, and a board selected in
    /// the TUI is not necessarily the default one. Resolving against the default
    /// would give a card on the `staging` board the categories configured for
    /// `default` — a wrong answer rather than a missing one, which is worse.
    ///
    /// The board is identified by **pointer identity** against the config's boards,
    /// because `build` receives a `&BoardConfiguration` and not a name. That is exact
    /// and needs no name plumbing; a board not found in the config falls back to its
    /// own columns with the global vocabulary, which is the honest reading of a
    /// configuration `tix` did not load.
    /// Public so the startup path can build a board from a single shared
    /// enumeration (tix #1518) instead of each caller re-deriving it.
    pub fn resolution_for(
        store: &Store,
        board_config: &BoardConfiguration,
    ) -> crate::workflow::CategoryResolution {
        let name = store
            .config
            .configs()
            .find(|(_, board)| std::ptr::eq(*board, board_config))
            .map(|(name, _)| name)
            .unwrap_or("default");
        crate::workflow::resolution(&store.config, board_config, name)
    }

    pub fn build(store: &Store, board_config: &BoardConfiguration) -> Self {
        Self::build_with(store, board_config, false, false)
    }

    /// [`BoardState::build`], optionally including **archived** issues (issue #1492).
    ///
    /// `include_archived == false` is the default and the fast path: enumeration reads
    /// [`Store::list`], which drops a dot-prefixed filename from the directory entry
    /// without opening the file. `true` reads [`Store::list_all`], which is what the
    /// TUI's archive toggle asks for *on demand* — the point being that a repository
    /// with thousands of archived issues is never walked for a board that does not
    /// show them.
    pub fn build_with_archived(
        store: &Store,
        board_config: &BoardConfiguration,
        include_archived: bool,
    ) -> Self {
        Self::build_with(store, board_config, include_archived, false)
    }

    /// [`BoardState::build_with_archived`], optionally rendering sub-issues under
    /// their parents (tix #1399).
    ///
    /// `show_children == true` reorders every column so a card's direct sub-issues
    /// follow it, marked `depth = 1` (see [`nest_children`]). The reorder happens at
    /// **build** time, not at draw time, because the selection index and the pointer
    /// hit-test both address cards by their index inside a column — a tree only the
    /// renderer knew about would make a click or a `j` land on the wrong card.
    pub fn build_with(
        store: &Store,
        board_config: &BoardConfiguration,
        include_archived: bool,
        show_children: bool,
    ) -> Self {
        let issues = if include_archived {
            store.list_all()
        } else {
            store.list()
        }
        .unwrap_or_default();
        let resolution = Self::resolution_for(store, board_config);
        Self::build_from_issues(
            &issues,
            board_config,
            &store.config,
            &resolution,
            show_children,
        )
    }

    /// Build a board from an in-memory slice of issues (issue #10 follow-up).
    ///
    /// The single build path: [`BoardState::build_with`] reads the store and
    /// delegates here, and the TUI's incremental refresh rebuilds from its
    /// in-memory corpus without re-reading the tree. `config` supplies the
    /// completion column; `resolution` is the category resolution of the board
    /// being built (see [`BoardState::resolution_for`]).
    pub fn build_from_issues(
        issues: &[Issue],
        board_config: &BoardConfiguration,
        config: &crate::config::Config,
        resolution: &crate::workflow::CategoryResolution,
        show_children: bool,
    ) -> Self {
        // WP09: the **service's** completion column, not `done_column`. The
        // `blocked_reasons` and `child_markers` helpers take a column *name* — that is
        // their existing signature and it is not what makes them wrong. What was
        // wrong is which name they were handed: on a board whose `category_map` puts
        // `completed` on `shipped` while `done_column` is `done`, the TUI's blocked
        // marker was computed against `done_column` while `tix list`'s was computed
        // against the service, so the same issue read as blocked in the TUI and clear
        // in the CLI. The name is now resolved once, by the service.
        let done_column = crate::workflow::completion_column_or_default(board_config, config);
        let done_column = done_column.as_str();
        let blocked = blocked_reasons(issues, done_column);
        let children = child_markers(issues, done_column);
        let show_mismatch = board_config.show_mismatch;
        let hidden_names: Vec<&str> = board_config
            .hidden_columns
            .iter()
            .map(String::as_str)
            .collect();
        let mut column_map: Vec<Vec<Card>> =
            board_config.columns.iter().map(|_| Vec::new()).collect();
        let mut mismatch_cards = Vec::new();

        let health_badges = health_badges(issues);
        // The same partition the filtered build uses, from the same shared index:
        // an unfiltered board and a project-filtered one must label a card's
        // project identically (WP06 T028).
        let projects = ProjectPartition::build(config, issues);
        // The epic partition, from the same shared membership index, so an
        // unfiltered board and an epic-filtered one label a card's epic identically
        // (WP06 T030).
        let epics = EpicPartition::build(config, issues);
        for issue in issues {
            let card = Card {
                reference: crate::id::canonical_ref(issue),
                number: issue.number,
                title: issue.title.clone(),
                priority: issue.priority.clone(),
                labels: issue.labels.clone(),
                assignee: issue.assignee.clone(),
                filename: issue.filename.clone(),
                commit: issue.commit.clone(),
                created: issue.created.clone(),
                due_date: issue.due_date.clone(),
                status: issue.status.display().to_string(),
                category: crate::workflow::category_of(issue, resolution)
                    .map(|c| c.label().to_string()),
                category_color: crate::workflow::category_of(issue, resolution)
                    .and_then(|c| c.color_hint()),
                done: crate::workflow::is_completed(issue, resolution),
                cycle: issue.cycles.as_ref().and_then(|v| v.first().cloned()),
                milestone: issue.milestones.as_ref().and_then(|v| v.first().cloned()),
                blocked: blocked.get(&issue.number).cloned(),
                children: children.get(&issue.number).cloned(),
                parent: issue.parent,
                depth: 0,
                archived: issue.archived,
                related: issue.related_issues.len(),
                health: health_badges.get(&issue.number).cloned(),
                projects: projects.memberships(issue.number),
                epics: epics.memberships(issue.number),
            };
            if let Some(idx) = board_config
                .columns
                .iter()
                .position(|c| c == issue.status.display())
            {
                column_map[idx].push(card);
            } else {
                mismatch_cards.push(card);
            }
        }

        for cards in column_map.iter_mut() {
            sort_cards(board_config, cards);
        }
        sort_cards(board_config, &mut mismatch_cards);

        let mut columns: Vec<BoardColumn> = Vec::new();
        let mut hidden: Vec<BoardColumn> = Vec::new();
        for (cards, name) in column_map.into_iter().zip(board_config.columns.iter()) {
            let col = BoardColumn {
                name: name.clone(),
                cards,
            };
            if hidden_names.contains(&name.as_str()) {
                hidden.push(col);
            } else {
                columns.push(col);
            }
        }

        let mismatch = BoardColumn {
            name: "Mismatched".to_string(),
            cards: mismatch_cards,
        };

        let mut state = BoardState {
            columns,
            hidden,
            mismatch,
            show_mismatch,
            active_col: 0,
            selected: 0,
            filter: None,
            hover: None,
            hover_col: None,
        };
        state.apply_child_order(show_children);
        state
    }

    /// Nest each column's sub-issues beneath their parents when `show_children` is
    /// on (tix #1399). A no-op when it is off, so the default build is untouched.
    ///
    /// Applied to the visible columns and the "Mismatched" pseudo-column — every
    /// surface `render` and `hit_test` actually address. Hidden columns have no
    /// rendered presence, so they are left in their flat order.
    pub(super) fn apply_child_order(&mut self, show_children: bool) {
        if !show_children {
            return;
        }
        for column in &mut self.columns {
            nest_children(&mut column.cards);
        }
        nest_children(&mut self.mismatch.cards);
    }

    /// True when no card anywhere is visible (used for zero-match feedback).
    pub fn is_empty(&self) -> bool {
        self.columns.iter().all(|c| c.cards.is_empty())
            && (!self.show_mismatch || self.mismatch.cards.is_empty())
    }

    pub fn total_cols(&self) -> usize {
        if self.show_mismatch {
            self.columns.len() + 1
        } else {
            self.columns.len()
        }
    }

    /// Columns a card can be moved into: the configured columns plus (when
    /// shown) the "Mismatched" sentinel, which is never a move target. The
    /// `</>` move keys navigate *among movable columns* only.
    pub fn real_cols(&self) -> usize {
        self.columns.len()
    }

    pub fn column_name(&self, idx: usize) -> &str {
        if idx < self.columns.len() {
            &self.columns[idx].name
        } else if idx == self.columns.len() && self.show_mismatch {
            &self.mismatch.name
        } else {
            "Unknown"
        }
    }

    /// The name under the active cursor, resolving **hidden** columns too
    /// (visible region first, then hidden, then Unknown). Lets `toggle` keep a
    /// logical cursor on a just-hidden column so a second press re-shows it
    /// (T017: "a second press on the same column re-shows it").
    pub fn active_column_name(&self) -> &str {
        let visible = self.columns.len();
        if self.active_col < visible {
            &self.columns[self.active_col].name
        } else {
            let hidden_idx = self.active_col - visible;
            if hidden_idx < self.hidden.len() {
                &self.hidden[hidden_idx].name
            } else {
                "Unknown"
            }
        }
    }

    pub fn column_cards(&self, idx: usize) -> &[Card] {
        if idx < self.columns.len() {
            &self.columns[idx].cards
        } else if idx == self.columns.len() && self.show_mismatch {
            &self.mismatch.cards
        } else {
            &[]
        }
    }

    pub fn get_selected_card(&self) -> Option<&Card> {
        self.column_cards(self.active_col).get(self.selected)
    }

    /// The `(column, row)` of the only card the board is displaying, if there is
    /// exactly one (tix #1744).
    ///
    /// "Displayed" is what `render` and `hit_test` address: the active board's
    /// visible columns plus the "Mismatched" pseudo-column when it is shown.
    /// Hidden columns never render, so their cards do not count. `None` when the
    /// board shows zero cards or more than one.
    pub fn sole_visible_card(&self) -> Option<(usize, usize)> {
        let mut found = None;
        for (col, column) in self.columns.iter().enumerate() {
            for row in 0..column.cards.len() {
                if found.is_some() {
                    return None;
                }
                found = Some((col, row));
            }
        }
        if self.show_mismatch {
            for row in 0..self.mismatch.cards.len() {
                if found.is_some() {
                    return None;
                }
                found = Some((self.columns.len(), row));
            }
        }
        found
    }

    pub fn move_left(&mut self) {
        let total = self.real_cols();
        self.active_col = if total == 0 {
            0
        } else if self.active_col >= total {
            total - 1
        } else {
            (self.active_col + total - 1) % total
        };
        self.clamp_selection();
    }

    pub fn move_right(&mut self) {
        let total = self.real_cols();
        self.active_col = if total == 0 || self.active_col >= total {
            0
        } else {
            (self.active_col + 1) % total
        };
        self.clamp_selection();
    }

    pub fn move_up(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    pub fn move_down(&mut self) {
        let cards = self.column_cards(self.active_col);
        if self.selected + 1 < cards.len() {
            self.selected += 1;
        }
    }

    /// Move the selection by `cards` (negative moves up), clamped to the column
    /// (tix #1442 follow-up).
    ///
    /// The page step: `move_up`/`move_down` are the one-card steps, this is the same
    /// move by a screenful. It clamps for the reason the detail pane's scroll does — a
    /// jump past the end should land on the last card, not walk off it.
    pub fn move_selection_by(&mut self, cards: i32) {
        let len = self.column_cards(self.active_col).len();
        if len == 0 {
            self.selected = 0;
            return;
        }
        let next = i32::try_from(self.selected)
            .unwrap_or(i32::MAX)
            .saturating_add(cards);
        self.selected = next.clamp(0, i32::try_from(len).unwrap_or(i32::MAX) - 1) as usize;
    }

    pub fn clamp_selection(&mut self) {
        let cards = self.column_cards(self.active_col);
        if cards.is_empty() {
            self.selected = 0;
        } else if self.selected >= cards.len() {
            self.selected = cards.len() - 1;
        }
    }

    pub fn select_column(&mut self, col: usize) {
        let total = self.real_cols();
        if total > 0 {
            self.active_col = col % total;
        }
        self.clamp_selection();
    }

    pub(super) fn group_footer(cards: &[Card], mode: Option<&str>) -> Option<String> {
        let sections = Self::group_sections(cards, mode)?;
        let text = sections
            .into_iter()
            .map(|section| {
                let pct = (section.done * 100).checked_div(section.total).unwrap_or(0);
                format!("{} {}/{} {pct}%", section.name, section.done, section.total)
            })
            .collect::<Vec<_>>()
            .join(" | ");
        // The grouped board keeps **direct issue navigation** (FR-004): the card
        // cursor and `Enter` open the issue's own detail and edit, with the group
        // label only as the section above it. The route is stated beside the
        // partition rather than implied by the card text.
        Some(format!("{text}  ·  {GROUP_OPEN_AFFORDANCE}"))
    }

    pub(super) fn card_group(card: &Card, key: &str) -> String {
        match key {
            "cycle" => card.cycle.clone().unwrap_or_else(|| "(none)".to_string()),
            "milestone" => card
                .milestone
                .clone()
                .unwrap_or_else(|| "(none)".to_string()),
            // WP06 T028: the project bucket is read off the card's resolved
            // memberships, so a `group:project` board shows one section per project
            // in declaration order, then `(multiple projects)`, then the labelled
            // `(no project)` bucket last.
            "project" => project_bucket_label(&card.projects),
            // WP06 T030: the epic bucket, read off the card's resolved references
            // — one section per epic in declaration order, then `(multiple epics)`,
            // then the labelled `(no epic)` bucket last.
            "epic" => epic_bucket_label(&card.epics),
            _ => "(none)".to_string(),
        }
    }

    pub(super) fn group_sections(cards: &[Card], mode: Option<&str>) -> Option<Vec<GroupSection>> {
        let key =
            mode.filter(|m| *m == "cycle" || *m == "milestone" || *m == "project" || *m == "epic")?;
        if cards.is_empty() {
            return None;
        }
        let mut sections = Vec::new();
        let mut current = String::new();
        let mut start = 0usize;
        let mut done = 0usize;
        let mut total = 0usize;
        for (idx, card) in cards.iter().enumerate() {
            let group = Self::card_group(card, key);
            if idx == 0 {
                current = group;
            } else if group != current {
                sections.push(GroupSection {
                    name: std::mem::take(&mut current),
                    start,
                    end: idx,
                    done,
                    total,
                });
                current = group;
                start = idx;
                done = 0;
                total = 0;
            }
            total += 1;
            if card.done {
                done += 1;
            }
        }
        sections.push(GroupSection {
            name: current,
            start,
            end: cards.len(),
            done,
            total,
        });
        Some(sections)
    }
}

/// Render options carried from the active board configuration into the board
/// draw. Kept tiny and copyable so tests and call sites stay light.
#[derive(Debug, Clone, Copy)]
pub struct BoardDisplay {
    pub wrap_titles: bool,
    pub title_lines: usize,
}

impl Default for BoardDisplay {
    fn default() -> Self {
        BoardDisplay {
            wrap_titles: true,
            title_lines: 3,
        }
    }
}

impl From<&crate::config::BoardConfiguration> for BoardDisplay {
    fn from(config: &crate::config::BoardConfiguration) -> Self {
        BoardDisplay {
            wrap_titles: config.wrap_titles,
            title_lines: config.title_lines,
        }
    }
}