perf-sentinel 0.29.0

CLI for perf-sentinel: polyglot performance anti-pattern detector
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
//! Terminal UI for interactive trace and finding inspection.
//!
//! Three top-level views form a single drill-down: `Analyze` (summary),
//! `Inspect` (the multi-panel browser: traces list, findings, correlations
//! and a detail span tree) and `Explain` (the selected trace's span tree
//! full screen). Enter descends `Analyze -> Inspect -> Explain`, Esc
//! ascends back.

use std::collections::HashMap;
use std::io;
use std::time::Duration;

use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, MouseButton,
    MouseEvent, MouseEventKind,
};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};

use sentinel_core::correlate::Trace;
#[cfg(feature = "daemon")]
use sentinel_core::daemon::query_api::AckSource;
use sentinel_core::detect::correlate_cross::CrossTraceCorrelation;
use sentinel_core::detect::{Finding, FindingType, Severity};
use sentinel_core::explain;
use sentinel_core::report::interpret::InterpretationLevel;
use sentinel_core::report::{Analysis, GreenSummary, QualityGate};
use sentinel_core::text_safety::{sanitize_for_terminal, strip_code_ticks};

use crate::disclose::DiscloseState;
use crate::tui_resize::{
    Axis, DragTarget, MIN_PCT, boundary_cell, in_range, near, pos_to_pct, set_cut,
};

#[cfg(feature = "daemon")]
use tokio::sync::mpsc;

#[cfg(feature = "daemon")]
pub use ack_modal::AckModalState;
#[cfg(feature = "daemon")]
use ack_modal::{AckOutcome, apply_ack_outcome, dispatch_modal_key, open_ack_modal_for_current};
use draw::draw;
#[cfg(feature = "daemon")]
pub(crate) use draw::{highlight_hline, highlight_vline, resize_highlight_style, tab_label_style};
/// Panel that currently has focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Panel {
    Traces,
    Findings,
    Detail,
    Correlations,
}

/// Top-level view in the drill-down. Enter descends
/// `Analyze -> Inspect -> Explain`, Esc ascends back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum View {
    /// Summary dashboard (`GreenOps` waste, top offenders, quality gate).
    Analyze,
    /// Multi-panel browser: traces, findings, correlations, detail.
    Inspect,
    /// The selected trace's annotated span tree, full screen.
    Explain,
    /// Read-only `disclose` preview: calendar stepper over the period,
    /// live intent/confidentiality toggles, aggregated summary, equivalent
    /// command. Standalone, with no drill-down to the other views.
    Disclose,
}

/// Summary data backing the Analyze view. Supplied by the launcher when
/// available. `None` degrades the view to a hint (e.g. an older daemon
/// without `/api/export/report`).
pub struct AnalyzeSummary {
    pub green_summary: GreenSummary,
    pub quality_gate: QualityGate,
    pub analysis: Analysis,
}

/// Order of the Inspect trace list. `s` cycles it: the TUI's primary
/// list is traces, so the severity/impact axes rank each trace by its
/// findings, mirroring the dashboard and `analyze --sort`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TraceSort {
    ById,
    Severity,
    Impact,
}

impl From<crate::render::FindingsSort> for TraceSort {
    fn from(mode: crate::render::FindingsSort) -> Self {
        match mode {
            crate::render::FindingsSort::Severity => Self::Severity,
            crate::render::FindingsSort::Impact => Self::Impact,
        }
    }
}

impl TraceSort {
    /// Impact leads: the list opens on it, and it is what a reader looks
    /// for. Id order stays one key away.
    fn next(self) -> Self {
        match self {
            Self::Impact => Self::Severity,
            Self::Severity => Self::ById,
            Self::ById => Self::Impact,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::ById => "id",
            Self::Severity => "severity",
            Self::Impact => "impact",
        }
    }
}

/// Signature tallies for a flat findings list, via the shared render
/// helpers so all surfaces agree on the key and the estimate.
fn build_recurrence(findings: &[Finding]) -> HashMap<String, crate::render::RecurrenceStats> {
    let mut index: HashMap<String, crate::render::RecurrenceStats> = HashMap::new();
    for f in findings {
        let entry = index.entry(crate::render::recurrence_key(f)).or_insert(
            crate::render::RecurrenceStats {
                count: 0,
                total_ops: 0,
            },
        );
        entry.count += 1;
        entry.total_ops += f
            .green_impact
            .as_ref()
            .map_or(0, |gi| gi.estimated_extra_io_ops);
    }
    index
}

/// Application state for the TUI.
pub struct App {
    pub traces: Vec<Trace>,
    /// All findings from the report (owned, flat list).
    all_findings: Vec<Finding>,
    /// Per-trace finding indices into `all_findings`.
    findings_by_trace: Vec<Vec<usize>>,
    /// `findings_by_trace` narrowed to `severity_filter`, the slice the
    /// Findings panel walks. Derived, never the source: the filter has to
    /// be reversible without re-reading the report.
    visible_by_trace: Vec<Vec<usize>>,
    /// Severity the Findings panel is narrowed to, `None` for all of
    /// them. The dashboard puts the same three values on pills.
    severity_filter: Option<Severity>,
    trace_ids: Vec<String>,
    trace_index: HashMap<String, usize>,

    /// Active top-level view. The panel-level `active_panel` only matters
    /// while `view == View::Inspect`.
    pub view: View,
    /// Summary backing the Analyze view. `None` renders a degraded hint.
    summary: Option<AnalyzeSummary>,
    /// Rendered line count of the Analyze body, precomputed by every
    /// builder that feeds it (the body is immutable afterwards) so the
    /// per-keypress scroll clamp does not rebuild the line vector.
    analyze_line_count: u16,

    /// Per-signature recurrence tallies over `all_findings`, computed
    /// once: the detail panel prints them and the impact sort ranks by
    /// them.
    recurrence: HashMap<String, crate::render::RecurrenceStats>,
    /// Aggregate avoidable ops of each finding's signature, indexed like
    /// `all_findings`. Resolved once: `recurrence_key` allocates a
    /// `String`, and the impact sorts would otherwise rebuild it twice
    /// per comparison, on every reorder and every Analyze redraw.
    avoidable_ops: Vec<u64>,
    /// Active order of the trace list.
    pub trace_sort: TraceSort,
    pub selected_trace: usize,
    pub selected_finding: usize,
    pub active_panel: Panel,
    pub scroll_offset: u16,
    /// Cached detail tree text per trace: (`trace_idx`, rendered tree).
    cached_detail: Option<(usize, String)>,
    /// Pre-rendered span trees keyed by `trace_id`, populated by callers
    /// that don't have raw spans in memory (e.g. `query inspect` which
    /// fetches trees from the daemon's `/api/explain/{trace_id}` endpoint).
    /// When `Some(text)`, takes precedence over the `build_tree` path that
    /// requires `traces[i].spans` to be populated.
    pre_rendered_trees: HashMap<String, String>,
    /// Cross-trace correlations to display in the Correlations panel.
    /// Empty in batch mode (correlator is daemon-only). Populated by
    /// `query inspect` from `/api/correlations`.
    correlations: Vec<CrossTraceCorrelation>,
    pub selected_correlation: usize,
    /// Report-level warnings, rendered at the top of the Analyze view.
    warnings: Vec<sentinel_core::report::warnings::Warning>,
    /// Panel that brought the user into Detail. Read by `escape` to
    /// return to the source panel (Findings or Correlations).
    detail_origin: Panel,

    /// Daemon URL when running under `query inspect`. `None` in batch
    /// mode (`inspect --input`), which disables `a`/`u` keys.
    #[cfg(feature = "daemon")]
    pub daemon_url: Option<String>,
    /// Resolved API key (env var or `--api-key-file`). `None` is a
    /// legitimate value when the daemon has no `[daemon.ack] api_key`.
    /// Used as the `X-API-Key` header on POST/DELETE ack writes.
    #[cfg(feature = "daemon")]
    pub api_key: Option<String>,
    /// Per-finding ack annotations keyed by signature. Populated at
    /// boot from `FindingResponse.acknowledged_by` and refreshed after
    /// every successful submit by `refetch_acks`.
    #[cfg(feature = "daemon")]
    pub acks_by_signature: HashMap<String, AckSource>,
    /// Modal overlay state for the ack/revoke flow. Hidden when not
    /// active. Drives `draw_ack_modal` and `handle_modal_key`.
    #[cfg(feature = "daemon")]
    pub ack_modal: AckModalState,

    /// Present only under `disclose --tui`. When `Some`, the tab bar shows
    /// just the standalone Disclose tab and the app opens on it. The
    /// analyze/inspect/explain drill-down is unused.
    disclose: Option<DiscloseState>,

    /// Inspect-view panel split ratios (percentages summing to 100),
    /// adjustable at runtime by dragging borders in mouse mode. `rows` is
    /// the vertical top/Detail split, `cols` is the Traces/Findings/
    /// Correlations top row. Reset to the defaults by `r`, not persisted.
    inspect_rows: [u16; 2],
    inspect_cols: [u16; 3],
    /// Mouse capture is opt-in (toggled by `m`): off preserves native
    /// terminal copy-paste, on lets borders be dragged.
    mouse_mode: bool,
    /// Border currently being dragged, set on mouse-down over a border.
    drag: Option<DragTarget>,
    /// Border currently under the cursor, set on mouse motion. Drives the
    /// resize-affordance highlight so the user sees a border is grabbable.
    hover: Option<DragTarget>,
    /// Inspect content area from the last frame, for hit-testing a drag.
    /// `Cell` lets `draw_inspect_view` store it through `&App`.
    inspect_area: std::cell::Cell<Rect>,
}

/// Default Inspect split ratios, also the `r`-reset target.
const INSPECT_ROWS_DEFAULT: [u16; 2] = [50, 50];
const INSPECT_COLS_DEFAULT: [u16; 3] = [20, 30, 50];

impl App {
    /// Create a new app from analysis findings and traces.
    #[must_use]
    pub fn new(findings: Vec<Finding>, mut traces: Vec<Trace>) -> Self {
        // Sort by trace_id: the upstream `correlate` stage yields traces in
        // randomized HashMap order, so without this the same input file
        // shows a different trace-list order on every launch. Unstable sort
        // is fine (trace_ids are unique) and avoids the merge-sort
        // allocation.
        traces.sort_unstable_by(|a, b| a.trace_id.cmp(&b.trace_id));

        let trace_ids: Vec<String> = traces.iter().map(|t| t.trace_id.clone()).collect();
        let trace_index: HashMap<String, usize> = traces
            .iter()
            .enumerate()
            .map(|(i, t)| (t.trace_id.clone(), i))
            .collect();

        let mut findings_by_trace: Vec<Vec<usize>> = vec![Vec::new(); traces.len()];
        for (idx, finding) in findings.iter().enumerate() {
            if let Some(&trace_vec_idx) = trace_index.get(&finding.trace_id) {
                findings_by_trace[trace_vec_idx].push(idx);
            }
        }

        let recurrence = build_recurrence(&findings);
        let avoidable_ops: Vec<u64> = findings
            .iter()
            .map(|f| {
                recurrence
                    .get(&crate::render::recurrence_key(f))
                    .map_or(0, |s| s.total_ops) as u64
            })
            .collect();

        let mut app = Self {
            traces,
            recurrence,
            avoidable_ops,
            // Opens on the named default (impact): the costliest problems
            // first, matching the dashboard and the embedded trees. Derived
            // rather than written, so the two surfaces cannot drift.
            trace_sort: crate::render::FindingsSort::default().into(),
            all_findings: findings,
            visible_by_trace: findings_by_trace.clone(),
            findings_by_trace,
            severity_filter: None,
            trace_ids,
            trace_index,
            view: View::Inspect,
            summary: None,
            analyze_line_count: 0,
            selected_trace: 0,
            selected_finding: 0,
            active_panel: Panel::Traces,
            scroll_offset: 0,
            cached_detail: None,
            pre_rendered_trees: HashMap::new(),
            correlations: Vec::new(),
            warnings: Vec::new(),
            selected_correlation: 0,
            detail_origin: Panel::Findings,
            #[cfg(feature = "daemon")]
            daemon_url: None,
            #[cfg(feature = "daemon")]
            api_key: None,
            #[cfg(feature = "daemon")]
            acks_by_signature: HashMap::new(),
            #[cfg(feature = "daemon")]
            ack_modal: AckModalState::default(),
            disclose: None,
            inspect_rows: INSPECT_ROWS_DEFAULT,
            inspect_cols: INSPECT_COLS_DEFAULT,
            mouse_mode: false,
            drag: None,
            hover: None,
            inspect_area: std::cell::Cell::new(Rect::default()),
        };
        // The state above says impact, so the list must be sorted that way
        // before the first paint, or the header would name an order the
        // list does not follow.
        app.reorder_traces();
        app
    }

    /// Attach the `disclose --tui` preview state. The caller pairs this with
    /// `with_initial_view(View::Disclose)`. The App is otherwise built with
    /// empty findings/traces.
    pub(crate) fn with_disclose(mut self, state: DiscloseState) -> Self {
        self.disclose = Some(state);
        self
    }

    /// Attach a daemon handle so `a`/`u` keys are active. Used by
    /// `query inspect` to wire the TUI into the live daemon ack flow.
    /// Without this, the TUI is read-only and the keys are no-op.
    #[cfg(feature = "daemon")]
    pub(crate) fn with_daemon_handle(
        mut self,
        daemon_url: String,
        api_key: Option<String>,
        acks_by_signature: HashMap<String, AckSource>,
    ) -> Self {
        self.daemon_url = Some(daemon_url);
        self.api_key = api_key;
        self.acks_by_signature = acks_by_signature;
        self
    }

    /// Attach pre-rendered span trees keyed by `trace_id`. Used by
    /// `query inspect` to populate the detail panel from daemon
    /// responses when the CLI has no raw spans.
    ///
    /// `pub(crate)` because the TUI module is internal to the
    /// `perf-sentinel` binary crate, not a published library API.
    // Only the daemon-gated `query inspect` flow calls this in
    // production; tests exercise it in every feature combo.
    #[cfg_attr(not(feature = "daemon"), allow(dead_code))]
    pub(crate) fn with_pre_rendered_trees(mut self, trees: HashMap<String, String>) -> Self {
        self.pre_rendered_trees = trees;
        self
    }

    /// Attach cross-trace correlations fetched from a daemon. The
    /// Correlations panel renders them as a navigable list.
    pub(crate) fn with_correlations(mut self, correlations: Vec<CrossTraceCorrelation>) -> Self {
        self.correlations = correlations;
        self
    }

    /// Attach the report's own warnings, which say what the numbers
    /// below them do not cover (dropped spans, an ignored config
    /// section, a truncated snapshot). The text report and the
    /// dashboard show them too. Without them the TUI reads as a
    /// complete report when it is a partial one.
    pub(crate) fn with_warnings(
        mut self,
        warnings: Vec<sentinel_core::report::warnings::Warning>,
    ) -> Self {
        self.warnings = warnings;
        // Warnings are part of the Analyze body, so the cached line count
        // has to follow them. Without this the degraded no-summary path
        // (which never calls `with_summary`) would keep a count of 0, so the
        // view could not be scrolled to the warnings past the viewport. The
        // builder order would also silently decide whether they count.
        self.refresh_analyze_line_count();
        self
    }

    /// Recompute the cached Analyze line count from the current body.
    /// Called by every builder that feeds that body, so the scroll clamp
    /// never trails the content regardless of the call order.
    fn refresh_analyze_line_count(&mut self) {
        self.analyze_line_count =
            u16::try_from(self.build_analyze_lines().len()).unwrap_or(u16::MAX);
    }

    /// Attach the summary backing the Analyze view (`GreenOps` waste, top
    /// offenders, quality gate). Without it the view shows a hint.
    pub(crate) fn with_summary(mut self, summary: AnalyzeSummary) -> Self {
        self.summary = Some(summary);
        // Build the body once to cache its line count. The summary and
        // findings are immutable afterwards, so the count never changes.
        self.refresh_analyze_line_count();
        self
    }

    /// Set the view the TUI opens on. `analyze --tui` lands on Analyze,
    /// `explain --tui` on Explain, `inspect` keeps the default Inspect.
    pub(crate) fn with_initial_view(mut self, view: View) -> Self {
        self.view = view;
        self
    }

    /// Pre-select a trace by id so the opening view (e.g. Explain for
    /// `explain --tui`) lands on it. No-op when the id is unknown.
    pub(crate) fn with_focus_trace(mut self, trace_id: &str) -> Self {
        if let Some(&idx) = self.trace_index.get(trace_id) {
            self.selected_trace = idx;
            self.selected_finding = 0;
            self.cached_detail = None;
        }
        self
    }

    /// Number of correlations available in the Correlations panel.
    #[must_use]
    pub fn correlation_count(&self) -> usize {
        self.correlations.len()
    }

    /// Number of traces available.
    #[must_use]
    pub fn trace_count(&self) -> usize {
        self.trace_ids.len()
    }

    /// Number of findings for the currently selected trace.
    #[must_use]
    pub fn finding_count(&self) -> usize {
        self.current_finding_indices().len()
    }

    /// Finding indices for the currently selected trace.
    fn current_finding_indices(&self) -> &[usize] {
        self.visible_by_trace
            .get(self.selected_trace)
            .map_or(&[], Vec::as_slice)
    }

    /// Currently selected finding, if any.
    pub(crate) fn current_finding(&self) -> Option<&Finding> {
        let indices = self.current_finding_indices();
        indices
            .get(self.selected_finding)
            .map(|&idx| &self.all_findings[idx])
    }

    /// Count the logical lines the Detail panel will render for the
    /// currently selected finding.
    ///
    /// Mirrors the line construction in [`draw_detail_panel`](draw::draw_detail_panel): keep the
    /// two in sync (the body comments track the per-row arithmetic).
    ///
    /// Used by [`App::move_down`] to clamp the Detail-panel scroll offset
    /// so `Down`/`j` cannot scroll past the content. Long wrapped lines
    /// count as one logical line, so the clamp is slightly conservative
    /// on wrapped output, accepted since ratatui does not expose the
    /// panel width at event-handling time.
    fn detail_panel_line_count(&self) -> u16 {
        let Some(finding) = self.current_finding() else {
            return 0;
        };
        // 7 always-present metadata rows (Namespace prints "-" when the
        // finding carries none) + 1 blank after the type header.
        let mut count: u16 = 8;
        // +1 for the optional "Source:" row that `draw_detail_panel` inserts
        // when the finding carries a non-empty code location, else the clamp
        // under-counts by 1 and the last span-tree line stays unreachable.
        if finding
            .code_location
            .as_ref()
            .is_some_and(|loc| !loc.display_string().is_empty())
        {
            count = count.saturating_add(1);
        }
        if finding.suggested_fix.is_some() {
            count = count.saturating_add(1);
        }
        // Timing only exists on the detectors that measure per-span
        // durations, classification only inside the n+1 family, and the
        // confidence row is absent on a batch run. The observation
        // window is unconditional, hence not counted here but in the
        // always-present rows below.
        if crate::render::format_span_timing(&finding.pattern).is_some() {
            count = count.saturating_add(1);
        }
        if crate::render::classification_label(finding).is_some() {
            count = count.saturating_add(1);
        }
        if !finding.confidence.is_batch() {
            count = count.saturating_add(1);
        }
        // The unconditional "Window:" row.
        count = count.saturating_add(1);
        if finding.green_impact.is_some() {
            count = count.saturating_add(1);
        }
        if let Some((ct, ref text)) = self.cached_detail
            && ct == self.selected_trace
        {
            // +2 for blank + "Span tree:" header, +N for the tree lines.
            let tree_count = u16::try_from(text.lines().count()).unwrap_or(u16::MAX);
            count = count.saturating_add(2).saturating_add(tree_count);
        } else {
            // +2 for blank + "Span tree:" header, +3 for the hint lines.
            count = count.saturating_add(5);
        }
        count
    }

    /// Get the cached detail tree text, computing it if needed.
    ///
    /// Cached per trace (not per finding): `build_tree` annotates every
    /// finding of the trace inline, so the tree is the same for all of them.
    fn detail_tree_text(&mut self) -> Option<String> {
        let trace_idx = self.selected_trace;

        if let Some((ct, ref text)) = self.cached_detail
            && ct == trace_idx
        {
            return Some(text.clone());
        }

        let trace_id = self.trace_ids.get(trace_idx)?.clone();

        // Prefer the pre-rendered tree (populated by `query inspect` from
        // daemon API responses) over the local build_tree path. This lets
        // the TUI display real span trees even when the caller has no raw
        // spans in memory.
        if let Some(text) = self.pre_rendered_trees.get(&trace_id) {
            let text = text.clone();
            self.cached_detail = Some((trace_idx, text.clone()));
            return Some(text);
        }

        let trace_vec_idx = self.trace_index.get(&trace_id).copied()?;
        let trace = &self.traces[trace_vec_idx];
        // When spans are empty (e.g. stub traces from `query inspect` without
        // pre-rendered trees), skip the build_tree path that would produce
        // an empty, confusing panel.
        if trace.spans.is_empty() {
            return None;
        }
        // The report's own findings for this trace, never a re-detection.
        // Spans rebuilt from a snapshot's masked trees carry no params and
        // a `?` template. The sanitizer-aware classifier reads those as
        // already-parameterized and suppresses the detection, which would
        // draw a clean tree under the finding the user selected. Reusing the
        // report's findings also keeps the tree consistent with
        // acknowledgment filtering.
        let per_trace_findings: Vec<Finding> = self.findings_by_trace[trace_vec_idx]
            .iter()
            .filter_map(|&i| self.all_findings.get(i).cloned())
            .collect();
        let tree = explain::build_tree(trace, &per_trace_findings);
        let text = explain::format_tree_text(&tree, false);
        self.cached_detail = Some((trace_idx, text.clone()));
        Some(text)
    }

    /// Cycle the Inspect trace order: aggregate-impact-first, which is
    /// what it opens on, then worst-severity-first, then id, the other
    /// axis breaking ties.
    pub fn cycle_trace_sort(&mut self) {
        self.trace_sort = self.trace_sort.next();
        self.reorder_traces();
    }

    /// Cycle the Findings panel between every severity and each one on
    /// its own, the same three values the dashboard puts on pills. A
    /// trace whose findings are all filtered out stays in the list with
    /// an empty panel rather than disappearing: the trace list answers
    /// "what ran", not "what matches".
    pub fn cycle_severity_filter(&mut self) {
        self.severity_filter = match self.severity_filter {
            None => Some(Severity::Critical),
            Some(Severity::Critical) => Some(Severity::Warning),
            Some(Severity::Warning) => Some(Severity::Info),
            Some(Severity::Info) => None,
        };
        self.apply_finding_filter();
    }

    /// Label for the Findings panel title, so the narrowed list says so.
    fn severity_filter_label(&self) -> &'static str {
        match self.severity_filter {
            None => "all",
            Some(Severity::Critical) => "critical",
            Some(Severity::Warning) => "warning",
            Some(Severity::Info) => "info",
        }
    }

    /// Rebuild the visible slices from the sorted source. Called on
    /// every filter change and after any reorder, since the derived
    /// vector would otherwise keep the previous order.
    fn apply_finding_filter(&mut self) {
        let findings = &self.all_findings;
        let wanted = self.severity_filter.as_ref();
        self.visible_by_trace = self
            .findings_by_trace
            .iter()
            .map(|indices| {
                indices
                    .iter()
                    .copied()
                    .filter(|&i| wanted.is_none_or(|s| findings[i].severity == *s))
                    .collect()
            })
            .collect();
        self.selected_finding = 0;
        self.scroll_offset = 0;
    }

    /// Re-sort the trace list under the active mode. Severity and impact
    /// go through the shared comparator so this surface cannot drift from
    /// `analyze --sort` and the dashboard, with the trace id as a final
    /// tie-break for a stable list.
    fn reorder_traces(&mut self) {
        let mut order: Vec<usize> = (0..self.traces.len()).collect();
        let mode = match self.trace_sort {
            TraceSort::ById => {
                order.sort_by(|&a, &b| self.trace_ids[a].cmp(&self.trace_ids[b]));
                self.apply_trace_order(&order);
                return;
            }
            TraceSort::Severity => crate::render::FindingsSort::Severity,
            TraceSort::Impact => crate::render::FindingsSort::Impact,
        };
        order.sort_by(|&a, &b| {
            crate::render::compare_severity_impact(
                mode,
                (&self.trace_rank(a), self.trace_ops(a) as u64),
                (&self.trace_rank(b), self.trace_ops(b) as u64),
            )
            .then_with(|| self.trace_ids[a].cmp(&self.trace_ids[b]))
        });
        self.apply_trace_order(&order);
    }

    /// Rank the findings inside each trace under the active mode, on the
    /// same comparator as the trace list and the dashboard. Without this
    /// the key would order the outer list while the inner one would keep
    /// detector order, so a trace ranked worst-first would open on
    /// whichever finding the detector emitted first. `ById` restores the
    /// report's own order, which is the index order in `all_findings`.
    fn reorder_findings(&mut self) {
        let mode = match self.trace_sort {
            TraceSort::ById => {
                for indices in &mut self.findings_by_trace {
                    indices.sort_unstable();
                }
                self.apply_finding_filter();
                return;
            }
            TraceSort::Severity => crate::render::FindingsSort::Severity,
            TraceSort::Impact => crate::render::FindingsSort::Impact,
        };
        // Impact ranks on the signature's aggregate avoidable ops, the
        // same figure `sort_findings` and the dashboard rank on, not on
        // this one detection's own count.
        let findings = &self.all_findings;
        let ops = &self.avoidable_ops;
        let mut sorted = std::mem::take(&mut self.findings_by_trace);
        for indices in &mut sorted {
            indices.sort_by(|&a, &b| {
                crate::render::compare_severity_impact(
                    mode,
                    (&findings[a].severity, ops[a]),
                    (&findings[b].severity, ops[b]),
                )
                // Index order as the final tie-break keeps the list
                // stable between two renders of the same data.
                .then(a.cmp(&b))
            });
        }
        self.findings_by_trace = sorted;
        self.apply_finding_filter();
    }

    /// Open the list in `mode` without cycling, for callers that were
    /// given an explicit `--sort`.
    pub fn with_initial_sort(mut self, mode: Option<crate::render::FindingsSort>) -> Self {
        if let Some(mode) = mode {
            let target = TraceSort::from(mode);
            // The constructor already ordered the list for its own default,
            // so asking for that same order must not sort it twice.
            if target != self.trace_sort {
                self.trace_sort = target;
                self.reorder_traces();
            }
        }
        self
    }

    /// Worst severity among the trace's findings. Severity orders
    /// Critical < Warning < Info, so worst = min, and a finding-less
    /// trace sorts last.
    fn trace_rank(&self, idx: usize) -> Severity {
        self.findings_by_trace[idx]
            .iter()
            .map(|&i| self.all_findings[i].severity.clone())
            .min()
            .unwrap_or(Severity::Info)
    }

    /// Aggregate avoidable ops of the signatures this trace's findings
    /// belong to, the same figure the detail panel prints.
    fn trace_ops(&self, idx: usize) -> usize {
        self.findings_by_trace[idx]
            .iter()
            .map(|&i| {
                let key = crate::render::recurrence_key(&self.all_findings[i]);
                self.recurrence.get(&key).map_or(0, |s| s.total_ops)
            })
            .sum()
    }

    /// Re-permute every trace-indexed structure and reset the cursor:
    /// a stale index after a reorder would point detail caches at the
    /// wrong trace.
    fn apply_trace_order(&mut self, order: &[usize]) {
        let mut traces: Vec<Option<Trace>> = std::mem::take(&mut self.traces)
            .into_iter()
            .map(Some)
            .collect();
        self.traces = order
            .iter()
            .map(|&i| traces[i].take().expect("permutation"))
            .collect();
        let mut ids: Vec<Option<String>> = std::mem::take(&mut self.trace_ids)
            .into_iter()
            .map(Some)
            .collect();
        self.trace_ids = order
            .iter()
            .map(|&i| ids[i].take().expect("permutation"))
            .collect();
        let mut by_trace: Vec<Option<Vec<usize>>> = std::mem::take(&mut self.findings_by_trace)
            .into_iter()
            .map(Some)
            .collect();
        self.findings_by_trace = order
            .iter()
            .map(|&i| by_trace[i].take().expect("permutation"))
            .collect();
        self.trace_index = self
            .trace_ids
            .iter()
            .enumerate()
            .map(|(i, id)| (id.clone(), i))
            .collect();
        self.selected_trace = 0;
        self.selected_finding = 0;
        self.cached_detail = None;
        // A stale offset would render the new trace's tree scrolled past
        // its own content, showing a blank panel.
        self.scroll_offset = 0;
        // The inner lists follow the same mode as the outer one, and the
        // visible slices index into the permuted source, so both are
        // rebuilt here (`reorder_findings` ends on `apply_finding_filter`)
        // rather than left for the caller to remember.
        self.reorder_findings();
    }

    /// Move selection up in the active panel.
    pub fn move_up(&mut self) {
        match self.active_panel {
            Panel::Traces => {
                if self.selected_trace > 0 {
                    self.selected_trace -= 1;
                    self.selected_finding = 0;
                    self.scroll_offset = 0;
                    self.cached_detail = None;
                }
            }
            Panel::Findings => {
                if self.selected_finding > 0 {
                    self.selected_finding -= 1;
                    self.scroll_offset = 0;
                }
            }
            Panel::Detail => {
                self.scroll_offset = self.scroll_offset.saturating_sub(1);
            }
            Panel::Correlations => {
                if self.selected_correlation > 0 {
                    self.selected_correlation -= 1;
                }
            }
        }
    }

    /// Move selection down in the active panel.
    pub fn move_down(&mut self) {
        match self.active_panel {
            Panel::Traces => {
                if self.selected_trace + 1 < self.trace_count() {
                    self.selected_trace += 1;
                    self.selected_finding = 0;
                    self.scroll_offset = 0;
                    self.cached_detail = None;
                }
            }
            Panel::Findings => {
                if self.selected_finding + 1 < self.finding_count() {
                    self.selected_finding += 1;
                    self.scroll_offset = 0;
                }
            }
            Panel::Detail => {
                // Clamp to `line_count - 1` so the last logical line stays
                // at least partially visible at the top of the viewport
                // when fully scrolled down. Prevents infinite scroll past
                // the content (which would leave the panel blank).
                let max_offset = self.detail_panel_line_count().saturating_sub(1);
                if self.scroll_offset < max_offset {
                    self.scroll_offset = self.scroll_offset.saturating_add(1);
                }
            }
            Panel::Correlations => {
                if self.selected_correlation + 1 < self.correlation_count() {
                    self.selected_correlation += 1;
                }
            }
        }
    }

    /// Move focus to the next panel.
    pub fn next_panel(&mut self) {
        self.active_panel = match self.active_panel {
            Panel::Traces => Panel::Findings,
            Panel::Findings => Panel::Detail,
            Panel::Detail => Panel::Correlations,
            Panel::Correlations => Panel::Traces,
        };
    }

    /// Move focus to the previous panel.
    pub fn prev_panel(&mut self) {
        self.active_panel = match self.active_panel {
            Panel::Traces => Panel::Correlations,
            Panel::Findings => Panel::Traces,
            Panel::Detail => Panel::Findings,
            Panel::Correlations => Panel::Detail,
        };
    }

    /// Flip mouse mode and, when turning it off, cancel any in-progress
    /// drag. The terminal capture side-effect is applied by the caller via
    /// [`set_mouse_capture`], keeping this pure and unit-testable.
    fn toggle_mouse_mode(&mut self) {
        self.mouse_mode = !self.mouse_mode;
        if !self.mouse_mode {
            self.drag = None;
            self.hover = None;
        }
    }

    /// Reset the Inspect split ratios to their defaults (`r`).
    fn reset_layout(&mut self) {
        self.inspect_rows = INSPECT_ROWS_DEFAULT;
        self.inspect_cols = INSPECT_COLS_DEFAULT;
    }

    /// Whether a mouse drag should resize panels right now. Only in the
    /// Inspect view (the sole resizable layout) and never behind the ack
    /// modal, which captures keys but not the mouse.
    fn accepts_panel_drag(&self) -> bool {
        if self.view != View::Inspect {
            return false;
        }
        #[cfg(feature = "daemon")]
        if self.ack_modal.is_visible() {
            return false;
        }
        true
    }

    /// Border (if any) under the cursor, using the last drawn Inspect area.
    fn hit_test(&self, col: u16, row: u16) -> Option<DragTarget> {
        let area = self.inspect_area.get();
        if area.width == 0 || area.height == 0 {
            return None;
        }
        // Horizontal borders live in the top row. They are checked before
        // the vertical border so the vertical ±1 tolerance can't shadow
        // the top row's bottom cell.
        let top_h = u16::try_from(u32::from(area.height) * u32::from(self.inspect_rows[0]) / 100)
            .unwrap_or(area.height);
        if in_range(row, area.y, top_h) {
            for b in 0..self.inspect_cols.len() - 1 {
                if near(
                    col,
                    boundary_cell(&self.inspect_cols, b, area.x, area.width),
                ) {
                    return Some(DragTarget {
                        axis: Axis::Horizontal,
                        boundary: b,
                    });
                }
            }
        }
        // Vertical border between the top row and the Detail panel.
        let vy = boundary_cell(&self.inspect_rows, 0, area.y, area.height);
        if near(row, vy) && in_range(col, area.x, area.width) {
            return Some(DragTarget {
                axis: Axis::Vertical,
                boundary: 0,
            });
        }
        None
    }

    /// Mouse-down: if the cursor is on a panel border, start dragging it.
    fn begin_drag(&mut self, col: u16, row: u16) {
        self.drag = self.hit_test(col, row);
    }

    /// The border highlighted right now: the one being dragged, else the
    /// one hovered. Drives the resize-affordance overlay.
    fn resize_target(&self) -> Option<DragTarget> {
        self.drag.or(self.hover)
    }

    /// Mouse-drag: move the active border to the cursor.
    fn apply_drag(&mut self, col: u16, row: u16) {
        let Some(target) = self.drag else {
            return;
        };
        let area = self.inspect_area.get();
        match target.axis {
            Axis::Vertical => set_cut(
                &mut self.inspect_rows,
                target.boundary,
                pos_to_pct(row, area.y, area.height),
                MIN_PCT,
            ),
            Axis::Horizontal => set_cut(
                &mut self.inspect_cols,
                target.boundary,
                pos_to_pct(col, area.x, area.width),
                MIN_PCT,
            ),
        }
    }

    /// Handle Enter key: drill into the next panel.
    ///
    /// - Traces -> Findings (when there are findings)
    /// - Findings -> Detail
    /// - Correlations -> Detail (jumps to `sample_trace_id` if known locally)
    /// - Detail -> Explain view (zooms the span tree full screen)
    pub fn enter(&mut self) {
        match self.active_panel {
            Panel::Traces => {
                if self.finding_count() > 0 {
                    self.active_panel = Panel::Findings;
                    self.selected_finding = 0;
                }
            }
            Panel::Findings => {
                self.enter_detail(Panel::Findings);
            }
            Panel::Correlations => {
                self.jump_to_correlation_sample_trace();
            }
            Panel::Detail => {
                // Deepest panel: zoom the span tree to the full-screen
                // Explain view.
                self.view = View::Explain;
                self.scroll_offset = 0;
            }
        }
    }

    /// Single entry point for any drill-down to `Panel::Detail`. Pairs
    /// `active_panel` with `detail_origin` so `escape` returns to the
    /// source panel. New drill-downs MUST route through this helper.
    fn enter_detail(&mut self, origin: Panel) {
        self.active_panel = Panel::Detail;
        self.detail_origin = origin;
        self.scroll_offset = 0;
    }

    /// Jump from Correlations to Detail for the selected correlation's
    /// `sample_trace_id`. No-op if the trace is unknown locally.
    fn jump_to_correlation_sample_trace(&mut self) {
        let Some(correlation) = self.correlations.get(self.selected_correlation) else {
            return;
        };
        let Some(sample_trace_id) = correlation.sample_trace_id.as_deref() else {
            return;
        };
        let Some(&position) = self.trace_index.get(sample_trace_id) else {
            return;
        };
        if position != self.selected_trace {
            self.selected_trace = position;
            self.cached_detail = None;
        }
        self.selected_finding = 0;
        self.enter_detail(Panel::Correlations);
    }

    /// Handle Escape: go back to previous panel. Detail returns to
    /// `detail_origin` (Findings or Correlations) so the operator lands
    /// back where the drill-down started.
    pub fn escape(&mut self) {
        match self.active_panel {
            // Top-level panels (reached by Tab cycling, not drilled into):
            // ascend to the Analyze view. The active panel is preserved so
            // descending lands back here, and both honor the tab-bar "Esc up"
            // hint rather than leaving Correlations a dead end.
            Panel::Traces | Panel::Correlations => {
                self.view = View::Analyze;
                self.scroll_offset = 0;
            }
            Panel::Findings => self.active_panel = Panel::Traces,
            Panel::Detail => self.active_panel = self.detail_origin,
        }
    }

    /// Logical line count of the Analyze view body, used to clamp the
    /// scroll offset. Returns the value cached by the builders that feed
    /// the body (`with_summary`, `with_warnings`) so the per-keypress
    /// clamp does not rebuild the line vector.
    fn analyze_content_line_count(&self) -> u16 {
        self.analyze_line_count
    }

    /// Logical line count of the Explain view body (the cached span tree
    /// for the selected trace, or the short unavailability hint).
    fn explain_content_line_count(&self) -> u16 {
        match &self.cached_detail {
            Some((ct, text)) if *ct == self.selected_trace => {
                u16::try_from(text.lines().count()).unwrap_or(u16::MAX)
            }
            _ => 2,
        }
    }

    /// Per-severity finding counts `(critical, warning, info)` over all
    /// findings, for the Analyze view header.
    fn severity_counts(&self) -> (usize, usize, usize) {
        let mut counts = (0usize, 0usize, 0usize);
        for finding in &self.all_findings {
            match finding.severity {
                Severity::Critical => counts.0 += 1,
                Severity::Warning => counts.1 += 1,
                Severity::Info => counts.2 += 1,
            }
        }
        counts
    }

    /// The report's warnings, pushed first so what the figures do not
    /// cover is read before the figures. Same content and same order as
    /// the text report and the dashboard banner.
    fn push_warning_lines(&self, lines: &mut Vec<Line<'static>>) {
        if self.warnings.is_empty() {
            return;
        }
        lines.push(Line::from(Span::styled(
            "Warnings:".to_string(),
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )));
        for w in &self.warnings {
            // Backticks live in the data so the HTML can render code
            // chips. A terminal shows them as literal noise.
            let plain = strip_code_ticks(&w.message);
            lines.push(Line::from(Span::raw(format!(
                "  [{}] {}",
                sanitize_for_terminal(&w.kind),
                sanitize_for_terminal(&plain),
            ))));
        }
        lines.push(Line::from(""));
    }

    /// Number of rows in the Analyze view's "Top findings" section, the
    /// same cut the dashboard's Overview card makes.
    const TOP_FINDINGS_ROWS: usize = 5;

    /// The worst findings across every trace, ranked by the signature's
    /// aggregate avoidable I/O with severity as the tie-break, the
    /// `FindingsSort::Impact` contract the dashboard's Overview card and
    /// `analyze --sort impact` already share. "Top offenders" above ranks
    /// endpoints by intensity, which answers a different question: where
    /// the waste is, not which problem to open first.
    fn push_top_findings_lines(&self, lines: &mut Vec<Line<'static>>, dim: Style) {
        if self.all_findings.is_empty() {
            return;
        }
        // Rank on the precomputed ops, so a redraw does not rebuild a
        // `recurrence_key` string twice per comparison.
        let mut ranked: Vec<(&Finding, u64)> = self
            .all_findings
            .iter()
            .zip(self.avoidable_ops.iter().copied())
            .collect();
        ranked.sort_by(|a, b| {
            crate::render::compare_severity_impact(
                crate::render::FindingsSort::Impact,
                (&a.0.severity, a.1),
                (&b.0.severity, b.1),
            )
        });
        lines.push(Line::from(Span::styled(
            "Top findings by impact:".to_string(),
            Style::default().add_modifier(Modifier::BOLD),
        )));
        for &(f, avoidable) in ranked.iter().take(Self::TOP_FINDINGS_ROWS) {
            lines.push(Line::from(vec![
                Span::raw("  - ".to_string()),
                // 9, not 8: `CRITICAL` is 8 characters, so a width of 8
                // would run the label into the finding type.
                Span::styled(
                    format!("{:<9}", severity_label(&f.severity)),
                    Style::default().fg(severity_color(&f.severity)),
                ),
                Span::raw(finding_type_label(&f.finding_type)),
                Span::styled(
                    format!(
                        "  {} \u{b7} {}",
                        sanitize_for_terminal(&f.service),
                        sanitize_for_terminal(&f.source_endpoint)
                    ),
                    dim,
                ),
                Span::styled(format!("  ~{avoidable} avoidable ops"), dim),
            ]));
        }
        lines.push(Line::from(""));
    }

    /// Build the Analyze view body as owned ratatui lines. Mirrors the
    /// sections of the CLI report (`render.rs`) as widgets: analysis
    /// metadata, findings by severity, I/O waste, top offenders, quality
    /// gate. All externally-sourced strings (endpoint, service) are
    /// sanitized for the terminal. Falls back to a hint when no summary
    /// was supplied (e.g. an older daemon without `/api/export/report`).
    fn build_analyze_lines(&self) -> Vec<Line<'static>> {
        let dim = dim_style();
        let Some(summary) = &self.summary else {
            let mut lines: Vec<Line<'static>> = Vec::new();
            self.push_warning_lines(&mut lines);
            lines.extend([
                Line::from(Span::styled("Summary unavailable.".to_string(), dim)),
                Line::from(Span::styled(
                    "No analysis summary was supplied (older daemon without /api/export/report?)."
                        .to_string(),
                    dim,
                )),
                Line::from(""),
                Line::from(Span::styled(
                    "Press Enter to inspect traces and findings.".to_string(),
                    dim,
                )),
            ]);
            return lines;
        };
        let gs = &summary.green_summary;
        let (crit, warn, info) = self.severity_counts();
        let total = self.all_findings.len();
        let mut lines: Vec<Line<'static>> = Vec::new();
        self.push_warning_lines(&mut lines);

        lines.push(Line::from(vec![
            Span::styled("Traces analyzed: ".to_string(), dim),
            Span::raw(summary.analysis.traces_analyzed.to_string()),
            Span::styled("   Events: ".to_string(), dim),
            Span::raw(summary.analysis.events_processed.to_string()),
            Span::styled("   Duration: ".to_string(), dim),
            Span::raw(format!("{} ms", summary.analysis.duration_ms)),
        ]));
        // Same reasoning as the CLI report and the dashboard header: a
        // thin report reads as a clean one unless the filtered spans are
        // stated. Absent on daemon snapshots, which carry no tally.
        if let Some(ingest) = &summary.analysis.ingest
            && ingest.spans_filtered > 0
        {
            let gaps = ingest.filtered_missing_db_statement + ingest.filtered_missing_http_url;
            let mut spans = vec![
                Span::styled("Spans ingested: ".to_string(), dim),
                Span::raw(ingest.spans_received.to_string()),
                Span::styled("   Filtered: ".to_string(), dim),
                Span::raw(ingest.spans_filtered.to_string()),
            ];
            if gaps > 0 {
                spans.push(Span::styled(
                    "   Missing db.statement/http.url: ".to_string(),
                    dim,
                ));
                spans.push(Span::styled(
                    gaps.to_string(),
                    Style::default().fg(Color::Yellow),
                ));
            }
            lines.push(Line::from(spans));
        }
        lines.push(Line::from(""));

        lines.push(Line::from(vec![
            Span::styled("Findings: ".to_string(), dim),
            Span::styled(
                total.to_string(),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::raw("   "),
            Span::styled(format!("{crit} critical"), Style::default().fg(Color::Red)),
            Span::raw(", "),
            Span::styled(
                format!("{warn} warning"),
                Style::default().fg(Color::Yellow),
            ),
            Span::raw(", "),
            Span::styled(format!("{info} info"), Style::default().fg(Color::Cyan)),
        ]));
        lines.push(Line::from(""));

        let band = gs.io_waste_ratio_band;
        lines.push(Line::from(vec![
            Span::styled("I/O waste ratio: ".to_string(), dim),
            // Percentage form, matching the CLI report (`print_green_summary`)
            // so the same metric does not read as a bare fraction here.
            Span::styled(
                format!("{:.1}%", gs.io_waste_ratio * 100.0),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::raw(" "),
            Span::styled(
                format!("({})", band.short_label()),
                Style::default().fg(interpret_band_color(band)),
            ),
        ]));
        lines.push(Line::from(vec![
            Span::styled("Avoidable I/O: ".to_string(), dim),
            Span::raw(format!(
                "{} of {} ops",
                gs.avoidable_io_ops, gs.total_io_ops
            )),
        ]));
        // Named by its energy source, never the window tag: on an
        // Electricity Maps daemon (`query inspect`) that tag is an
        // intensity source. The label only keeps `[A-Za-z0-9_+-]` tags.
        if let Some(src) = gs.energy_source_label() {
            lines.push(Line::from(vec![
                Span::styled("Energy: ".to_string(), dim),
                Span::raw(format!("{:.6} kWh", gs.energy_kwh)),
                Span::styled(format!("  ({src})"), dim),
            ]));
        }
        push_carbon_lines(&mut lines, gs, summary.analysis.traces_analyzed, dim);
        push_subsystem_waste_lines(&mut lines, gs, dim);
        lines.push(Line::from(""));

        if !gs.top_offenders.is_empty() {
            lines.push(Line::from(Span::styled(
                "Top offenders:".to_string(),
                Style::default().add_modifier(Modifier::BOLD),
            )));
            for offender in &gs.top_offenders {
                let oband = offender.io_intensity_band;
                let co2 = offender
                    .co2_grams
                    .map_or(String::new(), |c| format!(", {c:.6} gCO2"));
                lines.push(Line::from(vec![
                    Span::raw("  - ".to_string()),
                    Span::raw(sanitize_for_terminal(&offender.endpoint).into_owned()),
                    Span::styled(format!("  IIS {:.1} ", offender.io_intensity_score), dim),
                    Span::styled(
                        format!("({})", oband.short_label()),
                        Style::default().fg(interpret_band_color(oband)),
                    ),
                    Span::styled(
                        format!(
                            "  service: {}{}",
                            sanitize_for_terminal(&offender.service),
                            co2
                        ),
                        dim,
                    ),
                ]));
            }
            lines.push(Line::from(""));
        }

        self.push_top_findings_lines(&mut lines, dim);
        push_quality_gate_lines(&mut lines, &summary.quality_gate, dim);

        // Mandatory uncertainty disclaimer whenever CO2 estimates are shown,
        // matching the CLI report.
        if gs.co2.is_some() {
            lines.push(Line::from(""));
            lines.push(Line::from(Span::styled(
                "Note: CO\u{2082} estimates have ~2\u{00d7} multiplicative uncertainty (low = mid/2, high = mid\u{00d7}2). See docs/LIMITATIONS.md.".to_string(),
                dim,
            )));
        }
        // The bands use fixed heuristic thresholds, not the operator's config,
        // and the full per-region / scoring-config detail lives in the CLI
        // report. Flag both so the view is not mistaken for the full report.
        lines.push(Line::from(""));
        lines.push(Line::from(Span::styled(
            "Note: (healthy/moderate/high/critical) bands use fixed heuristic thresholds, independent of your config overrides.".to_string(),
            dim,
        )));
        lines.push(Line::from(Span::styled(
            "Per-region carbon breakdown and scoring config: run `analyze` for the full report."
                .to_string(),
            dim,
        )));
        lines
    }
}

/// Best-effort terminal restore shared by the panic hook and
/// [`RawModeGuard`]. The raw-mode probe makes it idempotent: on a
/// panic, the hook restores first and the guard's later drop becomes a
/// no-op instead of re-sending `LeaveAlternateScreen` (whose implied
/// cursor restore could reposition over the just-printed panic
/// message).
fn restore_terminal_if_raw() {
    // Fail open: if the probe itself errors, attempt the restore anyway.
    // A spurious restore on a cooked terminal is harmless, a leaked raw
    // mode is not.
    if crossterm::terminal::is_raw_mode_enabled().unwrap_or(true) {
        let _ = disable_raw_mode();
        // DisableMouseCapture is harmless when capture was never enabled.
        let _ = crossterm::execute!(io::stdout(), DisableMouseCapture, LeaveAlternateScreen);
    }
}

/// Enable or disable terminal mouse capture, shared by both TUIs. On lets
/// them receive drag events for border resizing, at the cost of native
/// copy-paste. Best-effort: a write failure leaves the in-memory flag
/// authoritative, and teardown always issues `DisableMouseCapture`.
pub(crate) fn set_mouse_capture(on: bool) {
    let _ = if on {
        crossterm::execute!(io::stdout(), EnableMouseCapture)
    } else {
        crossterm::execute!(io::stdout(), DisableMouseCapture)
    };
}

/// RAII terminal restore: leaves the alternate screen and disables raw
/// mode on drop, so an `Err` between terminal setup and loop exit (a
/// path the panic hook does not cover) cannot leak a raw-mode shell.
pub(crate) struct RawModeGuard;

impl Drop for RawModeGuard {
    fn drop(&mut self) {
        restore_terminal_if_raw();
    }
}

/// Install a panic hook that restores the terminal before the
/// standard hook prints the panic message. Without this, a panic
/// inside `run_loop` (e.g. from a future ratatui upgrade or from a
/// `block_on` in `submit_ack_modal`) leaves the operator with raw
/// mode + alternate screen still active, forcing a `reset` in their
/// shell.
///
/// Wrapped in `Once` so that calling `run` twice in the same process
/// (test re-entry, future embedding) does not stack hooks. The chain
/// to the previous hook is captured at first install and persists for
/// the process lifetime.
pub(crate) fn install_terminal_restore_panic_hook() {
    static INSTALL: std::sync::Once = std::sync::Once::new();
    INSTALL.call_once(|| {
        let prev_hook = std::panic::take_hook();
        std::panic::set_hook(Box::new(move |info| {
            restore_terminal_if_raw();
            prev_hook(info);
        }));
    });
}

/// The carbon block, mirroring the CLI `print_green_summary` so the Analyze
/// view never silently omits the headline figures, greyed with its cause when
/// nothing was scored. Split out of `build_analyze_lines` to keep that
/// function under the cognitive-complexity gate.
fn push_carbon_lines(
    lines: &mut Vec<Line<'static>>,
    gs: &GreenSummary,
    traces_analyzed: usize,
    dim: Style,
) {
    let Some(carbon) = gs.co2.as_ref() else {
        // Greyed rather than absent, so the reader sees why. The cause is
        // picked from the trace count, not from scoring_config, which a
        // daemon stamps whenever Electricity Maps is configured.
        lines.push(Line::from(Span::styled(
            if traces_analyzed == 0 {
                "Carbon: not computed (no traces analyzed)"
            } else {
                "Carbon: not computed ([green] enabled = false)"
            },
            dim,
        )));
        return;
    };
    // model/methodology are free `String`s on the daemon snapshot path
    // (`query inspect` reads them from /api/export/report), so sanitize like
    // the other daemon-sourced strings.
    let model = sanitize_for_terminal(&carbon.total.model);
    let methodology = sanitize_for_terminal(&carbon.total.methodology);
    lines.push(Line::from(Span::raw(format!(
        "Est. CO\u{2082}: {:.6} g (low {:.6}, high {:.6}, model {model})",
        carbon.total.mid, carbon.total.low, carbon.total.high,
    ))));
    lines.push(Line::from(Span::raw(format!(
        "Avoidable CO\u{2082}: {:.6} g (low {:.6}, high {:.6})",
        carbon.avoidable.mid, carbon.avoidable.low, carbon.avoidable.high,
    ))));
    lines.push(Line::from(Span::raw(format!(
        "Operational: {:.6} g   Embodied: {:.6} g   Methodology: {methodology}",
        carbon.operational_gco2, carbon.embodied_gco2,
    ))));
    if let Some(transport) = carbon.transport_gco2 {
        lines.push(Line::from(Span::raw(format!(
            "Transport: {transport:.6} g (cross-region network bytes)"
        ))));
    }
}

/// The quality-gate verdict and its per-rule lines. Split out of
/// `build_analyze_lines` to keep that function under the
/// cognitive-complexity gate.
fn push_quality_gate_lines(lines: &mut Vec<Line<'static>>, gate: &QualityGate, dim: Style) {
    // An empty rule set means the gate was never evaluated, e.g. a daemon
    // `/api/export/report` snapshot (which hardcodes passed=true, rules=[]).
    // Render it as "not evaluated" rather than a misleading green PASSED
    // next to live critical findings under `query inspect`.
    let (gate_label, gate_color) = if gate.rules.is_empty() {
        ("not evaluated", Color::DarkGray)
    } else if gate.passed {
        ("PASSED", Color::Green)
    } else {
        ("FAILED", Color::Red)
    };
    lines.push(Line::from(vec![
        Span::styled(
            "Quality gate: ".to_string(),
            Style::default().add_modifier(Modifier::BOLD),
        ),
        Span::styled(
            gate_label.to_string(),
            Style::default().fg(gate_color).add_modifier(Modifier::BOLD),
        ),
    ]));
    for rule in &gate.rules {
        let (rule_label, rule_color) = if rule.passed {
            ("PASS", Color::Green)
        } else {
            ("FAIL", Color::Red)
        };
        lines.push(Line::from(vec![
            Span::raw(format!(
                "  - {}: ",
                sentinel_core::quality_gate::rule_label(&rule.rule).map_or_else(
                    || sanitize_for_terminal(&rule.rule).into_owned(),
                    str::to_string
                )
            )),
            Span::styled(
                format!("{:.2} (actual {:.2}) ", rule.threshold, rule.actual),
                dim,
            ),
            Span::styled(rule_label.to_string(), Style::default().fg(rule_color)),
        ]));
    }
}

/// The database and broker waste lines, each greyed with its cause when
/// the figure is absent. Split out of `build_analyze_lines` to keep that
/// function under the cognitive-complexity gate.
fn push_subsystem_waste_lines(lines: &mut Vec<Line<'static>>, gs: &GreenSummary, dim: Style) {
    match &gs.database_waste {
        Some(db) => lines.push(Line::from(Span::raw(format!(
            "Database waste: {:.6} kWh of {:.6} kWh (model {})",
            db.waste_kwh,
            db.energy_kwh,
            sanitize_for_terminal(&db.model),
        )))),
        None => lines.push(Line::from(Span::styled(
            "Database waste: not measured (no SQL activity, a measured reading needs [green.alumet.database])",
            dim,
        ))),
    }
    match &gs.messaging_waste {
        Some(mw) => lines.push(Line::from(Span::raw(format!(
            "Broker waste: {:.6} kWh of {:.6} kWh (model {})",
            mw.waste_kwh,
            mw.energy_kwh,
            sanitize_for_terminal(&mw.model),
        )))),
        None => lines.push(Line::from(Span::styled(
            "Broker waste: not measured (no broker publish spans, or no broker energy backend)",
            dim,
        ))),
    }
}

/// Style for secondary / "dim" text shared by both TUIs. Uses the `DIM`
/// modifier on the terminal's default foreground rather than a fixed
/// gray: `Color::DarkGray` is legible on a light background but too dark
/// on a dark one, and `Color::Gray` is the reverse. Dimming the default
/// foreground adapts to either theme (light gray on dark, dark gray on
/// light).
pub(crate) fn dim_style() -> Style {
    Style::default().add_modifier(Modifier::DIM)
}

/// Concatenate rendered lines into plain text, for assertions. Shared
/// by the tui and monitor test modules.
#[cfg(test)]
pub(crate) fn line_text(lines: &[Line]) -> String {
    lines
        .iter()
        .map(|l| {
            l.spans
                .iter()
                .map(|s| s.content.as_ref())
                .collect::<String>()
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// Run the TUI event loop.
///
/// # Errors
///
/// Returns an error if terminal setup or event reading fails.
pub fn run(app: &mut App) -> io::Result<()> {
    install_terminal_restore_panic_hook();
    enable_raw_mode()?;
    // Restores raw mode + alternate screen on every exit path,
    // including an Err from the setup lines below.
    let _restore = RawModeGuard;
    let mut stdout = io::stdout();
    crossterm::execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let result = run_loop(&mut terminal, app);

    terminal.show_cursor()?;
    result
}

/// Outcome of a single keystroke at the run-loop level. The loop
/// returns `Quit` to break out, `Continue` to repaint and wait for the
/// next event.
#[derive(Debug)]
enum KeyOutcome {
    Continue,
    Quit,
}

fn run_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
) -> io::Result<()> {
    // Channel: spawned ack/revoke tasks send their outcome here. The
    // loop drains it before each redraw so the modal closes (or shows
    // the error) without blocking on the HTTP roundtrip.
    #[cfg(feature = "daemon")]
    let (tx_outcome, mut rx_outcome) = mpsc::unbounded_channel::<AckOutcome>();
    loop {
        #[cfg(feature = "daemon")]
        while let Ok(outcome) = rx_outcome.try_recv() {
            apply_ack_outcome(app, outcome);
        }
        // Pre-compute detail tree text (requires &mut self) before immutable
        // draw. Only the Inspect (Detail panel) and Explain views render it,
        // so skip the build_tree + clone work in the Analyze view.
        if matches!(app.view, View::Inspect | View::Explain) {
            app.detail_tree_text();
        }
        terminal.draw(|f| draw(f, app))?;

        // Block on `event::read` when no ack is in flight (0fps idle).
        // Poll with a short timeout only when a spawned task may push an
        // outcome we need to apply quickly.
        #[cfg(feature = "daemon")]
        let submitting = app.ack_modal.submitting;
        #[cfg(not(feature = "daemon"))]
        let submitting = false;
        if submitting && !event::poll(Duration::from_millis(50))? {
            continue;
        }
        match event::read()? {
            Event::Key(key) if key.kind == KeyEventKind::Press => {
                #[cfg(feature = "daemon")]
                let outcome = handle_keystroke(app, key.code, &tx_outcome);
                #[cfg(not(feature = "daemon"))]
                let outcome = handle_keystroke(app, key.code);
                if matches!(outcome, KeyOutcome::Quit) {
                    return Ok(());
                }
            }
            // Border dragging, only when a panel drag is currently
            // accepted (Inspect view, no modal up). The stored area is
            // stale otherwise. Resize repaints on the next loop turn,
            // which redraws unconditionally.
            Event::Mouse(me) if app.mouse_mode && app.accepts_panel_drag() => {
                handle_mouse(app, me);
            }
            _ => {}
        }
    }
}

/// Route a mouse event to the border-drag state machine. Motion updates
/// the hovered border so the resize affordance highlights under the cursor.
fn handle_mouse(app: &mut App, me: MouseEvent) {
    match me.kind {
        MouseEventKind::Down(MouseButton::Left) => app.begin_drag(me.column, me.row),
        MouseEventKind::Drag(MouseButton::Left) => app.apply_drag(me.column, me.row),
        MouseEventKind::Up(MouseButton::Left) => {
            app.drag = None;
            app.hover = app.hit_test(me.column, me.row);
        }
        MouseEventKind::Moved => app.hover = app.hit_test(me.column, me.row),
        _ => {}
    }
}

/// Dispatch a single keystroke. Modal-visible keys route to the form
/// handler, otherwise the standard panel-navigation keys + the
/// `a`/`u` ack shortcuts apply.
fn handle_keystroke(
    app: &mut App,
    code: KeyCode,
    #[cfg(feature = "daemon")] tx_outcome: &mpsc::UnboundedSender<AckOutcome>,
) -> KeyOutcome {
    #[cfg(feature = "daemon")]
    if app.ack_modal.is_visible() {
        dispatch_modal_key(app, code, tx_outcome);
        return KeyOutcome::Continue;
    }
    // Mouse mode is app-global state: toggle it from any drill-down view so
    // enabling it in Inspect then stepping into Explain can't trap capture
    // on. The standalone Disclose preview keeps its own key map.
    if app.disclose.is_none() && code == KeyCode::Char('m') {
        app.toggle_mouse_mode();
        set_mouse_capture(app.mouse_mode);
        return KeyOutcome::Continue;
    }
    let prev_view = app.view;
    let outcome = match app.view {
        View::Analyze => dispatch_analyze_key(app, code),
        View::Inspect => dispatch_panel_key(app, code),
        View::Explain => dispatch_explain_key(app, code),
        View::Disclose => dispatch_disclose_key(app, code),
    };
    // A view change invalidates the hovered/dragged border, which is only
    // tracked while in Inspect. Clear it so re-entry doesn't paint a
    // phantom highlight with no cursor under it.
    if app.view != prev_view {
        app.hover = None;
        app.drag = None;
    }
    outcome
}

/// Keys for the standalone Disclose preview: `g` cycles granularity,
/// `\u{2190}/\u{2192}` (`h`/`l`) step the period (or the active custom edge by a day),
/// `[`/`]` move the active custom edge by a month, `Tab` switches the
/// custom edge, `i`/`c` toggle intent/confidentiality, `\u{2191}/\u{2193}` (`j`/`k`)
/// scroll the summary. No view switching (the tab is autonomous).
fn dispatch_disclose_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    let Some(state) = app.disclose.as_mut() else {
        return KeyOutcome::Continue;
    };
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Char('g') => state.cycle_granularity(),
        KeyCode::Left | KeyCode::Char('h') => state.step(false),
        KeyCode::Right | KeyCode::Char('l') => state.step(true),
        KeyCode::Char('[') => state.step_month(false),
        KeyCode::Char(']') => state.step_month(true),
        KeyCode::Tab | KeyCode::BackTab => state.toggle_custom_field(),
        KeyCode::Char('i') => state.toggle_intent(),
        KeyCode::Char('c') => state.toggle_confidentiality(),
        KeyCode::Up | KeyCode::Char('k') => state.scroll(false),
        KeyCode::Down | KeyCode::Char('j') => state.scroll(true),
        _ => {}
    }
    KeyOutcome::Continue
}

/// Keys for the Analyze view: scroll the summary, Enter descends to the
/// Inspect view (keeping the active panel), Esc is a no-op (top of the
/// drill-down).
fn dispatch_analyze_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_offset = app.scroll_offset.saturating_sub(1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let max = app.analyze_content_line_count().saturating_sub(1);
            if app.scroll_offset < max {
                app.scroll_offset = app.scroll_offset.saturating_add(1);
            }
        }
        KeyCode::Enter => {
            // Descend to Inspect, keeping active_panel as-is so an
            // Esc-then-Enter round-trip lands back on the panel ascended from
            // (Traces or Correlations). A fresh `analyze --tui` launch already
            // has active_panel == Traces by default.
            app.view = View::Inspect;
            app.scroll_offset = 0;
        }
        _ => {}
    }
    KeyOutcome::Continue
}

/// Keys for the Explain view: scroll the span tree, Esc ascends back to
/// the Inspect view's Detail panel.
fn dispatch_explain_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Up | KeyCode::Char('k') => {
            app.scroll_offset = app.scroll_offset.saturating_sub(1);
        }
        KeyCode::Down | KeyCode::Char('j') => {
            let max = app.explain_content_line_count().saturating_sub(1);
            if app.scroll_offset < max {
                app.scroll_offset = app.scroll_offset.saturating_add(1);
            }
        }
        KeyCode::Esc => {
            app.view = View::Inspect;
            app.active_panel = Panel::Detail;
            app.scroll_offset = 0;
        }
        _ => {}
    }
    KeyOutcome::Continue
}

fn dispatch_panel_key(app: &mut App, code: KeyCode) -> KeyOutcome {
    match code {
        KeyCode::Char('q') => return KeyOutcome::Quit,
        KeyCode::Up | KeyCode::Char('k') => app.move_up(),
        KeyCode::Down | KeyCode::Char('j') => app.move_down(),
        KeyCode::Right | KeyCode::Tab | KeyCode::Char('l') => app.next_panel(),
        KeyCode::Left | KeyCode::BackTab | KeyCode::Char('h') => app.prev_panel(),
        KeyCode::Enter => app.enter(),
        KeyCode::Esc => app.escape(),
        KeyCode::Char('r') => app.reset_layout(),
        KeyCode::Char('s') => app.cycle_trace_sort(),
        KeyCode::Char('f') => app.cycle_severity_filter(),
        #[cfg(feature = "daemon")]
        KeyCode::Char('a') => open_ack_modal_for_current(app, false),
        #[cfg(feature = "daemon")]
        KeyCode::Char('u') => open_ack_modal_for_current(app, true),
        _ => {}
    }
    KeyOutcome::Continue
}

/// Map an interpretation band to a terminal color. Matches the CLI
/// report's `interpret_color` (`render.rs`) exactly so the same band reads
/// the same in `analyze` stdout and the TUI: Critical red, High yellow,
/// Moderate uncolored, Healthy green. Moderate is a non-empirical rule of
/// thumb, kept neutral so it does not compete with High.
fn interpret_band_color(level: InterpretationLevel) -> Color {
    match level {
        InterpretationLevel::Healthy => Color::Green,
        InterpretationLevel::Moderate => Color::Reset,
        InterpretationLevel::High => Color::Yellow,
        InterpretationLevel::Critical => Color::Red,
    }
}

fn severity_color(severity: &Severity) -> Color {
    match severity {
        Severity::Critical => Color::Red,
        Severity::Warning => Color::Yellow,
        Severity::Info => Color::Cyan,
    }
}

fn severity_label(severity: &Severity) -> &'static str {
    match severity {
        Severity::Critical => "CRITICAL",
        Severity::Warning => "WARNING",
        Severity::Info => "INFO",
    }
}

fn finding_type_label(ft: &FindingType) -> &'static str {
    ft.display_label()
}

#[cfg(feature = "daemon")]
mod ack_modal;
mod draw;
#[cfg(test)]
mod tests;