Skip to main content

nmbrs_tui/
run_state_actor.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Display-side actor that owns [`RunState`] and publishes
5//! immutable snapshots.
6//!
7//! See `docs/SRD/02_concurrency_model.md` §"Display and
8//! Diagnostic Decoupling" for the architectural rationale. In
9//! short:
10//!
11//! - **Downstream (core → UI):** the actor owns a private
12//!   mutable `RunState`. After every applied command, it
13//!   publishes a fresh `Arc<RunState>` into a shared
14//!   [`arc_swap::ArcSwap`]. UI / web / OOB readers do
15//!   `snapshot.load()` — a single atomic op, never a wait.
16//! - **Upstream (UI → core):** every mutation is a typed
17//!   [`RunStateCmd`] variant sent over an [`mpsc::Sender`]. The
18//!   actor's `match` is exhaustive, so a new mutation cannot be
19//!   added without the actor handling it.
20//!
21//! There is no shared `RwLock<RunState>` — the principle is that
22//! the renderer can never wait on the writer and the writer can
23//! never wait on the renderer.
24
25use std::sync::Arc;
26use std::sync::Mutex;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::sync::mpsc;
29use std::thread::JoinHandle;
30use std::time::{Duration, Instant};
31
32use arc_swap::ArcSwap;
33
34use nmbrs_metrics::summaries::binomial_summary::BinomialSummary;
35use nmbrs_metrics::summaries::ewma::Ewma;
36use nmbrs_metrics::summaries::peak_tracker::PeakTracker;
37use nmbrs_runtime::observer::PhaseProgressUpdate;
38use nmbrs_runtime::scene_tree::{SceneNodeId, SceneTree};
39
40use crate::state::{ActivePhase, LogEntry, LogSeverity, PhaseSummary, RunState};
41
42/// One log line on the **durable scrollback stream** — the second
43/// down-channel from the actor to the active terminal-mode sink.
44///
45/// The status footer is a latest-wins ArcSwap snapshot (only the
46/// newest matters); log scrollback is sequential DATA where every
47/// line must be delivered, in order, exactly once. ArcSwap cannot
48/// carry deltas, so a renderer that misses a swap loses the
49/// intermediate lines — the drop bug this stream removes. The
50/// actor feeds one `LogLine` per [`RunStateCmd::Log`] into an
51/// **unbounded** channel; the sink drains it fully every tick and
52/// emits every line. `seq` matches the ring's
53/// [`RunState::log_seq_total`] so the sink can skip lines already
54/// emitted on stderr before the display handoff (or by a prior
55/// sink before a Ctrl-T swap).
56pub(crate) struct LogLine {
57    pub seq: u64,
58    pub entry: LogEntry,
59    /// Uncolored margin body (`session · [n/N] · leaf`) computed by the
60    /// actor AT LOG-PROCESSING TIME — i.e. from state that includes every
61    /// command that preceded this line in the stream. The sink renders
62    /// this stamp (adding color/divider) instead of a render-time
63    /// snapshot margin, so a line's gutter can never disagree with the
64    /// event the line describes.
65    pub margin_body: String,
66    /// gutter/final — when this entry is a phase's ✓ outcome block and
67    /// the phase published a final gutter spec, the sink renders it as
68    /// the margin CELL of the block's DETAIL line (row 1). The header
69    /// row keeps the timing triad untouched; every other row gets the
70    /// standard stamp.
71    pub detail_gutter: Option<nmbrs_runtime::wrappers::gutter::GutterSpec>,
72}
73
74/// Single-consumer handle to the durable scrollback stream, held by
75/// whichever terminal-mode sink is currently rendering.
76///
77/// The receiver is single-consumer and must move between sinks
78/// across a Ctrl-T swap (terminal → TUI → terminal), so it lives in
79/// a shared cell on [`RunStateHandle`]. A sink `take`s it on start
80/// (via [`RunStateHandle::take_log_stream`]) and this guard restores
81/// it to the cell on drop — so the next sink brought up after a swap
82/// resumes draining the SAME stream, and the lines that buffered
83/// while the TUI owned the alternate screen flush into the restored
84/// scrollback. The cell's `Mutex` is touched only at start / teardown
85/// (never per render tick) and only one sink renders at a time, so it
86/// is a handoff latch, not shared render state.
87pub(crate) struct ScrollbackReceiver {
88    cell: Arc<Mutex<Option<mpsc::Receiver<LogLine>>>>,
89    rx: Option<mpsc::Receiver<LogLine>>,
90}
91
92impl ScrollbackReceiver {
93    /// Non-blocking receive of the next buffered log line, or `None`
94    /// when the stream is momentarily empty / the receiver wasn't
95    /// available (another sink holds it — shouldn't happen, since
96    /// sinks are torn down before the next is brought up).
97    pub(crate) fn try_next(&self) -> Option<LogLine> {
98        self.rx.as_ref().and_then(|rx| rx.try_recv().ok())
99    }
100}
101
102impl Drop for ScrollbackReceiver {
103    fn drop(&mut self) {
104        if let Some(rx) = self.rx.take() {
105            *self.cell.lock().unwrap_or_else(|e| e.into_inner()) = Some(rx);
106        }
107    }
108}
109
110/// One mutation of [`RunState`]. Every observer-driven and
111/// UI-driven write is one of these variants. The actor's
112/// `match` is exhaustive — adding a new mutation requires
113/// adding a variant and a handler arm, by design.
114#[derive(Debug)]
115pub enum RunStateCmd {
116    /// Session directory is ready — open `<dir>/transcript.log` and flush any
117    /// lines buffered since actor start.
118    OpenTranscript(std::path::PathBuf),
119    /// Latest sysmon sample window (session-level host utilization).
120    Sysmon(nmbrs_runtime::sysmon::SysmonSample),
121    /// Replace the scenario tree wholesale (called once after
122    /// pre-mapping).
123    InstallTree(SceneTree),
124    /// A phase has begun. Carries everything needed to seed an
125    /// [`ActivePhase`] entry.
126    PhaseStarting {
127        exec_id: u64,
128        /// SRD-100 P1c — dispatch-time scene-tree node id for this
129        /// phase. The actor flips THIS node (race-safe under
130        /// concurrent same-name dispatch) instead of re-matching by
131        /// `(name, status)`.
132        scene_node_id: SceneNodeId,
133        name: String,
134        labels: String,
135        /// Count of distinct op definitions in the phase (the
136        /// "shape" of the stanza; typically 1 for query workloads).
137        op_templates: usize,
138        /// Number of times the stanza will iterate (the "amount"
139        /// of work).
140        total_cycles: u64,
141        concurrency: usize,
142    },
143    /// A phase finished cleanly. The actor builds the
144    /// [`PhaseSummary`] from its own active-phase entry before
145    /// removing it.
146    PhaseCompleted {
147        exec_id: u64,
148        /// SRD-100 P1c — dispatch-time scene-tree node id (see
149        /// [`Self::PhaseStarting`]).
150        scene_node_id: SceneNodeId,
151        name: String,
152        labels: String,
153        duration_secs: f64,
154    },
155    /// A phase failed. The actor removes the active entry and
156    /// flips the tree node's status.
157    PhaseFailed {
158        exec_id: u64,
159        /// SRD-100 P1c — dispatch-time scene-tree node id (see
160        /// [`Self::PhaseStarting`]).
161        scene_node_id: SceneNodeId,
162        name: String,
163        labels: String,
164        error: String,
165    },
166    /// SRD-63 — an op-level status leaf (`readout: visible`) started, keyed
167    /// by its parent phase's scene-node id.
168    OpStarting {
169        parent: SceneNodeId,
170        op_name: String,
171    },
172    /// An op-level status leaf completed; `duration_secs` is its execution time.
173    /// The op's key measurable, arriving just before its completion.
174    OpMeasure {
175        parent: nmbrs_runtime::scene_tree::SceneNodeId,
176        op_name: String,
177        text: String,
178    },
179    OpCompleted {
180        parent: SceneNodeId,
181        op_name: String,
182        duration_secs: f64,
183    },
184    /// An op-level status leaf failed.
185    OpFailed {
186        parent: SceneNodeId,
187        op_name: String,
188        error: String,
189    },
190    /// Live update from the executor's progress thread.
191    PhaseProgress(PhaseProgressUpdate),
192    /// SRD-100 P2 — attach the per-phase live render handle to the
193    /// matching `ActivePhase`, fired once by the executor after the
194    /// activity's metrics/binder exist. The consumer-side status
195    /// renderers fold `active_phases` and render each phase's status
196    /// off its handle (no producer thread, no `status_render` scalar).
197    AttachPhaseRender(nmbrs_runtime::observer::PhaseRenderHandle),
198    /// Run is complete; flips `state.finished` so the renderer
199    /// drops out of its event loop.
200    RunFinished,
201    /// Append a log line to the ring buffer.
202    Log {
203        severity: LogSeverity,
204        tag: crate::state::EventTag,
205        message: String,
206    },
207    /// Latency frame ingest from the metrics scheduler. Updates
208    /// the live percentile fields, the rolling histories, and
209    /// each active phase's peak trackers.
210    LatencyFrame {
211        min: u64,
212        p50: u64,
213        p90: u64,
214        p99: u64,
215        p999: u64,
216        max: u64,
217    },
218    /// Sparkline samples for the throughput / secondary-counter
219    /// rows. Driven from the same metrics-frame drain as
220    /// `LatencyFrame`.
221    SparklineSamples {
222        ops: Option<f64>,
223        rows: Option<f64>,
224        rows_label: Option<String>,
225    },
226    /// Bookkeeping fields the runner sets before the run starts
227    /// (profiler / limit strings shown in the header strip).
228    SetMeta {
229        profiler: Option<String>,
230        limit: Option<String>,
231    },
232    /// Synchronous render checkpoint. Processed in command order
233    /// so its position in the queue marks "all preceding mutations
234    /// have been applied". The actor:
235    ///
236    /// 1. registers `tx` in the shared `pending_acks` queue,
237    /// 2. sets the `force_redraw` flag,
238    /// 3. publishes a fresh snapshot,
239    ///
240    /// after which the TUI thread observes `force_redraw`, drops
241    /// its poll timeout to zero, draws one frame against the
242    /// just-published state, and drains `pending_acks` — at which
243    /// point each registered `tx` is signalled and the original
244    /// caller's blocking `rx.recv()` returns.
245    ///
246    /// Used by [`crate::observer::TuiObserver::phase_completed`] /
247    /// [`crate::observer::TuiObserver::phase_failed`] to guarantee
248    /// at least one fully rendered frame of the just-completed
249    /// phase before the executor moves on. The `tick_rate`
250    /// throttle is bypassed for this single redraw.
251    FrameAck(mpsc::Sender<()>),
252    /// Queue barrier: acked by the actor the moment it is
253    /// processed, AFTER every command sent before it (the inbox is
254    /// ordered). Unlike [`Self::FrameAck`] it does not wait for a
255    /// TUI draw, so it works on every surface — the post-run
256    /// reporter uses it to guarantee the snapshot reflects all
257    /// lifecycle events before counting phases (a fast walk could
258    /// otherwise outrun the actor and report bogus not-run counts
259    /// and exit codes).
260    Barrier(mpsc::Sender<()>),
261}
262
263/// Synchronisation surface shared between the actor (which
264/// receives [`RunStateCmd::FrameAck`]) and the TUI app (which
265/// honours it). Cloned cheaply; held by both sides.
266///
267/// - `force_redraw` — when set, the TUI app drops its poll
268///   timeout to zero so the next iteration draws immediately,
269///   bypassing `tick_rate`. Cleared by the app after the draw.
270/// - `pending_acks` — `tx` channels handed in via `FrameAck`.
271///   Drained and signalled by the app after each `terminal.draw()`.
272#[derive(Clone, Default)]
273pub struct FrameSync {
274    pub force_redraw: Arc<AtomicBool>,
275    pub pending_acks: Arc<Mutex<Vec<mpsc::Sender<()>>>>,
276}
277
278impl FrameSync {
279    /// Drain every queued ack and signal it. Called by the TUI
280    /// app immediately after a successful `terminal.draw()`. The
281    /// `force_redraw` flag is cleared in the same call so the
282    /// app doesn't busy-spin until the next FrameAck arrives.
283    pub fn signal_post_draw(&self) {
284        self.force_redraw.store(false, Ordering::Release);
285        let mut q = self.pending_acks.lock().unwrap_or_else(|e| e.into_inner());
286        for tx in q.drain(..) {
287            // Receiver may have given up (recv_timeout); drop is
288            // fine.
289            let _ = tx.send(());
290        }
291    }
292}
293
294/// Handle the rest of the system uses to talk to the actor.
295///
296/// Cheap to clone — every field is itself `Arc`-style. The
297/// snapshot side is read with a single atomic load; the inbox
298/// side is fire-and-forget (`send` returns immediately, dropped
299/// silently if the actor has exited).
300#[derive(Clone)]
301pub struct RunStateHandle {
302    snapshot: Arc<ArcSwap<RunState>>,
303    inbox: mpsc::Sender<RunStateCmd>,
304    frame_sync: FrameSync,
305    /// Receiver end of the durable scrollback stream (see
306    /// [`LogLine`]), parked here between sinks so it survives a
307    /// Ctrl-T swap. Taken by the active terminal-mode sink via
308    /// [`Self::take_log_stream`] and restored on that sink's
309    /// teardown.
310    log_rx: Arc<Mutex<Option<mpsc::Receiver<LogLine>>>>,
311    /// One-way latch: `false` until a terminal-mode
312    /// [`crate::log_only_sink::LogOnlySink`] first claims the stream
313    /// (via [`Self::take_log_stream`]), then `true` for the rest of
314    /// the run. The actor feeds the scrollback stream ONLY while this
315    /// is set, so modes with no `LogOnlySink` (`tui=on` full TUI,
316    /// `tui=off` piped/CI, `tui=formatted`) never buffer a stream
317    /// nobody drains — the line still lands in the ring and
318    /// `session.log`. It is one-way (never cleared) so a Ctrl-T swap
319    /// window — when the sink is torn down and no one is draining —
320    /// keeps buffering, and the next terminal sink replays those lines
321    /// into the restored scrollback.
322    log_stream_active: Arc<AtomicBool>,
323}
324
325impl RunStateHandle {
326    /// Load the current snapshot. Always returns the most
327    /// recently published `Arc<RunState>` — the only way for
328    /// this to return a stale snapshot is if the actor hasn't
329    /// processed a sent command yet, which is the intended
330    /// decoupling.
331    pub fn load(&self) -> Arc<RunState> {
332        self.snapshot.load_full()
333    }
334
335    /// Send a command into the actor inbox. Fire-and-forget: if
336    /// the actor has exited, the send is dropped silently. The
337    /// actor never falls behind in a way that pressures the
338    /// caller — the caller doesn't wait for it.
339    pub fn send(&self, cmd: RunStateCmd) {
340        let _ = self.inbox.send(cmd);
341    }
342
343    /// Block until the TUI has rendered at least one frame that
344    /// reflects every command sent on this handle prior to the
345    /// call. Bypasses the TUI's `tick_rate` throttle so the
346    /// caller doesn't pay up to a full tick of latency.
347    ///
348    /// Returns `true` if the round trip completed inside `timeout`
349    /// and `false` if the TUI didn't respond (e.g. the app has
350    /// already exited or is wedged). Callers should treat a
351    /// `false` as best-effort: the run continues either way.
352    pub fn flush_frame(&self, timeout: Duration) -> bool {
353        let (tx, rx) = mpsc::channel::<()>();
354        if self.inbox.send(RunStateCmd::FrameAck(tx)).is_err() {
355            return false;
356        }
357        rx.recv_timeout(timeout).is_ok()
358    }
359
360    /// Block until the actor has PROCESSED every command sent on
361    /// this handle prior to the call (ordered-inbox barrier; no TUI
362    /// involvement, so it works on every surface). Best-effort:
363    /// `false` on timeout or a dead actor.
364    pub fn drain_barrier(&self, timeout: Duration) -> bool {
365        let (tx, rx) = mpsc::channel::<()>();
366        if self.inbox.send(RunStateCmd::Barrier(tx)).is_err() {
367            return false;
368        }
369        rx.recv_timeout(timeout).is_ok()
370    }
371
372    /// Access the shared frame-sync surface. The TUI app holds a
373    /// clone and consumes it from its draw loop.
374    pub fn frame_sync(&self) -> FrameSync {
375        self.frame_sync.clone()
376    }
377
378    /// Take ownership of the durable scrollback stream receiver for
379    /// the duration of a terminal-mode sink's render loop. The
380    /// returned [`ScrollbackReceiver`] restores the receiver to the
381    /// shared cell when it drops, so the next sink brought up after
382    /// a Ctrl-T swap resumes draining the same stream (the lines
383    /// that buffered while the TUI owned the alternate screen flush
384    /// into the restored scrollback). Only one sink renders at a
385    /// time, so at most one live `ScrollbackReceiver` exists.
386    ///
387    /// Flips the actor's [`Self::log_stream_active`] latch on first
388    /// call, so the actor begins buffering scrollback deltas. Callers
389    /// must set the latch (i.e. call this) BEFORE seeding their
390    /// `last_seen` cursor from `log_seq_total`, so no line sent in the
391    /// handoff window is lost: every line the sink expects to emit
392    /// (seq greater than the seed) is guaranteed to already be in the
393    /// stream.
394    pub(crate) fn take_log_stream(&self) -> ScrollbackReceiver {
395        self.log_stream_active.store(true, Ordering::Release);
396        let rx = self.log_rx.lock().unwrap_or_else(|e| e.into_inner()).take();
397        ScrollbackReceiver {
398            cell: self.log_rx.clone(),
399            rx,
400        }
401    }
402}
403
404/// Spawn the RunState actor on its own OS thread. Returns the
405/// handle (used by the observer, the TUI app, the web API, and
406/// any OOB introspection surface) and the thread `JoinHandle`
407/// (so the runner can join cleanly at shutdown).
408///
409/// The actor exits when every clone of the inbox sender is
410/// dropped — `Receiver::recv` returns `Err`, the loop falls
411/// through, and the final state is published one more time so
412/// post-shutdown readers see `finished = true`.
413/// Durable transcript of the display surface.
414///
415/// The settled half of the TUI — everything that has scrolled past an active
416/// phase — is exactly the [`LogLine`] stream: sequenced, append-only, and
417/// already carrying the actor-stamped `margin_body` (the gutter). The ACTIVE
418/// half is re-derived from the snapshot every render tick and never appended,
419/// so there is nothing to persist there and no boundary to guess at. Teeing
420/// here, at the one place margins are stamped, yields a file that is ordered
421/// and complete by construction — no second consumer of the scrollback
422/// stream, which a sink has exclusively taken.
423///
424/// The session directory is not known when the actor spawns (the runner
425/// creates it later), so lines are BUFFERED until
426/// [`RunStateCmd::OpenTranscript`] arrives and then flushed in order. Without
427/// that buffer the transcript would silently lose its opening lines — which
428/// are the ones naming the session, the workload, and the resolved params.
429#[derive(Default)]
430pub(crate) struct Transcript {
431    file: Option<std::io::BufWriter<std::fs::File>>,
432    pending: Vec<String>,
433}
434
435impl Transcript {
436    /// Render one settled line the way the terminal shows it: the gutter body,
437    /// a divider, then the message. Uncolored — a transcript is read later, by
438    /// tools as often as by people.
439    fn format(line: &LogLine) -> String {
440        format!("{:>27} │ {}", line.margin_body, line.entry.message)
441    }
442
443    fn record(&mut self, line: &LogLine) {
444        let text = Self::format(line);
445        match &mut self.file {
446            Some(f) => {
447                use std::io::Write;
448                let _ = writeln!(f, "{text}");
449                // Flushed per line: a transcript's whole value is being
450                // readable WHILE the run is in flight, and a run that dies is
451                // exactly when its tail matters most.
452                let _ = f.flush();
453            }
454            None => self.pending.push(text),
455        }
456    }
457
458    fn open(&mut self, path: &std::path::Path) {
459        let Ok(f) = std::fs::File::create(path) else {
460            return;
461        };
462        let mut w = std::io::BufWriter::new(f);
463        use std::io::Write;
464        for line in self.pending.drain(..) {
465            let _ = writeln!(w, "{line}");
466        }
467        let _ = w.flush();
468        self.file = Some(w);
469    }
470}
471
472pub fn spawn_run_state_actor(initial: RunState) -> (RunStateHandle, JoinHandle<()>) {
473    let snapshot = Arc::new(ArcSwap::new(Arc::new(initial.clone())));
474    let (tx, rx) = mpsc::channel::<RunStateCmd>();
475    // Durable, ordered, no-drop scrollback stream: the second
476    // down-channel (ArcSwap carries the latest-wins status; this
477    // carries every log delta). Unbounded so a burst of log lines
478    // never blocks the actor (which serves fire-and-forget
479    // producer threads) and never evicts an un-emitted line the
480    // way the bounded ring did. A slow terminal lets it grow during
481    // a burst (bounded by the run's total log volume); the sink
482    // drains it fully on the next lull.
483    let (log_tx, log_rx) = mpsc::channel::<LogLine>();
484    let log_rx = Arc::new(Mutex::new(Some(log_rx)));
485    // Latch: the actor feeds the scrollback stream only once a
486    // terminal-mode sink has claimed it (see `log_stream_active`).
487    let log_stream_active = Arc::new(AtomicBool::new(false));
488    let log_stream_active_for_thread = log_stream_active.clone();
489    let snapshot_for_thread = snapshot.clone();
490    let frame_sync = FrameSync::default();
491    let frame_sync_for_thread = frame_sync.clone();
492
493    let handle = std::thread::Builder::new()
494        .name("run-state-actor".into())
495        .spawn(move || {
496            let mut state = initial;
497            let mut transcript = Transcript::default();
498            // recv() blocks the actor thread when the inbox is
499            // empty — fine, this is a dedicated OS thread, not a
500            // tokio worker. SRD-02 §"No Blocking Primitives in
501            // Async Contexts" only forbids blocking *inside*
502            // tokio.
503            while let Ok(first) = rx.recv() {
504                handle_cmd(
505                    &mut state,
506                    &frame_sync_for_thread,
507                    &log_tx,
508                    &log_stream_active_for_thread,
509                    &mut transcript,
510                    first,
511                );
512                // Coalesce: drain any further-pending commands
513                // before publishing. Cuts publish cost when the
514                // executor bursts updates; readers always see
515                // the latest published state anyway.
516                while let Ok(more) = rx.try_recv() {
517                    handle_cmd(
518                        &mut state,
519                        &frame_sync_for_thread,
520                        &log_tx,
521                        &log_stream_active_for_thread,
522                        &mut transcript,
523                        more,
524                    );
525                }
526                snapshot_for_thread.store(Arc::new(state.clone()));
527            }
528            // Final publish on shutdown — straggler readers see
529            // post-shutdown state (finished = true, last logs).
530            snapshot_for_thread.store(Arc::new(state));
531            // Drop any acks still queued so blocked observers
532            // unblock instead of waiting out their full timeout.
533            frame_sync_for_thread.signal_post_draw();
534            // `log_tx` drops here; the sink's drain sees the
535            // stream disconnect only after every buffered line has
536            // been delivered (mpsc yields buffered items before
537            // `Disconnected`).
538        })
539        .expect("spawn run-state-actor thread");
540
541    (
542        RunStateHandle {
543            snapshot,
544            inbox: tx,
545            frame_sync,
546            log_rx,
547            log_stream_active,
548        },
549        handle,
550    )
551}
552
553/// Top-level command dispatch. Most commands route to `apply`,
554/// which mutates the [`RunState`] in place. `FrameAck` is handled
555/// here because its target is the [`FrameSync`] surface, not the
556/// state.
557fn handle_cmd(
558    state: &mut RunState,
559    frame_sync: &FrameSync,
560    log_tx: &mpsc::Sender<LogLine>,
561    log_stream_active: &AtomicBool,
562    transcript: &mut Transcript,
563    cmd: RunStateCmd,
564) {
565    match cmd {
566        RunStateCmd::OpenTranscript(path) => {
567            transcript.open(&path);
568        }
569        RunStateCmd::Barrier(tx) => {
570            // All prior commands are already applied (ordered inbox);
571            // ack immediately. Receiver may have timed out — ignore.
572            let _ = tx.send(());
573        }
574        RunStateCmd::FrameAck(tx) => {
575            // Register the tx so the TUI app can signal it after
576            // the next draw. Setting `force_redraw` bypasses the
577            // app's tick_rate so that draw fires within ~1 ms
578            // rather than waiting up to a full tick.
579            frame_sync
580                .pending_acks
581                .lock()
582                .unwrap_or_else(|e| e.into_inner())
583                .push(tx);
584            frame_sync.force_redraw.store(true, Ordering::Release);
585        }
586        RunStateCmd::Log {
587            severity,
588            tag,
589            message,
590        } => {
591            // Two sinks for the same line, kept in lock-step:
592            //  1. the bounded ring (inspector `log` view, TUI log
593            //     panel, post-run failure dump) — last 200 only;
594            //  2. the durable scrollback stream — every line, in
595            //     order, exactly once, never evicted. The ring's
596            //     `seq` tags the stream item so a terminal sink can
597            //     skip lines already emitted on stderr before the
598            //     display handoff (or by a prior sink pre-swap).
599            let entry = LogEntry {
600                severity,
601                message,
602                tag,
603                at: std::time::SystemTime::now(),
604            };
605            // The line is ALWAYS stamped and recorded to the transcript —
606            // the durable transcript is a property of the run, not of which
607            // display sink happens to be attached, so `tui=off` and
608            // `tui=formatted` produce the same file as `tui=terminal`.
609            //
610            // The in-memory STREAM, by contrast, is fed only once a
611            // terminal-mode sink has claimed it: with no drainer it would
612            // grow unbounded. So the stamping is unconditional and only the
613            // `send` is gated.
614            {
615                let stream_entry = entry.clone();
616                // gutter/final: a ✓ outcome block for a phase whose
617                // render handle carries a final gutter spec gets that
618                // spec attached — the sink renders it as the detail
619                // line's margin cell. The runtime stores the final
620                // spec BEFORE logging the outcome, and the phase is
621                // still in active_phases at this point (its
622                // PhaseCompleted follows this Log in the stream), so
623                // the head-line `[name]` match is unambiguous among
624                // actives.
625                let mut margin_body: Option<String> = None;
626                let detail_gutter = if stream_entry.tag.attached
627                    == Some(nmbrs_runtime::lifecycle::EventType::PhaseEnd)
628                    && stream_entry.tag.category == crate::state::EventCategory::Outcome
629                {
630                    let plain = crate::status_fold::strip_ansi(&stream_entry.message);
631                    let subject = plain
632                        .split('[')
633                        .nth(1)
634                        .map(|rest| rest.split(']').next().unwrap_or("").to_string())
635                        .and_then(|name| {
636                            state
637                                .active_phases
638                                .values()
639                                .find(|a| a.name == name.as_str())
640                        });
641                    // SRD-92 R1: the ✓ header wears the completing
642                    // NODE'S OWN triad ([n/N] from its plan seq, its
643                    // session-clock delta) — the workload-level stamp
644                    // can point at a still-running sibling under
645                    // concurrent dispatch.
646                    if let Some((s, n)) =
647                        subject.and_then(|a| a.render.as_ref()).and_then(|h| h.seq)
648                    {
649                        let sess = state.elapsed_secs();
650                        let leaf = subject.map(|a| (sess - a.session_started).max(0.0));
651                        margin_body = Some(crate::widgets::margin_body(
652                            n,
653                            &format!("[{s}/{n}]"),
654                            leaf,
655                            Some(sess),
656                        ));
657                    }
658                    subject
659                        .and_then(|a| a.render.as_ref())
660                        .and_then(|h| h.gutter.load_full())
661                        .map(|arc| (*arc).clone())
662                } else {
663                    None
664                };
665                let seq = state.push_log_entry(entry);
666                // Fire-and-forget: a momentarily-parked receiver
667                // (Ctrl-T swap window) still buffers; the next sink
668                // replays it into the restored scrollback.
669                let margin_body = margin_body.unwrap_or_else(|| state.margin_body_stamp());
670                let line = LogLine {
671                    seq,
672                    entry: stream_entry,
673                    margin_body,
674                    detail_gutter,
675                };
676                transcript.record(&line);
677                if log_stream_active.load(Ordering::Acquire) {
678                    let _ = log_tx.send(line);
679                }
680            }
681        }
682        RunStateCmd::PhaseCompleted {
683            exec_id,
684            scene_node_id,
685            name,
686            labels,
687            duration_secs,
688        } => {
689            // Preserve the per-op timing leaves into the durable
690            // scrollback: the footer's op rows (SRD-63 `readout:
691            // visible`) vanish with the active-phase block at
692            // completion, but their individual timings are exactly the
693            // detail the aggregate line forgets. Emit each op's FINAL
694            // leaf right under the phase's ✓ outcome block (the
695            // outcome Log line precedes this command in the stream, so
696            // ordering is inherent). Skipped/elided phases have no
697            // leaves recorded and emit nothing.
698            if log_stream_active.load(Ordering::Acquire)
699                && nmbrs_runtime::observer::completed_phase_display()
700                    == nmbrs_runtime::observer::CompletedPhaseDisplay::Full
701            {
702                let leaves = state.final_op_leaves(&name, &labels);
703                for (text, duration_cell) in leaves {
704                    let entry = LogEntry {
705                        severity: crate::state::LogSeverity::Info,
706                        message: text,
707                        // SRD-92: op leaves are detail rows of the ✓
708                        // block — no triad; their gutter cell carries
709                        // the node's execution duration (the default
710                        // cell for a visible node with no declared
711                        // gutter), the per-step time ledger retained
712                        // into scrollback.
713                        tag: nmbrs_runtime::observer::EventTag::at(
714                            nmbrs_runtime::lifecycle::EventType::PhaseEnd,
715                            nmbrs_runtime::observer::EventCategory::Evaluation,
716                        ),
717                        at: std::time::SystemTime::now(),
718                    };
719                    let stream_entry = entry.clone();
720                    let seq = state.push_log_entry(entry);
721                    let margin_body = state.margin_body_stamp();
722                    let line = LogLine {
723                        seq,
724                        entry: stream_entry,
725                        margin_body,
726                        detail_gutter: Some(nmbrs_runtime::wrappers::gutter::GutterSpec::Text(
727                            duration_cell,
728                        )),
729                    };
730                    transcript.record(&line);
731                    let _ = log_tx.send(line);
732                }
733            }
734            apply(
735                state,
736                RunStateCmd::PhaseCompleted {
737                    exec_id,
738                    scene_node_id,
739                    name,
740                    labels,
741                    duration_secs,
742                },
743            );
744        }
745        other => apply(state, other),
746    }
747}
748
749fn apply(state: &mut RunState, cmd: RunStateCmd) {
750    match cmd {
751        // Intercepted by `handle_cmd` (acked there); a stray one
752        // reaching the state-mutation fold is a harmless no-op.
753        RunStateCmd::Barrier(_) => {}
754        // Handled in `handle_cmd` (it owns the writer); no snapshot state.
755        RunStateCmd::OpenTranscript(_) => {}
756        RunStateCmd::Sysmon(sample) => {
757            state.sysmon = Some(sample);
758        }
759        RunStateCmd::InstallTree(tree) => {
760            state.install_tree(tree);
761        }
762        RunStateCmd::PhaseStarting {
763            exec_id,
764            scene_node_id,
765            name,
766            labels,
767            op_templates,
768            total_cycles: _,
769            concurrency,
770        } => {
771            state.set_phase_running(scene_node_id, &name, &labels, op_templates);
772            let key = crate::state::ActivePhaseId::new(exec_id, name.clone(), labels.clone());
773            // Sparkline capacity = bar width used by
774            // latency_detail_lines so the throughput row aligns
775            // with the latency rows.
776            let throughput_summary = Arc::new(BinomialSummary::new(60));
777            // 1 s half-life: short enough to track real
778            // throughput changes, long enough to stop the raw
779            // value from flickering between frames.
780            let rate_ewma = Arc::new(Ewma::new(Duration::from_secs(1)));
781            let latency_peak_5s = Arc::new(PeakTracker::max(Duration::from_secs(5)));
782            let latency_peak_10s = Arc::new(PeakTracker::max(Duration::from_secs(10)));
783            let session_started = state.elapsed_secs();
784            state.active_phases.insert(
785                key,
786                ActivePhase {
787                    name,
788                    labels,
789                    cursor_name: "?".into(),
790                    cursor_extent: 0,
791                    // Unknown until the first PhaseProgressUpdate carries it.
792                    daemon: false,
793                    rows_consumed: 0,
794                    rows_total: 0,
795                    fibers: concurrency,
796                    started_at: Instant::now(),
797                    session_started,
798                    ops_started: 0,
799                    ops_finished: 0,
800                    ops_ok: 0,
801                    skips: 0,
802                    errors: 0,
803                    retries: 0,
804                    ops_per_sec: 0.0,
805                    adapter_counters: Vec::new(),
806                    rows_per_batch: 0.0,
807                    relevancy: Vec::new(),
808                    throughput_summary,
809                    rate_ewma,
810                    latency_peak_5s,
811                    latency_peak_10s,
812                    render: None,
813                },
814            );
815            // Sparklines reset on every phase boundary so a
816            // short ann_query phase doesn't show several seconds
817            // of rampup throughput instead of its own.
818            state.ops_history.clear();
819            state.rows_history.clear();
820            state.rows_sparkline_label = None;
821        }
822        RunStateCmd::PhaseCompleted {
823            exec_id,
824            scene_node_id,
825            name,
826            labels,
827            duration_secs,
828        } => {
829            let key = crate::state::ActivePhaseId::new(exec_id, name.clone(), labels.clone());
830            let min_ns = state.min_nanos;
831            let p50_ns = state.p50_nanos;
832            let p99_ns = state.p99_nanos;
833            let max_ns = state.max_nanos;
834            let summary = state
835                .active_phases
836                .get(&key)
837                .map(|a| PhaseSummary {
838                    ops_finished: a.ops_finished,
839                    ops_ok: a.ops_ok,
840                    skips: a.skips,
841                    ops_started: a.ops_started,
842                    errors: a.errors,
843                    retries: a.retries,
844                    fibers: a.fibers,
845                    ops_per_sec: a.ops_per_sec,
846                    min_nanos: min_ns,
847                    p50_nanos: p50_ns,
848                    p99_nanos: p99_ns,
849                    max_nanos: max_ns,
850                    cursor_name: a.cursor_name.clone(),
851                    cursor_extent: a.cursor_extent,
852                    adapter_counters: a.adapter_counters.clone(),
853                    rows_per_batch: a.rows_per_batch,
854                    cursors: std::iter::once((a.cursor_name.clone(), a.ops_finished))
855                        .chain(a.adapter_counters.iter().map(|(n, t, _)| (n.clone(), *t)))
856                        .collect(),
857                    relevancy: a.relevancy.clone(),
858                    // Freeze the sparkline as a durable artifact —
859                    // the live Arc<BinomialSummary> is dropped with
860                    // the ActivePhase below.
861                    throughput_samples: a.throughput_summary.snapshot(),
862                })
863                .unwrap_or_default();
864            state.set_phase_completed(scene_node_id, &name, &labels, duration_secs, summary);
865            state.active_phases.remove(&key);
866        }
867        RunStateCmd::PhaseFailed {
868            exec_id,
869            scene_node_id,
870            name,
871            labels,
872            error,
873        } => {
874            state.set_phase_failed(scene_node_id, &name, &labels, &error);
875            state
876                .active_phases
877                .remove(&crate::state::ActivePhaseId::new(exec_id, name, labels));
878        }
879        RunStateCmd::OpStarting { parent, op_name } => {
880            state.op_starting(parent, &op_name);
881        }
882        RunStateCmd::OpMeasure {
883            parent,
884            op_name,
885            text,
886        } => {
887            state.op_measure(parent, &op_name, &text);
888        }
889        RunStateCmd::OpCompleted {
890            parent,
891            op_name,
892            duration_secs,
893        } => {
894            state.op_completed(parent, &op_name, duration_secs);
895        }
896        RunStateCmd::OpFailed {
897            parent,
898            op_name,
899            error,
900        } => {
901            state.op_failed(parent, &op_name, &error);
902        }
903        RunStateCmd::PhaseProgress(update) => {
904            if let Some(active) =
905                state.active_phase_mut(update.exec_id, &update.name, &update.labels)
906            {
907                active.cursor_name = update.cursor_name.clone();
908                active.cursor_extent = update.cursor_extent;
909                active.daemon = update.daemon;
910                active.rows_consumed = update.rows_consumed;
911                active.rows_total = update.rows_total;
912                active.fibers = update.fibers;
913                active.ops_started = update.ops_started;
914                active.ops_finished = update.ops_finished;
915                active.ops_ok = update.ops_ok;
916                active.skips = update.skips;
917                active.errors = update.errors;
918                active.retries = update.retries;
919                active.ops_per_sec = update.ops_per_sec;
920                active.adapter_counters = update
921                    .adapter_counters
922                    .iter()
923                    .map(|(n, t, r)| (n.clone(), *t, *r))
924                    .collect();
925                active.rows_per_batch = update.rows_per_batch;
926                active.relevancy = update
927                    .relevancy
928                    .iter()
929                    .map(|r| {
930                        (
931                            r.name.clone(),
932                            r.window_mean,
933                            r.total_mean,
934                            r.total_count,
935                            r.window_len,
936                        )
937                    })
938                    .collect();
939                active.throughput_summary.record(update.ops_per_sec);
940                active.rate_ewma.record_now(update.ops_per_sec);
941            }
942        }
943        RunStateCmd::AttachPhaseRender(handle) => {
944            // Attach to the live phase slot keyed by (exec_id, name,
945            // labels). If `phase_starting` hasn't been processed yet, or
946            // the phase already completed, the slot is absent and the
947            // handle is dropped — the consumer simply renders no status
948            // for that (now-gone) phase, which is correct.
949            let key = crate::state::ActivePhaseId::new(
950                handle.exec_id,
951                handle.name.as_str(),
952                handle.labels.as_str(),
953            );
954            if let Some(active) = state.active_phases.get_mut(&key) {
955                active.render = Some(handle);
956            }
957        }
958        RunStateCmd::RunFinished => {
959            state.finished = true;
960        }
961        RunStateCmd::Log { .. } => {
962            // Routed to `handle_cmd` before reaching this match (it
963            // feeds both the bounded ring and the durable scrollback
964            // stream); included here only to keep the match
965            // exhaustive.
966            unreachable!("Log is handled in handle_cmd before apply")
967        }
968        RunStateCmd::LatencyFrame {
969            min,
970            p50,
971            p90,
972            p99,
973            p999,
974            max,
975        } => {
976            state.min_nanos = min;
977            state.p50_nanos = p50;
978            state.p90_nanos = p90;
979            state.p99_nanos = p99;
980            state.p999_nanos = p999;
981            state.max_nanos = max;
982
983            const HISTORY_CAP: usize = 300; // 5 min at 1 Hz
984            state.min_history.push(min);
985            state.p50_history.push(p50);
986            state.p90_history.push(p90);
987            state.p99_history.push(p99);
988            state.p999_history.push(p999);
989            state.max_history.push(max);
990            let trim = |h: &mut Vec<u64>| {
991                if h.len() > HISTORY_CAP {
992                    h.remove(0);
993                }
994            };
995            trim(&mut state.min_history);
996            trim(&mut state.p50_history);
997            trim(&mut state.p90_history);
998            trim(&mut state.p99_history);
999            trim(&mut state.p999_history);
1000            trim(&mut state.max_history);
1001
1002            // Each active phase's peak trackers see this frame's
1003            // max latency. Frames are session-labeled today, so
1004            // every active phase observes the same max — fine
1005            // for single-phase scenarios; multi-phase will need
1006            // per-phase frame demux.
1007            let now = Instant::now();
1008            for active in state.active_phases.values() {
1009                active.latency_peak_5s.record(max, now);
1010                active.latency_peak_10s.record(max, now);
1011            }
1012        }
1013        RunStateCmd::SparklineSamples {
1014            ops,
1015            rows,
1016            rows_label,
1017        } => {
1018            if let Some(o) = ops {
1019                state.push_ops_sample(o);
1020            }
1021            if let Some(r) = rows {
1022                state.push_rows_sample(r);
1023            }
1024            state.rows_sparkline_label = rows_label;
1025        }
1026        RunStateCmd::SetMeta { profiler, limit } => {
1027            if let Some(p) = profiler {
1028                state.profiler = p;
1029            }
1030            if let Some(l) = limit {
1031                state.limit = l;
1032            }
1033        }
1034        RunStateCmd::FrameAck(_) => {
1035            // Routed to `handle_cmd` before reaching this match;
1036            // included here only to keep the match exhaustive.
1037            unreachable!("FrameAck is handled in handle_cmd before apply")
1038        }
1039    }
1040}
1041
1042#[cfg(test)]
1043mod scrollback_stream_tests {
1044    use super::*;
1045    use crate::state::{LogSeverity, RunState};
1046
1047    /// The durable scrollback stream carries EVERY log line, in order,
1048    /// exactly once — even when far more than the bounded ring's
1049    /// capacity (200) arrive before anything drains. This is the
1050    /// no-drop guarantee: the old renderer read log deltas off the
1051    /// bounded `RunState.log_messages` ring, which evicts its oldest
1052    /// entries past 200, so a renderer lagging the actor by >200 lines
1053    /// lost the un-emitted oldest ones. The stream is unbounded, so it
1054    /// cannot evict.
1055    #[test]
1056    fn stream_delivers_all_lines_past_ring_capacity() {
1057        let (handle, join) = spawn_run_state_actor(RunState::new("t", "default", "stdout"));
1058
1059        // Claim the stream first (as a real terminal-mode sink does),
1060        // which flips the actor's feed latch on so every subsequent
1061        // line is buffered.
1062        let rx = handle.take_log_stream();
1063
1064        // 500 > the 200-line ring capacity, all queued before a single
1065        // drain — the exact overflow condition that dropped lines.
1066        const N: u64 = 500;
1067        for i in 0..N {
1068            handle.send(RunStateCmd::Log {
1069                severity: LogSeverity::Info,
1070                tag: crate::state::EventTag::default(),
1071                message: format!("line-{i}"),
1072            });
1073        }
1074
1075        // Drain the durable stream, waiting for the actor thread to
1076        // finish enqueuing all N.
1077        let mut got: Vec<(u64, String)> = Vec::new();
1078        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1079        while (got.len() as u64) < N && std::time::Instant::now() < deadline {
1080            match rx.try_next() {
1081                Some(line) => got.push((line.seq, line.entry.message)),
1082                None => std::thread::sleep(std::time::Duration::from_millis(2)),
1083            }
1084        }
1085
1086        assert_eq!(
1087            got.len() as u64,
1088            N,
1089            "every log line must be delivered — none dropped despite \
1090             {N} lines arriving before any drain (ring cap is 200)"
1091        );
1092        // In order, contiguous seq 1..=N, messages line-0..line-(N-1).
1093        for (i, (seq, msg)) in got.iter().enumerate() {
1094            assert_eq!(*seq, i as u64 + 1, "seq monotonic + contiguous");
1095            assert_eq!(msg, &format!("line-{i}"), "delivered in order");
1096        }
1097
1098        drop(rx);
1099        drop(handle);
1100        let _ = join.join();
1101    }
1102
1103    /// The actor does NOT feed the stream until a terminal-mode sink
1104    /// claims it — so modes with no `LogOnlySink` (`tui=on` full TUI,
1105    /// `tui=off` piped/CI, `tui=formatted`) never accumulate an
1106    /// unbounded backlog on a stream nobody drains. Lines pushed before
1107    /// the claim still reach the ring + `session.log`; they just aren't
1108    /// buffered on the stream.
1109    #[test]
1110    fn stream_not_fed_until_a_sink_claims_it() {
1111        let (handle, join) = spawn_run_state_actor(RunState::new("t", "default", "stdout"));
1112
1113        // No sink has claimed the stream yet.
1114        for i in 0..300u64 {
1115            handle.send(RunStateCmd::Log {
1116                severity: LogSeverity::Info,
1117                tag: crate::state::EventTag::default(),
1118                message: format!("unfed-{i}"),
1119            });
1120        }
1121        std::thread::sleep(std::time::Duration::from_millis(60));
1122
1123        // Claim now: nothing that predates the claim is buffered.
1124        let rx = handle.take_log_stream();
1125        std::thread::sleep(std::time::Duration::from_millis(20));
1126        assert!(
1127            rx.try_next().is_none(),
1128            "an unclaimed stream must not buffer a backlog — no leak when \
1129             no LogOnlySink is draining"
1130        );
1131
1132        // Lines sent AFTER the claim ARE delivered.
1133        handle.send(RunStateCmd::Log {
1134            severity: LogSeverity::Info,
1135            tag: crate::state::EventTag::default(),
1136            message: "after-claim".into(),
1137        });
1138        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1139        let mut got = None;
1140        while got.is_none() && std::time::Instant::now() < deadline {
1141            match rx.try_next() {
1142                Some(line) => got = Some(line.entry.message),
1143                None => std::thread::sleep(std::time::Duration::from_millis(2)),
1144            }
1145        }
1146        assert_eq!(
1147            got.as_deref(),
1148            Some("after-claim"),
1149            "lines sent after the claim must flow through the stream"
1150        );
1151
1152        drop(rx);
1153        drop(handle);
1154        let _ = join.join();
1155    }
1156
1157    /// The receiver survives a sink teardown: the `ScrollbackReceiver`
1158    /// guard restores it to the shared cell on drop, so a subsequent
1159    /// `take_log_stream` (the next terminal-mode sink after a Ctrl-T
1160    /// swap) resumes the SAME stream and sees the lines that buffered
1161    /// while no sink was draining.
1162    #[test]
1163    fn stream_receiver_survives_sink_handoff() {
1164        let (handle, join) = spawn_run_state_actor(RunState::new("t", "default", "stdout"));
1165
1166        // First "sink" takes the stream, then tears down (guard drops).
1167        {
1168            let _rx = handle.take_log_stream();
1169        }
1170        // Lines buffered while no sink is draining.
1171        for i in 0..3u64 {
1172            handle.send(RunStateCmd::Log {
1173                severity: LogSeverity::Info,
1174                tag: crate::state::EventTag::default(),
1175                message: format!("swap-{i}"),
1176            });
1177        }
1178        // Second "sink" resumes the same stream and drains the backlog.
1179        let rx = handle.take_log_stream();
1180        let mut got = Vec::new();
1181        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
1182        while got.len() < 3 && std::time::Instant::now() < deadline {
1183            match rx.try_next() {
1184                Some(line) => got.push(line.entry.message),
1185                None => std::thread::sleep(std::time::Duration::from_millis(2)),
1186            }
1187        }
1188        assert_eq!(
1189            got,
1190            vec!["swap-0", "swap-1", "swap-2"],
1191            "the stream receiver must survive the sink handoff and \
1192             flush the backlog buffered while no sink was draining"
1193        );
1194
1195        drop(rx);
1196        drop(handle);
1197        let _ = join.join();
1198    }
1199}
1200
1201#[cfg(test)]
1202mod transcript_tests {
1203    use super::Transcript;
1204
1205    /// Lines logged BEFORE the session directory exists — the banner naming
1206    /// the session, the workload, the resolved params — are exactly the ones
1207    /// worth keeping, so they buffer and flush in order rather than being
1208    /// dropped for arriving early.
1209    #[test]
1210    fn buffers_until_opened_then_flushes_in_order() {
1211        let dir = std::env::temp_dir().join(format!(
1212            "nmbrs-transcript-{}-{}",
1213            std::process::id(),
1214            line!()
1215        ));
1216        std::fs::create_dir_all(&dir).unwrap();
1217        let path = dir.join("transcript.log");
1218
1219        let mut t = Transcript::default();
1220        for msg in ["first", "second"] {
1221            t.record(&super::LogLine {
1222                seq: 0,
1223                entry: crate::state::LogEntry {
1224                    severity: crate::state::LogSeverity::Info,
1225                    message: msg.into(),
1226                    tag: crate::state::EventTag::default(),
1227                    at: std::time::SystemTime::now(),
1228                },
1229                margin_body: "m".into(),
1230                detail_gutter: None,
1231            });
1232        }
1233        assert!(!path.exists(), "nothing is written before open");
1234        t.open(&path);
1235        t.record(&super::LogLine {
1236            seq: 2,
1237            entry: crate::state::LogEntry {
1238                severity: crate::state::LogSeverity::Info,
1239                message: "third".into(),
1240                tag: crate::state::EventTag::default(),
1241                at: std::time::SystemTime::now(),
1242            },
1243            margin_body: "m".into(),
1244            detail_gutter: None,
1245        });
1246
1247        let body = std::fs::read_to_string(&path).unwrap();
1248        let msgs: Vec<&str> = body
1249            .lines()
1250            .map(|l| l.rsplit('│').next().unwrap().trim())
1251            .collect();
1252        assert_eq!(
1253            msgs,
1254            vec!["first", "second", "third"],
1255            "buffered lines flush ahead of live ones, in order:\n{body}"
1256        );
1257        let _ = std::fs::remove_dir_all(&dir);
1258    }
1259
1260    /// The transcript carries the GUTTER, which is the whole reason it is not
1261    /// just session.log: the margin is what ties a line to the phase and
1262    /// clock position the operator saw it at.
1263    #[test]
1264    fn each_line_carries_its_margin_and_divider() {
1265        let rendered = Transcript::format(&super::LogLine {
1266            seq: 0,
1267            entry: crate::state::LogEntry {
1268                severity: crate::state::LogSeverity::Info,
1269                message: "phase done".into(),
1270                tag: crate::state::EventTag::default(),
1271                at: std::time::SystemTime::now(),
1272            },
1273            margin_body: "◷ 12.1s [1/4]".into(),
1274            detail_gutter: None,
1275        });
1276        assert!(rendered.contains("◷ 12.1s [1/4]"), "{rendered}");
1277        assert!(
1278            rendered.contains('│'),
1279            "divider separates gutter from message: {rendered}"
1280        );
1281        assert!(rendered.trim_end().ends_with("phase done"), "{rendered}");
1282    }
1283}