Skip to main content

nmbrs_tui/
observer.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! TUI-driving [`RunObserver`](nmbrs_runtime::observer::RunObserver) implementation.
5//!
6//! [`TuiObserver`] is the glue layer between
7//! [`nmbrs_runtime::observer::RunObserver`] (lifecycle callbacks
8//! emitted by the runner) and the rest of this crate
9//! ([`crate::run_state_actor`], [`crate::reporter::TuiReporter`],
10//! [`crate::app::App`]). The runner only knows about the trait;
11//! this module owns the translation of trait callbacks into
12//! [`crate::run_state_actor::RunStateCmd`] messages sent to the
13//! display-side actor.
14//!
15//! Lifecycle:
16//!
17//! 1. Persona spawns the RunState actor (via
18//!    [`crate::run_state_actor::spawn_run_state_actor`]),
19//!    constructs a [`TuiObserver`] holding the resulting
20//!    [`crate::run_state_actor::RunStateHandle`], and hands it
21//!    to [`nmbrs_runtime::runner::run_with_observer`].
22//! 2. The runner calls `phase_starting` / `phase_progress` /
23//!    `phase_completed` / `log` / etc. as the workload runs;
24//!    each call sends one or more `RunStateCmd`s into the
25//!    actor's inbox — no write lock anywhere.
26//! 3. The first `phase_starting` triggers
27//!    `TuiObserver::ensure_tui_started` which spawns the
28//!    [`crate::app::App`] thread (also a snapshot reader and
29//!    command sender); pre-phase work runs with plain stderr
30//!    output so a startup failure leaves the terminal clean.
31//! 4. After the run completes, the persona calls
32//!    [`TuiObserver::shutdown`] to wait on the TUI thread, then
33//!    [`print_post_run_summary`] for the post-teardown summary
34//!    line + tree, then exits with an appropriate status from
35//!    [`unreached_phase_exit_code`].
36
37use parking_lot::Mutex;
38use std::sync::atomic::{AtomicBool, Ordering};
39use std::sync::{Arc, mpsc};
40use std::thread::JoinHandle;
41use std::time::Duration;
42
43use nmbrs_metrics::cadence::Cadences;
44use nmbrs_metrics::metrics_query::MetricsQuery;
45use nmbrs_metrics::snapshot::MetricSet;
46
47use crate::reporter::TuiReporter;
48use crate::run_state_actor::{RunStateCmd, RunStateHandle};
49use crate::state::{EntryKind, LogEntry, LogSeverity, PhaseEntry, PhaseStatus, RunState};
50
51use nmbrs_runtime::lifecycle::EventType;
52use nmbrs_runtime::readouts as ro;
53
54/// Per-row `ReadoutContext` for the `[ok] [N/total] name
55/// 0.02s` lines. Routes through the SRD-63 `phase_summary`
56/// readout so the marker / sequence / duration formatting
57/// lives in one place. The call sites (the persisted
58/// scenario-tree render in [`render_scenario_tree`] and the
59/// focused-failures inset in [`print_post_run_summary`])
60/// supply the depth-based indent — the readout doesn't know
61/// about the surrounding chrome.
62struct SummaryRowContext {
63    name: String,
64    labels: String,
65    seq: Option<(usize, usize)>,
66    duration_secs: f64,
67    state: ro::LifecycleState,
68}
69
70/// Per-row `ReadoutContext` for scope-header rows in the
71/// post-run summary tree walk and the focused-error
72/// inset's scope ancestors. Routes through the SRD-63
73/// `scope_header` readout so the bullet + italic
74/// formatter lives alongside the rest of the engine
75/// (Push 8c).
76struct ScopeRowContext {
77    name: String,
78    use_color: bool,
79}
80
81impl ScopeRowContext {
82    fn new(name: &str, use_color: bool) -> Self {
83        Self {
84            name: name.to_string(),
85            use_color,
86        }
87    }
88}
89
90impl ro::ReadoutContext for ScopeRowContext {
91    fn subject_name(&self) -> &str {
92        &self.name
93    }
94    fn subject_seq(&self) -> Option<(usize, usize)> {
95        None
96    }
97    fn subject_labels(&self) -> &str {
98        ""
99    }
100    fn cycles_completed(&self) -> u64 {
101        0
102    }
103    fn cycles_total(&self) -> u64 {
104        0
105    }
106    fn ops_ok(&self) -> u64 {
107        0
108    }
109    fn errors(&self) -> u64 {
110        0
111    }
112    fn retries(&self) -> u64 {
113        0
114    }
115    fn concurrency(&self) -> usize {
116        0
117    }
118    fn elapsed_secs(&self) -> f64 {
119        0.0
120    }
121    fn consumed(&self) -> u64 {
122        0
123    }
124    fn status_metric_chips(&self) -> String {
125        String::new()
126    }
127    fn depth_indent(&self) -> &str {
128        ""
129    }
130    fn use_color(&self) -> bool {
131        self.use_color
132    }
133    fn event(&self) -> EventType {
134        EventType::EachStart
135    }
136}
137
138/// `ReadoutContext` for the post-run summary's session-scope
139/// readouts (`session_banner` for the opening line,
140/// `session_summary` for the `phases: …` rollup). Carries the
141/// scenario / workload identity and the per-status phase
142/// counts; everything else falls through to the trait
143/// defaults.
144struct SessionSummaryContext {
145    scenario_name: String,
146    workload_file: String,
147    completed: usize,
148    failed: usize,
149    pending: usize,
150    total: usize,
151}
152
153impl ro::ReadoutContext for SessionSummaryContext {
154    fn subject_name(&self) -> &str {
155        "session"
156    }
157    fn subject_id(&self) -> String {
158        "session".to_string()
159    }
160    fn event(&self) -> EventType {
161        EventType::SessionEnd
162    }
163    fn session_scenario_name(&self) -> &str {
164        &self.scenario_name
165    }
166    fn session_workload_file(&self) -> &str {
167        &self.workload_file
168    }
169    fn session_phases_completed(&self) -> usize {
170        self.completed
171    }
172    fn session_phases_failed(&self) -> usize {
173        self.failed
174    }
175    fn session_phases_pending(&self) -> usize {
176        self.pending
177    }
178    fn session_phases_total(&self) -> usize {
179        self.total
180    }
181}
182
183impl ro::ReadoutContext for SummaryRowContext {
184    fn subject_name(&self) -> &str {
185        &self.name
186    }
187    fn subject_seq(&self) -> Option<(usize, usize)> {
188        self.seq
189    }
190    fn subject_labels(&self) -> &str {
191        &self.labels
192    }
193    fn elapsed_secs(&self) -> f64 {
194        self.duration_secs
195    }
196    fn event(&self) -> EventType {
197        EventType::PhaseEnd
198    }
199    fn subject_state(&self) -> ro::LifecycleState {
200        self.state.clone()
201    }
202}
203
204/// Convert a TUI-side [`LogSeverity`] back to the activity-side
205/// [`nmbrs_runtime::observer::LogLevel`] for comparison against
206/// [`TuiObserver::min_level`]. The two enums carry the same four
207/// rungs in the same order; this is a flat one-to-one mapping
208/// kept private to the observer.
209fn log_severity_to_level(s: LogSeverity) -> nmbrs_runtime::observer::LogLevel {
210    match s {
211        LogSeverity::Debug => nmbrs_runtime::observer::LogLevel::Debug,
212        LogSeverity::Info => nmbrs_runtime::observer::LogLevel::Info,
213        LogSeverity::Warn => nmbrs_runtime::observer::LogLevel::Warn,
214        LogSeverity::Error => nmbrs_runtime::observer::LogLevel::Error,
215    }
216}
217
218/// `RunObserver` impl that drives [`crate::app::App`] from
219/// runner lifecycle events.
220///
221/// The TUI terminal takeover (raw mode + alternate screen) is
222/// deferred until the first phase actually starts. Pre-phase
223/// work runs with plain stderr output. This keeps the terminal
224/// clean if the run fails before any activity begins.
225pub struct TuiObserver {
226    state: RunStateHandle,
227    /// Base-cadence frame reporter, taken by the runner via
228    /// `reporters()`. Forwards every scheduler tick's delta
229    /// frame into the TUI so history rings + sparklines stay
230    /// live.
231    reporter: Mutex<Option<TuiReporter>>,
232    /// Receiver end of the base-frame channel. Taken when the
233    /// TUI thread is spawned on the first phase start.
234    frame_rx: Mutex<Option<mpsc::Receiver<MetricSet>>>,
235    /// User-declared cadences for the TUI's barchart view.
236    /// Surfaced to the runner through `RunObserver::cadences()`
237    /// so the cadence tree is planned with these values.
238    cadences: Cadences,
239    /// Shared `MetricsQuery` handle — populated by the runner
240    /// via `on_metrics_query` once the cadence reporter is
241    /// built.
242    metrics_query: Mutex<Option<Arc<MetricsQuery>>>,
243    /// Join handle for the TUI thread, once spawned.
244    tui_handle: Mutex<Option<JoinHandle<()>>>,
245    /// True once the TUI thread has been spawned and owns the
246    /// terminal. Shared with the thread so it can flip it
247    /// false on exit — which routes `log()` and phase
248    /// lifecycle events back to stderr if the user pressed `q`
249    /// before the run finished.
250    tui_active: Arc<AtomicBool>,
251    /// Minimum severity that the stderr fallback paths emit.
252    /// Same role as
253    /// [`nmbrs_runtime::observer::StderrObserver::min_level`] —
254    /// without this filter, dropping out of the TUI at runtime
255    /// (`q` pressed) drowned the operator in `Debug`-level
256    /// fiber-lifecycle traces. Default `Info`, override via
257    /// the workload's `loglevel=` param.
258    min_level: nmbrs_runtime::observer::LogLevel,
259}
260
261impl TuiObserver {
262    /// Build a fresh observer over a [`RunStateHandle`].
263    /// `cadences` is forwarded to the runner via
264    /// `RunObserver::cadences()`. Stderr fallback severity
265    /// defaults to `Info`; use [`Self::with_min_level`] to
266    /// override.
267    pub fn new(state: RunStateHandle, cadences: Cadences) -> Self {
268        let (reporter, frame_rx) = TuiReporter::channel();
269        Self {
270            state,
271            reporter: Mutex::new(Some(reporter)),
272            frame_rx: Mutex::new(Some(frame_rx)),
273            tui_handle: Mutex::new(None),
274            tui_active: Arc::new(AtomicBool::new(false)),
275            cadences,
276            metrics_query: Mutex::new(None),
277            min_level: nmbrs_runtime::observer::LogLevel::Info,
278        }
279    }
280
281    /// Override the minimum severity that the pre-TUI stderr
282    /// mirror and the post-TUI stderr fallback emit. Has no
283    /// effect on what the TUI's in-app log panel shows — that
284    /// is filtered by the panel's own LOD knobs.
285    pub fn with_min_level(mut self, min_level: nmbrs_runtime::observer::LogLevel) -> Self {
286        self.min_level = min_level;
287        self
288    }
289
290    /// Spawn the TUI thread on first use. Subsequent calls are
291    /// no-ops.
292    fn ensure_tui_started(&self) {
293        if self.tui_active.load(Ordering::Acquire) {
294            return;
295        }
296        let rx = match self.frame_rx.lock().take() {
297            Some(rx) => rx,
298            None => return, // already claimed
299        };
300        let query = match self.metrics_query.lock().clone() {
301            Some(q) => q,
302            None => return, // runner hasn't wired the query yet
303        };
304        let state = self.state.clone();
305        let tui_active = self.tui_active.clone();
306        let min_level = self.min_level;
307        let handle = std::thread::spawn(move || {
308            let mut app = crate::app::App::new(rx, state.clone(), query);
309            if let Err(e) = app.run() {
310                eprintln!("TUI error: {e}");
311            }
312            // TUI thread has exited and restored the terminal.
313            // If the run is still going (user hit `q` mid-run),
314            // flip the active flag FIRST so subsequent log() /
315            // phase_starting() calls route to stderr. Then
316            // replay the captured log ring buffer so the console
317            // looks as if tui=off were in effect from the
318            // start, plus a notice indicating the fallback.
319            let was_active = tui_active.swap(false, Ordering::AcqRel);
320            let snap = state.load();
321            if was_active && !snap.finished {
322                // Replay obeys the same severity filter the
323                // live stderr fallback below uses — otherwise
324                // dropping out of the TUI dumps the entire
325                // in-memory Debug-level ring buffer to the
326                // console, which is exactly the noise the
327                // user wanted suppressed.
328                for entry in &snap.log_messages {
329                    if log_severity_to_level(entry.severity) >= min_level {
330                        eprintln!("{}", entry.message);
331                    }
332                }
333                eprintln!("--- tui disabled (q pressed); falling back to tui=off mode ---");
334            }
335        });
336        *self.tui_handle.lock() = Some(handle);
337        self.tui_active.store(true, Ordering::Release);
338    }
339
340    /// Signal the TUI (if running) to exit and wait for the
341    /// terminal to be restored. Safe to call when the TUI never
342    /// started.
343    pub fn shutdown(&self) {
344        self.state.send(RunStateCmd::RunFinished);
345        let handle = self.tui_handle.lock().take();
346        if let Some(h) = handle {
347            let _ = h.join();
348        }
349    }
350}
351
352impl nmbrs_runtime::observer::RunObserver for TuiObserver {
353    fn op_measure(
354        &self,
355        parent_phase: nmbrs_runtime::scene_tree::SceneNodeId,
356        op_name: &str,
357        text: &str,
358    ) {
359        self.state
360            .send(crate::run_state_actor::RunStateCmd::OpMeasure {
361                parent: parent_phase,
362                op_name: op_name.to_string(),
363                text: text.to_string(),
364            });
365    }
366
367    fn session_dir_ready(&self, dir: &std::path::Path) {
368        // Opens <dir>/transcript.log in the actor and flushes everything
369        // buffered since actor start.
370        self.state
371            .send(crate::run_state_actor::RunStateCmd::OpenTranscript(
372                dir.join("transcript.log"),
373            ));
374    }
375
376    fn sysmon_update(&self, sample: &nmbrs_runtime::sysmon::SysmonSample) {
377        // Ambient session state, not a display trigger: no ensure_tui_started.
378        self.state.send(RunStateCmd::Sysmon(sample.clone()));
379    }
380
381    fn phase_starting(
382        &self,
383        scene_node_id: nmbrs_runtime::scene_tree::SceneNodeId,
384        name: &str,
385        labels: &str,
386        op_templates: usize,
387        total_cycles: u64,
388        concurrency: usize,
389    ) {
390        self.ensure_tui_started();
391        self.state.send(RunStateCmd::PhaseStarting {
392            exec_id: nmbrs_runtime::execution_context::current_exec_id(),
393            scene_node_id,
394            name: name.to_string(),
395            labels: labels.to_string(),
396            op_templates,
397            total_cycles,
398            concurrency,
399        });
400        // Route the human-readable line through the canonical
401        // event channel so it lands in `session.log` even when
402        // the TUI is suppressing stderr. Same `[name] (root-first
403        // coords): …` shape the terminal-mode observer emits, so
404        // the archived log reads identically to stderr.
405        let template_word = if op_templates == 1 {
406            "op template"
407        } else {
408            "op templates"
409        };
410        let cycle_word = if total_cycles == 1 { "cycle" } else { "cycles" };
411        let coords_part = if labels.is_empty() {
412            String::new()
413        } else {
414            format!(" {}", crate::widgets::coords_root_first(labels))
415        };
416        nmbrs_runtime::observer::log(
417            nmbrs_runtime::observer::LogLevel::Info,
418            &format!(
419                "[{name}]{coords_part}: {op_templates} {template_word}, {total_cycles} {cycle_word}, concurrency={concurrency}"
420            ),
421        );
422    }
423
424    fn phase_completed(
425        &self,
426        scene_node_id: nmbrs_runtime::scene_tree::SceneNodeId,
427        name: &str,
428        labels: &str,
429        duration_secs: f64,
430    ) {
431        self.state.send(RunStateCmd::PhaseCompleted {
432            exec_id: nmbrs_runtime::execution_context::current_exec_id(),
433            scene_node_id,
434            name: name.to_string(),
435            labels: labels.to_string(),
436            duration_secs,
437        });
438        // Block until the TUI has rendered at least one frame
439        // reflecting the just-completed phase before letting the
440        // executor proceed to the next one. Bypasses tick_rate;
441        // bounded so a wedged TUI can never hang the run.
442        // Skip when the TUI hasn't taken the screen yet — pre-
443        // TUI phase completions land on stderr / session.log and
444        // there's nothing to render.
445        if self.tui_active.load(Ordering::Acquire) {
446            self.state.flush_frame(std::time::Duration::from_secs(2));
447        }
448    }
449
450    fn phase_failed(
451        &self,
452        scene_node_id: nmbrs_runtime::scene_tree::SceneNodeId,
453        name: &str,
454        labels: &str,
455        error: &str,
456    ) {
457        self.state.send(RunStateCmd::PhaseFailed {
458            exec_id: nmbrs_runtime::execution_context::current_exec_id(),
459            scene_node_id,
460            name: name.to_string(),
461            labels: labels.to_string(),
462            error: error.to_string(),
463        });
464        // Same end-of-phase rendering guarantee as phase_completed.
465        if self.tui_active.load(Ordering::Acquire) {
466            self.state.flush_frame(std::time::Duration::from_secs(2));
467        }
468    }
469
470    fn op_starting(&self, parent_phase: nmbrs_runtime::scene_tree::SceneNodeId, op_name: &str) {
471        self.state.send(RunStateCmd::OpStarting {
472            parent: parent_phase,
473            op_name: op_name.to_string(),
474        });
475    }
476
477    fn op_completed(
478        &self,
479        parent_phase: nmbrs_runtime::scene_tree::SceneNodeId,
480        op_name: &str,
481        duration_secs: f64,
482    ) {
483        self.state.send(RunStateCmd::OpCompleted {
484            parent: parent_phase,
485            op_name: op_name.to_string(),
486            duration_secs,
487        });
488    }
489
490    fn op_failed(
491        &self,
492        parent_phase: nmbrs_runtime::scene_tree::SceneNodeId,
493        op_name: &str,
494        error: &str,
495    ) {
496        self.state.send(RunStateCmd::OpFailed {
497            parent: parent_phase,
498            op_name: op_name.to_string(),
499            error: error.to_string(),
500        });
501    }
502
503    fn phase_progress(&self, update: &nmbrs_runtime::observer::PhaseProgressUpdate) {
504        self.state.send(RunStateCmd::PhaseProgress(update.clone()));
505    }
506
507    fn phase_render_attach(&self, handle: nmbrs_runtime::observer::PhaseRenderHandle) {
508        // SRD-100 P2 — hand the per-phase render handle to the actor so
509        // the active sink folds `active_phases` and renders each phase's
510        // status itself (replacing the inline-status producer thread).
511        self.state.send(RunStateCmd::AttachPhaseRender(handle));
512    }
513
514    fn run_finished(&self) {
515        self.state.send(RunStateCmd::RunFinished);
516    }
517
518    fn log(&self, level: nmbrs_runtime::observer::LogLevel, message: &str) {
519        self.log_tagged(level, nmbrs_runtime::observer::EventTag::default(), message);
520    }
521
522    fn log_tagged(
523        &self,
524        level: nmbrs_runtime::observer::LogLevel,
525        tag: nmbrs_runtime::observer::EventTag,
526        message: &str,
527    ) {
528        let severity = match level {
529            nmbrs_runtime::observer::LogLevel::Trace => LogSeverity::Debug,
530            nmbrs_runtime::observer::LogLevel::Debug => LogSeverity::Debug,
531            nmbrs_runtime::observer::LogLevel::Info => LogSeverity::Info,
532            nmbrs_runtime::observer::LogLevel::Warn => LogSeverity::Warn,
533            nmbrs_runtime::observer::LogLevel::Error => LogSeverity::Error,
534        };
535        self.state.send(RunStateCmd::Log {
536            severity,
537            tag,
538            message: message.to_string(),
539        });
540        // Stderr fallback fires both *before* the TUI claims
541        // the terminal (pre-phase diagnostics like session id,
542        // metrics path, scenario tree) and *after* the TUI
543        // tears down mid-run (`q` pressed). Apply the same
544        // `min_level` filter `StderrObserver` uses, otherwise
545        // the post-`q` console gets Debug-level fiber-exit
546        // chatter that the operator doesn't want.
547        if !self.tui_active.load(Ordering::Acquire) && level >= self.min_level {
548            eprintln!("{message}");
549        }
550    }
551
552    fn suppresses_stderr(&self) -> bool {
553        self.tui_active.load(Ordering::Acquire)
554    }
555
556    fn live_suppress_flag(&self) -> Option<Arc<AtomicBool>> {
557        // Hand the runner the same flag the TUI thread flips on
558        // teardown — when the user dismisses the TUI mid-run,
559        // this AtomicBool drops to `false` and any consumer
560        // polling it (notably the activity's inline status
561        // thread) resumes its tui=off behavior automatically.
562        Some(self.tui_active.clone())
563    }
564
565    fn scenario_pre_mapped(&self, tree: &nmbrs_runtime::scene_tree::SceneTree) {
566        self.state.send(RunStateCmd::InstallTree(tree.clone()));
567    }
568
569    fn reporters(&self) -> Vec<(Duration, Box<dyn nmbrs_metrics::scheduler::Reporter>)> {
570        let mut guard = self.reporter.lock();
571        let Some(r) = guard.take() else {
572            return Vec::new();
573        };
574        vec![(
575            Duration::from_secs(1),
576            Box::new(r) as Box<dyn nmbrs_metrics::scheduler::Reporter>,
577        )]
578    }
579
580    fn cadences(&self) -> Option<Cadences> {
581        Some(self.cadences.clone())
582    }
583
584    fn on_metrics_query(&self, query: Arc<MetricsQuery>) {
585        *self.metrics_query.lock() = Some(query);
586    }
587}
588
589// ============================================================
590// Post-run summary
591// ============================================================
592
593/// Print a summary of the run after the TUI has torn down.
594///
595/// Without this, successful runs leave the terminal with no
596/// indication anything happened. Fails-soft if the state lock
597/// is poisoned.
598///
599/// `session_dir` is `None` when the caller cannot name a directory this run owns
600/// — a dry-run without an explicit `--session*`, whose own directory the CLI
601/// never learns. The summary still prints; only the artifact write is skipped.
602/// Passing the previous session's directory instead would write this run's
603/// artifacts into an unrelated real session.
604pub fn print_post_run_summary(
605    run_state: &RunStateHandle,
606    run_result: &Result<(), String>,
607    session_dir: Option<&std::path::Path>,
608) {
609    let s = run_state.load();
610    let s: &RunState = &s;
611
612    eprintln!();
613
614    // Count phases only (scope headers are visual, not
615    // executable).
616    let phases_only: Vec<&PhaseEntry> = s
617        .phases
618        .iter()
619        .filter(|p| p.kind == EntryKind::Phase)
620        .collect();
621    let completed = phases_only
622        .iter()
623        .filter(|p| matches!(p.status, PhaseStatus::Completed))
624        .count();
625    let failed = phases_only
626        .iter()
627        .filter(|p| matches!(p.status, PhaseStatus::Failed(_)))
628        .count();
629    let pending = phases_only
630        .iter()
631        .filter(|p| matches!(p.status, PhaseStatus::Pending))
632        .count();
633
634    // SRD-63 Push 9d: route the opening banner + the
635    // `phases:  X completed, Y failed, …` rollup through
636    // the readout engine. Both share one
637    // `SessionSummaryContext` so the totals and identity
638    // accessors agree.
639    let session_ctx = SessionSummaryContext {
640        scenario_name: s.scenario_name.clone(),
641        workload_file: s.workload_file.clone(),
642        completed,
643        failed,
644        pending,
645        total: phases_only.len(),
646    };
647    {
648        let mut s_buf = String::with_capacity(96);
649        let mut buf = ro::buf::StringBuf::new(&mut s_buf);
650        use ro::Readout;
651        ro::builtins::session_banner::SessionBanner.render(
652            &session_ctx,
653            ro::Lod::Labeled,
654            ro::ContentMode::Value,
655            &ro::ReadoutOptions::new(),
656            &mut buf,
657        );
658        if !s_buf.is_empty() {
659            eprintln!("{s_buf}");
660        }
661    }
662    match session_dir {
663        Some(d) => eprintln!("logs:    {}", d.display()),
664        // Naming `sessions/latest` here would be a lie: a dry-run does not claim
665        // it, so it still points at the previous real run.
666        None => eprintln!("logs:    (dry-run session; not linked as latest)"),
667    }
668
669    if phases_only.is_empty() {
670        eprintln!("phases:  none executed");
671    } else {
672        let mut s_buf = String::with_capacity(96);
673        {
674            let mut buf = ro::buf::StringBuf::new(&mut s_buf);
675            use ro::Readout;
676            ro::builtins::session_summary::SessionSummary.render(
677                &session_ctx,
678                ro::Lod::Labeled,
679                ro::ContentMode::Value,
680                &ro::ReadoutOptions::new(),
681                &mut buf,
682            );
683        }
684        eprintln!("{s_buf}");
685
686        // The full `[ok]` scenario-tree walk used to print here.
687        // On large runs (hundreds of phases) it scrolled the live
688        // session output off-screen and duplicated data available
689        // elsewhere, so it no longer prints to stderr. Instead the
690        // same view — rendered through the same `scope_header` /
691        // `phase_summary` readouts — is persisted to
692        // `<session_dir>/scenario_tree.txt` and replayable on
693        // demand via `nmbrs replay --format=tree`. The header above
694        // (session / logs / phases) plus the focused failures inset
695        // below are all that remain inline.
696        let tree = render_scenario_tree(&s.phases);
697        // `None` ⇒ no directory this run owns, so skip the write rather than put
698        // this run's tree in another session's directory. `nmbrs replay
699        // --format=tree` then has nothing to read for a dry-run, which is the
700        // correct trade against corrupting a real run. Only the write is skipped
701        // — the failures inset below still prints.
702        if let Some(tree_dir) = session_dir {
703            let tree_path = tree_dir.join("scenario_tree.txt");
704            match std::fs::write(&tree_path, &tree) {
705                Ok(()) => {
706                    eprintln!("scenario tree: nmbrs replay --format=tree");
707                }
708                Err(e) => {
709                    // Best-effort: a write failure must not crash the
710                    // post-run summary or hide the useful header. Note
711                    // it (not silently) and carry on without the
712                    // pointer, since the artifact it points at is
713                    // missing.
714                    nmbrs_runtime::observer::log(
715                        nmbrs_runtime::observer::LogLevel::Warn,
716                        &format!(
717                            "could not persist scenario tree to {}: {e}",
718                            tree_path.display()
719                        ),
720                    );
721                }
722            }
723        }
724    }
725
726    // Focused error inset: for each failed phase, print the
727    // chain of for_each / for_combinations / do_while scopes
728    // that enclose it, then the failed phase itself. The
729    // reader gets the exact binding context that led to the
730    // failure without having to open the full scenario tree
731    // (now persisted to `scenario_tree.txt` rather than printed
732    // inline).
733    let failed: Vec<(usize, &PhaseEntry)> = s
734        .phases
735        .iter()
736        .enumerate()
737        .filter(|(_, p)| p.kind == EntryKind::Phase && matches!(p.status, PhaseStatus::Failed(_)))
738        .collect();
739    if !failed.is_empty() {
740        eprintln!();
741        eprintln!("failures:");
742        for (idx, phase) in &failed {
743            for scope_idx in scope_ancestors(&s.phases, *idx) {
744                let scope = &s.phases[scope_idx];
745                let indent = " ".repeat(scope.depth);
746                // Scope descriptors live in `name` (e.g.
747                // `for_each k=10`); `labels` carries the
748                // structural-identity coord-path string and is
749                // always empty for Scope entries.
750                // Push 8c: route through `scope_header`
751                // readout — same formatter as the post-run
752                // summary above.
753                let mut s_buf = String::with_capacity(64);
754                {
755                    let mut buf = ro::buf::StringBuf::new(&mut s_buf);
756                    use ro::Readout;
757                    ro::builtins::scope_header::ScopeHeader.render(
758                        &ScopeRowContext::new(&scope.name, false),
759                        ro::Lod::Labeled,
760                        ro::ContentMode::Value,
761                        &ro::ReadoutOptions::new(),
762                        &mut buf,
763                    );
764                }
765                eprintln!("  {indent}{s_buf}");
766            }
767            let indent = " ".repeat(phase.depth);
768            // SRD-63 Push 9e: route the failed-phase inset
769            // through `phase_summary` with `show_labels=true`
770            // so the leaf-coord path lands on the failure
771            // line itself. The reader doesn't have to scroll
772            // up to recover which iteration failed; the
773            // failure block is self-contained. Output
774            // matches the prior direct eprintln byte-for-
775            // byte: `[!!] {name} ({labels}) ({err})` with
776            // labels omitted when empty.
777            let err = match &phase.status {
778                PhaseStatus::Failed(e) => e.clone(),
779                _ => String::new(),
780            };
781            let ctx = SummaryRowContext {
782                name: phase.name.clone(),
783                labels: phase.labels.clone(),
784                seq: None,
785                duration_secs: 0.0,
786                state: ro::LifecycleState::Failed(err),
787            };
788            let mut s_buf = String::with_capacity(96);
789            {
790                let mut buf = ro::buf::StringBuf::new(&mut s_buf);
791                let mut opts = ro::ReadoutOptions::new();
792                opts.set("show_labels", ro::OptionValue::Bool(true));
793                use ro::Readout;
794                ro::builtins::phase_summary::PhaseSummary.render(
795                    &ctx,
796                    ro::Lod::Labeled,
797                    ro::ContentMode::Value,
798                    &opts,
799                    &mut buf,
800                );
801            }
802            eprintln!("  {indent}{s_buf}");
803        }
804    }
805
806    // Dump recent log messages on failure for error
807    // context. Each line carries elapsed-since-session-
808    // start (in fractional seconds) plus severity. Header
809    // line names the UTC moment that "0.00000" corresponds
810    // to, so the operator can map the relative timestamps
811    // back to wall-clock if they need to correlate with
812    // other systems.
813    //
814    // The relative-seconds shape is more readable than full
815    // UTC for short-failure dumps: events 0.005 seconds
816    // apart show up as `1.34020` / `1.34520` rather than
817    // `19:14:32.040` / `19:14:32.045` where the operator
818    // has to do mental arithmetic.
819    if run_result.is_err() && !s.log_messages.is_empty() {
820        // The failure dump honours the same display
821        // threshold the live observer used (default Info)
822        // so DBG noise stays in the file but doesn't
823        // re-spam the console at the end of a failed run.
824        // Operators who want the dump fuller pass
825        // `loglevel=debug` (or set the env var) — same
826        // knob as the live path.
827        let display_min = nmbrs_runtime::observer::display_level();
828        let recent: Vec<&LogEntry> = s
829            .log_messages
830            .iter()
831            .rev()
832            .filter(|e| log_severity_to_level(e.severity) >= display_min)
833            .take(20)
834            .collect();
835        if recent.is_empty() {
836            // Everything in the ring was below the
837            // display threshold; nothing useful to show.
838            return;
839        }
840        eprintln!();
841        eprintln!("--- recent log messages ---");
842        eprintln!(
843            "  (elapsed-seconds since session start at {} UTC)",
844            nmbrs_runtime::session::format_log_timestamp(s.started_at_utc)
845        );
846        for entry in recent.into_iter().rev() {
847            let elapsed = entry
848                .at
849                .duration_since(s.started_at_utc)
850                .map(|d| d.as_secs_f64())
851                .unwrap_or(0.0);
852            let ts = format_elapsed_seconds(elapsed);
853            let level = log_severity_to_level(entry.severity);
854            let lvl_tag = match entry.severity {
855                crate::state::LogSeverity::Debug => "DBG",
856                crate::state::LogSeverity::Info => "INF",
857                crate::state::LogSeverity::Warn => "WRN",
858                crate::state::LogSeverity::Error => "ERR",
859            };
860            // Color the entire line by severity so the
861            // dump matches the live console look.
862            let line = format!("  {ts} {lvl_tag} {}", entry.message);
863            eprintln!(
864                "{}",
865                nmbrs_runtime::observer::colorize_log_line(level, &line)
866            );
867        }
868        eprintln!("---");
869    }
870}
871
872/// Render the full scenario-tree view — `· scenario 'x'` /
873/// `· each p` scope headers plus `[ok]/[!!]/[  ] [n/total]
874/// name 1.30s` phase lines, each indented by its scope depth
875/// — to a plain-text string.
876///
877/// This is the view that once printed to stderr at end-of-run
878/// (SRD-63 Push 8/9). It now lands in
879/// `<session_dir>/scenario_tree.txt` at run end and is
880/// replayable via `nmbrs replay --format=tree`, keeping the
881/// live session output clear on large runs.
882///
883/// The rows route through the same `scope_header` and
884/// `phase_summary` readouts the inline view used, so the
885/// persisted text matches byte-for-byte what stderr used to
886/// show. Two deliberate departures: color is off (a file
887/// artifact, read later, shouldn't carry ANSI), and there is
888/// no post-failure tail trim — that guard existed only to
889/// bound on-screen noise, which an on-demand artifact doesn't
890/// have. The persisted tree is always complete.
891fn render_scenario_tree(phases: &[PhaseEntry]) -> String {
892    use std::fmt::Write as _;
893    // `total` for the `[n/total]` sequence chip counts
894    // executable phases only (scope headers are visual).
895    let total = phases.iter().filter(|p| p.kind == EntryKind::Phase).count();
896    let mut out = String::with_capacity(total * 48);
897    for phase in phases.iter() {
898        let indent = " ".repeat(phase.depth);
899
900        if phase.kind == EntryKind::Scope {
901            // Group header — no status glyph. Scope nodes store
902            // their descriptor (e.g. `for_each k=10`) in `name`;
903            // `labels` is reserved for phase identity. Routes
904            // through the `scope_header` readout so the bullet +
905            // italic formatter lives in one place.
906            let mut s_buf = String::with_capacity(64);
907            {
908                let mut buf = ro::buf::StringBuf::new(&mut s_buf);
909                use ro::Readout;
910                ro::builtins::scope_header::ScopeHeader.render(
911                    &ScopeRowContext::new(&phase.name, false),
912                    ro::Lod::Labeled,
913                    ro::ContentMode::Value,
914                    &ro::ReadoutOptions::new(),
915                    &mut buf,
916                );
917            }
918            let _ = writeln!(out, "  {indent}{s_buf}");
919            continue;
920        }
921
922        // Per-phase summary line through the `phase_summary`
923        // readout. Zero-duration completions (the `dryrun=phase`
924        // sentinel) render without the " 0.00s" suffix.
925        let ctx = SummaryRowContext {
926            name: phase.name.clone(),
927            labels: phase.labels.clone(),
928            seq: phase.seq.map(|sq| (sq, total)),
929            duration_secs: phase.duration_secs.unwrap_or(0.0),
930            state: match &phase.status {
931                PhaseStatus::Completed => ro::LifecycleState::Completed,
932                PhaseStatus::Running => ro::LifecycleState::Running,
933                PhaseStatus::Pending => ro::LifecycleState::Pending,
934                PhaseStatus::Failed(err) => ro::LifecycleState::Failed(err.clone()),
935            },
936        };
937        let mut s_buf = String::with_capacity(64);
938        {
939            let mut buf = ro::buf::StringBuf::new(&mut s_buf);
940            use ro::Readout;
941            ro::builtins::phase_summary::PhaseSummary.render(
942                &ctx,
943                ro::Lod::Labeled,
944                ro::ContentMode::Value,
945                &ro::ReadoutOptions::new(),
946                &mut buf,
947            );
948        }
949        let _ = writeln!(out, "  {indent}{s_buf}");
950    }
951    out
952}
953
954/// Render `elapsed_secs` so the integer-seconds part takes
955/// just enough columns and the fractional part fills the
956/// remaining width up to a 7-character target. Once the
957/// session's been running long enough that the integer part
958/// needs ≥4 columns, the fractional part stabilises at 3
959/// digits (millisecond precision) and the seconds column
960/// keeps growing.
961///
962/// Examples:
963/// -   `0.00012` → `0.00012` (5 fractional digits — early-
964///     session events, dense)
965/// -   `9.91234` → `9.91234`
966/// -  `12.5`     → `12.5000` (4 fractional digits)
967/// - `123.4`     → `123.400` (3 fractional digits)
968/// - `1234.5678` → `1234.568` (3 fractional digits, integer widens)
969fn format_elapsed_seconds(elapsed_secs: f64) -> String {
970    let s = elapsed_secs.max(0.0);
971    if s < 10.0 {
972        format!("{s:.5}") // 0.00000 → 9.99999  (7 chars)
973    } else if s < 100.0 {
974        format!("{s:.4}") // 10.0000 → 99.9999 (7 chars)
975    } else {
976        // 100.0+ : 3 fractional digits fixed; the integer part widens
977        // (7 chars over 100–999.999, 8+ from 1000.000 on).
978        format!("{s:.3}")
979    }
980}
981
982/// Return the indices of scope entries that enclose
983/// `target_idx`, ordered outermost-first. Walks backward from
984/// the target collecting the nearest scope at each
985/// strictly-shallower depth.
986fn scope_ancestors(phases: &[PhaseEntry], target_idx: usize) -> Vec<usize> {
987    if target_idx >= phases.len() {
988        return Vec::new();
989    }
990    let mut needed_depth = phases[target_idx].depth;
991    let mut ancestors: Vec<usize> = Vec::new();
992    for i in (0..target_idx).rev() {
993        let p = &phases[i];
994        if p.kind == EntryKind::Scope && p.depth < needed_depth {
995            ancestors.push(i);
996            needed_depth = p.depth;
997            if needed_depth == 0 {
998                break;
999            }
1000        }
1001    }
1002    ancestors.reverse();
1003    ancestors
1004}
1005
1006/// Returns `Some(2)` if any phases were pre-mapped (reachable
1007/// via scenario traversal) but never reached `Running` status —
1008/// the caller should print a warning and exit with this code.
1009/// Returns `None` if every reachable phase was visited.
1010///
1011/// A zero-cycle phase is fine when the data source legitimately
1012/// has no data — that phase still transitions Pending → Running
1013/// → Completed. What this catches is phases the executor should
1014/// have visited but didn't.
1015pub fn unreached_phase_exit_code(run_state: &RunStateHandle) -> Option<i32> {
1016    let s = run_state.load();
1017    let s: &RunState = &s;
1018    let unreached: Vec<&PhaseEntry> = s
1019        .phases
1020        .iter()
1021        .filter(|p| p.kind == EntryKind::Phase && matches!(p.status, PhaseStatus::Pending))
1022        .collect();
1023    if unreached.is_empty() {
1024        return None;
1025    }
1026    // A user-initiated stop (Ctrl-C) intentionally leaves later phases
1027    // unrun — that's not an error, and dumping the whole pending list is
1028    // noise. Exit with the conventional SIGINT code, no phase dump (the
1029    // "graceful shutdown requested" notice already fired). The dump below
1030    // is reserved for the genuine case: a phase failed and stopped the
1031    // run, leaving downstream phases stranded.
1032    if nmbrs_runtime::session_signals::stop_requested() {
1033        return Some(130);
1034    }
1035    // An SRD-83 workload-shell stop condition also intentionally halts
1036    // the walk, deliberately leaving the tail phases unrun. That is a
1037    // graceful early stop, not stranding-by-failure (a failed phase
1038    // exits via the `run_result` error path before this check). Treat
1039    // it like Ctrl-C: no warning, clean exit. The trip was already
1040    // logged ("workload stop condition tripped … halting remaining
1041    // walk"), so the skip is not silent.
1042    //
1043    // A FAULT stop (SRD-82 Part 4 `*Failed:stop`) likewise halts the
1044    // walk on purpose — the failed phase already drives the non-zero
1045    // exit via `run_result`, and its tail was deliberately skipped, so
1046    // this check stays quiet rather than re-reporting the tail as
1047    // stranded. The "scenario stop-on-error … halting remaining walk"
1048    // log already records the skip.
1049    if nmbrs_runtime::session_signals::graceful_stop_requested()
1050        || nmbrs_runtime::session_signals::fault_stop_requested()
1051    {
1052        return None;
1053    }
1054    eprintln!();
1055    eprintln!(
1056        "warning: {} pre-mapped phase(s) were not executed:",
1057        unreached.len()
1058    );
1059    for p in &unreached {
1060        let labels = if p.labels.is_empty() {
1061            String::new()
1062        } else {
1063            format!(" ({})", p.labels)
1064        };
1065        eprintln!("  - {}{labels}", p.name);
1066    }
1067    Some(2)
1068}
1069
1070#[cfg(test)]
1071mod elapsed_format_tests {
1072    use super::format_elapsed_seconds;
1073
1074    #[test]
1075    fn buckets_widen_seconds_keep_seven_until_thousand() {
1076        // [0, 10): one integer digit + 5 fractional
1077        assert_eq!(format_elapsed_seconds(0.0), "0.00000");
1078        assert_eq!(format_elapsed_seconds(0.000123), "0.00012");
1079        assert_eq!(format_elapsed_seconds(9.99999), "9.99999");
1080        // [10, 100): two integer digits + 4 fractional
1081        assert_eq!(format_elapsed_seconds(10.0), "10.0000");
1082        assert_eq!(format_elapsed_seconds(99.9999), "99.9999");
1083        // [100, 1000): three integer digits + 3 fractional
1084        assert_eq!(format_elapsed_seconds(100.0), "100.000");
1085        assert_eq!(format_elapsed_seconds(999.999), "999.999");
1086        // [1000, ∞): integer widens, millis stays at 3
1087        assert_eq!(format_elapsed_seconds(1234.5678), "1234.568");
1088        assert_eq!(format_elapsed_seconds(12345.6), "12345.600");
1089    }
1090
1091    #[test]
1092    fn negative_or_clock_skew_clamps_to_zero() {
1093        // SystemTime can run backward across a clock
1094        // adjustment. Don't surface a negative-elapsed
1095        // string; just clamp.
1096        assert_eq!(format_elapsed_seconds(-0.5), "0.00000");
1097    }
1098}
1099
1100#[cfg(test)]
1101mod scenario_tree_tests {
1102    //! Coverage for [`render_scenario_tree`] — the persisted
1103    //! end-of-run tree view that `nmbrs replay --format=tree`
1104    //! streams back. The rows must route through the
1105    //! `scope_header` / `phase_summary` readouts so the file
1106    //! carries the same `· scope` / `[ok]/[!!]/[  ]` shapes the
1107    //! surface once printed inline.
1108    use super::render_scenario_tree;
1109    use crate::state::{EntryKind, RunState, SceneTree};
1110
1111    /// A scope header, a failed phase under it, and a pending
1112    /// (never-run) phase after it must render with the right
1113    /// markers, plain (no ANSI), and correct `[n/total]` seqs.
1114    #[test]
1115    fn renders_scope_failed_and_pending_rows() {
1116        let mut t = SceneTree::new();
1117        let scope = t.push(t.root(), EntryKind::Scope, "for_each n", "");
1118        let boom = t.push(scope, EntryKind::Phase, "boom", "n=1");
1119        let _never = t.push(t.root(), EntryKind::Phase, "never", "");
1120        let mut s = RunState::new("wl.yaml", "default", "testkit");
1121        s.install_tree(t);
1122        // boom runs then fails; never is left Pending.
1123        s.set_phase_running(boom, "boom", "n=1", 1);
1124        s.set_phase_failed(boom, "boom", "n=1", "synthetic failure");
1125
1126        let tree = render_scenario_tree(&s.phases);
1127
1128        // Scope header (cyan bullet, italic name) — plain here.
1129        assert!(
1130            tree.contains("· for_each n"),
1131            "scope header missing:\n{tree}"
1132        );
1133        // Failed leaf: [!!] marker + trailing (err), seq [1/2].
1134        assert!(
1135            tree.contains("[!!] [1/2] boom"),
1136            "failed marker/seq missing:\n{tree}"
1137        );
1138        assert!(
1139            tree.contains("(synthetic failure)"),
1140            "failure text missing:\n{tree}"
1141        );
1142        // Pending leaf: [  ] marker + (not run), seq [2/2].
1143        assert!(
1144            tree.contains("[  ] [2/2] never"),
1145            "pending marker/seq missing:\n{tree}"
1146        );
1147        assert!(
1148            tree.contains("(not run)"),
1149            "(not run) suffix missing:\n{tree}"
1150        );
1151        // Plain artifact — no ANSI escapes leak into the file.
1152        assert!(
1153            !tree.contains('\u{1b}'),
1154            "persisted tree must be plain (no ANSI):\n{tree:?}"
1155        );
1156    }
1157
1158    /// Completed phases render `[ok]` and drop the marker/seq
1159    /// only — no color, no `(not run)` noise. Guards the happy
1160    /// path the large-run maintainer cares about.
1161    #[test]
1162    fn completed_phase_renders_ok_marker() {
1163        let mut t = SceneTree::new();
1164        let p = t.push(t.root(), EntryKind::Phase, "warmup", "");
1165        let mut s = RunState::new("wl.yaml", "default", "testkit");
1166        s.install_tree(t);
1167        s.set_phase_running(p, "warmup", "", 1);
1168        s.set_phase_completed(p, "warmup", "", 0.02, crate::state::PhaseSummary::default());
1169
1170        let tree = render_scenario_tree(&s.phases);
1171        assert!(
1172            tree.contains("[ok] [1/1] warmup"),
1173            "completed marker/seq missing:\n{tree}"
1174        );
1175        assert!(
1176            !tree.contains("(not run)"),
1177            "completed row must not carry (not run):\n{tree}"
1178        );
1179    }
1180}