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

/// Draw the F6 Repos mode (tix #1529): the configured child repositories and,
/// when known, the parent. With none configured, a short instruction instead.
/// One row of the `F7` Health tab (mission `project-issue-health-status-01M3C8HX`).
pub struct HealthRow {
    /// The scope the row describes.
    pub scope: crate::health::HealthScope,
    /// The state, in the vocabulary's spelling.
    pub state: String,
    /// How the value was obtained: `current`, `derived` or `override`.
    pub layer: String,
    /// The derived rollup's one-line form, when the scope has contributors.
    pub derived: Option<String>,
}

/// The `F7` **Stats** page (WP06 T030-T033; WP05 T024–T027; WP06 T029–T032 of mission
/// `burndown-scope-analytics-01M3C9J1`): a tab strip over the **Health** tab the page
/// shipped with, the **Time** tab `per-issue-time-tracking-01M3C9A4` adds, and the
/// **Burndown** tab [`crate::ui::analytics`] adds over the shared analytics document.
///
/// A tab on a page that already exists, not a new mode — the rule
/// [`crate::ui::roadmap`] documents for the `F10` Portfolio page. The strip is one
/// row, the hint beneath it is the active tab's own, and each tab owns its body:
/// [`render_stats_health`] renders exactly the data `tix health board` and
/// `tix health show` expose, [`render_stats_time`] exactly the totals, entries and
/// findings the shared time DTOs hold, and [`render_stats_burndown`] exactly the chart
/// document `tix analytics burndown` reads.
pub(in crate::app) fn render_stats(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let block = Block::default().borders(Borders::ALL).title("Stats (F7)");
    let inner = block.inner(area);
    f.render_widget(block, area);
    if inner.height == 0 || inner.width == 0 {
        return;
    }
    let strip = Rect {
        x: inner.x,
        y: inner.y,
        width: inner.width,
        height: 1,
    };
    f.render_widget(Paragraph::new(stats_tab_line(app.stats_tab)), strip);
    if inner.height <= 1 {
        return;
    }
    let hint = Rect {
        x: inner.x,
        y: inner.y + 1,
        width: inner.width,
        height: 1,
    };
    f.render_widget(
        Paragraph::new(Span::styled(
            app.stats_tab.hint(),
            Style::default().fg(Color::DarkGray),
        )),
        hint,
    );
    if inner.height <= 2 {
        return;
    }
    let body = Rect {
        x: inner.x,
        y: inner.y + 2,
        width: inner.width,
        height: inner.height - 2,
    };
    match app.stats_tab {
        StatsTab::Health => render_stats_health(app, f, body),
        StatsTab::Time => render_stats_time(app, f, body),
        StatsTab::Burndown => render_stats_burndown(app, f, body),
    }
}

/// The page's tab strip: `F7 Stats` on the left, then every tab, the active one cyan
/// and bracketed — the same shape `crate::ui::portfolio`'s strip has, so the two
/// tabbed pages read alike.
pub(in crate::app) fn stats_tab_line(active: StatsTab) -> Line<'static> {
    let mut spans = vec![Span::styled(
        "F7 Stats ",
        Style::default()
            .fg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    )];
    for (index, tab) in StatsTab::ALL.iter().enumerate() {
        if index > 0 {
            spans.push(Span::raw(" "));
        }
        let style = if *tab == active {
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::DarkGray)
        };
        spans.push(Span::styled(format!("[{}]", tab.label()), style));
    }
    Line::from(spans)
}

/// One `label: value` line in the Stats page's own field style.
pub(in crate::app) fn stats_line(label: &str, value: &str) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("{label}: "), Style::default().fg(Color::DarkGray)),
        Span::raw(value.to_string()),
    ])
}

/// The `F7` Stats page, Health tab (WP06 T030-T033).
///
/// Renders exactly the data `tix health board` and `tix health show` expose — the
/// same document, the same policy version, the same contributors, the same
/// diagnostics with their remedies (C-007, and the mission's own surface contract).
/// Read-only: there is no key here that writes.
pub(in crate::app) fn render_stats_health(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let inner = area;
    if inner.height == 0 || inner.width == 0 {
        return;
    }

    let Some(document) = app.health.as_ref() else {
        f.render_widget(
            Paragraph::new(vec![Line::from(Span::styled(
                "Health is unavailable: the repository could not be read.",
                Style::default().fg(Color::Red),
            ))]),
            inner,
        );
        return;
    };

    let rows = app.stats_rows();
    let mut lines: Vec<Line<'static>> = Vec::new();
    let summary = crate::commands::health::HealthSummary::of(document);
    lines.push(Line::from(Span::styled(
        summary.render().trim_end().to_string(),
        Style::default().fg(Color::DarkGray),
    )));
    lines.push(Line::from(""));

    // The explicit empty state the surface contract asks for. It is a *banner* rather
    // than a replacement for the rows: every issue is in the document (C-006 makes a
    // legacy issue an explicit `unknown`), so a page that drew nothing until someone
    // recorded a value would hide the very issues the reader came to look at. "No
    // health is recorded" says what is missing, and the rows say where.
    let recorded_any = document.scopes.iter().any(|entry| entry.recorded.is_some());
    if !recorded_any {
        lines.push(Line::from(Span::styled(
            "No health is recorded.",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )));
        lines.push(Line::from(
            "Record a state with `tix health set <issue> --state <state> --rationale <why>`,",
        ));
        lines.push(Line::from(
            "or open an issue and press `H` to fill the form in.",
        ));
        lines.push(Line::from(""));
    }

    lines.push(Line::from(Span::styled(
        "  SCOPE             STATE             LAYER     DERIVED",
        Style::default().fg(Color::DarkGray),
    )));
    for (index, row) in rows.iter().enumerate() {
        let selected = index == app.stats_cursor;
        let marker = if selected { "> " } else { "  " };
        let style = if selected {
            Style::default().add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };
        let derived = row.derived.clone().unwrap_or_else(|| "-".to_string());
        lines.push(Line::from(Span::styled(
            format!(
                "{marker}{:<16}  {:<16}  {:<8}  {derived}",
                row.scope.as_str(),
                row.state,
                row.layer
            ),
            style,
        )));
    }

    if !document.diagnostics.is_empty() {
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!("{} diagnostics", document.diagnostics.len()),
            Style::default().fg(Color::DarkGray),
        )));
        for diagnostic in &document.diagnostics {
            let shared = diagnostic.to_diagnostic();
            lines.push(Line::from(format!(
                "{}  {}  {}",
                shared.kind.as_str(),
                shared.scope,
                shared.message
            )));
            if let Some(remedy) = &shared.remedy {
                lines.push(Line::from(Span::styled(
                    format!("  remedy: {remedy}"),
                    Style::default().fg(Color::DarkGray),
                )));
            }
        }
    }
    f.render_widget(Paragraph::new(lines), inner);
}

/// Parse a form's minutes field, or the message to show in the form.
///
/// The one refusal the TUI raises itself: the CLI receives `--minutes` as an integer
/// from `clap`, while a text field has to say what an integer looks like. Everything
/// else about the value — negative, absurd, missing — is the service's own validation
/// (`invalid_duration`), so "what a duration is" has one owner.
pub(in crate::app) fn feed_minutes(text: &str, hint: &str) -> std::result::Result<i64, String> {
    let text = text.trim();
    text.parse()
        .map_err(|_| format!("minutes {text:?} is not a whole number of minutes; {hint}"))
}

/// The issue column of the Time tab's entry table, so a scope spanning several issues
/// says which issue each row belongs to.
pub(in crate::app) fn time_issue_cell(issue: u32) -> String {
    format!("#{issue:<5}")
}

/// The `F7` Stats page, **Time** tab (WP05 T024–T027).
///
/// Everything drawn here is a field of a shared DTO or one of its own renderings: the
/// scope's total, its counts and its findings
/// ([`TimeTotal`](crate::time_tracking::aggregate::TimeTotal)), the entry rows
/// ([`TimeSnapshot::entries`](crate::time_tracking::aggregate::TimeSnapshot::entries)),
/// the breakdown's groups
/// ([`by_issue`](crate::time_tracking::aggregate::TimeSnapshot::by_issue) and its
/// siblings) and the audit view
/// ([`audit`](crate::time_tracking::aggregate::TimeSnapshot::audit)). Nothing is
/// summed, validated or grouped here, so the tab, `tix time …` and the detail pane
/// cannot disagree about a figure (C-006); an absent value is `-` and never a `0`
/// (T015), and the empty state is a sentence rather than a blank pane.
#[allow(clippy::too_many_lines)]
pub(in crate::app) fn render_stats_time(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let Some(state) = app.stats_time.as_ref() else {
        f.render_widget(
            Paragraph::new(vec![Line::from(Span::styled(
                "Time is unavailable: the issues could not be read.",
                Style::default().fg(Color::Red),
            ))]),
            area,
        );
        return;
    };
    let total = state.total();
    let rows = state.rows();
    let mut lines: Vec<Line<'static>> = Vec::new();

    lines.push(stats_line("scope", &total.filter.describe()));
    lines.push(stats_line("state", total.state().as_str()));
    lines.push(stats_line(
        "total_minutes",
        &crate::ui::detail::dash_number(total.total_minutes),
    ));
    lines.push(stats_line(
        "entries",
        &format!(
            "{} counted, {} malformed, {} undated",
            total.entry_count, total.malformed_count, total.undated_count
        ),
    ));
    lines.push(stats_line(
        "deleted",
        &crate::ui::detail::dash_number(total.deleted_count),
    ));

    // The state is the answer, and it is never inferred from a zero: a refused scope
    // counted nothing at all, `nothing` recorded none, `unknown` selected entries and
    // no usable number came back, and only `recorded` has a sum behind it.
    match total.state() {
        crate::time_tracking::aggregate::TimeTotalState::Recorded => {}
        crate::time_tracking::aggregate::TimeTotalState::Nothing => {
            lines.push(Line::from(Span::styled(
                "No time is recorded for this scope.",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            )));
        }
        crate::time_tracking::aggregate::TimeTotalState::Unknown => {
            // `unknown` has **two** producers and the sentence must be true for both:
            // every selected entry was malformed (findings exist, and they name each),
            // or the scope names a period and the valid entries it selected carry no
            // date — an entry no period can place, which the DTO counts as
            // `undated_count` and which produces **no** finding, because the entry
            // itself is fine (C-005). Promising findings there pointed a reader at
            // nothing; the undated section below is where those entries are named.
            let sentence = if total.malformed_count > 0 {
                "This scope selected entries and none carried a usable duration — the findings \
                 below name each."
            } else {
                "This scope names a period and the entries it selected carry no date, so no period \
                 can place them — the total is unknown, not a zero."
            };
            lines.push(Line::from(Span::styled(
                sentence,
                Style::default().fg(Color::Yellow),
            )));
        }
        crate::time_tracking::aggregate::TimeTotalState::InvalidFilter
        | crate::time_tracking::aggregate::TimeTotalState::UnknownIssue => {
            lines.push(Line::from(Span::styled(
                "The scope was refused: no entry was counted, and the findings below say what to \
                 change (`f` edits the filter).",
                Style::default()
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            )));
        }
    }
    if total.is_partial() {
        lines.push(Line::from(Span::styled(
            "The total is partial: the counts above name what it left out.",
            Style::default().fg(Color::Yellow),
        )));
    }

    // Malformed entries are reported, never hidden and never silently zero (T027).
    for finding in &total.diagnostics {
        lines.push(stats_line(
            "finding",
            &format!("{}: {}", finding.kind.as_str(), finding.reason),
        ));
        lines.push(stats_line("  remedy", &finding.remedy));
    }

    // An entry a period cannot place is **selected and reported**, never hidden: its
    // value is unknown to the period rather than zero (C-005), which is what
    // `undated_count` counts — and because the entry-level rows below can only show
    // what the period placed, the shared per-issue breakdown names the issues that
    // hold one, so a reader who sees `1 undated` can find it. Both numbers are the
    // DTO's own ([`TimeTotal::undated_count`] and `by_issue`'s groups).
    if total.undated_count > 0 {
        lines.push(stats_line(
            "undated",
            &format!(
                "{} — an entry that carries no date is in no period, so a period-bounded scope \
                 counts it as unplaceable (its value is unknown to the period, not zero)",
                total.undated_count
            ),
        ));
        let scope = state.scope();
        for group in state.snapshot.by_issue(&scope) {
            if group.undated_count == 0 {
                continue;
            }
            lines.push(Line::from(format!(
                "  {} holds {}",
                group.group.label(),
                group.undated_count
            )));
        }
        lines.push(stats_line(
            "  remedy",
            "drop the period bounds with `f`, or give the entry a date",
        ));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        format!("current entries ({})", rows.len()),
        Style::default()
            .fg(Color::DarkGray)
            .add_modifier(Modifier::BOLD),
    )));
    if rows.is_empty() {
        lines.push(Line::from(
            "  none — press `a` to add one, or `f` to widen the scope",
        ));
    } else {
        lines.push(Line::from(Span::styled(
            format!(
                "  {:<7} {}",
                "ISSUE",
                crate::ui::detail::time_entry_heading()
            ),
            Style::default().fg(Color::DarkGray),
        )));
        let selected = state.cursor.min(rows.len() - 1);
        for (index, indexed) in rows.iter().enumerate() {
            let marker = if index == selected { "> " } else { "  " };
            let style = if index == selected {
                Style::default().add_modifier(Modifier::BOLD)
            } else {
                Style::default()
            };
            lines.push(Line::from(Span::styled(
                format!(
                    "{marker}{} {}",
                    time_issue_cell(indexed.issue),
                    crate::ui::detail::time_entry_row(&indexed.entry)
                ),
                style,
            )));
        }
    }

    if state.breakdown != TimeBreakdown::All {
        let groups = state.groups();
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!(
                "breakdown by {} ({} groups)",
                state.breakdown.label(),
                groups.len()
            ),
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )));
        for group in &groups {
            lines.push(Line::from(format!(
                "  {:<14} {:<14} {:>9}  {} counted, {} malformed, {} undated",
                group.group.label(),
                group.state().as_str(),
                crate::ui::detail::dash_number(group.total_minutes),
                group.entry_count,
                group.malformed_count,
                group.undated_count,
            )));
        }
    }

    // The History side, on demand: what the current projection no longer holds is
    // still attributable, which is what makes a correction or a deletion auditable
    // rather than silent (C-003, C-004, FR-005).
    if state.audit {
        let audit = state.audit_view();
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            format!(
                "history (audit): {} deleted, {} corrected",
                audit.deleted_count, audit.corrected_count
            ),
            Style::default()
                .fg(Color::DarkGray)
                .add_modifier(Modifier::BOLD),
        )));
        for issue in &audit.issues {
            lines.push(Line::from(format!(
                "  #{}  current {}  deleted {}  corrected {}",
                issue.issue,
                issue.current,
                issue.deletions.len(),
                issue.corrections,
            )));
            for deletion in &issue.deletions {
                lines.push(Line::from(format!(
                    "      {} by {} at {}",
                    crate::ui::detail::dash_cell(deletion.entry_id.as_deref()),
                    crate::ui::detail::dash_cell(Some(deletion.deleted_by.as_str())),
                    crate::ui::detail::dash_cell(Some(deletion.deleted_at.as_str())),
                )));
            }
        }
        for finding in &audit.diagnostics {
            lines.push(stats_line(
                "  audit finding",
                &format!("{}: {}", finding.kind.as_str(), finding.reason),
            ));
        }
    }

    f.render_widget(Paragraph::new(lines), area);
}

/// The `F7` Stats page, **Burndown** tab (WP06 T029–T032).
///
/// Everything drawn here is built by [`crate::ui::analytics::frame`] under this module —
/// and that builder's body is the shared document's own fields: the resolved scope's
/// period and snapshot binding, the fold's formula version, day count, covered span and
/// coverage tally, each day's five values and its coverage marker, the forecast's status
/// and derived values, and every finding with its reason and its remedy. Nothing is
/// summed, converted, grouped or projected here, so the tab, `tix analytics burndown` and
/// the MCP summaries cannot disagree about a figure (C-008, NFR-003).
///
/// The body **scrolls** to keep the selected day visible: the day table is the one thing
/// on this page taller than a frame, and a cursor that could move off screen would be a
/// cursor the reader cannot see. The scope header scrolls with it — the strip and the hint
/// above the body are the page's, and stay put.
///
/// Read-only: there is no key on this tab that writes, and a render never reads the disk
/// (the fold behind the state is taken when the tab is opened and after each control).
pub(in crate::app) fn render_stats_burndown(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let Some(state) = app.stats_burndown.as_ref() else {
        f.render_widget(
            Paragraph::new(vec![Line::from(Span::styled(
                "Burndown is unavailable: the tab has not been read yet.",
                Style::default().fg(Color::Red),
            ))]),
            area,
        );
        return;
    };
    let body = crate::ui::analytics::frame(state);
    // Half a frame of lead-in, so the selected day sits mid-pane and the days around it
    // are readable; never past the end, so the last day can still reach the bottom row.
    let lead = usize::from(area.height / 2);
    let offset = body.cursor_line.saturating_sub(lead);
    let offset = u16::try_from(offset).unwrap_or(u16::MAX);
    f.render_widget(Paragraph::new(body.lines).scroll((offset, 0)), area);
}

/// The time-entry form's overlay (WP05 T025).
///
/// Drawn over the Time tab, which keeps rendering underneath, and its title says which
/// of the three mutations it will ask for. A refusal is drawn **inside** the form, so
/// the values the reader typed stay on screen beside the reason the submission did not
/// happen.
pub(in crate::app) fn render_time_form(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let Some(form) = app.time_form.as_ref() else {
        return;
    };
    let width = area.width.min(78);
    let height = area.height.min(12);
    let rect = Rect {
        x: area.x + (area.width.saturating_sub(width)) / 2,
        y: area.y + (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };
    let block = Block::default().borders(Borders::ALL).title(form.title());
    let inner = block.inner(rect);
    f.render_widget(Clear, rect);
    f.render_widget(block, rect);
    if inner.height == 0 {
        return;
    }
    let field = |index: usize, label: &str, value: &str| {
        let focused = form.field == index;
        Line::from(vec![
            Span::styled(format!("{label:<10}"), Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!("[{value}]"),
                if focused {
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                },
            ),
        ])
    };
    let mut lines: Vec<Line<'static>> = Vec::new();
    if form.is_add() {
        lines.push(field(0, "issue", &form.issue));
        lines.push(field(1, "minutes", &form.minutes));
        lines.push(field(2, "date", &form.date));
        lines.push(field(3, "author", &form.author));
        lines.push(field(4, "note", &form.note));
    } else if form.is_edit() {
        lines.push(field(0, "minutes", &form.minutes));
        lines.push(field(1, "date", &form.date));
        lines.push(field(2, "author", &form.author));
        lines.push(field(3, "note", &form.note));
        lines.push(field(4, "reason", &form.reason));
        lines.push(Line::from(Span::styled(
            "a blank field keeps the recorded value; the reason is required",
            Style::default().fg(Color::DarkGray),
        )));
    } else {
        lines.push(field(0, "reason", &form.reason));
        lines.push(field(
            1,
            "confirm",
            if form.confirm {
                "confirmed"
            } else {
                "press space to confirm"
            },
        ));
        lines.push(Line::from(Span::styled(
            "a deletion removes the current entry; its value and its event stay in History",
            Style::default().fg(Color::DarkGray),
        )));
    }
    if let Some(error) = &form.error {
        lines.push(Line::from(Span::styled(
            error.clone(),
            Style::default().fg(Color::Red),
        )));
    }
    lines.push(Line::from(Span::styled(
        "Tab: next field   space: confirm   Enter: submit   Esc: cancel",
        Style::default().fg(Color::DarkGray),
    )));
    f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

/// The Time tab's filter editor (WP05 T026).
///
/// The four criteria the shared `TimeFilter` is built from. Applying one writes
/// nothing; an unreadable bound is refused by that type's own validator, whose message
/// and remedy are drawn here while the form stays open.
pub(in crate::app) fn render_time_filter_form(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let Some(form) = app.time_filter_form.as_ref() else {
        return;
    };
    let width = area.width.min(72);
    let height = area.height.min(12);
    let rect = Rect {
        x: area.x + (area.width.saturating_sub(width)) / 2,
        y: area.y + (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };
    let block = Block::default().borders(Borders::ALL).title("Time filter");
    let inner = block.inner(rect);
    f.render_widget(Clear, rect);
    f.render_widget(block, rect);
    if inner.height == 0 {
        return;
    }
    let field = |index: usize, label: &str, value: &str| {
        let focused = form.field == index;
        Line::from(vec![
            Span::styled(format!("{label:<10}"), Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!("[{value}]"),
                if focused {
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                },
            ),
        ])
    };
    let mut lines = vec![
        field(0, "issue", &form.issue),
        field(1, "assignee", &form.assignee),
        field(2, "from", &form.from),
        field(3, "to", &form.to),
        Line::from(Span::styled(
            "blank criteria are dropped; the period is inclusive (`YYYY-MM-DD`)",
            Style::default().fg(Color::DarkGray),
        )),
    ];
    if let Some(error) = &form.error {
        lines.push(Line::from(Span::styled(
            error.clone(),
            Style::default().fg(Color::Red),
        )));
    }
    lines.push(Line::from(Span::styled(
        "Tab: next field   Enter: apply   Esc: cancel",
        Style::default().fg(Color::DarkGray),
    )));
    f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), inner);
}

/// The health form's overlay (WP06 T032).
///
/// Drawn over the page, and it says which layer it will write: `current` writes the
/// issue's own value, `override` layers a value over its derived one. The fields are
/// the CLI's own audit arguments, so the two surfaces accept the same mutation.
pub(in crate::app) fn render_health_form(app: &App, f: &mut ratatui::Frame, area: Rect) {
    let Some(form) = app.health_form.as_ref() else {
        return;
    };
    let width = area.width.min(72);
    let height = area.height.min(10);
    let rect = Rect {
        x: area.x + (area.width.saturating_sub(width)) / 2,
        y: area.y + (area.height.saturating_sub(height)) / 2,
        width,
        height,
    };
    let block = Block::default().borders(Borders::ALL).title(format!(
        "Health for #{} ({}, for {})",
        form.issue,
        form.layer_name(),
        "an issue's own value"
    ));
    let inner = block.inner(rect);
    f.render_widget(Clear, rect);
    f.render_widget(block, rect);
    if inner.height == 0 {
        return;
    }
    let field = |index: usize, label: &str, value: &str| {
        let focused = form.field == index;
        Line::from(vec![
            Span::styled(format!("{label:<10}"), Style::default().fg(Color::DarkGray)),
            Span::styled(
                format!("[{value}]"),
                if focused {
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD)
                } else {
                    Style::default()
                },
            ),
        ])
    };
    let lines = vec![
        field(0, "state", &form.state),
        field(1, "actor", &form.actor),
        field(2, "rationale", &form.rationale),
        field(3, "layer", form.layer_name()),
        Line::from(Span::styled(
            "Tab: next field   space: toggle layer   Enter: record   Esc: cancel",
            Style::default().fg(Color::DarkGray),
        )),
    ];
    f.render_widget(Paragraph::new(lines), inner);
}