Skip to main content

nmbrs_tui/
log_only_observer.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! `LogOnlyObserver` — `RunObserver` impl for `tui=off` mode.
5//!
6//! Mirror image of [`crate::observer::TuiObserver`] but with no
7//! TUI thread, no terminal takeover, and no alt-screen. Every
8//! observer-lifecycle callback fires two writes:
9//!
10//! 1. Send the corresponding [`crate::run_state_actor::RunStateCmd`]
11//!    to the actor so the snapshot is populated. This makes the
12//!    inspector socket / web API work in `tui=off` mode and gives
13//!    the future Ctrl-T toggle a non-empty state to display.
14//! 2. Synchronously write the same line to stderr (filtered by
15//!    `min_level`). Identical output to the legacy
16//!    [`nmbrs_runtime::observer::StderrObserver`] path —
17//!    operators see no behaviour change.
18//!
19//! This is the minimum-viable observer for Phase 1 of the
20//! display-sink refactor (see [`crate::display_sink`]). Phase 2
21//! moves the stderr writes onto a separate
22//! [`crate::log_only_sink::LogOnlySink`] thread that drains
23//! [`crate::state::RunState::log_seq_total`] from the actor's
24//! snapshots, so the same observer can drive a TUI sink, a
25//! line-mode emulation sink, or a plain-stderr sink without
26//! changing the observer surface.
27
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::mpsc;
31
32use nmbrs_metrics::cadence::Cadences;
33use nmbrs_metrics::metrics_query::MetricsQuery;
34use nmbrs_metrics::scheduler::Reporter;
35use nmbrs_metrics::snapshot::MetricSet;
36use nmbrs_runtime::observer::{EventTag, LogLevel, PhaseProgressUpdate, RunObserver};
37use parking_lot::Mutex;
38
39use crate::frame_broker::FrameBroker;
40
41/// Per-row context for the live mid-run scope-ancestor
42/// walker. Carries just the scope's display name and the
43/// surface's color setting so the `scope_header` readout
44/// can render the cyan-bullet + italic-name byte sequence
45/// without each emit site rebuilding it. SRD-63 Push 8c.
46struct ScopeAncestorContext {
47    name: String,
48    use_color: bool,
49}
50
51impl nmbrs_runtime::readouts::ReadoutContext for ScopeAncestorContext {
52    fn subject_name(&self) -> &str {
53        &self.name
54    }
55    fn subject_seq(&self) -> Option<(usize, usize)> {
56        None
57    }
58    fn subject_labels(&self) -> &str {
59        ""
60    }
61    fn cycles_completed(&self) -> u64 {
62        0
63    }
64    fn cycles_total(&self) -> u64 {
65        0
66    }
67    fn ops_ok(&self) -> u64 {
68        0
69    }
70    fn errors(&self) -> u64 {
71        0
72    }
73    fn retries(&self) -> u64 {
74        0
75    }
76    fn concurrency(&self) -> usize {
77        0
78    }
79    fn elapsed_secs(&self) -> f64 {
80        0.0
81    }
82    fn consumed(&self) -> u64 {
83        0
84    }
85    fn status_metric_chips(&self) -> String {
86        String::new()
87    }
88    fn depth_indent(&self) -> &str {
89        ""
90    }
91    fn use_color(&self) -> bool {
92        self.use_color
93    }
94    fn event(&self) -> nmbrs_runtime::lifecycle::EventType {
95        // Live mid-run scope-ancestor walker fires the
96        // scope_header readout at the same boundary that
97        // `EventType::EachStart` would fire it at — replay the
98        // live render path against historical state.
99        nmbrs_runtime::lifecycle::EventType::EachStart
100    }
101}
102use crate::run_state_actor::{RunStateCmd, RunStateHandle};
103use crate::state::LogSeverity;
104
105/// `tui=off` observer. Holds the actor handle so every event
106/// also lands in the snapshot.
107///
108/// Stderr writes are *coordinated*: this observer only writes
109/// directly when `sink_active` is `false`. When a
110/// [`crate::log_only_sink::LogOnlySink`] (or any other
111/// log-rendering [`crate::display_sink::DisplaySink`]) is up, it
112/// flips `sink_active = true` and takes over rendering by
113/// draining the actor's snapshot. The handoff is racy by design:
114/// any line that fires *before* the sink sets the flag goes
115/// straight to stderr (matching legacy `StderrObserver` timing
116/// for early diagnostics); after the flag flips, the sink owns
117/// the channel.
118///
119/// Pre-flag lines are also written to the actor, so the sink's
120/// initial snapshot read sees them — but the sink's first poll
121/// records `last_seen_seq = current log_seq_total` and only
122/// renders entries newer than that. No duplicates.
123pub struct LogOnlyObserver {
124    state: RunStateHandle,
125    /// Minimum severity that reaches stderr. Session log file
126    /// (via the async sink in `nmbrs_runtime::log_sink`) gets
127    /// every level regardless. Defaults to `Info` to match the
128    /// TUI log panel's default filter.
129    min_level: LogLevel,
130    /// `false` until a sink claims log rendering. While false,
131    /// `log()` writes to stderr synchronously; once flipped,
132    /// stderr writes are suppressed and the sink owns the
133    /// surface. Set by `LogOnlySink` on start (it drains the
134    /// snapshot's log ring) AND held high by the supervisor
135    /// while a `TuiSink` is up (the TUI shows its own log
136    /// panel — the observer must not double-write).
137    sink_active: Arc<AtomicBool>,
138    /// Distinct from `sink_active`: this flag tells the
139    /// activity's inline-status thread (the
140    /// `\r\x1b[K…` rewriter in `nmbrs-runtime::activity`) to
141    /// yield. Set only when an alt-screen TUI owns the
142    /// terminal — i.e. `tui=on` from-startup or after a
143    /// Ctrl-T swap into `TuiSink`. In plain `tui=terminal`
144    /// mode the inline status line stays visible alongside
145    /// the LogOnlySink's log-line drain; both write to stderr
146    /// without conflict (status rewrites the bottom line via
147    /// `\r`, log lines scroll up). Surfaced via
148    /// [`RunObserver::live_suppress_flag`].
149    inline_suppress: Arc<AtomicBool>,
150    /// Multi-consumer fan-out for cadence-reporter frames.
151    /// Returned via [`RunObserver::reporters`] so the runner
152    /// registers it with the cadence scheduler. Sinks that need
153    /// frames (e.g. `TuiSink`) call [`Self::subscribe_frames`]
154    /// to grab their own `Receiver`. Sinks that don't (e.g.
155    /// `LogOnlySink`) simply skip subscription — the broker's
156    /// per-publish cost with zero subscribers is one mutex lock
157    /// on an empty `Vec`.
158    frame_broker: FrameBroker,
159    /// User-declared cadences forwarded to the runner via
160    /// [`RunObserver::cadences`]. Same shape `TuiObserver`
161    /// already uses; the actor-driven path inherits the
162    /// behaviour without divergence.
163    cadences: Cadences,
164    /// `MetricsQuery` handle the runner publishes via
165    /// [`RunObserver::on_metrics_query`] once the cadence
166    /// reporter is built. Sinks that render per-cadence views
167    /// (the TUI's barchart) call [`Self::metrics_query`] to
168    /// pick it up at sink-start time.
169    metrics_query: Mutex<Option<Arc<MetricsQuery>>>,
170    /// Scope-ancestor chain (Scope-kind scene-tree node ids,
171    /// outer-first) of the most recently announced phase. The
172    /// observer diffs against this on every `phase_starting`
173    /// to emit only the *newly-entered* scope headers, so the
174    /// terminal-mode log reads as a hierarchic tree walk
175    /// rather than a flat sequence of striated coord tuples.
176    /// `None` until the first phase fires.
177    last_scope_chain: Mutex<Option<Vec<usize>>>,
178}
179
180impl LogOnlyObserver {
181    /// Build with the given actor handle, default `Info` stderr
182    /// severity floor, and the user-declared cadences.
183    pub fn new(state: RunStateHandle, cadences: Cadences) -> Self {
184        Self {
185            state,
186            min_level: LogLevel::Info,
187            sink_active: Arc::new(AtomicBool::new(false)),
188            inline_suppress: Arc::new(AtomicBool::new(false)),
189            frame_broker: FrameBroker::new(),
190            cadences,
191            metrics_query: Mutex::new(None),
192            last_scope_chain: Mutex::new(None),
193        }
194    }
195
196    /// Override the stderr severity floor. The session log file
197    /// is unaffected.
198    pub fn with_min_level(mut self, level: LogLevel) -> Self {
199        self.min_level = level;
200        self
201    }
202
203    /// The console-owning-adapter display mode: a console-owning adapter
204    /// (stdout to a terminal, plotter) holds an **interactive** terminal,
205    /// so its compositing rule is *don't project to the console at all* —
206    /// the screen is the adapter's. This yields the whole console
207    /// projection (`sink_active`, the same flag a real sink raises to
208    /// claim the surface) and the inline `✓` status line
209    /// (`inline_suppress`). Every signal — banners, the scope/phase
210    /// readouts, completion notices — still flows through the channel to
211    /// `session.log` (the file write in
212    /// [`nmbrs_runtime::observer::log_tagged`] is independent of these
213    /// flags); it just isn't rendered to *this* surface.
214    ///
215    /// Only applied on an interactive TTY: a non-interactive run
216    /// (pipe/file) keeps stdout and stderr as separate streams, so the
217    /// console projection flows to stderr as usual and CI/tests capture
218    /// it.
219    pub fn reserve_console_for_adapter(self) -> Self {
220        self.sink_active.store(true, Ordering::Release);
221        self.inline_suppress.store(true, Ordering::Release);
222        self
223    }
224
225    /// Returns the shared coordination flag. The owner of the
226    /// active log-rendering sink flips this to `true` while
227    /// rendering and back to `false` on shutdown. This is the
228    /// hand-off the observer uses to decide whether to write
229    /// stderr directly.
230    pub fn sink_active_flag(&self) -> Arc<AtomicBool> {
231        self.sink_active.clone()
232    }
233
234    /// Returns the inline-status suppression flag. Distinct
235    /// from `sink_active_flag` — this one's job is to tell the
236    /// activity's inline-status thread (the `\r\x1b[K…`
237    /// per-cycle rewriter in `nmbrs-runtime::activity`) to
238    /// yield while an alt-screen TUI owns the terminal. Held
239    /// high by the supervisor when `TuiSink` is up; held low
240    /// (or unset) in plain `tui=terminal` mode so the live
241    /// status line stays visible alongside the log-line drain.
242    pub fn inline_suppress_flag(&self) -> Arc<AtomicBool> {
243        self.inline_suppress.clone()
244    }
245
246    /// The minimum severity threshold this observer was built
247    /// with. The active sink reads this so its drain applies
248    /// the same filter the observer would have, keeping output
249    /// consistent across the synchronous-pre-sink and
250    /// asynchronous-post-sink legs.
251    pub fn min_level(&self) -> LogLevel {
252        self.min_level
253    }
254
255    /// Subscribe to the cadence-frame fan-out. Returns a fresh
256    /// `mpsc::Receiver`; the caller (a sink) owns it for its
257    /// lifetime. Cleanup is automatic — when the receiver is
258    /// dropped, the broker prunes the matching sender on the
259    /// next publish. Multiple subscribers coexist (toggle path
260    /// hands out separate receivers to terminal- and TUI-side
261    /// sinks).
262    pub fn subscribe_frames(&self) -> mpsc::Receiver<MetricSet> {
263        self.frame_broker.subscribe()
264    }
265
266    /// Snapshot of the metrics query handle published by the
267    /// runner via [`RunObserver::on_metrics_query`]. Returns
268    /// `None` until the cadence reporter is built — sinks that
269    /// need it (TuiSink) call this at start-time, when the
270    /// runner has already wired the query.
271    pub fn metrics_query(&self) -> Option<Arc<MetricsQuery>> {
272        self.metrics_query.lock().clone()
273    }
274}
275
276fn level_to_severity(level: LogLevel) -> LogSeverity {
277    match level {
278        LogLevel::Trace => LogSeverity::Debug,
279        LogLevel::Debug => LogSeverity::Debug,
280        LogLevel::Info => LogSeverity::Info,
281        LogLevel::Warn => LogSeverity::Warn,
282        LogLevel::Error => LogSeverity::Error,
283    }
284}
285
286impl RunObserver for LogOnlyObserver {
287    fn op_measure(
288        &self,
289        parent_phase: nmbrs_runtime::scene_tree::SceneNodeId,
290        op_name: &str,
291        text: &str,
292    ) {
293        self.state
294            .send(crate::run_state_actor::RunStateCmd::OpMeasure {
295                parent: parent_phase,
296                op_name: op_name.to_string(),
297                text: text.to_string(),
298            });
299    }
300
301    fn session_dir_ready(&self, dir: &std::path::Path) {
302        // Opens <dir>/transcript.log in the actor and flushes everything
303        // buffered since actor start.
304        self.state
305            .send(crate::run_state_actor::RunStateCmd::OpenTranscript(
306                dir.join("transcript.log"),
307            ));
308    }
309
310    fn sysmon_update(&self, sample: &nmbrs_runtime::sysmon::SysmonSample) {
311        // Same forward the full-TUI observer does: the sample is ambient
312        // session state consumed by the status fold at repaint.
313        self.state
314            .send(crate::run_state_actor::RunStateCmd::Sysmon(sample.clone()));
315    }
316
317    fn scenario_pre_mapped(&self, tree: &nmbrs_runtime::scene_tree::SceneTree) {
318        // Forward the pre-mapped scene tree to the actor so
319        // `print_post_run_summary` (and any future sink reading
320        // from the snapshot) can render hierarchy and indent
321        // phases by scope depth in `tui=off` mode too. Without
322        // this, every `set_phase_running` call falls through to
323        // the "unknown phase, push under root" fallback in
324        // `RunState::set_phase_running`, flattening the tree into
325        // a plain phase list.
326        self.state.send(RunStateCmd::InstallTree(tree.clone()));
327    }
328
329    fn phase_starting(
330        &self,
331        scene_node_id: nmbrs_runtime::scene_tree::SceneNodeId,
332        name: &str,
333        labels: &str,
334        op_templates: usize,
335        total_cycles: u64,
336        concurrency: usize,
337    ) {
338        // Snapshot mutation: same RunStateCmd shape TuiObserver
339        // sends, so the snapshot model is identical between modes.
340        self.state.send(RunStateCmd::PhaseStarting {
341            exec_id: nmbrs_runtime::execution_context::current_exec_id(),
342            scene_node_id,
343            name: name.to_string(),
344            labels: labels.to_string(),
345            op_templates,
346            total_cycles,
347            concurrency,
348        });
349
350        // Hierarchic stderr emit. The terminal-mode log walks
351        // the scenario tree as the runtime visits it; the
352        // observer maintains a "last announced scope chain" and
353        // emits headers only for the *newly-entered* scopes on
354        // each phase_starting call. The result reads like the
355        // post-run summary: scope headers indented per depth,
356        // phase rows nested under their innermost scope, no
357        // redundant striated coord tuple repeated on every
358        // phase line.
359        let template_word = if op_templates == 1 {
360            "op template"
361        } else {
362            "op templates"
363        };
364        let cycle_word = if total_cycles == 1 { "cycle" } else { "cycles" };
365
366        // ANSI color codes — only when stderr is a TTY and
367        // `NO_COLOR` isn't set. See `nmbrs_runtime::observer::use_color`.
368        // Falls back to plain text in pipelined / CI contexts
369        // so log archives stay readable.
370        let color = nmbrs_runtime::observer::use_color();
371        let dim = if color { "\x1b[2m" } else { "" };
372        let bold = if color { "\x1b[1m" } else { "" };
373        let cyan = if color { "\x1b[36m" } else { "" };
374        let italic = if color { "\x1b[3m" } else { "" };
375        let reset = if color { "\x1b[0m" } else { "" };
376
377        let tree = match nmbrs_runtime::scene_tree::current() {
378            Some(t) => t,
379            None => {
380                // Pre-map didn't run (or the resume planner
381                // hasn't published yet). Without a scene tree we
382                // also have no scope-ancestor headers to emit,
383                // so this branch becomes a true no-op — the
384                // condensed ✓ line from `nmbrs-runtime::activity`
385                // is the sole per-phase log entry, same as the
386                // hierarchic path below.
387                let _ = (
388                    op_templates,
389                    total_cycles,
390                    concurrency,
391                    template_word,
392                    cycle_word,
393                    name,
394                    labels,
395                    bold,
396                    color,
397                );
398                return;
399            }
400        };
401
402        // Resolve this phase's scene-tree node + walk its
403        // ancestors collecting every Scope-kind ancestor in
404        // outer-first order. Phase nodes have either Phase or
405        // Root parents at the top of the chain — we only emit
406        // Scope ancestors as headers. SRD-100 P1c — address the
407        // dispatch-time node directly (race-safe under concurrent
408        // same-name dispatch); fall back to a by-name lookup only
409        // for a runtime-materialized phase absent from this
410        // (possibly pre-map-snapshot) tree handle.
411        let phase_node = tree
412            .nodes
413            .get(scene_node_id)
414            .filter(|n| n.kind == nmbrs_runtime::scene_tree::NodeKind::Phase && n.name == name)
415            .or_else(|| {
416                tree.find_phase(
417                    name,
418                    labels,
419                    Some(&nmbrs_runtime::scene_tree::PhaseStatus::Running),
420                )
421                .and_then(|id| tree.nodes.get(id))
422            });
423        let (seq, phase_depth, ancestor_chain) = match phase_node {
424            Some(n) => {
425                let mut chain: Vec<usize> = Vec::new();
426                let mut cursor = n.parent;
427                while let Some(pid) = cursor {
428                    if let Some(p) = tree.nodes.get(pid) {
429                        if p.kind == nmbrs_runtime::scene_tree::NodeKind::Scope {
430                            chain.push(pid);
431                        }
432                        cursor = p.parent;
433                    } else {
434                        break;
435                    }
436                }
437                chain.reverse(); // outer-first
438                let seq = n
439                    .seq
440                    .map(|s| format!("{dim}[{s}/{}]{reset} ", tree.total_phases()))
441                    .unwrap_or_default();
442                let depth = n.depth.saturating_sub(1);
443                (seq, depth, chain)
444            }
445            None => (String::new(), 0, Vec::new()),
446        };
447
448        // Diff against the last announced chain. The shared
449        // prefix doesn't re-emit; everything past the divergence
450        // point gets its own indented header line.
451        let mut guard = self.last_scope_chain.lock();
452        let last_chain = guard.clone().unwrap_or_default();
453        let common_prefix = last_chain
454            .iter()
455            .zip(ancestor_chain.iter())
456            .take_while(|(a, b)| a == b)
457            .count();
458        // Push 8c: scope-ancestor headers route through
459        // the `scope_header` readout so the same
460        // formatter drives both the live mid-run walk
461        // here and the post-run summary tree walk in
462        // `nmbrs-tui::observer`. The depth-based indent
463        // chrome is the surface's job per SRD-63 §10.
464        for new_id in &ancestor_chain[common_prefix..] {
465            if let Some(scope) = tree.nodes.get(*new_id) {
466                let depth = scope.depth.saturating_sub(1);
467                let indent = " ".repeat(depth);
468                let mut s_buf = String::with_capacity(64);
469                {
470                    use nmbrs_runtime::readouts as ro;
471                    let mut buf = ro::buf::StringBuf::new(&mut s_buf);
472                    use ro::Readout;
473                    let ctx = ScopeAncestorContext {
474                        name: scope.name.clone(),
475                        use_color: nmbrs_runtime::observer::use_color(),
476                    };
477                    ro::builtins::scope_header::ScopeHeader.render(
478                        &ctx,
479                        ro::Lod::Labeled,
480                        ro::ContentMode::Value,
481                        &ro::ReadoutOptions::new(),
482                        &mut buf,
483                    );
484                }
485                let _ = (cyan, italic);
486                nmbrs_runtime::observer::log(LogLevel::Info, &format!("{indent}{s_buf}"));
487            }
488        }
489        *guard = Some(ancestor_chain);
490        drop(guard);
491
492        // No phase-starting detail row. The condensed completed-
493        // phase line emitted by `nmbrs-runtime::activity` (the
494        // ✓ DONE summary, single line carrying identity + stats
495        // + duration) is now the only per-phase log entry. Scope
496        // ancestor headers above this point still emit, so the
497        // hierarchic walk reads the same on its way down — only
498        // the redundant "[N/total] [name] (coords): …" preview
499        // is dropped (its info is fully captured by the ✓ line).
500        let _ = (
501            phase_depth,
502            op_templates,
503            total_cycles,
504            concurrency,
505            template_word,
506            cycle_word,
507            seq,
508            labels,
509        );
510    }
511
512    fn phase_completed(
513        &self,
514        scene_node_id: nmbrs_runtime::scene_tree::SceneNodeId,
515        name: &str,
516        labels: &str,
517        duration_secs: f64,
518    ) {
519        self.state.send(RunStateCmd::PhaseCompleted {
520            exec_id: nmbrs_runtime::execution_context::current_exec_id(),
521            scene_node_id,
522            name: name.to_string(),
523            labels: labels.to_string(),
524            duration_secs,
525        });
526        // No stderr line: the executor's own diag emits the
527        // formatted "phase 'X' complete (Ns)" via `observer::log`,
528        // which routes back through `Self::log` below. Re-emitting
529        // here would duplicate. Same reasoning as the legacy
530        // StderrObserver — see the comment on its
531        // phase_completed.
532    }
533
534    fn phase_failed(
535        &self,
536        scene_node_id: nmbrs_runtime::scene_tree::SceneNodeId,
537        name: &str,
538        labels: &str,
539        error: &str,
540    ) {
541        self.state.send(RunStateCmd::PhaseFailed {
542            exec_id: nmbrs_runtime::execution_context::current_exec_id(),
543            scene_node_id,
544            name: name.to_string(),
545            labels: labels.to_string(),
546            error: error.to_string(),
547        });
548        // Same as phase_completed — diag covers the visible line.
549    }
550
551    fn phase_progress(&self, update: &PhaseProgressUpdate) {
552        self.state.send(RunStateCmd::PhaseProgress(update.clone()));
553    }
554
555    // SRD-63 — op-level status leaves (`readout: visible`). The managed
556    // (LogOnly) surface is what `nmbrs run` shows, so it must forward these to
557    // the actor just like `TuiObserver` does, or `phase_ops` never populates
558    // and the leaves never render in the footer.
559    fn op_starting(&self, parent_phase: nmbrs_runtime::scene_tree::SceneNodeId, op_name: &str) {
560        self.state.send(RunStateCmd::OpStarting {
561            parent: parent_phase,
562            op_name: op_name.to_string(),
563        });
564    }
565
566    fn op_completed(
567        &self,
568        parent_phase: nmbrs_runtime::scene_tree::SceneNodeId,
569        op_name: &str,
570        duration_secs: f64,
571    ) {
572        self.state.send(RunStateCmd::OpCompleted {
573            parent: parent_phase,
574            op_name: op_name.to_string(),
575            duration_secs,
576        });
577    }
578
579    fn op_failed(
580        &self,
581        parent_phase: nmbrs_runtime::scene_tree::SceneNodeId,
582        op_name: &str,
583        error: &str,
584    ) {
585        self.state.send(RunStateCmd::OpFailed {
586            parent: parent_phase,
587            op_name: op_name.to_string(),
588            error: error.to_string(),
589        });
590    }
591
592    fn phase_render_attach(&self, handle: nmbrs_runtime::observer::PhaseRenderHandle) {
593        // SRD-100 P2 — route the per-phase render handle to the actor;
594        // LogOnlySink folds `active_phases` and renders each phase's
595        // status footer off it (no inline-status producer thread).
596        self.state.send(RunStateCmd::AttachPhaseRender(handle));
597    }
598
599    fn run_finished(&self) {
600        self.state.send(RunStateCmd::RunFinished);
601        // Re-emit the canonical end-of-run marker through the observer
602        // so session.log captures it. `RunLifecycle` category so a
603        // console-owning adapter can keep it off the console.
604        nmbrs_runtime::observer::log(LogLevel::Info, "all phases complete");
605    }
606
607    fn log(&self, level: LogLevel, message: &str) {
608        self.log_tagged(level, EventTag::default(), message);
609    }
610
611    fn log_tagged(&self, level: LogLevel, tag: EventTag, message: &str) {
612        // Snapshot side: every log entry is stored in the ring
613        // (capped at 200) with `log_seq_total` advanced, carrying
614        // its `tag` (attachment + category axes) so the terminal
615        // sink can derive its scrollback filtering from them. The
616        // active sink drains via the seq delta; the inspector
617        // socket reads the ring directly.
618        self.state.send(RunStateCmd::Log {
619            severity: level_to_severity(level),
620            tag,
621            message: message.to_string(),
622        });
623        // Stderr side: synchronous write — only when no sink
624        // has claimed rendering. Once a `LogOnlySink` (or other
625        // log-rendering sink) flips `sink_active`, it takes over
626        // and writes from the snapshot drain. The handoff is
627        // race-free by construction: pre-flag lines go to stderr
628        // *and* into the actor; the sink's first poll skips
629        // everything ≤ the seq it observed at startup, so no
630        // duplicate is rendered.
631        if !self.sink_active.load(Ordering::Acquire) && level >= self.min_level {
632            if message.starts_with("session: graceful shutdown requested")
633                || message.starts_with("session: force-exit")
634            {
635                eprintln!();
636            }
637            // SRD-87 §5: the live-surface write goes through the log bucket
638            // (the channel owns the fd, color-coding by severity); the
639            // `!sink_active`/`min_level` gate above stays here as the spine's
640            // handoff coordination.
641            nmbrs_runtime::output_channel::log_to_surface(level, message);
642        }
643    }
644
645    fn suppresses_stderr(&self) -> bool {
646        // Tracks `sink_active`: whenever a sink is actively
647        // rendering (LogOnlySink draining the log ring,
648        // TuiSink running an alt-screen App), the runner
649        // should NOT write log lines synchronously to stderr
650        // — the sink owns that surface.
651        //
652        // The runner also gates the periodic progress-event
653        // thread on this flag (executor.rs around the
654        // `phase_progress` emit site): when true, a thread
655        // wakes every 500 ms to emit `PhaseProgressUpdate`
656        // events into the actor so any active panel-style
657        // renderer (today's `TuiSink`, future custom sinks)
658        // sees live data. Returning false here suppressed
659        // that thread's spawn — which is exactly why the TUI
660        // status panel went silent after a Ctrl-T toggle.
661        self.sink_active.load(Ordering::Acquire)
662    }
663
664    fn live_suppress_flag(&self) -> Option<Arc<AtomicBool>> {
665        // Inline-status suppression is the right semantic here:
666        // the activity's inline-status thread should yield only
667        // when an alt-screen renderer owns the terminal, NOT
668        // just because LogOnlySink is doing log-line drain.
669        // (LogOnlySink's log lines and the inline status line
670        // share stderr without conflict — different rendering
671        // strategies for different content.)
672        Some(self.inline_suppress.clone())
673    }
674
675    fn reporters(&self) -> Vec<(std::time::Duration, Box<dyn Reporter>)> {
676        // Hand the cadence scheduler a clone of the frame
677        // broker as its 1-second base reporter. The broker is
678        // Arc-shared, so calls to `Self::subscribe_frames` from
679        // sinks reach the same backing storage.
680        vec![(
681            std::time::Duration::from_secs(1),
682            Box::new(self.frame_broker.clone()) as Box<dyn Reporter>,
683        )]
684    }
685
686    fn cadences(&self) -> Option<Cadences> {
687        Some(self.cadences.clone())
688    }
689
690    fn on_metrics_query(&self, query: Arc<MetricsQuery>) {
691        *self.metrics_query.lock() = Some(query);
692    }
693}