darq 0.1.0

darq CLI + TUI — autonomous issue → PR pipeline with SAT and a learning loop.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
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
#![allow(dead_code)]
// App state includes scaffolding fields reserved for future panels (shifts, blueprints,
// backlog, judges). They are wired into state updates but not yet rendered.

use std::collections::{HashMap, VecDeque};
use std::time::Instant;

use chrono::{DateTime, Utc};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use darq_core::types::{Run, RunStatus};
use ratatui::prelude::*;
use ratatui::widgets::*;

use crate::daemon::client::DaemonEvent;
use crate::tui::TuiEvent;

// ── Event-stream typed display state ──
//
// Populated by handle_daemon_event from all 12 RunEvent variants. Rendered by
// Phase-3 widgets (currently unused by the legacy 6-panel grid; that changes in
// Phase 3.2 when panels.rs is rewritten).

/// Max event lines kept in the visible waterfall buffer.
pub const WATERFALL_CAP: usize = 200;

/// Width of the agent-oscilloscope decay trace (samples).
/// One sample per render frame; at 30 Hz this gives ~6 seconds of history.
pub const SCOPE_WIDTH: usize = 200;

/// Per-frame multiplicative decay applied to each scope sample.
/// At 30 Hz, 0.985 → ~5 seconds for a unit spike to decay to ~0.1
/// (visibly fades over the full ~6s scope window).
pub const SCOPE_DECAY: f32 = 0.985;

/// Three-state agent classification used by the scope shape + suffix.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AgentPhase {
    /// No connected agent or heartbeat went stale (>30s).
    Idle,
    /// Agent is alive (recent heartbeat) but quiet (no tool_use in last 5s).
    /// On the scope, rendered as a sine carrier wave shaped by the active station.
    Thinking,
    /// Agent is actively producing — recent tool_use within 5s.
    /// Tall event spikes dominate the trace.
    Producing,
}

/// Per-station scope carrier — varies sine base/amplitude/period so each
/// workflow station has a recognizable shape on the oscilloscope.
#[derive(Debug, Clone, Copy)]
pub struct CarrierProfile {
    pub base: f32,
    pub amp: f32,
    pub period_ms: f32,
}

/// Event kind for color/glyph dispatch in the waterfall widget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventKind {
    Heartbeat,
    StateTransition,
    ToolUse,
    SessionUpdate,
    Artifact,
    BlueprintsInjected,
    Routing,
    Warning,
    Error,
    Success,
}

/// A single displayable event in the waterfall.
#[derive(Debug, Clone)]
pub struct EventDisplayed {
    pub ts: DateTime<Utc>,
    pub kind: EventKind,
    pub text: String,
    pub run_id: Option<String>,
}

/// Per-persona SAT state — current displayed needle position, latest score target,
/// and a short note carrying the most recent qualitative feedback (if any).
#[derive(Debug, Clone, Default)]
pub struct SatPersonaState {
    pub current: f32, // 0..100, animated needle position (Phase 4.5)
    pub target: f32,  // 0..100, from most recent SatPersonaScore event
    pub last_updated: Option<DateTime<Utc>>,
    pub note: Option<String>,
}

/// Station state in the 7-step chain topology.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StationState {
    Pending,
    Active,
    Completed,
    Failed,
    NotApplicable,
}

impl StationState {
    pub fn glyph(self) -> &'static str {
        match self {
            Self::Pending => "",
            Self::Active => "",
            Self::Completed => "",
            Self::Failed => "",
            Self::NotApplicable => "·",
        }
    }
}

/// Rolling chain of 7 stations (plan, implement, review, fix, merge, sat, learn).
#[derive(Debug, Clone)]
pub struct ChainState {
    pub stations: [StationState; 7],
    pub elapsed_ms: [Option<u64>; 7],
}

impl Default for ChainState {
    fn default() -> Self {
        Self {
            stations: [StationState::Pending; 7],
            elapsed_ms: [None; 7],
        }
    }
}

/// Map the workflow_kind string from a RunEvent to a station index (0..7).
/// Unknown kinds return None (skipped by the handler).
pub fn workflow_kind_to_station(kind: &str) -> Option<usize> {
    match kind {
        "plan_issue" | "plan" => Some(0),
        "implement_issue" | "implement" => Some(1),
        "review_pr" | "review" => Some(2),
        "fix_review" | "fix" => Some(3),
        "merge_pr" | "merge" => Some(4),
        "sat_verify" | "sat" => Some(5),
        "learn_update" | "learn" => Some(6),
        _ => None,
    }
}

/// Which secondary panel currently occupies the right column. Phase 6.
/// Default = `SatDials`. Toggles via single keystrokes from the footer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PanelMode {
    #[default]
    SatDials,
    Shifts,
    Blueprints,
    Backlog,
    Judges,
}

/// Waterfall filter mode. Phase 6.6 cycles via `[f]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum WaterfallFilter {
    #[default]
    All,
    Errors,
    Tools,
    Routing,
}

impl WaterfallFilter {
    pub fn next(self) -> Self {
        match self {
            Self::All => Self::Errors,
            Self::Errors => Self::Tools,
            Self::Tools => Self::Routing,
            Self::Routing => Self::All,
        }
    }
    pub fn label(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Errors => "errors",
            Self::Tools => "tools",
            Self::Routing => "routing",
        }
    }
    pub fn matches(self, kind: EventKind) -> bool {
        match self {
            Self::All => true,
            Self::Errors => matches!(kind, EventKind::Error | EventKind::Warning),
            Self::Tools => matches!(kind, EventKind::ToolUse),
            Self::Routing => matches!(kind, EventKind::Routing | EventKind::StateTransition),
        }
    }
}

/// Live agent thinking metrics, populated from AgentHeartbeat events.
/// Drives the waiting-invisibility fix: active station shows elapsed + output growth.
#[derive(Debug, Clone)]
pub struct AgentHeartbeatState {
    pub elapsed_secs: u64,
    pub output_chars: u64,
    /// When the most recent heartbeat frame arrived (wall-clock).
    pub last_frame_at: Instant,
    /// Output_chars from the previous frame, to compute the per-second growth rate.
    pub prev_output_chars: u64,
    /// Wall-clock of the previous frame, for the rate denominator.
    pub prev_frame_at: Instant,
}

impl AgentHeartbeatState {
    /// Chars-per-second since the last frame. Returns 0 on the first frame.
    pub fn rate_per_sec(&self) -> u64 {
        let dt = self
            .last_frame_at
            .duration_since(self.prev_frame_at)
            .as_secs_f32();
        if dt < 0.1 {
            return 0;
        }
        let delta = self.output_chars.saturating_sub(self.prev_output_chars) as f32;
        (delta / dt) as u64
    }
}

/// Marker for a recent station-completion — drives the single-shot trail animation
/// across the chain topology connector. Replaces the always-on packet (annoying).
#[derive(Debug, Clone, Copy)]
pub struct CompletionTrail {
    pub station_idx: usize,
    pub at: Instant,
}

/// Shift-end summary card. Captured when a focused shift hits a terminal status.
/// Fills the empty space below the waterfall with key stats — gives visual weight
/// to the climax of the run and uses the otherwise-wasted real estate.
#[derive(Debug, Clone)]
pub struct TerminalCard {
    pub run_id: String,
    pub final_status: String, // "completed" / "failed" / "cancelled"
    pub duration_secs: u64,
    pub verdict: Option<String>, // SAT verdict if any
    pub total_events: usize,
    pub blueprints: usize,
    pub tool_count: u32,
}

/// One retrieved blueprint, populated by `BlueprintsInjected` (Phase 5) events.
#[derive(Debug, Clone)]
pub struct BlueprintMatch {
    pub run_id: String,
    pub utility_name: String,
    pub similarity: f32,
    pub kind: BlueprintKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlueprintKind {
    Reuse,
    Avoid,
}

// ── Panel Navigation ──

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Panel {
    Milestone,
    Runs,
    Approvals,
    PrState,
    SatStatus,
    Learnings,
}

impl Panel {
    pub fn next(self) -> Self {
        match self {
            Self::Milestone => Self::Runs,
            Self::Runs => Self::Approvals,
            Self::Approvals => Self::PrState,
            Self::PrState => Self::SatStatus,
            Self::SatStatus => Self::Learnings,
            Self::Learnings => Self::Milestone,
        }
    }

    pub fn prev(self) -> Self {
        match self {
            Self::Milestone => Self::Learnings,
            Self::Runs => Self::Milestone,
            Self::Approvals => Self::Runs,
            Self::PrState => Self::Approvals,
            Self::SatStatus => Self::PrState,
            Self::Learnings => Self::SatStatus,
        }
    }
}

// ── Actions ──

pub enum Action {
    Quit,
    ApproveRun(String),
    TriggerNext,
}

// ── Display Types ──

pub struct RunInfo {
    pub id: String,
    pub status: String,
    pub issue: String,
    pub duration: String,
}

pub struct PrInfo {
    pub number: u64,
    pub title: String,
    pub status: String,
}

// ── Confirmation State ──

pub struct Confirmation {
    pub action: Action,
    pub prompt: String,
}

// ── App State ──

pub struct App {
    pub focused: Panel,
    pub tick_count: u64,
    pub runs_state: TableState,
    pub approvals_state: ListState,
    pub milestone_name: Option<String>,
    pub runs: Vec<RunInfo>,
    pub approvals: Vec<RunInfo>,
    pub prs: Vec<PrInfo>,
    pub sat_summary: String,
    pub learnings: Vec<String>,
    pub confirmation: Option<Confirmation>,
    pub status_message: String,
    // ── Phase-2+ state (populated by handle_daemon_event from all 12 RunEvents) ──
    /// Rolling waterfall of displayable events (capped at WATERFALL_CAP).
    pub waterfall: VecDeque<EventDisplayed>,
    /// Currently-focused shift (used for chain state + sat scores).
    pub focus_run_id: Option<String>,
    /// 7-station chain state for the focused shift.
    pub chain_state: ChainState,
    /// Per-persona SAT state (key: persona name, lowercase).
    pub sat_scores: HashMap<String, SatPersonaState>,
    /// Most recent SAT verdict text ("PASS" / "FAIL").
    pub sat_verdict: Option<String>,
    /// Tool-use counter for the focused shift (incremented on `ToolUse` events once
    /// Phase 5 emits them; stays 0 until then).
    pub tool_count: u32,
    /// Blueprints retrieved during the focused shift's plan station. Populated by
    /// Phase 5's `BlueprintsInjected` event; empty until then.
    pub blueprints: Vec<BlueprintMatch>,
    /// Rolling throughput window (events per tick, max 32 entries → ~16 s at 2 Hz).
    pub throughput_window: VecDeque<u32>,
    /// Events received in the current tick bucket, reset on each `TuiEvent::Tick`.
    pub events_this_tick: u32,
    /// Wall-clock anchor for time-based animations (Phase 4).
    pub start_time: Instant,
    /// When the most recent render frame ran (for delta-time interpolation).
    pub last_render: Instant,
    /// Most recently failed station + when the glitch should clear (Phase 4.6).
    pub glitch: Option<(usize, Instant)>,
    /// Daemon uptime seconds, fetched periodically from Method::Stats (Phase 5.8).
    pub daemon_uptime_secs: u64,
    /// Total blueprint store size, from Method::Stats (Phase 5.8). 0 = "—" in TUI.
    pub daemon_blueprint_count: u64,
    /// Which panel currently occupies the right column (Phase 6.1).
    pub mode: PanelMode,
    /// Active waterfall filter (Phase 6.6).
    pub waterfall_filter: WaterfallFilter,
    /// Reduce-motion mode (Phase 7.2): set from `DARQ_TUI_REDUCE_MOTION` env var.
    /// When true, disable: breathing animation, waterfall fade-out, animated packet,
    /// needle interpolation. Heartbeat dot still pulses (essential signal).
    pub reduce_motion: bool,
    /// Transient red dot on the header heartbeat after a recent failure (Phase 7.5).
    pub failure_dot_until: Option<Instant>,
    /// Per-shift started_at timestamp, used to live-recompute durations each Tick.
    /// Captured from `status_changed → running` events, or from update_from_runs().
    pub run_started_at: HashMap<String, DateTime<Utc>>,
    /// Per-shift completed_at timestamp — freezes duration once a shift finishes.
    pub run_completed_at: HashMap<String, DateTime<Utc>>,
    /// Live agent heartbeat metrics for the focused shift. Cleared on focus change
    /// and on station transition. Populated from AgentHeartbeat events.
    pub agent_heartbeat: Option<AgentHeartbeatState>,
    /// Most recent station completion — fires a 250ms trail across the connector.
    /// Replaces the always-on animated packet.
    pub completion_trail: Option<CompletionTrail>,
    /// True when this App is driving a replay session (no daemon connection).
    /// Used by the header to hide daemon-only fields like `uptime`.
    pub is_replay: bool,
    /// Snapshot of a shift's terminal state — drives the "shift complete" callout
    /// card that fills the empty space below the waterfall when a run finishes.
    pub terminal_card: Option<TerminalCard>,
    /// Show the keybinding help modal (toggled by `?`).
    pub show_help: bool,
    /// Decay-trace samples for the chain-topology agent oscilloscope.
    /// Each render frame, all samples decay; on each event arrival, the rightmost
    /// sample spikes proportional to event intensity. Capped at SCOPE_WIDTH.
    pub scope_trace: VecDeque<f32>,
    /// Most recent tool name from a ToolUse event — drives the live-action line.
    pub last_tool: Option<String>,
    /// When the most recent ToolUse event arrived — used to detect "thinking"
    /// state on the scope (recent heartbeat AND no recent tool_use = thinking).
    pub last_tool_at: Option<Instant>,
    pub event_status: String,
    pub event_count: u64,
}

impl App {
    pub fn new() -> Self {
        let mut runs_state = TableState::default();
        runs_state.select(Some(0));

        let mut approvals_state = ListState::default();
        approvals_state.select(Some(0));

        Self {
            focused: Panel::Milestone,
            tick_count: 0,
            runs_state,
            approvals_state,
            milestone_name: Some("v1.0".into()),
            runs: vec![],
            approvals: vec![],
            prs: vec![],
            sat_summary: "No SAT runs yet".into(),
            learnings: vec![],
            confirmation: None,
            status_message: "Starting...".into(),
            event_status: "Events: not subscribed".into(),
            event_count: 0,
            waterfall: VecDeque::with_capacity(WATERFALL_CAP),
            focus_run_id: None,
            chain_state: ChainState::default(),
            sat_scores: HashMap::new(),
            sat_verdict: None,
            tool_count: 0,
            blueprints: Vec::new(),
            throughput_window: VecDeque::with_capacity(32),
            events_this_tick: 0,
            start_time: Instant::now(),
            last_render: Instant::now(),
            glitch: None,
            daemon_uptime_secs: 0,
            daemon_blueprint_count: 0,
            mode: PanelMode::default(),
            waterfall_filter: WaterfallFilter::default(),
            reduce_motion: std::env::var("DARQ_TUI_REDUCE_MOTION")
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false),
            failure_dot_until: None,
            run_started_at: HashMap::new(),
            run_completed_at: HashMap::new(),
            agent_heartbeat: None,
            completion_trail: None,
            is_replay: false,
            terminal_card: None,
            show_help: false,
            scope_trace: VecDeque::with_capacity(SCOPE_WIDTH),
            last_tool: None,
            last_tool_at: None,
        }
    }

    /// Classify the agent's current state for the scope shape.
    /// Now considers chain_state too: any active station = at least Thinking,
    /// even before the first heartbeat arrives. Eliminates the dead 10s window
    /// at the start of each station where the scope was flat.
    pub fn agent_phase(&self) -> AgentPhase {
        // Recent tool_use (<5s) → producing (highest priority).
        if let Some(t) = self.last_tool_at
            && t.elapsed().as_secs() < 5
        {
            return AgentPhase::Producing;
        }
        // Heartbeat fresh (<30s) → thinking.
        if let Some(hb) = &self.agent_heartbeat
            && hb.last_frame_at.elapsed().as_secs() <= 30
        {
            return AgentPhase::Thinking;
        }
        // Even with no heartbeat yet, an active station means the agent IS
        // working — show thinking carrier so the scope isn't dead during
        // station startup.
        if self.active_station_idx().is_some() {
            return AgentPhase::Thinking;
        }
        AgentPhase::Idle
    }

    /// Index of the currently-active station in chain_state (0..7), if any.
    pub fn active_station_idx(&self) -> Option<usize> {
        self.chain_state
            .stations
            .iter()
            .position(|s| matches!(s, StationState::Active))
    }

    /// Per-station carrier profile — gives each workflow station a recognizable
    /// scope signature. base = always-on amplitude, amp = sine wave amplitude,
    /// period_ms = sine period (slow = contemplative, fast = busy).
    pub fn station_carrier_profile(&self) -> CarrierProfile {
        match self.active_station_idx() {
            Some(0) => CarrierProfile {
                base: 0.20,
                amp: 0.15,
                period_ms: 6000.0,
            }, // PLAN — slow contemplation
            Some(1) => CarrierProfile {
                base: 0.40,
                amp: 0.25,
                period_ms: 3000.0,
            }, // IMPLEMENT — busy
            Some(2) => CarrierProfile {
                base: 0.30,
                amp: 0.20,
                period_ms: 4500.0,
            }, // REVIEW — measured
            Some(3) => CarrierProfile {
                base: 0.35,
                amp: 0.20,
                period_ms: 3500.0,
            }, // FIX — focused
            Some(4) => CarrierProfile {
                base: 0.15,
                amp: 0.05,
                period_ms: 8000.0,
            }, // MERGE — quiet automation
            Some(5) => CarrierProfile {
                base: 0.40,
                amp: 0.30,
                period_ms: 5000.0,
            }, // SAT — deliberation
            Some(6) => CarrierProfile {
                base: 0.25,
                amp: 0.10,
                period_ms: 7000.0,
            }, // LEARN — contemplative
            _ => CarrierProfile {
                base: 0.25,
                amp: 0.25,
                period_ms: 8000.0,
            }, // generic thinking
        }
    }

    /// Push a spike onto the scope trace at the rightmost sample.
    /// `intensity` is 0..=1 — different event kinds scale differently.
    fn scope_spike(&mut self, intensity: f32) {
        // Make sure the buffer has full width — pad with zeros first time.
        while self.scope_trace.len() < SCOPE_WIDTH {
            self.scope_trace.push_back(0.0);
        }
        // Bump the latest sample (rightmost) — additive so back-to-back events stack.
        if let Some(last) = self.scope_trace.back_mut() {
            *last = (*last + intensity).min(1.0);
        }
    }

    /// Advance the scope: decay all samples, shift left, append a fresh sample.
    /// Called once per render tick. The fresh sample is 0 by default — but in
    /// `Thinking` phase we inject a low-amplitude sine carrier so the operator
    /// can SEE the agent thinking (vs flatline = idle/disconnected).
    fn scope_step(&mut self) {
        if self.scope_trace.is_empty() {
            // Pre-fill the buffer once so render can downsample immediately.
            for _ in 0..SCOPE_WIDTH {
                self.scope_trace.push_back(0.0);
            }
        }
        for s in self.scope_trace.iter_mut() {
            *s *= SCOPE_DECAY;
        }
        if self.scope_trace.len() >= SCOPE_WIDTH {
            self.scope_trace.pop_front();
        }
        // Inject a thinking-carrier sample (0 in Idle/Producing, sine in Thinking).
        let carrier = self.thinking_carrier_sample();
        self.scope_trace.push_back(carrier);
    }

    /// Sine carrier — shape varies by active station so each of the 7 workflow
    /// stations has a recognizable signature on the oscilloscope:
    ///   PLAN      — slow contemplative roll
    ///   IMPLEMENT — busy mid-frequency wave (overridden by tool_use spikes)
    ///   REVIEW    — measured, slightly slower
    ///   FIX       — focused medium tempo
    ///   MERGE     — quiet, almost-flat automation
    ///   SAT       — long deliberation rolls
    ///   LEARN     — slow contemplation
    /// Returns 0.0 only when truly idle (no heartbeat, no active station).
    fn thinking_carrier_sample(&self) -> f32 {
        let phase = self.agent_phase();
        if phase == AgentPhase::Idle {
            return 0.0;
        }
        // In Producing phase, carrier still adds a baseline (event spikes
        // overshoot it). In Thinking phase, the carrier IS the signal.
        let prof = self.station_carrier_profile();
        use std::f32::consts::PI;
        let p = (self.elapsed_ms() as f32 / prof.period_ms) * 2.0 * PI;
        prof.base + prof.amp * p.sin()
    }

    /// Refresh the displayed `duration` field on each RunInfo from started_at.
    /// Called every Tick so the focused-shift / shifts-list "12m44s" counters
    /// actually count up while a shift is running.
    fn refresh_durations(&mut self) {
        let now = Utc::now();
        for run in self.runs.iter_mut().chain(self.approvals.iter_mut()) {
            let Some(started) = self.run_started_at.get(&run.id) else {
                continue;
            };
            let end = self.run_completed_at.get(&run.id).copied().unwrap_or(now);
            let secs = (end - *started).num_seconds().max(0) as u64;
            run.duration = format_short_secs(secs);
        }
    }

    /// Toggle a panel mode: pressing the same key twice returns to SatDials.
    pub fn toggle_mode(&mut self, target: PanelMode) {
        self.mode = if self.mode == target {
            PanelMode::SatDials
        } else {
            target
        };
    }

    /// Wall-clock elapsed since startup. Used for time-based animations
    /// (breathing, packet position, sparkline phase).
    pub fn elapsed_ms(&self) -> u64 {
        self.start_time.elapsed().as_millis() as u64
    }

    /// Step needle interpolation on each render frame: current += (target - current) * (1 - exp(-dt*rate)).
    /// Rate chosen so a 420ms settling time yields ~95% of target.
    /// Under reduce_motion, snaps current → target instead of interpolating.
    pub fn step_animations(&mut self) {
        let now = Instant::now();
        let dt = now.duration_since(self.last_render).as_secs_f32();
        self.last_render = now;
        if self.reduce_motion {
            for state in self.sat_scores.values_mut() {
                state.current = state.target;
            }
        } else {
            const RATE: f32 = 7.1;
            let factor = 1.0 - (-dt * RATE).exp();
            for state in self.sat_scores.values_mut() {
                state.current += (state.target - state.current) * factor;
            }
        }
        // Clear expired glitch.
        if let Some((_, expires_at)) = self.glitch
            && now >= expires_at
        {
            self.glitch = None;
        }
        // Clear expired failure dot.
        if let Some(until) = self.failure_dot_until
            && now >= until
        {
            self.failure_dot_until = None;
        }
        // Clear expired completion trail (250ms lifetime).
        if let Some(trail) = self.completion_trail
            && now.duration_since(trail.at) > std::time::Duration::from_millis(250)
        {
            self.completion_trail = None;
        }
    }

    /// Push a new event to the waterfall, dropping the oldest if at capacity.
    /// In replay mode, rewrite the ts to wall-clock now — captured timestamps
    /// can be days old and would clamp every line to max-fade. The fade-out is
    /// "age since the line appeared on the screen", not "age in the original run."
    fn push_waterfall(&mut self, mut ev: EventDisplayed) {
        if self.is_replay {
            ev.ts = Utc::now();
        }
        if self.waterfall.len() >= WATERFALL_CAP {
            self.waterfall.pop_front();
        }
        self.waterfall.push_back(ev);
    }

    /// Update focus to a given run_id, resetting per-shift state (chain + sat).
    fn refocus(&mut self, run_id: &str) {
        if self.focus_run_id.as_deref() != Some(run_id) {
            self.focus_run_id = Some(run_id.to_string());
            self.chain_state = ChainState::default();
            self.sat_scores.clear();
            self.sat_verdict = None;
            self.tool_count = 0;
            self.blueprints.clear();
            self.agent_heartbeat = None;
            self.completion_trail = None;
            self.last_tool = None;
            self.last_tool_at = None;
        }
    }

    pub fn handle_event(&mut self, event: TuiEvent) -> Option<Action> {
        match event {
            TuiEvent::Key(key) => {
                // If confirmation is active, handle y/n/esc
                if self.confirmation.is_some() {
                    return self.handle_confirmation(key);
                }
                self.handle_key(key)
            }
            TuiEvent::Tick => {
                self.tick_count += 1;
                // Roll the throughput window: commit this tick's count, reset bucket.
                if self.throughput_window.len() >= 32 {
                    self.throughput_window.pop_front();
                }
                self.throughput_window.push_back(self.events_this_tick);
                self.events_this_tick = 0;
                // Recompute live durations on each Tick (~2 Hz) so the counters
                // tick up while shifts are running.
                self.refresh_durations();
                self.status_message = format!(
                    "Tick #{} | Runs: {} | Waterfall: {} | {}",
                    self.tick_count,
                    self.runs.len(),
                    self.waterfall.len(),
                    self.event_status
                );
                None
            }
            TuiEvent::Render => None,
            TuiEvent::DaemonEvent(event) => {
                self.event_count += 1;
                self.event_status = format!("Events: {} received", self.event_count);
                self.status_message = format!("Last event: {}", event.event);
                self.handle_daemon_event(event);
                None
            }
        }
    }

    /// Handle an event pushed from the daemon. Dispatches every known RunEvent
    /// variant into typed state (waterfall, chain, sat, blueprints, tool count).
    /// See docs/stream-audit.md for the full variant catalog.
    fn handle_daemon_event(&mut self, event: DaemonEvent) {
        if event.event != "run_event" {
            return;
        }

        let data = &event.data;
        let event_type = data.get("type").and_then(|v| v.as_str()).unwrap_or("");
        let run_id = data.get("run_id").and_then(|v| v.as_str()).unwrap_or("");
        let ts = data
            .get("timestamp")
            .and_then(|v| v.as_str())
            .and_then(|s| s.parse::<DateTime<Utc>>().ok())
            .unwrap_or_else(Utc::now);

        // Count for the throughput sparkline (Phase 3.4 renders it).
        self.events_this_tick = self.events_this_tick.saturating_add(1);

        // Spike the agent oscilloscope per event kind. Intensities chosen so
        // tool_use bursts visually dominate (the "agent doing real work" signal),
        // heartbeats register as moderate pulses, and routine state changes as
        // small ticks.
        let intensity = match event_type {
            "tool_use" => 0.85,
            "agent_heartbeat" => 0.55,
            "sat_persona_score" => 0.7,
            "blueprints_injected" => 0.9,
            "artifact_added" => 0.6,
            "step_started" | "step_completed" | "step_failed" => 0.4,
            "log" => match data.get("level").and_then(|v| v.as_str()) {
                Some("error") => 1.0,
                Some("warn") => 0.7,
                _ => 0.25,
            },
            "sat_verdict" => 1.0,
            _ => 0.2,
        };
        self.scope_spike(intensity);

        match event_type {
            // ── status_changed ──
            "status_changed" => {
                let from = data.get("from").and_then(|v| v.as_str()).unwrap_or("?");
                let to = data.get("to").and_then(|v| v.as_str()).unwrap_or("?");

                // Track started_at when a shift transitions to running, completed_at
                // when it reaches a terminal state. Powers refresh_durations() in Tick.
                if to == "running" && !run_id.is_empty() {
                    self.run_started_at.entry(run_id.to_string()).or_insert(ts);
                }
                if matches!(
                    to,
                    "completed" | "failed" | "cancelled" | "merged" | "cooled"
                ) && !run_id.is_empty()
                {
                    self.run_completed_at.insert(run_id.to_string(), ts);
                    // Capture a "shift complete" callout for the waterfall when the
                    // focused shift reaches a terminal state.
                    if self.focus_run_id.as_deref() == Some(run_id) {
                        let started = self.run_started_at.get(run_id).copied();
                        let dur = match started {
                            Some(s) => (ts - s).num_seconds().max(0) as u64,
                            None => 0,
                        };
                        self.terminal_card = Some(TerminalCard {
                            run_id: run_id.to_string(),
                            final_status: to.to_string(),
                            duration_secs: dur,
                            verdict: self.sat_verdict.clone(),
                            total_events: self.waterfall.len(),
                            blueprints: self.blueprints.len(),
                            tool_count: self.tool_count,
                        });
                    }
                }

                // Legacy 6-panel state update (kept until Phase 3 rewrites panels.rs).
                if let Some(run) = self.runs.iter_mut().find(|r| r.id == run_id) {
                    run.status = to.to_string();
                } else if let Some(idx) = self.approvals.iter().position(|r| r.id == run_id) {
                    let mut info = self.approvals.remove(idx);
                    info.status = to.to_string();
                    self.runs.push(info);
                } else if !run_id.is_empty() {
                    // Pick the best-available issue label. Real status_changed events
                    // don't carry issue metadata — but synthetic captures may include
                    // it for replay fidelity. Falls back to the short run_id.
                    let issue_num = data.get("issue_number").and_then(|v| v.as_u64());
                    let issue_title = data
                        .get("issue_title")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let issue_label = match (issue_num, issue_title.as_deref()) {
                        (Some(n), Some(t)) => format!("#{n} {t}"),
                        (Some(n), None) => format!("#{n}"),
                        (None, Some(t)) => t.to_string(),
                        _ => format!("Run {}", &run_id[..8.min(run_id.len())]),
                    };
                    self.runs.push(RunInfo {
                        id: run_id.to_string(),
                        status: to.to_string(),
                        issue: issue_label,
                        duration: "0s".into(),
                    });
                }

                // Auto-focus the first run we see transitioning to running.
                if to == "running" && self.focus_run_id.is_none() {
                    self.refocus(run_id);
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::StateTransition,
                    text: format!("status · {from}{to}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── step_started ──
            "step_started" => {
                let workflow_kind = data
                    .get("workflow_kind")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let workflow_name = data
                    .get("workflow_name")
                    .and_then(|v| v.as_str())
                    .unwrap_or(workflow_kind);

                if self.focus_run_id.as_deref() == Some(run_id)
                    && let Some(idx) = workflow_kind_to_station(workflow_kind)
                {
                    self.chain_state.stations[idx] = StationState::Active;
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Routing,
                    text: format!("▸ station started · {workflow_name}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── step_completed ──
            "step_completed" => {
                let workflow_kind = data
                    .get("workflow_kind")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let workflow_name = data
                    .get("workflow_name")
                    .and_then(|v| v.as_str())
                    .unwrap_or(workflow_kind);
                let summary = data.get("summary").and_then(|v| v.as_str()).unwrap_or("");
                let duration_ms = data
                    .get("duration_ms")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0);

                if self.focus_run_id.as_deref() == Some(run_id)
                    && let Some(idx) = workflow_kind_to_station(workflow_kind)
                {
                    self.chain_state.stations[idx] = StationState::Completed;
                    self.chain_state.elapsed_ms[idx] = Some(duration_ms);
                    // Single-shot trail across the just-completed span (replaces
                    // the always-on packet animation, which was distracting).
                    self.completion_trail = Some(CompletionTrail {
                        station_idx: idx,
                        at: Instant::now(),
                    });
                    // Station transition — clear the per-station heartbeat state
                    // so the next station starts fresh.
                    self.agent_heartbeat = None;
                }

                // Cosmetic for replay mode: when learn_update finishes, its summary
                // says "N patterns extracted, M total in store". Parse the M to
                // populate `daemon_blueprint_count` since Method::Stats doesn't
                // fire when replaying. Live runs still get authoritative values
                // from Stats — this is a no-op pre-empted by the Stats fetch.
                if workflow_kind == "learn_update"
                    && let Some(total) = parse_total_in_store(summary)
                {
                    self.daemon_blueprint_count = total;
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Success,
                    text: format!("{workflow_name} · {summary}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── step_failed ──
            "step_failed" => {
                let workflow_kind = data
                    .get("workflow_kind")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let error = data.get("error").and_then(|v| v.as_str()).unwrap_or("?");

                if self.focus_run_id.as_deref() == Some(run_id)
                    && let Some(idx) = workflow_kind_to_station(workflow_kind)
                {
                    self.chain_state.stations[idx] = StationState::Failed;
                    // Trigger 120ms glitch on the failed station (Phase 4.6).
                    // Skipped under reduce_motion.
                    if !self.reduce_motion {
                        self.glitch =
                            Some((idx, Instant::now() + std::time::Duration::from_millis(120)));
                    }
                    // Phase 7.5: 5s transient red dot in the header.
                    self.failure_dot_until =
                        Some(Instant::now() + std::time::Duration::from_secs(5));
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Error,
                    text: format!("{workflow_kind} cooled · {error}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── contract_violation ──
            "contract_violation" => {
                let workflow_kind = data
                    .get("workflow_kind")
                    .and_then(|v| v.as_str())
                    .unwrap_or("");
                let error = data.get("error").and_then(|v| v.as_str()).unwrap_or("?");

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Error,
                    text: format!("✖ contract violation · {workflow_kind} · {error}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── agent_heartbeat ──
            "agent_heartbeat" => {
                let elapsed = data
                    .get("elapsed_secs")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0);
                let chars = data
                    .get("output_chars")
                    .and_then(|v| v.as_u64())
                    .unwrap_or(0);

                // Update live thinking state for the focused shift — feeds the
                // active station tile + footer status (waiting-invisibility fix).
                if self.focus_run_id.as_deref() == Some(run_id) {
                    let now = Instant::now();
                    let prev = self.agent_heartbeat.as_ref();
                    let (prev_chars, prev_at) = match prev {
                        Some(s) => (s.output_chars, s.last_frame_at),
                        None => (chars, now),
                    };
                    self.agent_heartbeat = Some(AgentHeartbeatState {
                        elapsed_secs: elapsed,
                        output_chars: chars,
                        last_frame_at: now,
                        prev_output_chars: prev_chars,
                        prev_frame_at: prev_at,
                    });
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Heartbeat,
                    text: format!("▸ heartbeat · {elapsed}s · {chars} chars"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── log ──
            "log" => {
                let level = data.get("level").and_then(|v| v.as_str()).unwrap_or("info");
                let message = data.get("message").and_then(|v| v.as_str()).unwrap_or("");

                let kind = match level {
                    "error" => EventKind::Error,
                    "warn" | "warning" => EventKind::Warning,
                    _ => EventKind::StateTransition,
                };
                let glyph = match level {
                    "error" => "",
                    "warn" | "warning" => "",
                    _ => "",
                };

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind,
                    text: format!("{glyph} {message}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── artifact_added ──
            "artifact_added" => {
                let artifact_kind = data.get("kind").and_then(|v| v.as_str()).unwrap_or("?");

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Artifact,
                    text: format!("▲ artifact · {artifact_kind}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── approval_recorded ──
            "approval_recorded" => {
                let decision = data.get("decision").and_then(|v| v.as_str()).unwrap_or("?");

                // Legacy panel state.
                if let Some(idx) = self.approvals.iter().position(|r| r.id == run_id) {
                    let mut info = self.approvals.remove(idx);
                    info.status = "running".into();
                    self.runs.push(info);
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::Routing,
                    text: format!("↺ approval · {decision}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── tool_use (Phase 5.1/5.2) ──
            "tool_use" => {
                let title = data.get("title").and_then(|v| v.as_str()).unwrap_or("");
                let kind = data.get("kind").and_then(|v| v.as_str()).unwrap_or("");

                if self.focus_run_id.as_deref() == Some(run_id) {
                    self.tool_count = self.tool_count.saturating_add(1);
                    // Capture for the live-action line in chain topology.
                    self.last_tool = Some(if !title.is_empty() {
                        title.to_string()
                    } else {
                        kind.to_string()
                    });
                    self.last_tool_at = Some(Instant::now());
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::ToolUse,
                    text: format!("⚡ tool_use · {kind} · {title}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── blueprints_injected (Phase 5.4/5.5) ──
            "blueprints_injected" => {
                let matches = data
                    .get("matches")
                    .and_then(|v| v.as_array())
                    .cloned()
                    .unwrap_or_default();

                // Hydrate App.blueprints state for the [b] toggle panel.
                if self.focus_run_id.as_deref() == Some(run_id) {
                    self.blueprints.clear();
                    for m in &matches {
                        if let (Some(rid), Some(util), Some(sim)) = (
                            m.get("run_id").and_then(|v| v.as_str()),
                            m.get("utility_name").and_then(|v| v.as_str()),
                            m.get("similarity").and_then(|v| v.as_f64()),
                        ) {
                            let kind_str =
                                m.get("kind").and_then(|v| v.as_str()).unwrap_or("reuse");
                            let bk = if kind_str == "avoid" {
                                BlueprintKind::Avoid
                            } else {
                                BlueprintKind::Reuse
                            };
                            self.blueprints.push(BlueprintMatch {
                                run_id: rid.into(),
                                utility_name: util.into(),
                                similarity: sim as f32,
                                kind: bk,
                            });
                        }
                    }
                }

                let top = matches
                    .iter()
                    .filter_map(|m| m.get("similarity").and_then(|v| v.as_f64()))
                    .fold(0.0_f64, f64::max);

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::BlueprintsInjected,
                    text: format!(
                        "▼ blueprints injected · top {:.2} · {} matches",
                        top,
                        matches.len()
                    ),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── sat_started ──
            "sat_started" => {
                let parent = data
                    .get("parent_run_id")
                    .and_then(|v| v.as_str())
                    .unwrap_or("?");

                self.sat_verdict = Some("… judging".into());
                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::SessionUpdate,
                    text: format!("◆ sat started · parent {}", &parent[..8.min(parent.len())]),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── sat_persona_score ──
            "sat_persona_score" => {
                let persona = data
                    .get("persona")
                    .and_then(|v| v.as_str())
                    .unwrap_or("?")
                    .to_lowercase();
                let score = data.get("score").and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;

                let entry = self.sat_scores.entry(persona.clone()).or_default();
                entry.target = score;
                entry.last_updated = Some(ts);
                // current will animate toward target via step_animations.

                // Phase 6.3: auto-return to SatDials when judging is happening.
                // Blueprints / other modes lose priority while scores are being recorded.
                if self.mode == PanelMode::Blueprints {
                    self.mode = PanelMode::SatDials;
                }

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::SessionUpdate,
                    text: format!("◆ sat_persona · {persona} · score {score:.1}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            // ── sat_verdict ──
            "sat_verdict" => {
                let verdict = data
                    .get("verdict")
                    .and_then(|v| v.as_str())
                    .unwrap_or("?")
                    .to_string();

                self.sat_verdict = Some(verdict.clone());

                let kind = if verdict.to_uppercase().contains("PASS") {
                    EventKind::Success
                } else {
                    EventKind::Error
                };
                let glyph = if verdict.to_uppercase().contains("PASS") {
                    ""
                } else {
                    ""
                };

                self.push_waterfall(EventDisplayed {
                    ts,
                    kind,
                    text: format!("{glyph} sat verdict · {verdict}"),
                    run_id: Some(run_id.to_string()),
                });
            }

            _ => {
                // Unknown variant — surface as a raw line so we notice schema drift.
                self.push_waterfall(EventDisplayed {
                    ts,
                    kind: EventKind::StateTransition,
                    text: format!("? unknown · {event_type}"),
                    run_id: Some(run_id.to_string()),
                });
            }
        }
    }

    fn handle_confirmation(&mut self, key: KeyEvent) -> Option<Action> {
        match key.code {
            KeyCode::Char('y') | KeyCode::Char('Y') => {
                let conf = self.confirmation.take().unwrap();
                match conf.action {
                    Action::ApproveRun(id) => Some(Action::ApproveRun(id)),
                    Action::TriggerNext => Some(Action::TriggerNext),
                    Action::Quit => Some(Action::Quit),
                }
            }
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => {
                self.confirmation = None;
                None
            }
            _ => None,
        }
    }

    fn handle_key(&mut self, key: KeyEvent) -> Option<Action> {
        // Ctrl+C always quits
        if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
            return Some(Action::Quit);
        }

        match key.code {
            KeyCode::Char('q') => Some(Action::Quit),
            KeyCode::Char('?') => {
                self.show_help = !self.show_help;
                None
            }
            KeyCode::Esc if self.show_help => {
                self.show_help = false;
                None
            }
            // ── Phase 6 mode toggles ──
            KeyCode::Char('s') => {
                self.toggle_mode(PanelMode::Shifts);
                None
            }
            KeyCode::Char('b') => {
                self.toggle_mode(PanelMode::Blueprints);
                None
            }
            KeyCode::Char('k') => {
                self.toggle_mode(PanelMode::Backlog);
                None
            }
            KeyCode::Char('j') => {
                self.toggle_mode(PanelMode::Judges);
                None
            }
            KeyCode::Char('d') => {
                // Force back to dials regardless of current mode.
                self.mode = PanelMode::SatDials;
                None
            }
            KeyCode::Char('f') => {
                self.waterfall_filter = self.waterfall_filter.next();
                None
            }
            KeyCode::Enter => {
                // Approve focused shift if it's awaiting approval.
                if let Some(rid) = &self.focus_run_id
                    && self.approvals.iter().any(|r| r.id == *rid)
                {
                    return Some(Action::ApproveRun(rid.clone()));
                }
                None
            }
            KeyCode::Tab => {
                self.focused = self.focused.next();
                None
            }
            KeyCode::BackTab => {
                self.focused = self.focused.prev();
                None
            }
            KeyCode::Up => {
                self.move_selection(-1);
                None
            }
            KeyCode::Down => {
                self.move_selection(1);
                None
            }
            KeyCode::Esc => {
                self.deselect();
                None
            }
            KeyCode::Char('a') if self.focused == Panel::Approvals => {
                if let Some(idx) = self.approvals_state.selected()
                    && let Some(run) = self.approvals.get(idx)
                {
                    self.confirmation = Some(Confirmation {
                        action: Action::ApproveRun(run.id.clone()),
                        prompt: format!("Approve run {}? [y/n]", &run.id[..8.min(run.id.len())]),
                    });
                }
                None
            }
            KeyCode::Char('n') => {
                self.confirmation = Some(Confirmation {
                    action: Action::TriggerNext,
                    prompt: "Trigger next action? [y/n]".into(),
                });
                None
            }
            _ => None,
        }
    }

    fn move_selection(&mut self, delta: i32) {
        match self.focused {
            Panel::Runs => {
                if self.runs.is_empty() {
                    return;
                }
                let current = self.runs_state.selected().unwrap_or(0) as i32;
                let next = (current + delta).clamp(0, self.runs.len() as i32 - 1) as usize;
                self.runs_state.select(Some(next));
            }
            Panel::Approvals => {
                if self.approvals.is_empty() {
                    return;
                }
                let current = self.approvals_state.selected().unwrap_or(0) as i32;
                let next = (current + delta).clamp(0, self.approvals.len() as i32 - 1) as usize;
                self.approvals_state.select(Some(next));
            }
            _ => {}
        }
    }

    fn deselect(&mut self) {
        match self.focused {
            Panel::Runs => self.runs_state.select(None),
            Panel::Approvals => self.approvals_state.select(None),
            _ => {}
        }
    }

    /// Update all panel data from a list of runs.
    pub fn update_from_runs(&mut self, runs: Vec<Run>) {
        self.runs.clear();
        self.approvals.clear();

        for run in &runs {
            let issue = match (&run.issue_number, &run.issue_title) {
                (Some(num), Some(title)) => format!("#{} \u{2014} {}", num, title),
                (Some(num), None) => format!("#{}", num),
                _ => "-".into(),
            };
            // Capture timestamps so refresh_durations() can live-tick this row.
            if let Some(t) = run.started_at {
                self.run_started_at.entry(run.id.clone()).or_insert(t);
            }
            if let Some(t) = run.completed_at {
                self.run_completed_at.insert(run.id.clone(), t);
            }
            let duration = format_duration(run.started_at, run.completed_at);
            let info = RunInfo {
                id: run.id.clone(),
                status: run.status.to_string(),
                issue,
                duration,
            };

            match run.status {
                RunStatus::AwaitingApproval => self.approvals.push(info),
                _ => self.runs.push(info),
            }
        }

        // Keep selection in bounds
        if !self.runs.is_empty() && self.runs_state.selected().is_none() {
            self.runs_state.select(Some(0));
        }
        if !self.approvals.is_empty() && self.approvals_state.selected().is_none() {
            self.approvals_state.select(Some(0));
        }
    }

    pub fn render(&mut self, frame: &mut Frame) {
        // Step time-based animations before drawing.
        self.step_animations();
        // Advance the agent oscilloscope one sample.
        self.scope_step();
        crate::tui::panels::render_all(frame, self);
    }
}

fn format_duration(start: Option<DateTime<Utc>>, end: Option<DateTime<Utc>>) -> String {
    let start = match start {
        Some(s) => s,
        None => return "-".into(),
    };
    let end = end.unwrap_or_else(Utc::now);
    let secs = (end - start).num_seconds().max(0) as u64;
    format_short_secs(secs)
}

/// Parse "5 patterns extracted, 1248 total in store" → Some(1248).
/// Returns None if the pattern doesn't match — best-effort cosmetic helper.
fn parse_total_in_store(summary: &str) -> Option<u64> {
    let after = summary.split(',').nth(1)?.trim();
    // Expect "<N> total in store"
    let n_str = after.split_whitespace().next()?;
    n_str.parse::<u64>().ok()
}

/// Format a non-negative duration into the compact "Ns / Nm:SSs / NhMMm" form
/// the chain topology and shifts list use (`6s`, `8m22s`, `1h05m`).
fn format_short_secs(secs: u64) -> String {
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m{:02}s", secs / 60, secs % 60)
    } else {
        format!("{}h{:02}m", secs / 3600, (secs % 3600) / 60)
    }
}