Skip to main content

nmbrs_runtime/
runner.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Shared run pipeline for persona binaries.
5//!
6//! Encapsulates workload parsing → Polydat compilation → activity
7//! construction → execution (single or phased).
8//!
9//! Each persona binary links its adapter crates (which register
10//! themselves via `inventory::submit!`) and calls [`run()`].
11//! The persona adds nothing but adapters and node functions —
12//! all orchestration logic lives here.
13
14use std::collections::HashMap;
15use std::sync::Arc;
16
17use crate::activity::Activity;
18use crate::adapter::{find_adapter_registration, registered_adapter_params};
19use crate::bindings::build_workload_root_kernel;
20use crate::opseq::SequencerType;
21use crate::synthesis::OpBuilder;
22use nmbrs_metrics::labels::Labels;
23use nmbrs_metrics::scheduler::Reporter;
24use nmbrs_workload::tags::TagFilter;
25
26/// The run-style `key=value` param vocabulary, injected by the CLI layer
27/// from its own command-spec (`nmbrs::completion::RUN_KV_PARAMS`) so there is
28/// ONE source of truth and zero hand-synced copies. `None` until installed
29/// (library/test consumers that drive the runner directly without the CLI):
30/// in that case the param-vocabulary validations below are skipped — those
31/// are a CLI-surface concern, and the binary always installs the list before
32/// any run. See [`install_known_params`] / [`known_params`].
33static KNOWN_PARAMS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
34
35/// Install the run-style param vocabulary (the keys the CLI command-spec
36/// accepts, sans the trailing `=`). Called once at binary startup from the
37/// CLI layer, which owns the canonical list. Idempotent — first wins.
38pub fn install_known_params(keys: Vec<&'static str>) {
39    let _ = KNOWN_PARAMS.set(keys);
40}
41
42/// The installed param vocabulary, or `None` when no CLI layer registered
43/// one. Validators treat `None` as "skip the closed-vocabulary check" so a
44/// direct library/test driver isn't held to the CLI's param surface.
45/// Adapter-specific params are still discovered from inventory regardless.
46fn known_params() -> Option<&'static [&'static str]> {
47    KNOWN_PARAMS.get().map(|v| v.as_slice())
48}
49
50/// Whether `name` is an installed CLI param key. When no vocabulary is
51/// installed (library/test driver), every name is treated as known so the
52/// closed-vocabulary validations no-op rather than false-reject a workload.
53pub(crate) fn is_cli_param(name: &str) -> bool {
54    known_params().map(|p| p.contains(&name)).unwrap_or(true)
55}
56
57/// Spec-derived flag vocabulary (SRD-15 CLI substrate): the run command's
58/// DECLARED flags, split by arity, installed at binary startup exactly like
59/// [`install_known_params`]. Before this, [`parse_params`] validated argv
60/// against its own hardcoded lists ([`RECOGNIZED_BARE_FLAGS`] /
61/// [`SESSION_DIR_FLAGS`]), which had drifted from the spec — declared flags
62/// like `--no-prompt` (bool) and the space form of `--kernel-opt` were
63/// hard-rejected while help and completion advertised them. The hardcoded lists remain only as the
64/// library/test-driver fallback.
65static KNOWN_BARE_FLAGS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
66static KNOWN_VALUE_FLAGS: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
67
68/// Install the run-style flag vocabulary (long forms + aliases from the CLI
69/// command-spec, split by arity). Idempotent — first wins.
70pub fn install_known_flags(bare: Vec<&'static str>, value: Vec<&'static str>) {
71    let _ = KNOWN_BARE_FLAGS.set(bare);
72    let _ = KNOWN_VALUE_FLAGS.set(value);
73}
74
75/// Recognized bare (boolean) flag: the installed spec list, or the
76/// hardcoded fallback. `--refine` is runner-internal (injected by the
77/// refine command, never user-declared) so it is always recognized.
78pub(crate) fn is_recognized_bare_flag(arg: &str) -> bool {
79    arg == "--refine"
80        || KNOWN_BARE_FLAGS
81            .get()
82            .map(|v| v.contains(&arg))
83            .unwrap_or_else(|| RECOGNIZED_BARE_FLAGS.contains(&arg))
84}
85
86/// Recognized value-taking flag (space form consumes the next token):
87/// the installed spec list, or the hardcoded session-flag fallback.
88pub(crate) fn known_value_flags() -> &'static [&'static str] {
89    KNOWN_VALUE_FLAGS
90        .get()
91        .map(|v| v.as_slice())
92        .unwrap_or(SESSION_DIR_FLAGS)
93}
94
95/// Every recognized flag, bare and value-taking: the candidates an
96/// unrecognized `--flag` is matched against for a suggestion.
97fn known_flags() -> Vec<&'static str> {
98    let bare: &[&str] = KNOWN_BARE_FLAGS
99        .get()
100        .map(|v| v.as_slice())
101        .unwrap_or(RECOGNIZED_BARE_FLAGS);
102    bare.iter().chain(known_value_flags()).copied().collect()
103}
104
105/// A CLI flag's value, accepting `--flag=value` and `--flag value`.
106///
107/// The same two spellings [`crate::session::resolve_flag`] accepts, minus its
108/// environment-variable fallback and conflict check — for flags that are
109/// CLI-only by design. Written out because the flags declared in the command
110/// spec are advertised (in `--help` and completion) as taking a value, and a
111/// reader matching only `--flag=` would silently ignore the spelling the
112/// completer suggests.
113fn cli_flag_value(args: &[String], flag: &str) -> Option<String> {
114    let eq_prefix = format!("{flag}=");
115    let mut iter = args.iter();
116    while let Some(arg) = iter.next() {
117        if let Some(rest) = arg.strip_prefix(&eq_prefix) {
118            return Some(rest.to_string());
119        }
120        if arg == flag {
121            return iter.next().cloned();
122        }
123    }
124    None
125}
126
127/// Session-dir file holding end-of-run summary output that is
128/// routed to stdout (SRD-46 `to stdout`) but could not be written
129/// inline because a TUI owned the terminal. The post-run printer
130/// flushes it verbatim once the terminal is back in cooked mode.
131///
132/// Dot-prefixed, and deliberately NOT matching the `_summary.`
133/// artifact pattern: artifacts are the `sessiondir` destination,
134/// and their presence must never by itself imply a stdout write.
135pub const DEFERRED_STDOUT_FILE: &str = ".report_stdout.md";
136
137/// Convert the workload-model `SummaryConfig` (parsed from the
138/// `summary:` workload field or the `--summary` CLI flag) into
139/// the SQLite reporter's `ReportConfig`. Used by both the
140/// in-run summary path (workload finished, render to
141/// `summary.md`) and the standalone `nmbrs --summary` command,
142/// so both produce identical output for the same spec.
143pub fn report_config_from_summary(
144    config: &nmbrs_workload::model::SummaryConfig,
145    exec_id_filter: Option<u64>,
146) -> nmbrs_metrics::reporters::sqlite::ReportConfig {
147    nmbrs_metrics::reporters::sqlite::ReportConfig {
148        columns: config.columns.clone(),
149        row_filters: config.row_filters.clone(),
150        aggregates: config
151            .aggregates
152            .iter()
153            .map(|a| nmbrs_metrics::reporters::sqlite::ReportAggregate {
154                function: a.function.to_string(),
155                column_pattern: a.column_pattern.clone(),
156                label_key: a.label_key.clone(),
157                label_pattern: a.label_pattern.clone(),
158                group_by: a.group_by.clone(),
159            })
160            .collect(),
161        show_details: config.show_details,
162        exec_id_filter,
163    }
164}
165
166/// Try to resolve a workload name (bare or with extension) to an
167/// actual file path, searching the current directory and
168/// `./workloads/`. Returns `None` if nothing matches.
169///
170/// Exposed for shell-completion tooling. Application code should
171/// just use [`run_with_observer`] which calls this internally.
172pub fn resolve_workload_file_public(name: &str) -> Option<String> {
173    resolve_workload_file(name)
174}
175
176/// List the scenario names declared at the top level of a workload
177/// YAML file. Used by shell-completion tooling to offer
178/// `scenario=<tab>` suggestions. Returns an empty vector on any
179/// parse error — completion is best-effort, not a hard check.
180pub fn scenarios_in_workload_file(path: &str) -> Vec<String> {
181    let Ok(src) = std::fs::read_to_string(path) else {
182        return Vec::new();
183    };
184    let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(&src) else {
185        return Vec::new();
186    };
187    let Some(scenarios) = doc.get("scenarios") else {
188        return Vec::new();
189    };
190    let Some(map) = scenarios.as_mapping() else {
191        return Vec::new();
192    };
193    map.keys()
194        .filter_map(|k| k.as_str().map(String::from))
195        .collect()
196}
197
198/// Run a workload. Adapters are discovered from link-time inventory
199/// registrations — the calling binary just needs to link the adapter
200/// crates it wants available.
201/// Execution depth: how far through the pipeline to go.
202///
203/// Ordering (shallowest → deepest):
204/// `Phase < Dispenser < Op < Cycle < Full`.
205/// `PartialOrd`/`Ord` follow this ordering so depth-gating
206/// sites can write `ctx.diag.depth >= ExecDepth::Cycle` etc.
207#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
208pub enum ExecDepth {
209    /// Compile scope-level kernels, stop before op-template
210    /// kernels / adapter `map_op` / metric instruments. No
211    /// adapters created.
212    Phase,
213    /// `dryrun=dispenser`: phase walk + every op template's
214    /// dispenser is constructed (adapter `map_op` fires; the
215    /// wrapper plan resolves and wraps; the cursor source
216    /// factory is built). NO cycles run. This is the
217    /// construction-time inspection level: catches `map_op`
218    /// failures (bad prepared statement, schema mismatch),
219    /// wrapper-resolver violations, source-factory init
220    /// errors — without paying any per-cycle cost. Distinct
221    /// from `Phase` (which builds NO dispensers) and `Op`
222    /// (which runs full cycles with the wrapper short-
223    /// circuit).
224    Dispenser,
225    /// `dryrun=op`: phase walk + dispenser construction +
226    /// per-cycle wrapper-stack execution. The DRYRUN wrapper
227    /// short-circuits the inner adapter `execute()`; every
228    /// other layer (bind-point eval, wrapper pulls, metric
229    /// timing) runs faithfully. The auto-bump in the runner
230    /// lifts `Op` to `Cycle` so the cycle loop actually
231    /// dispatches.
232    Op,
233    /// Run cycles with dry-run adapter.
234    Cycle,
235    /// Normal execution.
236    Full,
237}
238
239/// Diagnostic configuration parsed from `dryrun=` parameter.
240#[derive(Clone)]
241pub struct DiagnosticConfig {
242    /// How far to execute.
243    pub depth: ExecDepth,
244    /// Emit value-provenance / wiring view: how each named wire
245    /// was computed and where its inputs originated. Surfaced by
246    /// `dryrun=wiring`. (Was previously `dryrun=polydat` — the rename
247    /// keeps the polydat runtime an internal concept; the user-
248    /// facing concept is "wiring" between named values.)
249    pub show_wiring: bool,
250    /// Emit dimensional labels for all phases.
251    pub show_labels: bool,
252    /// Walk the post-construction component tree, render every
253    /// declared dynamic control, and exit. SRD 23 §"Enumeration:
254    /// controls are structural".
255    pub list_controls: bool,
256}
257
258impl DiagnosticConfig {
259    /// Normal execution, no diagnostics.
260    pub fn normal() -> Self {
261        Self {
262            depth: ExecDepth::Full,
263            show_wiring: false,
264            show_labels: false,
265            list_controls: false,
266        }
267    }
268
269    /// Parse from `dryrun=` value (e.g., "phase,wiring" or "cycle").
270    /// If no depth flag (phase/cycle/full) is given, defaults to `Phase`.
271    pub fn parse(spec: &str) -> Self {
272        let mut config = Self::normal();
273        let mut depth_set = false;
274        for flag in spec.split(',') {
275            match flag.trim() {
276                "phase" => {
277                    config.depth = ExecDepth::Phase;
278                    depth_set = true;
279                }
280                "dispenser" => {
281                    config.depth = ExecDepth::Dispenser;
282                    depth_set = true;
283                }
284                "op" => {
285                    config.depth = ExecDepth::Op;
286                    depth_set = true;
287                }
288                "cycle" => {
289                    config.depth = ExecDepth::Cycle;
290                    depth_set = true;
291                }
292                "full" => {
293                    config.depth = ExecDepth::Full;
294                    depth_set = true;
295                }
296                "wiring" => {
297                    // Value-provenance view. Needs depth >= Op for
298                    // kernels to exist; bump depth so a bare
299                    // `dryrun=wiring` produces output instead of
300                    // silently doing nothing.
301                    config.show_wiring = true;
302                    if !depth_set {
303                        config.depth = ExecDepth::Op;
304                        depth_set = true;
305                    }
306                }
307                "labels" => config.show_labels = true,
308                "controls" => {
309                    // Implies an early exit before any phase
310                    // runs — `controls` is a discovery dump, not
311                    // an execution mode.
312                    config.list_controls = true;
313                    config.depth = ExecDepth::Phase;
314                    depth_set = true;
315                }
316                // `emit` / `silent` / `json` are the dryrun output
317                // modes — they live on `ActivityConfig::dry_run_mode`
318                // and drive the dryrun template-parameter injection
319                // that the outermost `DryRunWrapper` keys off. The
320                // runner reads them via a separate
321                // `params.get("dryrun")` lookup below and bumps
322                // depth to Cycle so the cycle path runs. The depth-
323                // config parser tolerates these tokens silently so
324                // an operator passing `dryrun=fields` doesn't see a
325                // misleading "unknown flag" warning.
326                "fields" | "silent" | "json" => {}
327                // `dryrun=kernels` is a planning-only mode — it
328                // builds the scope tree, then walks every
329                // materialised scope and prints its polydat
330                // source. Depth stays at Phase; the runner
331                // dispatches to a kernel-dump short-circuit
332                // before any phase activation.
333                "kernels" => {}
334                _ => crate::diag!(
335                    crate::observer::LogLevel::Warn,
336                    "warning: unknown dryrun flag '{flag}'"
337                ),
338            }
339        }
340        // Default to phase depth if no explicit depth was given
341        if !depth_set {
342            config.depth = ExecDepth::Phase;
343        }
344        config
345    }
346}
347
348/// Walk a component subtree and print every declared control
349/// (name, type, current value, scope, final flag, applier
350/// count) in a stable order. Used by `dryrun=controls` and any
351/// other discovery-style call site.
352pub fn render_controls_tree(
353    root: &std::sync::Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
354    out: &mut dyn std::io::Write,
355) -> std::io::Result<()> {
356    use nmbrs_metrics::component::find;
357    use nmbrs_metrics::selector::Selector;
358
359    writeln!(out, "Declared dynamic controls (SRD 23):")?;
360    let all = find(root, &Selector::new());
361    let mut entries: Vec<(String, String, String, String, String, String)> = Vec::new();
362    for comp in all {
363        let guard = match comp.read() {
364            Ok(g) => g,
365            Err(_) => continue,
366        };
367        let path = guard
368            .effective_labels()
369            .iter()
370            .map(|(k, v)| format!("{k}={v}"))
371            .collect::<Vec<_>>()
372            .join(",");
373        for ctl in guard.controls().list() {
374            let scope = match ctl.branch_scope() {
375                nmbrs_metrics::controls::BranchScope::Local => "local",
376                nmbrs_metrics::controls::BranchScope::Subtree => "subtree",
377            };
378            let final_marker = match ctl.final_scope() {
379                Some(s) => format!("final@{s}"),
380                None => "-".to_string(),
381            };
382            entries.push((
383                if path.is_empty() {
384                    "<root>".into()
385                } else {
386                    path.clone()
387                },
388                ctl.name().to_string(),
389                ctl.value_type_name().to_string(),
390                ctl.value_string(),
391                format!(
392                    "scope={scope}, {final_marker}, appliers={}",
393                    ctl.applier_count()
394                ),
395                if ctl.accepts_f64_writes() {
396                    "f64-writable".into()
397                } else {
398                    "no-f64".into()
399                },
400            ));
401        }
402    }
403    if entries.is_empty() {
404        writeln!(out, "  (no controls declared)")?;
405        return Ok(());
406    }
407    entries.sort();
408    for (path, name, ty, value, meta, write) in entries {
409        writeln!(
410            out,
411            "  {path}\n    {name}: {value}  [{ty}]  {meta}  {write}",
412        )?;
413    }
414    Ok(())
415}
416
417/// Render the SRD-13d scope-elision summary for `dryrun=op`.
418/// One line per scope-tree node (DFS pre-order), showing the
419/// logical name and the materialised/elides-to mark.
420///
421/// Format follows SRD-13d §5.3:
422/// ```text
423/// scope elision summary
424/// ------------------------
425/// workload                                           materialised=true
426/// workload.scenario.default                          materialised=false  elides-to=workload
427/// workload.scenario.default.phase.predict            materialised=true
428/// ```
429///
430/// `materialised=true` means the node owns a kernel; `false`
431/// means it elides into its nearest materialised ancestor
432/// (shown as `elides-to=<logical_name>`). Nodes whose mark
433/// is still `None` (predicate hasn't fired — should not
434/// happen post-`classify_and_mark`) are surfaced as `unknown`
435/// rather than silently skipped.
436pub fn render_scope_elision_summary(
437    tree: &crate::scope_tree::ScopeTree,
438    out: &mut dyn std::io::Write,
439) -> std::io::Result<()> {
440    let summary = crate::scope_elision::elision_summary(tree);
441    // Width of the logical-name column — 4-space gutter past
442    // the longest name (or 48ch min) so the materialised marks
443    // line up cleanly even with deeply-nested phase trees.
444    let name_width = summary
445        .iter()
446        .map(|(_, _, _, name, _)| name.len())
447        .max()
448        .unwrap_or(0)
449        .max(48);
450
451    writeln!(out, "scope elision summary")?;
452    writeln!(out, "------------------------")?;
453    for (idx, _depth, materialised, logical_name, _kind) in &summary {
454        match materialised {
455            Some(true) => {
456                writeln!(
457                    out,
458                    "{:<width$}    materialised=true",
459                    logical_name,
460                    width = name_width
461                )?;
462            }
463            Some(false) => {
464                let elides_to = tree
465                    .nearest_materialised(*idx)
466                    .map(|p| tree.nodes[p].logical_name.clone())
467                    .unwrap_or_else(|| "<unknown>".to_string());
468                writeln!(
469                    out,
470                    "{:<width$}    materialised=false  elides-to={}",
471                    logical_name,
472                    elides_to,
473                    width = name_width
474                )?;
475            }
476            None => {
477                writeln!(
478                    out,
479                    "{:<width$}    materialised=unknown",
480                    logical_name,
481                    width = name_width
482                )?;
483            }
484        }
485    }
486    Ok(())
487}
488
489pub async fn run(args: &[String]) -> Result<(), String> {
490    // Default tui=off observer — stderr with the same Info-level
491    // filter the TUI's log panel applies by default. `loglevel=`
492    // CLI param overrides; absent means Info.
493    //
494    // We need to peek at one CLI param before kicking off the
495    // full runner pipeline. Strip a leading `run` subcommand the
496    // same way `run_with_observer` does at its own param-parse
497    // step, so this peek doesn't reject perfectly valid CLI
498    // shapes (`nmbrs run loglevel=debug …`).
499    let stripped: &[String] = match args.first().map(|s| s.as_str()) {
500        Some("run") => &args[1..],
501        _ => args,
502    };
503    let cli_params = parse_params(stripped);
504    let min_level = cli_params
505        .get("loglevel")
506        .or_else(|| cli_params.get("loglevel-display"))
507        .or_else(|| cli_params.get("loglevel_display"))
508        .and_then(|s| parse_log_level(s))
509        .unwrap_or(crate::observer::LogLevel::Info);
510    let retain_level = cli_params
511        .get("loglevel-retain")
512        .or_else(|| cli_params.get("loglevel_retain"))
513        .and_then(|s| parse_log_level(s))
514        .unwrap_or(crate::observer::LogLevel::Debug);
515    crate::observer::set_retain_level(retain_level);
516    crate::observer::set_display_level(min_level);
517    run_with_observer(
518        args,
519        Arc::new(crate::observer::StderrObserver::with_min_level(min_level)),
520    )
521    .await
522}
523
524/// Parse a CLI/workload `loglevel=` value. Case-insensitive,
525/// accepts the standard names plus the abbreviations the log
526/// sink emits (`DBG` / `INF` / `WRN` / `ERR`).
527pub fn parse_log_level(s: &str) -> Option<crate::observer::LogLevel> {
528    use crate::observer::LogLevel;
529    match s.trim().to_ascii_lowercase().as_str() {
530        "trace" | "trc" => Some(LogLevel::Trace),
531        "debug" | "dbg" => Some(LogLevel::Debug),
532        "info" | "inf" => Some(LogLevel::Info),
533        "warn" | "wrn" | "warning" => Some(LogLevel::Warn),
534        "error" | "err" => Some(LogLevel::Error),
535        _ => None,
536    }
537}
538
539/// Run with a custom observer for phase lifecycle events.
540/// The TUI persona uses this to inject a TuiObserver that updates
541/// the display state instead of printing to stderr.
542pub async fn run_with_observer(
543    args: &[String],
544    observer: Arc<dyn crate::observer::RunObserver>,
545) -> Result<(), String> {
546    let args: &[String] = match args.first().map(|s| s.as_str()) {
547        Some("run") => &args[1..],
548        // Reject unknown subcommands — don't silently fall through to execution
549        Some(cmd) if !cmd.contains('=') && !cmd.ends_with(".yaml") && !cmd.ends_with(".yml") => {
550            return Err(format!(
551                "unknown command '{cmd}'. Use 'run' or pass a workload file."
552            ));
553        }
554        _ => args,
555    };
556    // Reject conflicting duplicate `key=value` params (e.g. two
557    // different `scenario=` values) before any work — otherwise the
558    // last silently wins. Errors here, before session creation.
559    detect_conflicting_duplicate_params(args)?;
560    run_impl(args, observer).await
561}
562
563/// The session-level metrics services [`build_session_metrics`] builds.
564struct SessionMetrics {
565    cadence_reporter: std::sync::Arc<nmbrs_metrics::cadence_reporter::CadenceReporter>,
566    cadence_tree: nmbrs_metrics::cadence::CadenceTree,
567    metrics_query: std::sync::Arc<nmbrs_metrics::metrics_query::MetricsQuery>,
568    /// Stops the metrics scheduler.
569    stop_handle: std::sync::Arc<nmbrs_metrics::scheduler::StopHandle>,
570}
571
572/// SRD-88 — build the session-level metrics services: the cadence
573/// tree + reporter, the shared `MetricsQuery`, and the metrics
574/// scheduler (whose `StopHandle` is returned). One set per session;
575/// every execution sharing the session routes through these. Reads
576/// the session component (capture root), the sqlite reporter (cadence
577/// subscription), and the observer (cadence prefs + live reporters).
578fn build_session_metrics(
579    session: &crate::session::Session,
580    sqlite_reporter: &std::sync::Arc<
581        std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>,
582    >,
583    observer: &Arc<dyn crate::observer::RunObserver>,
584    merged_params: &HashMap<String, String>,
585    openmetrics_url: &Option<String>,
586    args: &[String],
587    params: &HashMap<String, String>,
588) -> Result<SessionMetrics, String> {
589    // `metrics_cadence` (effective param) may set a sub-second finest
590    // cadence + base interval; otherwise the default 1 s base + declared
591    // cadences. The base interval drives both the cadence tree and the
592    // scheduler tick below, so the finest cadence the settle detector
593    // samples and the capture pulse stay in lockstep.
594    let (base_interval, cadences) = resolve_cadence_config(merged_params, observer)?;
595    let cadence_tree = nmbrs_metrics::cadence::CadenceTree::plan_validated(
596        cadences,
597        nmbrs_metrics::cadence::DEFAULT_MAX_FAN_IN,
598        base_interval,
599    )
600    .map_err(|e| format!("cadence tree: {e}"))?;
601    let cadence_reporter = Arc::new(nmbrs_metrics::cadence_reporter::CadenceReporter::new(
602        cadence_tree.clone(),
603    ));
604    let metrics_query = Arc::new(nmbrs_metrics::metrics_query::MetricsQuery::new(
605        cadence_reporter.clone(),
606        session.component.clone(),
607    ));
608    session.set_metrics_query(metrics_query.clone());
609    nmbrs_metrics::polydat_nodes::set_global_query(metrics_query.clone());
610    // SRD-86 §"The metric-reader surface" / SRD-90 §M5 — install the live
611    // in-process metrics-access service the `metricsql_*` nodes locate via
612    // `queryapi::live_access()`. It is a HYBRID (SRD-90): the in-memory cadence
613    // tier (fine, recent, retention-bounded) over the session's durable sqlite
614    // store (coarse, the older tail), composed by union-minus-overlap — a recent
615    // windowed read is served entirely from memory (the common case never opens
616    // sqlite), and a query older than the in-memory horizon spills to the
617    // durable tail. Both tiers scope to the reading execution (mem via the
618    // read-exec hook; cold via `CurrentReadExec`), so a concurrent spill never
619    // leaks a neighbour's series. Best-effort: if the sqlite tail can't be
620    // opened (sqlite disabled, db absent), the live service is the mem tier
621    // alone — byte-identical to before this seam.
622    let mem_access = std::sync::Arc::new(nmbrs_metrics::queryapi::MetricsQueryAccess::new(
623        metrics_query.clone(),
624    ));
625    // The composed read store: the in-memory cadence tier over the durable
626    // sqlite tail (union-minus-overlap). The cold tier reads `All` executions
627    // at the SQL level — per-execution scoping is the injected `exec_id`
628    // dimensional label (below), uniform across both tiers.
629    let composed: std::sync::Arc<dyn nmbrs_metrics::queryapi::MetricAccess> = {
630        let db = session.output_dir.join("metrics.db");
631        match nmbrs_metrics::queryapi::sqlite::SqliteDataSource::open(&db) {
632            Ok(cold) => {
633                let cold = cold.with_execution_selection(
634                    nmbrs_metrics::queryapi::sqlite::ExecutionSelection::All,
635                );
636                let mem_for_horizon = mem_access.clone();
637                std::sync::Arc::new(nmbrs_metrics::queryapi::HybridStore::new(vec![
638                    nmbrs_metrics::queryapi::Tier::new(
639                        mem_access.clone(),
640                        std::sync::Arc::new(move || mem_for_horizon.earliest_ms()),
641                    ),
642                    nmbrs_metrics::queryapi::Tier::unbounded(std::sync::Arc::new(cold)),
643                ]))
644            }
645            Err(e) => {
646                crate::diag!(
647                    crate::observer::LogLevel::Debug,
648                    "metrics: hybrid sqlite tail unavailable ({e}); live reads are in-memory only"
649                );
650                mem_access.clone()
651            }
652        }
653    };
654    // SRD-89 §3b / SRD-90 §M6 — scope every live read to its execution via the
655    // `exec_id` dimensional-label matcher, applied uniformly to both tiers.
656    nmbrs_metrics::queryapi::install_live_access(std::sync::Arc::new(
657        nmbrs_metrics::queryapi::ExecScopedAccess::new(composed),
658    ));
659    // SRD-88 — teach the live-metric reader which execution is asking, so
660    // its reads scope to that execution's own series (the store is shared
661    // across concurrent executions). The hook reads nmbrs-runtime's
662    // task-local execution context; `None` outside any scope (single-run).
663    nmbrs_metrics::queryapi::install_read_exec_id_hook(|| {
664        crate::execution_context::try_current().map(|c| c.exec_id)
665    });
666    observer.on_metrics_query(metrics_query.clone());
667
668    let session_for_capture = session.component.clone();
669    let mut sched_builder = nmbrs_metrics::scheduler::SchedulerBuilder::new()
670        .base_interval(base_interval)
671        .with_cadence_reporter(cadence_reporter.clone())
672        .with_cadence_tree(cadence_tree.clone());
673
674    // SRD-42 §"SQLite — near-time persistence": subscribe the
675    // SQLite reporter via the CadenceReporter push path so slow
676    // disk can't stall the cascade. The subscription runs on its
677    // own dispatch thread with a per-subscription timeout.
678    //
679    // Preferred write cadence is 30 s — coarse enough to keep
680    // write volume low for long runs, fine enough for post-run
681    // analysis. Aligns to the nearest declared cadence ≥ 30 s
682    // (default declared set includes 30 s so this resolves exactly).
683    // Journal mode is WAL (set in SqliteReporter::new via
684    // `PRAGMA journal_mode=WAL`), so readers never block writers.
685    //
686    // Always-on: this subscription fires whenever the SQLite
687    // reporter was constructed successfully. Operators don't need
688    // to opt in with any extra param — every run produces a
689    // `metrics.db` in its session directory by default.
690    let sqlite_cadence = cadence_tree.align_to_declared(std::time::Duration::from_secs(30));
691    if let (Some(cadence), Ok(guard)) = (sqlite_cadence, sqlite_reporter.lock())
692        && guard.is_some()
693    {
694        drop(guard);
695        let sqlite_for_sub = sqlite_reporter.clone();
696        match cadence_reporter.subscribe(
697            cadence,
698            Box::new(MutexReporter(sqlite_for_sub)),
699            nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
700        ) {
701            Ok(_) => {
702                crate::diag!(
703                    crate::observer::LogLevel::Info,
704                    "metrics: SQLite writes every {:?} (WAL mode)",
705                    cadence
706                );
707            }
708            Err(e) => {
709                crate::diag!(
710                    crate::observer::LogLevel::Warn,
711                    "metrics: SQLite subscription failed: {e}"
712                );
713            }
714        }
715    }
716
717    // Single-file metrics log — opt-in, for OUTSIDE OBSERVERS. The session
718    // SQLite db is always written and stays the system of record; this only
719    // duplicates the same coalesced cadence windows into one plain JSONL file so
720    // a process can tail or ship metrics without linking SQLite, opening a db
721    // another process is writing in WAL mode, or knowing the schema. Enable via
722    // any of (a path enables it; `true` uses `<session>/metrics.jsonl`):
723    //   * `--metrics-log[=<path>]` flag on the CLI
724    //   * `metrics-log=<path|true>` in workload params
725    //   * `NMBRS_METRICS_LOG=<path|true>` env var
726    // Tell display surfaces where the session lives, so the one that keeps a
727    // durable transcript can open it and flush what it buffered before the
728    // directory existed. Default-on: the settled half of the display is
729    // already sequenced, append-only data, so persisting it costs one file
730    // handle and answers "what did the run actually show me" after the fact.
731    observer.session_dir_ready(&session.output_dir);
732
733    // Session-level system-performance sampler (host utilization from
734    // /proc). Enabled per session with `sysmon=all` or a comma list of
735    // categories (`sysmon=cpu,io,ram,rambw,storage`); off when absent.
736    // Interval via `sysmon-interval=<seconds>` (default 5).
737    //
738    // rambw is REQUIRED-EXPLICIT once enabled: an unsupported host aborts
739    // the session with enable instructions rather than silently monitoring
740    // less than was asked for — `check_rambw_requirements` is the gate.
741    if let Some(setting) = params.get("sysmon") {
742        let selection = crate::sysmon::parse_selection(setting)?;
743        let interval = match params.get("sysmon-interval") {
744            None => std::time::Duration::from_secs(5),
745            Some(v) => match v.trim_end_matches('s').parse::<f64>() {
746                Ok(secs) if secs > 0.0 => std::time::Duration::from_secs_f64(secs),
747                _ => {
748                    return Err(format!(
749                        "sysmon-interval: expected seconds (e.g. `sysmon-interval=5`), got '{v}'"
750                    ));
751                }
752            },
753        };
754        let membw_peak_bytes_per_s = match params.get("sysmon-membw-gbps") {
755            None => None,
756            Some(v) => match v.parse::<f64>() {
757                Ok(gbps) if gbps > 0.0 => Some(gbps * 1e9),
758                _ => {
759                    return Err(format!(
760                        "sysmon-membw-gbps: expected the host's peak memory bandwidth \
761                     in GB/s, got '{v}'"
762                    ));
763                }
764            },
765        };
766        let mut config = crate::sysmon::SysmonConfig {
767            cats: crate::sysmon::Categories::ALL,
768            interval,
769            membw_peak_bytes_per_s,
770        };
771        match selection {
772            // `any` — best-effort by stated request: enable what the host
773            // supports and ANNOUNCE each skip, one line per subsystem.
774            crate::sysmon::Selection::Any => {
775                let (cats, skipped) = crate::sysmon::resolve_any(&config);
776                config.cats = cats;
777                for reason in skipped {
778                    crate::diag!(
779                        crate::observer::LogLevel::Warn,
780                        "sysmon: skipping a subsystem: {reason}"
781                    );
782                }
783            }
784            // Named categories are REQUIRED: the rambw gate runs before
785            // spawn so an unsupported host is a clean session abort with
786            // instructions. The session directory already exists at this
787            // point (Session::start ran) — the same is true of every config
788            // error raised from here, and the next run gets its own
789            // directory.
790            crate::sysmon::Selection::Cats(cats) => {
791                config.cats = cats;
792                crate::sysmon::check_rambw_requirements(&config)?;
793            }
794        }
795        crate::sysmon::spawn(config, session.component.clone(), observer.clone())?;
796        crate::diag!(
797            crate::observer::LogLevel::Info,
798            "sysmon: sampling {setting} every {interval:?}"
799        );
800    }
801
802    let metrics_log_setting: Option<String> = args
803        .iter()
804        .find_map(|a| {
805            a.strip_prefix("--metrics-log")
806                .map(|rest| rest.strip_prefix('=').unwrap_or("true").to_string())
807        })
808        .or_else(|| params.get("metrics-log").cloned())
809        .or_else(|| std::env::var("NMBRS_METRICS_LOG").ok());
810    // `true` / `false`, or a file path. A retired boolean spelling
811    // (`on`, `1`, …) is an error naming the canonical word, never a
812    // file named `on`.
813    let metrics_log_path = match metrics_log_setting.as_deref() {
814        None | Some("false") => None,
815        Some("true") => Some(session.output_dir.join("metrics.jsonl")),
816        Some(retired @ ("on" | "off" | "yes" | "no" | "1" | "0" | "")) => {
817            return Err(format!(
818                "metrics-log={retired}: write metrics-log=true, metrics-log=false, \
819                 or metrics-log=<path>"
820            ));
821        }
822        Some(explicit) => {
823            // An explicit path from the `--metrics-log=` FLAG is the
824            // operator's own and is taken verbatim. The `metrics-log`
825            // PARAM (a workload file can set it) and the env form are
826            // confined to the session directory: a shared workload
827            // must never be able to name a write target elsewhere.
828            let from_flag = args.iter().any(|a| a.starts_with("--metrics-log"));
829            if from_flag {
830                Some(std::path::PathBuf::from(explicit))
831            } else {
832                Some(crate::session::confine_to_dir(&session.output_dir, explicit).map_err(
833                    |e| format!("metrics-log: {e} (an explicit path outside the session directory is only accepted from the --metrics-log= flag)"),
834                )?)
835            }
836        }
837    };
838    if let Some(log_path) = metrics_log_path {
839        match nmbrs_metrics::reporters::metrics_log::MetricsLogReporter::new(&log_path) {
840            Ok(reporter) => {
841                // Same cadence as the database, deliberately: the log is an
842                // alternative READ of what the db holds, so matching granularity
843                // is what makes the two comparable.
844                if let Some(cadence) =
845                    cadence_tree.align_to_declared(std::time::Duration::from_secs(30))
846                {
847                    match cadence_reporter.subscribe(
848                        cadence,
849                        Box::new(reporter),
850                        nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
851                    ) {
852                        Ok(_) => {
853                            crate::diag!(
854                                crate::observer::LogLevel::Info,
855                                "metrics: JSONL log every {:?} -> {} (session db unaffected)",
856                                cadence,
857                                log_path.display()
858                            );
859                        }
860                        Err(e) => {
861                            crate::diag!(
862                                crate::observer::LogLevel::Warn,
863                                "metrics: metrics log subscribe failed: {e}"
864                            );
865                        }
866                    }
867                }
868            }
869            Err(e) => {
870                crate::diag!(
871                    crate::observer::LogLevel::Warn,
872                    "metrics: metrics log disabled: {e}"
873                );
874            }
875        }
876    }
877
878    // Per-instance JSONL snapshot reporter — opt-in. Writes
879    // one file per (metric, label-tuple) in `<session>/metrics/`,
880    // one JSON record appended per snapshot tick. Useful when
881    // you want a per-instance trace to tail / awk / import
882    // into a notebook without opening the SQLite db, but most
883    // sessions never read these files and the SQLite db
884    // already carries the same data. Enable via any of:
885    //   * `--per-instance-metrics` flag on the CLI
886    //   * `per-instance-metrics=true` in workload params
887    //   * `NMBRS_PER_INSTANCE_METRICS=true` env var
888    let per_instance_enabled = args.iter().any(|a| a == "--per-instance-metrics")
889        || params.get("per-instance-metrics").map_or(Ok(false), |s| {
890            nmbrs_workload::boolean::parse_bool("per-instance-metrics", s)
891        })?
892        || nmbrs_workload::boolean::env_flag("NMBRS_PER_INSTANCE_METRICS")?;
893    if per_instance_enabled {
894        let per_instance_dir = session.output_dir.join("metrics");
895        match nmbrs_metrics::reporters::per_instance::PerInstanceReporter::new(&per_instance_dir) {
896            Ok(reporter) => {
897                if let Some(cadence) =
898                    cadence_tree.align_to_declared(std::time::Duration::from_secs(30))
899                {
900                    match cadence_reporter.subscribe(
901                        cadence,
902                        Box::new(reporter),
903                        nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
904                    ) {
905                        Ok(_) => {
906                            crate::diag!(
907                                crate::observer::LogLevel::Info,
908                                "metrics: per-instance JSONL writes every {:?} into {}",
909                                cadence,
910                                per_instance_dir.display()
911                            );
912                        }
913                        Err(e) => {
914                            crate::diag!(
915                                crate::observer::LogLevel::Warn,
916                                "metrics: per-instance subscription failed: {e}"
917                            );
918                        }
919                    }
920                }
921            }
922            Err(e) => {
923                crate::diag!(
924                    crate::observer::LogLevel::Warn,
925                    "metrics: per-instance reporter disabled ({}): {e}",
926                    per_instance_dir.display()
927                );
928            }
929        }
930    }
931
932    // Same routing for the VictoriaMetrics / Prometheus push reporter
933    // when `--report-to` (or equivalent param) was provided.
934    // `jobname` / `instance` params match the nosqlbench-java
935    // `PromPushReporterComponent` convention; they're substituted
936    // into any `JOBNAME` / `INSTANCE` placeholders in the URL.
937    if let Some(url) = openmetrics_url.as_ref()
938        && let Some(cadence) = cadence_tree.align_to_declared(std::time::Duration::from_secs(10))
939    {
940        let jobname = merged_params
941            .get("jobname")
942            .cloned()
943            .unwrap_or_else(|| "default".to_string());
944        let instance = merged_params
945            .get("instance")
946            .cloned()
947            .unwrap_or_else(|| "default".to_string());
948        let mut vm =
949            match nmbrs_metrics::reporters::victoriametrics::VictoriaMetricsReporter::from_spec(url)
950            {
951                Ok(r) => r,
952                Err(_) => {
953                    nmbrs_metrics::reporters::victoriametrics::VictoriaMetricsReporter::new(url)
954                }
955            };
956        vm = vm.with_jobname(jobname).with_instance(instance);
957        if let Some(token_path) = merged_params.get("prompush_apikeyfile") {
958            match vm.with_bearer_token_file(token_path) {
959                Ok(r) => vm = r,
960                Err(e) => {
961                    crate::diag!(
962                        crate::observer::LogLevel::Warn,
963                        "prompush_apikeyfile '{token_path}': {e}"
964                    );
965                    vm = nmbrs_metrics::reporters::victoriametrics
966                            ::VictoriaMetricsReporter::from_spec(url)
967                            .unwrap_or_else(|_| nmbrs_metrics::reporters::victoriametrics
968                                ::VictoriaMetricsReporter::new(url))
969                            .with_jobname(
970                                merged_params.get("jobname").cloned()
971                                    .unwrap_or_else(|| "default".to_string()),
972                            )
973                            .with_instance(
974                                merged_params.get("instance").cloned()
975                                    .unwrap_or_else(|| "default".to_string()),
976                            );
977                }
978            }
979        }
980        let _ = cadence_reporter.subscribe(
981            cadence,
982            Box::new(vm),
983            nmbrs_metrics::cadence_reporter::SubscriptionOpts::default(),
984        );
985    }
986
987    // Register the observer's reporters at their requested cadences
988    // on the scheduler tree (base-interval live-frame forwarding for
989    // sparklines / live histogram).
990    for (interval, reporter) in observer.reporters() {
991        sched_builder = sched_builder.add_reporter(interval, BoxedReporter(reporter));
992    }
993
994    let scheduler = sched_builder.build(Box::new(move || {
995        nmbrs_metrics::component::capture_tree(&session_for_capture, base_interval)
996    }));
997    let stop_handle = Arc::new(scheduler.start());
998
999    // Install the session-wide Ctrl-C handler. First SIGINT
1000    // requests cooperative shutdown (fibers exit at cycle
1001    // boundary, profiler + cadence reporter flush in normal
1002    // teardown order); second SIGINT force-exits. Idempotent —
1003    // safe to call again on retry / reentry paths.
1004    crate::session_signals::install_signal_handler();
1005
1006    // SRD-93 M7 — SIGQUIT inventory: log every Running component's
1007    // labels + instrument count, so "why is nothing moving" is
1008    // answerable from outside even when the run is wedged. Runs on
1009    // the signal-dispatch thread; read-only over the tree.
1010    let dump_root = session.component.clone();
1011    crate::session_signals::set_diag_dump_hook(Box::new(move || {
1012        fn walk(
1013            node: &std::sync::Arc<std::sync::RwLock<nmbrs_metrics::component::Component>>,
1014            out: &mut Vec<String>,
1015        ) {
1016            let g = node.read().unwrap_or_else(|e| e.into_inner());
1017            if g.state() == nmbrs_metrics::component::ComponentState::Running {
1018                out.push(format!(
1019                    "{} ({} instrument(s))",
1020                    g.effective_labels(),
1021                    g.instruments().len(),
1022                ));
1023            }
1024            for child in g.children() {
1025                walk(child, out);
1026            }
1027        }
1028        let mut lines = Vec::new();
1029        walk(&dump_root, &mut lines);
1030        crate::diag!(
1031            crate::observer::LogLevel::Info,
1032            "session: SIGQUIT inventory — {} running component(s)",
1033            lines.len()
1034        );
1035        for line in lines {
1036            crate::diag!(crate::observer::LogLevel::Info, "  {line}");
1037        }
1038    }));
1039
1040    Ok(SessionMetrics {
1041        cadence_reporter,
1042        cadence_tree,
1043        metrics_query,
1044        stop_handle,
1045    })
1046}
1047
1048/// SRD-88 — the shared, session-tier context, created ONCE per session
1049/// (`SessionHost::setup`); every execution sharing the session runs
1050/// against it. Holds the session (dir / id / `session` component), the
1051/// durable sqlite store + shutdown guard, the session-aligned metrics
1052/// services and the session-tier profiler. Per-execution work +
1053/// workload load happens in `run_execution`.
1054struct SessionHost {
1055    session: crate::session::Session,
1056    sqlite_reporter:
1057        std::sync::Arc<std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>>,
1058    cadence_reporter: std::sync::Arc<nmbrs_metrics::cadence_reporter::CadenceReporter>,
1059    #[allow(dead_code)]
1060    cadence_tree: nmbrs_metrics::cadence::CadenceTree,
1061    #[allow(dead_code)]
1062    metrics_query: std::sync::Arc<nmbrs_metrics::metrics_query::MetricsQuery>,
1063    stop_handle: std::sync::Arc<nmbrs_metrics::scheduler::StopHandle>,
1064    refine_plan: Option<Arc<crate::refine_plan::RefinePlan>>,
1065    resume_target: Option<std::path::PathBuf>,
1066    refine_requested: bool,
1067    refine_scope: Option<String>,
1068    /// SRD-106 — the session id the `stick_session` rung
1069    /// re-attached to, when it engaged. Drives the D4
1070    /// `session_notice` announcement (first notable event of
1071    /// the run) and nothing else.
1072    stick_reattached: Option<String>,
1073    profiler: Option<crate::profiler::ProfileGuard>,
1074    sqlite_guard: nmbrs_metrics::reporters::sqlite::SqliteShutdownGuard,
1075    /// SRD-88 — the checkpoint writer is SESSION-tier: one per session
1076    /// (`<session>/checkpoint.jsonl` + its single resume lock), shared
1077    /// by every execution. Per-execution resume *plans* are still
1078    /// derived per execution in `run_execution` from `saved_doc` + that
1079    /// execution's pre-map; only the writer/lock is shared (so N
1080    /// concurrent in-process executions don't fight over the lock).
1081    checkpoint_writer: std::sync::Arc<crate::checkpoint::CheckpointWriter>,
1082    saved_doc: Option<crate::checkpoint::Checkpoint>,
1083}
1084
1085impl SessionHost {
1086    /// Build the shared session-tier context. Workload-INDEPENDENT:
1087    /// session identity = `scenario=` param; metrics services +
1088    /// profiler read CLI `params`, not workload-merged params.
1089    fn setup(
1090        args: &[String],
1091        observer: Arc<dyn crate::observer::RunObserver>,
1092    ) -> Result<SessionHost, String> {
1093        // Set global observer so all code can log through it
1094        crate::observer::set_global_observer(observer.clone());
1095
1096        // Wire error handler logging through the observer.
1097        // Per-cycle error lines fire from inside an executing
1098        // phase, so prefix with the running phase's scope-depth
1099        // indent — the same alignment the polling-op messages,
1100        // phase startup/complete lines, and DONE summary use.
1101        // The errorhandler crate stays scope-agnostic; the
1102        // bridging closure here is what makes the output
1103        // hierarchic in tui=terminal mode.
1104        //
1105        // Level = Debug so the per-cycle warns land in the
1106        // session log (retain_level defaults to Debug) but
1107        // don't spam the realtime status surface (display_level
1108        // defaults to Info). The structured form of each
1109        // per-cycle error is collected into the phase's
1110        // PhaseErrorDetail buffer and rendered in one block by
1111        // the `error_readout` builtin at PhaseEnd — the
1112        // operator sees the normative ✓/✗ phase line first,
1113        // then the error block, instead of N noisy lines
1114        // interleaved with progress as the phase runs.
1115        nmbrs_errorhandler::handlers::set_log_fn(|msg| {
1116            let indent = crate::scene_tree::running_phase_indent();
1117            crate::observer::log(crate::observer::LogLevel::Debug, &format!("{indent}{msg}"));
1118        });
1119
1120        // Route nmbrs-metrics diagnostic warnings through the observer so
1121        // reporter write failures, histogram-record errors, etc. don't
1122        // slip past the TUI as raw stderr prints. Indent matches the
1123        // running phase the same way the errorhandler bridge above does
1124        // — these emits fire mid-phase from the metrics pipeline.
1125        nmbrs_metrics::diag::set_warn_fn(|msg| {
1126            let indent = crate::scene_tree::running_phase_indent();
1127            crate::observer::log(crate::observer::LogLevel::Warn, &format!("{indent}{msg}"));
1128        });
1129        nmbrs_metrics::diag::set_info_fn(|msg| {
1130            let indent = crate::scene_tree::running_phase_indent();
1131            crate::observer::log(crate::observer::LogLevel::Info, &format!("{indent}{msg}"));
1132        });
1133
1134        // Audit sink is installed after session creation
1135        // below (so it can target `<session>/audit.log`).
1136        // Until then, the crate-default eprintln fallback
1137        // is in effect for any audit::log calls fired
1138        // during init. Workload-emitted lines fire mid-phase
1139        // (well after the install), so they don't reach
1140        // stderr.
1141
1142        let args = normalize_args(args);
1143        let params = parse_params(&args);
1144        // The run's effective params (workload `params:` overlaid by CLI, CLI
1145        // wins) — the consolidated set the session-tier services read, so a
1146        // setting like `metrics_cadence` / `jobname` / `per-instance-metrics`
1147        // works whether declared in the workload or passed on the command line.
1148        // Operational reads below (resume, session identity) stay on the raw CLI
1149        // `params` — they are not workload-declarable.
1150        let eff_params = effective_params(&args);
1151        // `scenario_for_session` is recomputed below from the refine block's
1152        // params (the session-dir name); `openmetrics_url` feeds the
1153        // session metrics services.
1154        let openmetrics_url: Option<String> = cli_flag_value(&args[..], "--report-openmetrics-to")
1155            .or_else(|| {
1156                args.iter()
1157                    .find_map(|a| a.strip_prefix("report-openmetrics-to="))
1158                    .map(|s| s.to_string())
1159            });
1160        // SRD-106 Part 3 — the `stick_session` resolution rung: the
1161        // LOWEST-precedence session rung. A workload may declare that
1162        // iterative re-attachment is its intended usage; when the
1163        // operator expressed no session intent of their own, a run
1164        // re-attaches to `sessions/latest` and layers a new execution
1165        // per SRD-77 — mechanically the refine path, so the D2
1166        // provenance gates govern what re-runs. Defeated by ANY
1167        // explicit session selection (`--session*` name/path/reuse),
1168        // any re-attachment flag (`resume=` / `--resume-latest` /
1169        // `--refine`), the `--session new` bare token, and dryruns
1170        // (resume-inert per SRD-44). CLI `stick_session=true|false`
1171        // overrides the workload's declaration.
1172        let stick_reattach: Option<std::path::PathBuf> = {
1173            let cli_stick: Option<bool> = params
1174                .get("stick_session")
1175                .map(|v| nmbrs_workload::boolean::parse_bool("stick_session", v))
1176                .transpose()?;
1177            let stick_on =
1178                cli_stick.unwrap_or_else(|| peek_stick_session(&params, &args).unwrap_or(false));
1179            let reattach_expressed = args
1180                .iter()
1181                .any(|a| a == "--refine" || a == "--resume-latest")
1182                || params.contains_key("resume")
1183                || params.contains_key("resume_latest");
1184            if !stick_on || reattach_expressed || crate::session::args_request_dryrun(&args) {
1185                None
1186            } else {
1187                let spec = crate::session::resolve_session_dir(&args);
1188                let operator_selected = !spec.is_empty()
1189                    || spec.force_new
1190                    || spec.reuse != crate::session::SessionReuse::Error;
1191                if operator_selected {
1192                    None
1193                } else {
1194                    // `sessions/latest` must resolve to a prior session
1195                    // with a checkpoint — anything less means there is
1196                    // nothing valid to re-attach to, and the run falls
1197                    // through to today's fresh-session default silently
1198                    // (no announcement for a no-op).
1199                    let latest = crate::session::default_sessions_root().join("latest");
1200                    std::fs::read_link(&latest)
1201                        .ok()
1202                        .map(|t| {
1203                            if t.is_absolute() {
1204                                t
1205                            } else {
1206                                crate::session::default_sessions_root().join(t)
1207                            }
1208                        })
1209                        .filter(|d| d.join("checkpoint.jsonl").is_file())
1210                }
1211            }
1212        };
1213        let stick_reattached: Option<String> = stick_reattach
1214            .as_ref()
1215            .and_then(|d| d.file_name())
1216            .and_then(|s| s.to_str())
1217            .map(String::from);
1218        if let Some(id) = stick_reattached.as_deref() {
1219            crate::diag!(
1220                crate::observer::LogLevel::Info,
1221                "stick_session: re-attaching to {id} — pass `--session new` to start fresh"
1222            );
1223        }
1224
1225        let resume_target: Option<std::path::PathBuf> = {
1226            let explicit = params.get("resume").filter(|s| !s.is_empty()).map(|s| {
1227                let p = std::path::PathBuf::from(s);
1228                if p.is_file() {
1229                    p
1230                } else if p.is_dir() {
1231                    p.join("checkpoint.jsonl")
1232                } else {
1233                    crate::session::default_sessions_root()
1234                        .join(s)
1235                        .join("checkpoint.jsonl")
1236                }
1237            });
1238            let resume_latest = params.get("resume_latest").map_or(Ok(false), |s| {
1239                nmbrs_workload::boolean::parse_bool("resume_latest", s)
1240            })? || args.iter().any(|a| a == "--resume-latest")
1241                || stick_reattach.is_some();
1242            if resume_latest {
1243                // Resolve the symlink to a concrete session dir
1244                // *now* — once `Session::new` runs the symlink will
1245                // be repointed at the new session.
1246                let latest = crate::session::default_sessions_root().join("latest");
1247                let resolved = std::fs::read_link(&latest)
1248                    .ok()
1249                    .map(|target| {
1250                        if target.is_absolute() {
1251                            target
1252                        } else {
1253                            crate::session::default_sessions_root().join(target)
1254                        }
1255                    })
1256                    .map(|d| d.join("checkpoint.jsonl"));
1257                explicit.or(resolved)
1258            } else {
1259                explicit
1260            }
1261        };
1262
1263        // SRD-77 refine: the `nmbrs refine` verb injects `--refine`
1264        // into argv before delegating to the runner. Detected here
1265        // so we can load the session's prior `phase_outcomes` and
1266        // build a skip plan + bump `exec_id` before the session is
1267        // re-attached. Implies `--resume-latest` semantics for
1268        // session dir resolution (the resolver at line 950+ already
1269        // produces the right `resume_target` when `--resume-latest`
1270        // was passed alongside `--refine` by `refine_command`).
1271        // SRD-106: an engaged `stick_session` re-attach IS a refine
1272        // layering — new execution, prior outcomes as provenance.
1273        let refine_requested = args.iter().any(|a| a == "--refine") || stick_reattach.is_some();
1274
1275        // Session: root context for this run. Creates logs/{scenario}_{timestamp}/
1276        // for fresh runs; reuses the prior session dir when resuming
1277        // so the metrics.db is appended-to in-place per SRD-44
1278        // §"Wholesale metrics-purge".
1279        let scenario_for_session = params
1280            .get("scenario")
1281            .map(|s| s.as_str())
1282            .unwrap_or("default");
1283        // SRD-77 — refine_plan is populated only when:
1284        //   1. `--refine` was passed (refine verb is in flight)
1285        //   2. The resume_target resolves to an existing session dir
1286        // Computed BEFORE Session construction so the plan's
1287        // `next_exec_id` can flow into `Session::refine`.
1288        // SRD-77 refine scope. Default `missing` (skip phases with
1289        // a prior completed outcome) when `--refine` is set without
1290        // an explicit `scope=`. `scope=all` builds the plan for
1291        // exec_id bumping + session re-attach but leaves the skip
1292        // set empty, so every phase runs and new outcomes overwrite
1293        // the prior ones (the cardinal history stays — prior rows
1294        // keep their old exec_id, new rows land under the bumped
1295        // exec_id). `scope=changed` requires `phase_hash` storage
1296        // on PhaseOutcome (follow-up push) and is rejected here
1297        // with a "not yet implemented" diag so the operator isn't
1298        // silently dropped to `missing` semantics.
1299        let refine_scope: Option<&str> = params
1300            .get("scope")
1301            .map(|s| s.as_str())
1302            .filter(|_| refine_requested);
1303        let refine_plan: Option<Arc<crate::refine_plan::RefinePlan>> = if refine_requested {
1304            resume_target
1305                .as_ref()
1306                .and_then(|p| p.parent().map(|d| d.to_path_buf()))
1307                .and_then(|prior_dir| {
1308                    if !prior_dir.exists() {
1309                        crate::diag!(
1310                            crate::observer::LogLevel::Warn,
1311                            "refine: prior session dir not found ({}); \
1312                         running every phase as if this were a fresh `nmbrs run`",
1313                            prior_dir.display()
1314                        );
1315                        return None;
1316                    }
1317                    let mut plan =
1318                        crate::refine_plan::RefinePlan::load_from_session_dir(&prior_dir);
1319                    if plan.is_none() {
1320                        crate::diag!(
1321                            crate::observer::LogLevel::Warn,
1322                            "refine: no readable phase_outcomes in {}; \
1323                         running every phase as if this were a fresh `nmbrs run`",
1324                            prior_dir.display()
1325                        );
1326                    }
1327                    if let Some(p) = plan.as_mut() {
1328                        p.scope = match refine_scope {
1329                            Some("all") => {
1330                                crate::diag!(
1331                                    crate::observer::LogLevel::Info,
1332                                    "refine: scope=all — every phase will run \
1333                                 under exec_id={}",
1334                                    p.next_exec_id
1335                                );
1336                                crate::refine_plan::RefineScope::All
1337                            }
1338                            Some("changed") => {
1339                                crate::diag!(
1340                                    crate::observer::LogLevel::Info,
1341                                    "refine: scope=changed — comparing each \
1342                                 phase's program hash against the prior \
1343                                 outcome; unchanged phases skip, changed \
1344                                 phases re-run under exec_id={}",
1345                                    p.next_exec_id
1346                                );
1347                                crate::refine_plan::RefineScope::Changed
1348                            }
1349                            _ => crate::refine_plan::RefineScope::Missing,
1350                        };
1351                    }
1352                    plan.map(Arc::new)
1353                })
1354        } else {
1355            None
1356        };
1357        // SRD-77 — `--on-removed=` policy. When refine attaches to
1358        // a session whose prior outcomes name phases the current
1359        // workload no longer declares, the default behavior is
1360        // ERROR (refuse to proceed) — silently keeping orphan
1361        // outcomes hides intent, silently dropping them loses
1362        // data. `--on-removed=keep` retains them (no work);
1363        // `--on-removed=drop` is reserved for a future push that
1364        // wires the deletion + interactive confirm.
1365        //
1366        // The check compares the prior `phase_name` set against
1367        // the current workload's `phases:` map keys. Sweep-cell
1368        // variants (same name, different labels) are aggregated by
1369        // name here — a missing name covers every prior cell of
1370        // it. Tighter (name+labels) granularity is a follow-up
1371        // when label-set comparison becomes load-bearing.
1372        // (`on_removed_policy` is consulted per-execution, in `run_execution`.)
1373        // Build the session (the shared, session-tier container). SRD-88:
1374        // the session carries only `session=<id>`; the execution's
1375        // identity (`exec_id`, `workload`) is declared one tier down, on
1376        // its own component (below). [[HOST:session]]
1377        let session = match (refine_plan.as_ref(), resume_target.as_ref()) {
1378            (Some(plan), Some(p)) if p.exists() => {
1379                let prior_dir = p
1380                    .parent()
1381                    .map(|d| d.to_path_buf())
1382                    .unwrap_or_else(crate::session::latest_session_dir);
1383                crate::diag!(
1384                    crate::observer::LogLevel::Info,
1385                    "refine: attached to session {}; \
1386                 prior outcomes={}, completed phases to skip={}, \
1387                 next exec_id={}",
1388                    prior_dir.display(),
1389                    plan.prior_outcomes_seen,
1390                    plan.completed.len(),
1391                    plan.next_exec_id
1392                );
1393                crate::session::Session::reattach(prior_dir, scenario_for_session)
1394            }
1395            (_, Some(p)) if p.exists() => {
1396                let prior_dir = p
1397                    .parent()
1398                    .map(|d| d.to_path_buf())
1399                    .unwrap_or_else(crate::session::latest_session_dir);
1400                crate::session::Session::reattach(prior_dir, scenario_for_session)
1401            }
1402            _ => crate::session::Session::new_with_args(scenario_for_session, &args),
1403        };
1404        let session_log_path = session.output_dir.join("session.log");
1405        if let Err(e) = crate::observer::set_log_file(&session_log_path) {
1406            crate::diag!(
1407                crate::observer::LogLevel::Warn,
1408                "warning: failed to open session log {}: {e}",
1409                session_log_path.display()
1410            );
1411        }
1412
1413        // `--trace=<spec>` (repeatable). Collected from raw `args`
1414        // because parse_params is HashMap-keyed and would collapse
1415        // repeated flags. See trace_router for spec grammar.
1416        let trace_specs = collect_repeated_flag(&args, "trace");
1417        match crate::trace_router::init(&trace_specs, &session.output_dir) {
1418            Ok(0) => {} // no --trace specified, router stays empty
1419            Ok(n) => crate::diag!(
1420                crate::observer::LogLevel::Info,
1421                "trace router: {n} route(s) configured"
1422            ),
1423            Err(e) => crate::diag!(
1424                crate::observer::LogLevel::Warn,
1425                "trace router init failed: {e}"
1426            ),
1427        }
1428
1429        crate::diag!(
1430            crate::observer::LogLevel::Info,
1431            "session: {} ({})",
1432            session.id,
1433            session.output_dir.display()
1434        );
1435
1436        // Polydat library audit channel: route polydat's
1437        // `audit::log/info/warn/...` calls through this
1438        // process's observer so they land in `session.log`
1439        // alongside every other diagnostic line, with a
1440        // `[lib]` subsystem tag so the operator can filter them
1441        // out if they're noisy. Replaces the standalone
1442        // `<session>/audit.log` file — same content, one fewer
1443        // place to look.
1444        // SRD-82 §"Panic reporting: one full render" — the runtime's
1445        // fiber/op catchers render eval-panic diagnostics in full via
1446        // the phase error list, so the polydat hook degrades to a
1447        // one-line notice instead of the full body + backtrace hint.
1448        polydat::set_panic_reporting_downstream(true);
1449
1450        polydat::audit::set_log_fn(|level, msg| {
1451            use polydat::audit::LogLevel as AuditLevel;
1452            let mapped = match level {
1453                AuditLevel::Trace | AuditLevel::Debug => crate::observer::LogLevel::Debug,
1454                AuditLevel::Info => crate::observer::LogLevel::Info,
1455                AuditLevel::Warn => crate::observer::LogLevel::Warn,
1456                AuditLevel::Error => crate::observer::LogLevel::Error,
1457            };
1458            crate::observer::log(mapped, &format!("[lib] {msg}"));
1459        });
1460
1461        // SQLite metrics in session directory. SRD-88: creating the
1462        // reporter (connection + schema + the session-INVARIANT
1463        // `session` metadata key) is session-tier — one per session,
1464        // shared by every execution. The per-execution metadata
1465        // (workload / scenario / params / the SRD-77 `executions` row)
1466        // is written separately below, per execution, so N concurrent
1467        // executions each record their own without clobbering.
1468        let sqlite_path = session.metrics_path();
1469        let sqlite_reporter = nmbrs_metrics::reporters::sqlite::SqliteReporter::new(&sqlite_path)
1470            .map(|mut r| {
1471                r.set_metadata("session", &session.id);
1472                crate::diag!(
1473                    crate::observer::LogLevel::Info,
1474                    "metrics: {}",
1475                    sqlite_path.display()
1476                );
1477                r
1478            })
1479            .map_err(|e| {
1480                crate::diag!(
1481                    crate::observer::LogLevel::Warn,
1482                    "warning: SQLite metrics disabled: {e}"
1483                )
1484            })
1485            .ok();
1486        let sqlite_reporter = std::sync::Arc::new(std::sync::Mutex::new(sqlite_reporter));
1487
1488        // RAII shutdown guard — runs `consolidate_wal` at session
1489        // end via Drop. Reliable across every Rust unwind path:
1490        // normal completion, error `?` propagation, first-Ctrl-C
1491        // → stop flag → runner unwind. The only path that skips
1492        // it is `std::process::exit` (second Ctrl-C force-exit),
1493        // which is the operator's declared "I don't want to
1494        // wait" escape hatch. The guard MUST live until after
1495        // every reporter has finished writing — bind it here at
1496        // the top of the run-impl block so it drops in
1497        // last-created / first-dropped order relative to local
1498        // variables; the explicit `_` binding pins its lifetime
1499        // to the function scope (otherwise the temporary would
1500        // drop immediately).
1501        let _sqlite_shutdown_guard =
1502            nmbrs_metrics::reporters::sqlite::SqliteShutdownGuard::new(sqlite_reporter.clone());
1503
1504        // Periodic WAL checkpoint so concurrent read-only
1505        // tooling (`nmbrs report` against a live session,
1506        // ad-hoc `sqlite3 metrics.db` inspection, the realtime
1507        // metricsql preview) sees committed writes without
1508        // waiting for session end. SQLite's WAL holds frames
1509        // until either:
1510        //   1. `wal_autocheckpoint` (page-count threshold,
1511        //      default 1000 pages) fires on a writer, OR
1512        //   2. an explicit `PRAGMA wal_checkpoint(...)` runs.
1513        //
1514        // Under bursty workloads (a tight rampup followed by a
1515        // long synchronous wait — exactly the SRD-75
1516        // ensure_compacted shape) writers can stall under the
1517        // autocheckpoint threshold for many minutes, during
1518        // which readers see stale data. A 60-second background
1519        // task running `PRAGMA wal_checkpoint(PASSIVE)` bounds
1520        // the staleness without blocking writers.
1521        //
1522        // PASSIVE mode is the cheap variant: it merges all
1523        // currently-committed WAL frames into the main `.db`
1524        // without truncating the WAL file or pausing writers.
1525        // The tokio task runs for the runtime's lifetime and is
1526        // cancelled on shutdown; the final `consolidate_wal`
1527        // (TRUNCATE flavour) at session end produces the
1528        // archival "no -wal sidecar" form.
1529        {
1530            let reporter = sqlite_reporter.clone();
1531            tokio::spawn(async move {
1532                let mut interval = tokio::time::interval(std::time::Duration::from_secs(60));
1533                // First tick is immediate; skip it so the
1534                // post-session-start state has a chance to
1535                // settle before the first checkpoint fires.
1536                interval.tick().await;
1537                loop {
1538                    interval.tick().await;
1539                    if let Ok(g) = reporter.lock()
1540                        && let Some(r) = g.as_ref()
1541                    {
1542                        r.passive_checkpoint();
1543                    }
1544                }
1545            });
1546        }
1547
1548        // SRD-88 — session-tier metrics services, configured from CLI params.
1549        let SessionMetrics {
1550            cadence_reporter,
1551            cadence_tree,
1552            metrics_query,
1553            stop_handle,
1554        } = build_session_metrics(
1555            &session,
1556            &sqlite_reporter,
1557            &observer,
1558            &eff_params,
1559            &openmetrics_url,
1560            &args,
1561            &eff_params,
1562        )?;
1563        crate::session_signals::install_signal_handler();
1564        let _profiler =
1565            crate::profiler::ProfileGuard::maybe_start(&params, Some(&session.output_dir));
1566
1567        // SRD-88 — the SESSION-tier checkpoint writer (one per session;
1568        // holds the single resume lock) + the resume doc. Executions share
1569        // the writer and each derives its own resume plan from `saved_doc`.
1570        let checkpoint_path = session.output_dir.join("checkpoint.jsonl");
1571        let saved_doc = match resume_target.as_ref() {
1572            Some(p) => match crate::checkpoint::storage::read(p) {
1573                Ok(Some(doc)) => Some(doc),
1574                Ok(None) => {
1575                    crate::diag!(
1576                        crate::observer::LogLevel::Warn,
1577                        "resume: no checkpoint found at {} — fresh session",
1578                        p.display()
1579                    );
1580                    None
1581                }
1582                Err(e) => return Err(format!("resume: {e}")),
1583            },
1584            None => None,
1585        };
1586        let invocation = saved_doc.as_ref().map(|d| d.invocation + 1).unwrap_or(1);
1587        let started_at = saved_doc
1588            .as_ref()
1589            .map(|d| d.started_at.clone())
1590            .unwrap_or_else(crate::checkpoint::storage::now_rfc3339);
1591        // A dry-run is resume-inert (SRD-44): it short-circuits ops and may
1592        // run against placeholder params, so it must persist NO checkpoint —
1593        // otherwise its (synthetic) phase completions poison a later
1594        // `--resume-latest`. `Session::new_with_args` already withholds the
1595        // `latest` symlink from a dry-run; this withholds the checkpoint too.
1596        let checkpoint_writer =
1597            std::sync::Arc::new(if crate::session::args_request_dryrun(&args) {
1598                crate::checkpoint::CheckpointWriter::disabled(checkpoint_path.clone())
1599            } else {
1600                match saved_doc.as_ref() {
1601                    Some(_doc) => crate::checkpoint::CheckpointWriter::from_existing(
1602                        checkpoint_path.clone(),
1603                        saved_doc.clone().unwrap(),
1604                        crate::checkpoint::storage::now_rfc3339(),
1605                        invocation,
1606                    ),
1607                    None => crate::checkpoint::CheckpointWriter::new(
1608                        checkpoint_path.clone(),
1609                        session.id.clone(),
1610                        started_at,
1611                        invocation,
1612                    ),
1613                }
1614            });
1615
1616        Ok(SessionHost {
1617            session,
1618            sqlite_reporter,
1619            cadence_reporter,
1620            cadence_tree,
1621            metrics_query,
1622            stop_handle,
1623            refine_plan,
1624            resume_target,
1625            refine_requested,
1626            refine_scope: refine_scope.map(|s| s.to_string()),
1627            stick_reattached,
1628            profiler: _profiler,
1629            sqlite_guard: _sqlite_shutdown_guard,
1630            checkpoint_writer,
1631            saved_doc,
1632        })
1633    }
1634
1635    /// Session teardown — once, after every execution (SRD-88).
1636    async fn shutdown(self) {
1637        if let Some(mut profiler) = self.profiler {
1638            profiler.finish();
1639        }
1640        self.stop_handle.stop().await;
1641        let _teardown_t = std::time::Instant::now();
1642        self.cadence_reporter.shutdown().await;
1643        crate::diag!(
1644            crate::observer::LogLevel::Debug,
1645            "shutdown: cadence reporter flush+join {:?}",
1646            _teardown_t.elapsed()
1647        );
1648        // Release the live-access reader (the HybridStore's sqlite cold-tier
1649        // connection on metrics.db) BEFORE consolidating the WAL: the
1650        // `journal_mode=DELETE` flip in `consolidate_wal` needs an EXCLUSIVE
1651        // db lock, which a still-open reader connection on the same file
1652        // blocks ("database is locked"). The session is fully stopped here, so
1653        // no live reads remain.
1654        nmbrs_metrics::queryapi::uninstall_live_access();
1655        crate::diag!(
1656            crate::observer::LogLevel::Info,
1657            "shutting down — consolidating metrics.db WAL"
1658        );
1659        self.sqlite_guard.consume();
1660        crate::diag!(crate::observer::LogLevel::Info, "shutdown complete");
1661        // Shutdown-ladder bookkeeping: the run drained through the full
1662        // process-level cleanup, so a still-ticking level-1 countdown
1663        // (Ctrl-C during the final drain) goes quiet instead of
1664        // announcing op cancellation for a run that no longer has ops.
1665        crate::session_signals::mark_shutdown_complete();
1666    }
1667}
1668
1669/// SRD-88 — run ONE execution against a shared [`SessionHost`]. Does
1670/// NOT tear the session down (that is `SessionHost::shutdown`).
1671async fn run_execution(
1672    host: &SessionHost,
1673    args: &[String],
1674    observer: Arc<dyn crate::observer::RunObserver>,
1675) -> Result<(), String> {
1676    let session = &host.session;
1677    let session_id = host.session.id.clone();
1678    let sqlite_reporter = host.sqlite_reporter.clone();
1679    let cadence_reporter = host.cadence_reporter.clone();
1680    let stop_handle = host.stop_handle.clone();
1681    let resume_target = host.resume_target.clone();
1682    let refine_plan = host.refine_plan.clone();
1683    let refine_requested = host.refine_requested;
1684    let refine_scope = host.refine_scope.as_deref();
1685    let stick_reattached = host.stick_reattached.clone();
1686    let mut diag = DiagnosticConfig::normal();
1687
1688    // Detect scenario shorthand: `workload.yaml <scenario_name>` → `scenario=<name>`
1689    let args = normalize_args(args);
1690    let mut params = parse_params(&args);
1691
1692    // ── SRD-109 Part 2 — driver-manifest resolution ──
1693    //
1694    // `driver=<name>` resolves a driver manifest (local
1695    // `drivers/<name>/driver.yaml` under the cwd first, then the
1696    // bundled catalog entry `drivers/<name>/driver`; both at once
1697    // favors the local one, with a warning). The manifest supplies
1698    // the implementation library (as workload= when none was
1699    // given, else as impl=), the backing adapter, and default
1700    // params at lowest precedence. A `driver=` value matching no
1701    // manifest is an error: `driver=` never names an adapter.
1702    if let Some(driver_name) = params.get("driver").cloned() {
1703        let (manifest, library_ref) = resolve_driver_manifest(&driver_name)?;
1704        // A positional `<file>.yaml` argument counts as a given
1705        // workload — the manifest's library must not displace it.
1706        let workload_given = params.contains_key("workload")
1707            || args
1708                .iter()
1709                .any(|a| a.ends_with(".yaml") || a.ends_with(".yml"));
1710        apply_driver_manifest(
1711            &mut params,
1712            &driver_name,
1713            manifest,
1714            library_ref,
1715            workload_given,
1716        )?;
1717    }
1718    let params = params;
1719
1720    // Load workload — from inline op= or YAML file.
1721    let mut workload_file: Option<String> = None;
1722    // SRD-85: true when the workload came from the bundled
1723    // catalog — its identity is a catalog name, not a path, and
1724    // relative resolution context falls back to the cwd.
1725    let mut workload_is_bundled = false;
1726    let mut workload_source_text: Option<String> = None;
1727    let mut workload = if let Some(op_str) = params.get("op") {
1728        if params.contains_key("workload") {
1729            crate::diag!(
1730                crate::observer::LogLevel::Warn,
1731                "warning: op= overrides workload="
1732            );
1733        }
1734        nmbrs_workload::inline::synthesize_inline_workload(op_str)
1735            .map_err(|e| format!("inline workload: {e}"))?
1736    } else {
1737        let workload_raw = params
1738            .get("workload")
1739            .cloned()
1740            .or_else(|| {
1741                args.iter()
1742                    .find(|a| a.ends_with(".yaml") || a.ends_with(".yml"))
1743                    .cloned()
1744            })
1745            .ok_or("no workload specified. Use workload=file.yaml or op=\"...\"")?;
1746
1747        // SRD-85 resolution: local files first (as-is, with
1748        // extensions, under cwd `workloads/`), then the bundled
1749        // catalog by exact name. Both at once is a hard error.
1750        match resolve_workload(&workload_raw)? {
1751            ResolvedWorkload::Path(workload_path) => {
1752                workload_file = Some(workload_path.clone());
1753
1754                // SRD-72: parse_workload_from_path resolves any
1755                // `extends:` chain before delegating to parse_workload.
1756                // The merged YAML text is what the parser consumes; the
1757                // raw on-disk text is still kept for diagnostic
1758                // `<path>:<line>:<col>` reporting (no source-map across
1759                // include boundaries today — diagnostics on inherited
1760                // fields point at the merged-output position).
1761                let yaml_source = std::fs::read_to_string(&workload_path)
1762                    .map_err(|e| format!("read workload '{workload_path}': {e}"))?;
1763                let workload = nmbrs_workload::parse::parse_workload_from_path(
1764                    std::path::Path::new(&workload_path),
1765                    &params,
1766                )
1767                .map_err(|e| format!("parse workload: {e}"))?;
1768                workload_source_text = Some(yaml_source);
1769                workload
1770            }
1771            ResolvedWorkload::Bundled(bundled) => {
1772                // Catalog name is the workload identity for the
1773                // session (session.log, summaries, phase
1774                // outcomes) — bundled runs have no path.
1775                workload_file = Some(bundled.name.to_string());
1776                workload_is_bundled = true;
1777                // SRD-72 + SRD-85: a bundled workload's
1778                // `extends:` chain resolves through the catalog
1779                // (no directory context).
1780                let (merged, res_warnings) =
1781                    nmbrs_workload::extends::load_and_merge_bundled(bundled)
1782                        .map_err(|e| format!("bundled workload `{}`: {e}", bundled.name))?;
1783                let mut workload = nmbrs_workload::parse::parse_workload(&merged, &params)
1784                    .map_err(|e| format!("parse bundled workload `{}`: {e}", bundled.name))?;
1785                workload.resolution_warnings.extend(res_warnings);
1786                workload_source_text = Some(bundled.source.to_string());
1787                workload
1788            }
1789        }
1790    };
1791
1792    // ── SRD-108 Part B — implementation binding (load time) ──
1793    //
1794    // Two invocation forms:
1795    //   workload=<impl>                  — the impl's `implements:`
1796    //       pulls its blueprint; the BLUEPRINT becomes the
1797    //       effective workload with the impl's op bodies bound in.
1798    //   workload=<blueprint> impl=<impl> — the blueprint is the
1799    //       entry point; `impl=` names the implementation, whose
1800    //       own `implements:` must resolve to the same blueprint.
1801    // All rules are load errors; by the time synthesis runs the
1802    // workload is ordinary and fully concrete.
1803    let impl_param = params.get("impl").cloned();
1804    if let Some(target) = workload.implements.clone() {
1805        if impl_param.is_some() {
1806            return Err(format!(
1807                "workload '{}' is an implementation (declares \
1808                 `implements:`), so `impl=` does not apply — invoke \
1809                 either the implementation directly or the blueprint \
1810                 with impl=",
1811                workload_file.as_deref().unwrap_or("<inline>")
1812            ));
1813        }
1814        workload = bind_into_declared_blueprint(
1815            workload,
1816            &target,
1817            workload_file.as_deref(),
1818            workload_is_bundled,
1819            &params,
1820        )?;
1821    } else if let Some(impl_ref) = impl_param {
1822        let base_dir = (!workload_is_bundled)
1823            .then(|| {
1824                workload_file
1825                    .as_deref()
1826                    .map(std::path::Path::new)
1827                    .and_then(|p| p.parent().map(|d| d.to_path_buf()))
1828            })
1829            .flatten();
1830        let bundled_origin = workload_is_bundled
1831            .then_some(workload_file.as_deref())
1832            .flatten();
1833        let (implementation, impl_id) =
1834            load_secondary_workload(&impl_ref, &params, base_dir.as_deref(), bundled_origin)?;
1835        let declared = implementation.implements.clone().ok_or_else(|| {
1836            format!(
1837                "impl='{impl_ref}' resolves to '{impl_id}', which declares no \
1838             `implements:` — an implementation module must name its \
1839             blueprint"
1840            )
1841        })?;
1842        // The impl's declared target must be the SAME document the
1843        // operator invoked as workload=.
1844        // The impl doc's `implements:` resolves relative to the
1845        // IMPL doc's own directory (extends precedent).
1846        let impl_dir = std::path::Path::new(&impl_id)
1847            .parent()
1848            .map(|d| d.to_path_buf());
1849        let declared_id =
1850            workload_ref_identity(&declared, impl_dir.as_deref(), Some(impl_id.as_str()))?;
1851        let invoked_id = workload_file
1852            .clone()
1853            .map(|f| canonical_identity(&f))
1854            .unwrap_or_default();
1855        if declared_id != invoked_id {
1856            return Err(format!(
1857                "impl='{impl_id}' declares implements='{declared}' \
1858                 (resolves to '{declared_id}'), which is not the invoked \
1859                 workload '{invoked_id}'"
1860            ));
1861        }
1862        crate::diag!(
1863            crate::observer::LogLevel::Info,
1864            "implements: binding '{impl_id}' into blueprint '{invoked_id}'"
1865        );
1866        nmbrs_workload::implements::bind_implementation(&mut workload, implementation)
1867            .map_err(|e| format!("implements binding: {e}"))?;
1868    }
1869    {
1870        let unbound = nmbrs_workload::implements::unbound_abstract_slots(&workload);
1871        if !unbound.is_empty() {
1872            return Err(format!(
1873                "abstract op slot(s) [{}] unbound — pass impl=<workload> \
1874                 or invoke an implementing workload (SRD-108)",
1875                unbound.join(", ")
1876            ));
1877        }
1878    }
1879
1880    // Overlay CLI params on the workload's declared params (CLI wins) so
1881    // synthesis (next) can read the operator's `cycles=N` / `concurrency=N`
1882    // overrides and promote them onto the synthetic phase. Same precedence
1883    // rule the session-tier services use via [`effective_params`], so a key
1884    // means the same thing whether declared in the workload or on the CLI.
1885    // Also covers the inline (`op=`) path that loaded empty params.
1886    workload.params = overlay_cli_params(std::mem::take(&mut workload.params), &params);
1887
1888    // Unification: the scenario-tree executor is the sole
1889    // execution path. Workloads that arrive without an
1890    // explicit `phases:` block (the `op=` inline form, the
1891    // `blocks:` shorthand, top-level `ops:` lists) get an
1892    // implicit `main` phase + `default` scenario synthesized
1893    // here. Idempotent on workloads that already declare
1894    // phases. See [`nmbrs_workload::model::Workload::synthesize_default_phase`].
1895    workload.synthesize_default_phase();
1896
1897    let merged_params = workload.params.clone();
1898
1899    // A workload's own `driver:` param is not an adapter selector
1900    // (only a CLI `driver=` names a manifest, resolved above).
1901    if merged_params.contains_key("driver") && !params.contains_key("driver") {
1902        return Err(format!(
1903            "workload param `driver: {}` does not select an adapter; write `adapter: {}`",
1904            merged_params["driver"], merged_params["driver"]
1905        ));
1906    }
1907
1908    // Extract core config
1909    let driver = merged_params
1910        .get("adapter")
1911        .cloned()
1912        .unwrap_or_else(|| "stdout".into());
1913    let explicit_cycles: Option<u64> = merged_params.get("cycles").and_then(|s| parse_count(s));
1914    let concurrency: usize = match merged_params.get("concurrency") {
1915        Some(s) => s
1916            .parse()
1917            .map_err(|_| format!("concurrency value '{s}' is not a valid integer"))?,
1918        None => 1,
1919    };
1920    let rate: Option<f64> = match merged_params.get("rate") {
1921        Some(s) => Some(
1922            s.parse()
1923                .map_err(|_| format!("rate value '{s}' is not a valid number"))?,
1924        ),
1925        None => None,
1926    };
1927    // Workload-root total-attempts budget — the `tries` sigil for the
1928    // conditional TriesDispenser (SRD-82 Part 3b). Absent = ops without
1929    // their own `tries:` run single-attempt with no retry wrapper. `N ≥ 2`
1930    // retries adapter-retryable op errors (CQL timeouts/overloads) up to N
1931    // total attempts before the failure propagates to the result level;
1932    // `1` = explicit single-attempt; `0` = ops fail without executing.
1933    let tries: Option<u32> = match merged_params.get("tries") {
1934        Some(s) => Some(
1935            s.parse()
1936                .map_err(|_| format!("tries value '{s}' is not a valid integer"))?,
1937        ),
1938        None => None,
1939    };
1940    let tag_filter = merged_params.get("tags").cloned();
1941    let seq_type = merged_params
1942        .get("seq")
1943        .map(|s| SequencerType::parse(s).unwrap_or(SequencerType::Bucket))
1944        .unwrap_or(SequencerType::Bucket);
1945    let mut error_spec = merged_params
1946        .get("errors")
1947        .cloned()
1948        .unwrap_or_else(|| ".*:warn,stop".to_string());
1949    // `error_rate_max` — the OPT-IN session-wide error-rate circuit
1950    // breaker. When set, a phase fails once >this share of its ops error
1951    // (after a 50-op floor); per-phase `error_rate_max:` overrides it.
1952    // NO default (SRD-82 §"AggregateGuard retired as a default"): the
1953    // former silent 0.1 default was hidden, non-optional, and possibly
1954    // not what the operator wanted — operators built duplicate
1955    // `stop_when` backstops precisely because this one was invisible.
1956    // Aggregate health belongs to visible, workload-authored `stop_when`
1957    // conditions (SRD-83); this knob remains only as an explicit opt-in.
1958    let error_rate_max: Option<f64> = match merged_params.get("error_rate_max") {
1959        Some(s) => match s.trim().parse::<f64>() {
1960            Ok(v) if v >= 0.0 => Some(v),
1961            _ => {
1962                eprintln!(
1963                    "error: error_rate_max must be a non-negative number \
1964                           (e.g. 0.1 = 10%); got '{s}'"
1965                );
1966                std::process::exit(2);
1967            }
1968        },
1969        None => None,
1970    };
1971    // SRD-44 §"--force-retry-failed": when set on a resume
1972    // invocation, prepend a `.*:retry,warn` rule to the errors
1973    // cascade so any failure surfaces a retry rather than the
1974    // workload's normal stop / fail behaviour. Idempotent: when
1975    // set on a fresh run, it still applies (doesn't gate on
1976    // is_resume) — operators who want the override on a fresh
1977    // run get it; operators who pass it accidentally without
1978    // resume= get the same generous-retry policy they'd see on
1979    // resume.
1980    let force_retry_failed = params.get("force_retry_failed").map_or(Ok(false), |s| {
1981        nmbrs_workload::boolean::parse_bool("force_retry_failed", s)
1982    })? || args.iter().any(|a| a == "--force-retry-failed");
1983    if force_retry_failed {
1984        error_spec = format!(".*:retry,warn;{error_spec}");
1985        crate::diag!(
1986            crate::observer::LogLevel::Info,
1987            "--force-retry-failed: errors cascade prefixed with '.*:retry,warn'"
1988        );
1989    }
1990
1991    // Validate CLI parameters (runner-known + adapter-registered + workload-declared).
1992    //
1993    // Allow-list = installed param vocabulary ∪ adapter-registered ∪
1994    // `workload.declared_params` (the original YAML keys from
1995    // the workload's `params:` block). We do **not** consult
1996    // `workload.params` here — `parse.rs` merges every CLI arg
1997    // into that map regardless of whether the workload declared
1998    // it, so checking against it would let any CLI param through
1999    // and silently drop typos like `profile=perf` (vs.
2000    // `profiler=perf`). `declared_params` preserves the user's
2001    // declared surface independent of CLI overlays, which is
2002    // what the closed-vocabulary check needs. Skipped entirely
2003    // when no CLI vocabulary is installed (library/test driver).
2004    if let Some(cli_params) = known_params() {
2005        let adapter_params = registered_adapter_params();
2006        let all_known: Vec<&str> = cli_params
2007            .iter()
2008            .copied()
2009            .chain(adapter_params.iter().copied())
2010            .chain(workload.declared_params.iter().map(|s| s.as_str()))
2011            .collect();
2012        for key in params.keys() {
2013            if !all_known.contains(&key.as_str()) {
2014                return Err(unrecognized_param_error(&args, key, &all_known));
2015            }
2016        }
2017    }
2018
2019    // Validate workload-declared params are actually referenced.
2020    // Unreferenced params can shadow runner params (e.g., a workload
2021    // declaring `concurrency` as a param masks the CLI parameter
2022    // validation, but if nothing in the workload uses `{concurrency}`
2023    // the value is silently ignored).
2024    //
2025    // AND the reverse direction (SRD-N param-reference validator):
2026    // every `{name}` placeholder in the workload must resolve to a
2027    // declared param, a known runner/adapter param, or an iter-var
2028    // introduced by some Comprehension in the scenario tree. A
2029    // stray `{undeclared}` would otherwise survive
2030    // `expand_workload_params` as a literal and trip the Polydat parser
2031    // later with a cryptic "expected expression, got LBrace" — that
2032    // surfaces too late and doesn't name the offender. The check
2033    // here points at the placeholder by name so the operator sees
2034    // what to fix.
2035    {
2036        // First — catch `{name}` placeholders that appear inside
2037        // Polydat expression bodies outside of string literals. The
2038        // Polydat grammar doesn't accept `{...}` as expression syntax;
2039        // a `{name}` there will always fail compile with a
2040        // cryptic "expected expression, got LBrace". Catch it
2041        // here with a targeted message naming the YAML file and
2042        // line so the operator can jump straight to it.
2043        let mut invalid_polydat_braces: Vec<PolydatBraceFinding> =
2044            collect_polydat_brace_refs(&workload);
2045        if !invalid_polydat_braces.is_empty() {
2046            invalid_polydat_braces.sort();
2047            invalid_polydat_braces.dedup();
2048            let file_path = workload_file.as_deref().unwrap_or("<inline>");
2049            let lines: Vec<String> = invalid_polydat_braces
2050                .iter()
2051                .map(|f| {
2052                    let yaml_line = workload_source_text
2053                        .as_deref()
2054                        .and_then(|src| find_yaml_line_for_brace(src, &f.placeholder));
2055                    let prefix = match yaml_line {
2056                        Some(n) => format!("{file_path}:{n}"),
2057                        None => file_path.to_string(),
2058                    };
2059                    format!(
2060                        "  {prefix}: in {} — `{{{}}}`. Use bare `{}`.",
2061                        f.location, f.placeholder, f.placeholder
2062                    )
2063                })
2064                .collect();
2065            return Err(format!(
2066                "`{{...}}` braces in Polydat expression context (invalid syntax).\n\
2067                 Polydat accepts bare identifiers; braces are only for YAML string\n\
2068                 interpolation (op `prepared:`/`raw:`, `cycles:`, etc.).\n{}",
2069                lines.join("\n"),
2070            ));
2071        }
2072
2073        let referenced = collect_param_references(&workload);
2074        let adapter_params: std::collections::HashSet<&'static str> =
2075            registered_adapter_params().into_iter().collect();
2076        let iter_var_names = collect_iter_var_names(&workload);
2077        let wire_names = collect_polydat_binding_names(&workload);
2078
2079        // Declared/known direction: every declared param must be
2080        // referenced — except adapter-registered params, which
2081        // the driver consumes directly from the merged params
2082        // (e.g. `host`/`port`/`consistency` for CQL). Declaring
2083        // one in `params:` is how a workload surfaces the knob
2084        // with a default in `describe workloads` without a
2085        // textual `{name}` reference.
2086        // Every offender is named, in sorted order, so one run shows
2087        // the whole list and two runs show the same one.
2088        let mut unreferenced: Vec<&str> = workload
2089            .declared_params
2090            .iter()
2091            .map(|s| s.as_str())
2092            .filter(|name| !is_cli_param(name) && !adapter_params.contains(name))
2093            .filter(|name| !referenced.contains(name))
2094            .collect();
2095        unreferenced.sort_unstable();
2096        unreferenced.dedup();
2097        match unreferenced.as_slice() {
2098            [] => {}
2099            [name] => {
2100                return Err(format!(
2101                    "workload declares param '{name}' but it is never referenced as \
2102                     '{{{name}}}' in any op, phase, scenario, or binding. Remove it or use it."
2103                ));
2104            }
2105            names => {
2106                return Err(format!(
2107                    "workload declares params [{}] but none of them is ever referenced \
2108                     (as '{{name}}' or by bare name) in any op, phase, scenario, or \
2109                     binding. Remove them or use them.",
2110                    names.join(", ")
2111                ));
2112            }
2113        }
2114
2115        // Undeclared direction: every curly-brace placeholder
2116        // must resolve. The legitimate-name set spans every
2117        // declaration site the runtime can satisfy:
2118        //   - workload.declared_params (the `params:` block)
2119        //   - the installed CLI param vocabulary (`cycles`, `concurrency`, …)
2120        //   - adapter-registered params (driver-specific config)
2121        //   - iter-vars from Comprehensions in the scenario tree
2122        //     (`k`, `limit`, `profile` from `for_each: "k in …"`)
2123        let declared_set: std::collections::HashSet<&str> = workload
2124            .declared_params
2125            .iter()
2126            .map(|s| s.as_str())
2127            .collect();
2128        let mut undeclared: Vec<&str> = referenced
2129            .placeholders
2130            .iter()
2131            .map(|s| s.as_str())
2132            .filter(|name| !declared_set.contains(*name))
2133            .filter(|name| !is_cli_param(name))
2134            .filter(|name| !adapter_params.contains(name))
2135            .filter(|name| !iter_var_names.contains(*name))
2136            .filter(|name| !wire_names.contains(*name))
2137            .collect();
2138        if !undeclared.is_empty() {
2139            undeclared.sort();
2140            return Err(format!(
2141                "workload references undeclared placeholder{plural} {names} — \
2142                 add to the `params:` block, or check for a typo. Recognised \
2143                 sources for `{{name}}` placeholders: workload `params:`, \
2144                 runner/adapter built-ins, scenario-tree iter-vars from \
2145                 `for_each:`/`for_combinations:`, and wire names from Polydat \
2146                 `bindings:`.",
2147                plural = if undeclared.len() == 1 { "" } else { "s" },
2148                names = undeclared
2149                    .iter()
2150                    .map(|n| format!("`{{{n}}}`"))
2151                    .collect::<Vec<_>>()
2152                    .join(", "),
2153            ));
2154        }
2155    }
2156
2157    // Extract workload structure before consuming. M3.6:
2158    // `workload_params` is the set of *workload-declared* params
2159    // (the YAML `params:` block, with CLI overrides applied) —
2160    // these are what get injected as `const` bindings on the
2161    // workload kernel. The full `workload.params` map also
2162    // contains ad-hoc CLI params like `cycles=`, `workload=`,
2163    // `tags=`, etc., which are not declared bindings and must
2164    // not become identifiers in the Polydat source. Filter by
2165    // `declared_params` to keep only the YAML-declared subset.
2166    let declared: std::collections::HashSet<&String> = workload.declared_params.iter().collect();
2167    let workload_params: HashMap<String, String> = workload
2168        .params
2169        .iter()
2170        .filter(|(k, _)| declared.contains(*k))
2171        .map(|(k, v)| (k.clone(), v.clone()))
2172        .collect();
2173    drop(declared);
2174    let mut phases = workload.phases;
2175    // Inline-expression rewrite per phase. The
2176    // `rewrite_inline_exprs` call later in this function (around
2177    // line 818) operates on `all_ops_for_compile` — a flattened
2178    // copy used for the workload-level kernel — but
2179    // `build_op_template_scope_kernel` (SRD-13d Phase 9) reads
2180    // op definitions from `phases.get(name).ops`, which is the
2181    // ORIGINAL parsed structure. Without this per-phase rewrite,
2182    // op-template kernels never see the synthesised
2183    // `__expr_N := <expr>` bindings and the conditional /
2184    // inline-expression machinery breaks for any op that lands
2185    // on the Phase 9 path. Rewriting in place here keeps the
2186    // two compile paths consistent.
2187    for phase in phases.values_mut() {
2188        crate::scope::rewrite_inline_exprs(&mut phase.ops)?;
2189    }
2190    let phase_order = workload.phase_order;
2191    let scenarios = workload.scenarios;
2192    let workload_readouts = workload.readouts.clone();
2193    // SRD-32a Push 3 — workload-root wrapper override.
2194    // Innermost-to-outermost list, extracted once and
2195    // installed onto every Activity via `set_wrappers_override`
2196    // before `run_with_driver` runs the cascade. Per-op
2197    // `wrappers:` overrides on individual templates shadow
2198    // this entry; CLI flags (not yet implemented) would set
2199    // it independently on the Activity.
2200    let workload_wrappers_override: Option<Vec<String>> = workload
2201        .wrappers
2202        .as_ref()
2203        .filter(|c| !c.order.is_empty())
2204        .map(|c| c.order.clone());
2205    // SRD-63 §8 / Push 8: extract the CLI `--readout=<body>`
2206    // override before any binder is built. Resolved through
2207    // the same `resolve_flag` helper as `--session-path`,
2208    // so it picks up the matching `NMBRS_READOUT` env var
2209    // when set. `None` ⇒ workload bindings + builtin
2210    // defaults run unchanged.
2211    let cli_readout_override = crate::session::resolve_flag(&args[..], "--readout");
2212
2213    // SRD-32a Push 3 — CLI overrides for wrapper composition
2214    // ordering. Two flags:
2215    //
2216    // - `--wrap-order=<list>` — innermost-to-outermost
2217    //   permutation that applies to every op in this run.
2218    //   Workload-root and per-op blocks shadow it (config-
2219    //   locality wins, SRD-04 Rule 5). When neither workload-
2220    //   level override is set, this CLI value plumbs through
2221    //   to `Activity::wrappers_override` for every phase.
2222    // - `--wrap-default-order=<list>` — replaces the
2223    //   resolver's *built-in* default-order tiebreaker for
2224    //   the run. Useful when the operator wants a permanent
2225    //   tilt (e.g. always put validate outside throttle in
2226    //   their environment) without editing every workload.
2227    //   Validated against the constraint graph at session
2228    //   start; an inconsistent list is a hard error.
2229    //
2230    // Both flags accept a comma-separated list. Empty / unset
2231    // ⇒ runtime default applies.
2232    let cli_wrap_order: Option<Vec<String>> =
2233        crate::session::resolve_flag(&args[..], "--wrap-order")
2234            .map(|s| {
2235                s.split(',')
2236                    .map(|t| t.trim().to_string())
2237                    .filter(|t| !t.is_empty())
2238                    .collect()
2239            })
2240            .filter(|v: &Vec<String>| !v.is_empty());
2241    let cli_wrap_default_order: Option<Vec<String>> =
2242        crate::session::resolve_flag(&args[..], "--wrap-default-order")
2243            .map(|s| {
2244                s.split(',')
2245                    .map(|t| t.trim().to_string())
2246                    .filter(|t| !t.is_empty())
2247                    .collect()
2248            })
2249            .filter(|v: &Vec<String>| !v.is_empty());
2250
2251    // Effective workload-level wrapper override: workload's
2252    // own `wrappers: { order: [...] }` block wins over the
2253    // CLI flag (config-locality, SRD-04 Rule 5). Per-op
2254    // overrides on individual ParsedOps shadow either.
2255    let workload_wrappers_override: Option<Vec<String>> =
2256        workload_wrappers_override.or(cli_wrap_order);
2257    // Unified report block (SRD-46). Tables auto-render at
2258    // end-of-run; plot specs persist into the session db so
2259    // post-hoc `nmbrs report ...` can replay them. Empty
2260    // `report:` block ⇒ no auto-render and no persisted specs.
2261    let workload_report = workload.report.clone();
2262    let workload_summaries: HashMap<String, nmbrs_workload::model::SummaryConfig> = workload_report
2263        .items()
2264        .filter(|i| matches!(i.kind, nmbrs_workload::report::Kind::Table))
2265        .map(|i| {
2266            (
2267                i.name.clone(),
2268                nmbrs_workload::model::SummaryConfig::parse(&i.body),
2269            )
2270        })
2271        .collect();
2272
2273    // Collect ALL ops: top-level ops + all phase inline ops.
2274    let mut ops = workload.ops;
2275
2276    // Filter top-level ops by tags (CLI-level tag filter)
2277    if let Some(ref filter) = tag_filter {
2278        ops =
2279            TagFilter::filter_ops(&ops, filter).map_err(|e| format!("invalid tag filter: {e}"))?;
2280    }
2281
2282    // Classify phase ops for compilation:
2283    // - Phases with own bindings or for_each: saved raw, compiled per-phase
2284    // - Phases without own bindings: included in outer (workload) kernel
2285    let mut phase_ops_for_compile: Vec<nmbrs_workload::model::ParsedOp> = Vec::new();
2286    let mut phase_raw_ops: HashMap<String, Vec<nmbrs_workload::model::ParsedOp>> = HashMap::new();
2287    let mut phases_needing_own_kernel: std::collections::HashSet<String> =
2288        std::collections::HashSet::new();
2289    for (name, phase) in &phases {
2290        let has_own_bindings = phase.ops.iter().any(|op| !op.bindings.is_empty());
2291        if phase.for_each.is_some() || has_own_bindings {
2292            phase_raw_ops.insert(name.clone(), phase.ops.clone());
2293            phases_needing_own_kernel.insert(name.clone());
2294        } else {
2295            phase_ops_for_compile.extend(phase.ops.iter().cloned());
2296        }
2297    }
2298
2299    // For non-phased workloads, require at least some ops
2300    if ops.is_empty() && phases.is_empty() {
2301        return Err("no ops selected (tag filter may have excluded all ops)".into());
2302    }
2303
2304    if phases.is_empty() {
2305        crate::diag!(
2306            crate::observer::LogLevel::Info,
2307            "{} ops, {} cycles, concurrency={}, adapter={}",
2308            ops.len(),
2309            explicit_cycles
2310                .map(|c| c.to_string())
2311                .unwrap_or("auto".into()),
2312            concurrency,
2313            driver
2314        );
2315    } else {
2316        // Always log to session.log; stderr suppression is the
2317        // observer's job (TuiObserver gates eprintln internally).
2318        crate::diag!(
2319            crate::observer::LogLevel::Info,
2320            "{} phases, {} top-level ops, adapter={}",
2321            phases.len(),
2322            ops.len(),
2323            driver
2324        );
2325    }
2326
2327    // Collect --polydat-lib=path flags
2328    let polydat_lib_paths: Vec<std::path::PathBuf> = args
2329        .iter()
2330        .filter_map(|a| a.strip_prefix("--polydat-lib="))
2331        .map(std::path::PathBuf::from)
2332        .collect();
2333    let strict = args.iter().any(|a| a == "--strict")
2334        || params.get("strict").map_or(Ok(false), |s| {
2335            nmbrs_workload::boolean::parse_bool("strict", s)
2336        })?;
2337
2338    // SRD-68 follow-up — session-wide op-template synthesis opt level.
2339    // `--kernel-opt=release|diagnostic` or `kernel_opt=…`. Release
2340    // (default) lets the closure-binding economy DCE unreferenced
2341    // magic-extern slots; Diagnostic force-allocates body/count/ok and
2342    // every result-binding LHS slot so step-debug / cycle-replay can
2343    // inspect writes the workload doesn't otherwise consume.
2344    let kernel_opt: polydat::kernel::KernelOptLevel = {
2345        let raw =
2346            cli_flag_value(&args[..], "--kernel-opt").or_else(|| params.get("kernel_opt").cloned());
2347        match raw {
2348            None => polydat::kernel::KernelOptLevel::default(),
2349            Some(s) => polydat::kernel::KernelOptLevel::parse(s.trim()).map_err(|bad| {
2350                format!("unknown --kernel-opt value '{bad}' — use 'release' or 'diagnostic'")
2351            })?,
2352        }
2353    };
2354
2355    // Parse dryrun= param into diagnostic config
2356    if let Some(spec) = params.get("dryrun") {
2357        diag = DiagnosticConfig::parse(spec);
2358    }
2359
2360    // skipped_phases= — how fully-gated-off phases are represented
2361    // (elide | mark | prune). Default: mark.
2362    if let Some(spec) = params.get("skipped_phases") {
2363        match crate::observer::SkippedPhaseDisplay::parse(spec) {
2364            Some(mode) => crate::observer::set_skipped_phase_display(mode),
2365            None => {
2366                return Err(format!(
2367                    "unknown skipped_phases value '{spec}' — use 'elide', 'mark', or 'prune'"
2368                ));
2369            }
2370        }
2371    }
2372
2373    // completed_phases= — how much of a completed node's block is
2374    // retained in scrollback (full | headers). Default: full (SRD-92
2375    // R5 — completion is never a full collapse).
2376    if let Some(spec) = params.get("completed_phases") {
2377        match crate::observer::CompletedPhaseDisplay::parse(spec) {
2378            Some(mode) => crate::observer::set_completed_phase_display(mode),
2379            None => {
2380                return Err(format!(
2381                    "unknown completed_phases value '{spec}' — use 'full' or 'headers'"
2382                ));
2383            }
2384        }
2385    }
2386
2387    // "Never Ignore Silently" — scenario-parse errors are
2388    // ALWAYS fatal regardless of strict mode. The parser used
2389    // to silently drop unknown scenario-node keys (e.g.
2390    // `iterate:` misspellings, stray `phases:` siblings),
2391    // which led to downstream "phase 'iterate' not found"
2392    // confusion masking the real bug. The parser now collects
2393    // every malformed-node case here and we refuse to dispatch.
2394    if !workload.scenario_parse_errors.is_empty() {
2395        return Err(format!(
2396            "scenario parse error{plural} — workload is malformed:\n  - {msgs}",
2397            plural = if workload.scenario_parse_errors.len() == 1 {
2398                ""
2399            } else {
2400                "s"
2401            },
2402            msgs = workload.scenario_parse_errors.join("\n  - "),
2403        ));
2404    }
2405
2406    // SRD-46 + SRD-15: surface report-block warnings collected
2407    // by the parser. Strict mode promotes to a hard error so a
2408    // workload with `defaults`-collisions or empty groups can't
2409    // silently pass; otherwise we log them and continue.
2410    if !workload.report_warnings.is_empty() {
2411        if strict {
2412            return Err(format!(
2413                "report-block warnings (strict mode promotes to errors):\n  - {}",
2414                workload.report_warnings.join("\n  - "),
2415            ));
2416        }
2417        for w in &workload.report_warnings {
2418            crate::observer::log_tagged(
2419                crate::observer::LogLevel::Warn,
2420                crate::observer::EventTag::in_flight(crate::observer::EventCategory::Report),
2421                &format!("report: {w}"),
2422            );
2423        }
2424    }
2425
2426    // SRD-85 nearest-first reference resolution: a target that
2427    // matched multiple same-named resources resolved to the
2428    // nearest (filesystem favored) and is surfaced here — the
2429    // shadowing is allowed but never silent. Strict promotes.
2430    if !workload.resolution_warnings.is_empty() {
2431        if strict {
2432            return Err(format!(
2433                "reference-resolution warnings (strict mode promotes to errors):\n  - {}",
2434                workload.resolution_warnings.join("\n  - "),
2435            ));
2436        }
2437        for w in &workload.resolution_warnings {
2438            crate::observer::log_tagged(
2439                crate::observer::LogLevel::Warn,
2440                crate::observer::EventTag::in_flight(crate::observer::EventCategory::Resolution),
2441                &format!("resolve: {w}"),
2442            );
2443        }
2444    }
2445
2446    // Dry-run mode resolution.
2447    //
2448    // The mode string is a LABEL — there is no "silent" or
2449    // "op" or "cycle" adapter. The real adapter from the
2450    // workload is constructed in full (connect, prepare,
2451    // metadata, dispenser init); the `DryRunWrapper` is
2452    // installed at the outermost wrapper position and per-
2453    // cycle short-circuits the inner stack so the adapter's
2454    // `execute()` never fires. The mode string carries
2455    // operator intent through the log (`dryrun: injected
2456    // `dryrun: <mode>` …`) and only the `fields` mode has a
2457    // structural side-effect (forces the fields wrapper on so
2458    // rendered op text reaches stdout).
2459    //
2460    // Mapping:
2461    //   dryrun=cycle  → mode="cycle",  wrapper short-circuit
2462    //   dryrun=op     → mode="op",     wrapper short-circuit
2463    //   dryrun=silent → mode="silent", wrapper short-circuit
2464    //   dryrun=fields → mode="fields", wrapper short-circuit + fields-render on
2465    //   dryrun=full   → mode=None,     real execution
2466    let dry_run: Option<&str> = if diag.depth == ExecDepth::Cycle {
2467        Some("cycle")
2468    } else {
2469        params.get("dryrun").and_then(|s| match s.as_str() {
2470            "fields" => Some("fields"),
2471            "silent" => Some("silent"),
2472            "op" => Some("op"),
2473            _ => None,
2474        })
2475    };
2476
2477    // Auto-bump depth to Cycle for any dryrun mode that
2478    // installs the wrapper — cycles must dispatch for the
2479    // wrapper to have anything to short-circuit. Without the
2480    // bump, `dryrun=silent` / `dryrun=fields` / `dryrun=op`
2481    // would silently produce no output because the
2482    // phase-early-complete branch at executor.rs:2998 elides
2483    // the cycle loop when depth < Cycle.
2484    if dry_run.is_some() && diag.depth < ExecDepth::Cycle {
2485        diag.depth = ExecDepth::Cycle;
2486    }
2487
2488    // (OpenMetrics push URL is resolved in `SessionHost::setup` — the
2489    // metrics push reporter is a session-tier service.)
2490
2491    // Resolve the resume source BEFORE creating the new session
2492    // — `Session::new` eagerly remaps `logs/latest` at the new
2493    // session id, so any path resolution that depends on the old
2494    // `latest` target has to happen first. Stored as
2495    // `resume_target` and consulted later when constructing the
2496    // checkpoint writer + plan. SRD-44 §"Resume CLI surface".
2497    //
2498    // SRD-88 — per-execution: the session name (host already used the
2499    // same value to name the session dir) + the refine on-removed
2500    // policy, recomputed here from this execution's params.
2501    let scenario_for_session = params
2502        .get("scenario")
2503        .map(|s| s.as_str())
2504        .unwrap_or("default");
2505    let on_removed_policy: &str = params
2506        .get("on_removed")
2507        .map(|s| s.as_str())
2508        .unwrap_or("error");
2509    if let Some(plan) = refine_plan.as_ref() {
2510        let current_names: std::collections::HashSet<&str> =
2511            phases.keys().map(|s| s.as_str()).collect();
2512        let mut removed: Vec<&str> = plan
2513            .seen_identities
2514            .iter()
2515            .map(|(name, _)| name.as_str())
2516            .filter(|n| !current_names.contains(n))
2517            .collect();
2518        removed.sort();
2519        removed.dedup();
2520        if !removed.is_empty() {
2521            match on_removed_policy {
2522                "error" => {
2523                    return Err(format!(
2524                        "refine: workload removes {n} phase{plural} that have \
2525                         prior outcomes in this session:\n  - {names}\n\
2526                         Pass `on_removed=keep` to retain the prior outcomes \
2527                         (no work, no error); `on_removed=drop` is reserved \
2528                         (not yet implemented). Default `error` refuses to \
2529                         proceed so accidental axis-trim doesn't drop history \
2530                         silently.",
2531                        n = removed.len(),
2532                        plural = if removed.len() == 1 { "" } else { "s" },
2533                        names = removed.join("\n  - "),
2534                    ));
2535                }
2536                "keep" => {
2537                    crate::diag!(
2538                        crate::observer::LogLevel::Info,
2539                        "refine: on_removed=keep — retaining prior outcomes \
2540                         for {n} removed phase(s): {names}",
2541                        n = removed.len(),
2542                        names = removed.join(", ")
2543                    );
2544                }
2545                "drop" => {
2546                    crate::diag!(
2547                        crate::observer::LogLevel::Warn,
2548                        "refine: on_removed=drop is reserved — not yet \
2549                         implemented. Treating as `keep` (retaining prior \
2550                         outcomes) for now: {names}",
2551                        names = removed.join(", ")
2552                    );
2553                }
2554                other => {
2555                    return Err(format!(
2556                        "refine: unknown on_removed= policy '{other}'; \
2557                         expected `error` (default), `keep`, or `drop`"
2558                    ));
2559                }
2560            }
2561        }
2562    }
2563
2564    // SRD-88 — a CONCURRENT execution runs inside a scoped
2565    // `ExecutionContext` whose `exec_id` was allocated distinctly per
2566    // sibling; use it so each concurrent execution's metric rows /
2567    // metadata / `executions` row are separable. Outside a scoped
2568    // context (single-run), fall back to the SRD-77 verb/exec_id:
2569    // `refine` numbers from the prior outcomes' max+1, `run`/`resume`
2570    // start at 1 — byte-identical to before.
2571    let (exec_verb, exec_id_seed): (&'static str, u64) =
2572        match crate::execution_context::try_current() {
2573            Some(ctx) => ("run", ctx.exec_id),
2574            None => match (refine_plan.as_ref(), resume_target.as_ref()) {
2575                (Some(plan), Some(p)) if p.exists() => ("refine", plan.next_exec_id),
2576                (_, Some(p)) if p.exists() => ("resume", 1),
2577                _ => ("run", 1),
2578            },
2579        };
2580    // SRD-88 §2 — start this execution under the session: derive
2581    // its component (carrying `exec_id` + `workload`) as a child
2582    // of the session component. Phase components attach under
2583    // `execution.component`, so every metric inherits this
2584    // execution's identity without any tier redeclaring a label.
2585    let execution = crate::session::Execution::start(
2586        session,
2587        workload_file.as_deref().unwrap_or("inline"),
2588        scenario_for_session,
2589        exec_verb,
2590        exec_id_seed,
2591    );
2592    let exec_id = execution.exec_id;
2593
2594    // dryrun=controls: defer the tree walk until after phase
2595    // construction. `list_controls` implies depth=Phase, which
2596    // means every phase compiles and attaches its component —
2597    // that's when activity-scoped controls get declared — but
2598    // no cycles run. Walking here would only see session-root
2599    // controls. The renderer fires at the very end of the run,
2600    // just before the session returns.
2601
2602    // Direct the diagnostic log sink at <session_dir>/session.log so every
2603    // observer::log() call is captured durably, even under the TUI.
2604    // SRD-77 / SRD-88 — per-execution metadata + the in-flight
2605    // `executions` row. Written through the shared session reporter
2606    // but scoped to THIS execution's `exec_id`, so concurrent
2607    // executions sharing the session each record their own workload
2608    // / scenario / params without clobbering. `ended_at_nanos` /
2609    // `disposition` stay NULL until the shutdown-flush guard updates
2610    // them. `scope` is non-NULL only under refine.
2611    {
2612        let mut cli_keys: Vec<&String> = params.keys().collect();
2613        cli_keys.sort();
2614        let cli_text: String = cli_keys
2615            .iter()
2616            .filter_map(|k| params.get(*k).map(|v| format!("{k}={v}")))
2617            .collect::<Vec<_>>()
2618            .join("\n");
2619        let scope_for_row: Option<&str> = if refine_requested {
2620            Some(refine_scope.unwrap_or("missing"))
2621        } else {
2622            None
2623        };
2624        if let Ok(mut guard) = sqlite_reporter.lock()
2625            && let Some(r) = guard.as_mut()
2626        {
2627            let exec_id = execution.exec_id;
2628            let sid = session.id.clone();
2629            r.set_execution_metadata(&sid, exec_id, "workload", &execution.workload);
2630            r.set_execution_metadata(&sid, exec_id, "scenario", &execution.scenario);
2631            r.set_execution_metadata(
2632                &sid,
2633                exec_id,
2634                "start_time",
2635                &format!(
2636                    "{}",
2637                    std::time::SystemTime::now()
2638                        .duration_since(std::time::UNIX_EPOCH)
2639                        .unwrap()
2640                        .as_secs()
2641                ),
2642            );
2643            for (k, v) in &merged_params {
2644                r.set_execution_metadata(&sid, exec_id, &format!("param.{k}"), v);
2645            }
2646            // Reproducibility: the metrics db alone re-creates the run
2647            // (raw workload YAML + verbatim CLI params).
2648            if let Some(yaml) = workload_source_text.as_deref() {
2649                r.set_execution_metadata(&sid, exec_id, "workload_yaml", yaml);
2650            }
2651            r.set_execution_metadata(&sid, exec_id, "cli_params", &cli_text);
2652            r.insert_execution_start(
2653                &session.id,
2654                execution.exec_id,
2655                execution.verb,
2656                scope_for_row,
2657                execution.started_at_nanos,
2658                workload_source_text.as_deref().unwrap_or(""),
2659                &cli_text,
2660            );
2661        }
2662    }
2663
2664    // SRD-63 Push 9a: fire `EventType::SessionStart` once at the
2665    // workload root. Workloads bind structural rows to
2666    // this slot via `readouts: { on_session_start: … }`;
2667    // unbound slots stay quiet (no built-in default
2668    // emission today). Fires whether the run takes the
2669    // phased or single-activity branch below.
2670    {
2671        let session_ctx = crate::readout_context::LifecycleContext {
2672            event: crate::lifecycle::EventType::SessionStart,
2673            subject_name: session.id.clone(),
2674            subject_labels: String::new(),
2675            depth_indent: String::new(),
2676            use_color: crate::observer::use_color(),
2677            stick_reattached: stick_reattached.clone().unwrap_or_default(),
2678        };
2679        // SRD-106 D4 — when the stick_session rung engaged, seed
2680        // the slot with the `session_notice` builtin so the
2681        // announcement is the first notable event of the run,
2682        // ahead of any phase event. Workload-bound
2683        // on_session_start readouts still render after it; runs
2684        // without stick keep the slot's quiet default.
2685        let default_body = if stick_reattached.is_some() {
2686            crate::readouts::parse::bake("session_notice")
2687                .map(|(body, _)| body)
2688                .ok()
2689        } else {
2690            None
2691        };
2692        crate::readout_context::fire_lifecycle(
2693            crate::lifecycle::EventType::SessionStart,
2694            &workload_readouts,
2695            default_body,
2696            &session_ctx,
2697            Some(&sqlite_reporter),
2698        );
2699    }
2700
2701    // Merge all ops for param expansion and Polydat compilation.
2702    let _num_top_level_ops = ops.len();
2703    let mut all_ops_for_compile: Vec<nmbrs_workload::model::ParsedOp> = ops;
2704    all_ops_for_compile.extend(phase_ops_for_compile);
2705
2706    // === Pre-compile rewrites ===
2707    //
2708    // Stage 2 (post-M3.6): the workload-params kernel
2709    // (`crate::params::build_workload_params_kernel`) installs
2710    // every workload param as a `final <name> := <literal>`
2711    // binding on the workload-root kernel. Descendant scopes
2712    // see those bindings via `materialize_wiring_from_outer` + standard GK
2713    // scope-chain lookup. The legacy
2714    // `rewrite_workload_param_idents_in_bindings` text pass
2715    // (which substituted `{name}` → literal value before
2716    // compilation) was redundant once that path landed and
2717    // produced broken output for in-string placeholders
2718    // (`"{dataset}:{profile}"` → `""example":"default""`),
2719    // so it has been retired.
2720    //
2721    // What's left here: rewrite inline `{{expr}}` constructs to
2722    // named bindings so the Polydat compiler can hoist them as
2723    // `const __expr_N := …` entries. That pass is a bind-point
2724    // shape transform, not a value substitution — it operates
2725    // independently of workload params.
2726    crate::scope::rewrite_inline_exprs(&mut all_ops_for_compile)?;
2727
2728    // The workload-level `bindings:` (top-level YAML block) is
2729    // a first-class workload-scope input — separate from any
2730    // op's bindings. We pass it through to the compiler as a
2731    // distinct source so cursor declarations and other
2732    // workload-scoped Polydat statements land on the workload kernel
2733    // alongside the workload params, *without* going through
2734    // the op-binding param-ident rewrite (which would text-
2735    // substitute `{name}` placeholders inside string literals).
2736    // Polydat's standard string-interpolation handles `{name}` at
2737    // compile time against the `final <name> := <literal>`
2738    // bindings that workload-params injection installs (M3.6 path).
2739    // SRD-13f Push D: workload-level `bindings:` reach the
2740    // workload-root kernel ONLY through this explicit channel
2741    // now. The parser no longer merges workload bindings into
2742    // ops (`nmbrs_workload::parse::inline_block_sugar_into_op`
2743    // is the only remaining parser-time inlining; it operates
2744    // on block-level YAML sugar, not workload-level). Both
2745    // BindingsDef forms route through here:
2746    //   - PolydatSource: pass through verbatim.
2747    //   - Map: legacy semicolon-chain syntax translated to GK
2748    //     source lines via `legacy_chain_map_to_polydat_lines`.
2749    let workload_level_polydat: Option<String> = match &workload.bindings {
2750        nmbrs_workload::model::BindingsDef::PolydatSource(s) if !s.trim().is_empty() => {
2751            Some(s.clone())
2752        }
2753        nmbrs_workload::model::BindingsDef::Map(m) if !m.is_empty() => Some(
2754            crate::bindings::legacy_chain_map_to_polydat_lines(m)
2755                .map_err(|e| format!("workload-level bindings: {e}"))?,
2756        ),
2757        _ => None,
2758    };
2759
2760    // === Polydat Compilation ===
2761
2762    let workload_dir: Option<&std::path::Path> = if workload_is_bundled {
2763        // A catalog name is not a path — don't derive a bogus
2764        // directory from its namespace segments. Bundled
2765        // workloads get the cwd as their relative-resolution
2766        // context (same as inline workloads).
2767        Some(std::path::Path::new("."))
2768    } else {
2769        workload_file
2770            .as_ref()
2771            .and_then(|p| std::path::Path::new(p).parent())
2772            .or_else(|| Some(std::path::Path::new(".")))
2773    };
2774
2775    let mut config_refs: Vec<String> = params
2776        .values()
2777        .filter(|v| v.starts_with('{') && v.ends_with('}'))
2778        .map(|v| {
2779            let mut inner = v[1..v.len() - 1].to_string();
2780            // Expand workload params in config expressions
2781            for (key, value) in &workload_params {
2782                let placeholder = format!("{{{key}}}");
2783                if inner.contains(&placeholder) {
2784                    inner = inner.replace(&placeholder, value);
2785                }
2786            }
2787            inner
2788        })
2789        .collect();
2790    for (name, phase) in &phases {
2791        if phase.for_each.is_some() {
2792            continue; // for_each phase cycles resolved per-iteration
2793        }
2794        if let Some(ref c) = phase.cycles
2795            && c.starts_with('{')
2796            && c.ends_with('}')
2797        {
2798            let mut inner = c[1..c.len() - 1].to_string();
2799            for (key, value) in &workload_params {
2800                let placeholder = format!("{{{key}}}");
2801                if inner.contains(&placeholder) {
2802                    inner = inner.replace(&placeholder, value);
2803                }
2804            }
2805            config_refs.push(inner);
2806        }
2807        let _ = name; // suppress unused warning
2808    }
2809
2810    // Parse limit param for cursor clamping
2811    let cursor_limit: Option<u64> = merged_params.get("limit").and_then(|s| s.parse().ok());
2812
2813    // Build the workload-params root kernel first. This is the
2814    // canonical home for every declared workload parameter —
2815    // one `final <name> := <literal>` per param, compiled into
2816    // a stand-alone kernel whose outputs every descendant
2817    // `materialize_wiring_from_outer`s through. Replaces the prior approach
2818    // of patching params into multiple places (per-op binding
2819    // text substitution, per-kernel `final` injection in
2820    // `build_scope`). See `nmbrs-runtime::params`.
2821    // `build_workload_params_kernel` already prefixes its error
2822    // with "workload params kernel:" and appends the generated
2823    // source for diagnosis — propagate it verbatim rather than
2824    // re-wrapping (which doubled the prefix and dropped the
2825    // source dump).
2826    let params_kernel = crate::params::build_workload_params_kernel(&workload_params)?;
2827
2828    // Build the workload kernel directly as a subscope of the
2829    // params kernel via the typed PolydatKernel-controlled
2830    // construction path. Cells from params flow in via the
2831    // cascade — no late-binding step required.
2832    // Build the workload kernel as a subscope of the params
2833    // kernel and share ONE Arc across both consumers (the
2834    // scope tree's canonical reference AND the OpBuilder's
2835    // source kernel). A second materialize_subscope would
2836    // produce a sibling kernel with its own freshly-seeded
2837    // shared cells — disconnected from the canonical, so
2838    // result-binding writes from one chain wouldn't be visible
2839    // to the other. Sharing the Arc keeps the cell handles
2840    // identical end-to-end: detect_dialect's writes reach
2841    // await_index's reads through the same Mutex<Value>.
2842    // SRD-13f Push D: the workload-root kernel still owns the
2843    // canonical workload-scope bindings, but descendant kernels
2844    // (phase kernel, op-template kernel) carry a cascade copy
2845    // of the workload-level Polydat source as local matter — so
2846    // fiber.main_kernel evaluates dynamic workload bindings
2847    // (e.g. cycle-dependent) on its own state per cycle. See
2848    // `compile_from_scope` (and its callers in
2849    // `executor.rs::run_phase`) for the cascade-copy plumbing.
2850    // No eager pull at workload-root construction: that would
2851    // (a) fire side-effecting nodes like `testkit_throw_at` outside the
2852    // phase cascade context, and (b) cache stale values for
2853    // cycle-dependent bindings.
2854    let workload_canonical_kernel: std::sync::Arc<crate::scope_kernel::ScopeKernel> =
2855        std::sync::Arc::new(
2856            build_workload_root_kernel(
2857                &params_kernel,
2858                &all_ops_for_compile,
2859                workload_dir,
2860                polydat_lib_paths.clone(),
2861                strict,
2862                &config_refs,
2863                "outer workload bindings",
2864                cursor_limit,
2865                &workload_params,
2866                workload_level_polydat.as_deref(),
2867            )
2868            .map_err(|e| format!("outer workload bindings: {e}"))?,
2869        );
2870    let kernel = workload_canonical_kernel.clone();
2871
2872    // Strip workload-level adapter and the CLI `driver=` manifest
2873    // selector from op params (adapter is resolved per-phase/per-op,
2874    // not from workload params)
2875    for op in &mut all_ops_for_compile {
2876        op.params.remove("adapter");
2877        op.params.remove("driver");
2878    }
2879    for ops in phase_raw_ops.values_mut() {
2880        for op in ops.iter_mut() {
2881            op.params.remove("adapter");
2882            op.params.remove("driver");
2883        }
2884    }
2885
2886    let builder = Arc::new(OpBuilder::new(kernel));
2887
2888    // Unification — the scenario-tree executor is the sole
2889    // execution path. `Workload::synthesize_default_phase` (called
2890    // at load time) guarantees `phases` is non-empty for any
2891    // workload that has work to do; the empty-ops error fired
2892    // earlier in this fn covers the "literally nothing to run"
2893    // case. The legacy single-activity branch is gone.
2894    {
2895        // --- Phased execution ---
2896        let scenario_name = params
2897            .get("scenario")
2898            .map(|s| s.as_str())
2899            .unwrap_or("default");
2900        let scenario_nodes = resolve_scenario(&scenarios, &phase_order, scenario_name)?;
2901
2902        // Build the canonical scope tree (SRD 18b §"Canonical
2903        // traversal"). Mirrors the scenario tree 1:1 with parent
2904        // pointers, depth, and pragma slots. Today consumed by
2905        // observer pre-mapping and diagnostic display; future
2906        // steps drive execution from this tree directly.
2907        let scope_tree = {
2908            let mut t = crate::scope_tree::ScopeTree::build(scenario_name, &scenario_nodes);
2909            // Populate phase-leaf pragmas from each phase's GK
2910            // source and chain each scope's `PragmaSet` to its
2911            // parent's. SRD 18b §"Pragma chain along the scope
2912            // tree"; SRD 15 §"Pragma Scope".
2913            t.populate_pragmas(&phases);
2914            // Validate iter-var name uniqueness against workload
2915            // params and enclosing iter vars. Aliasing creates an
2916            // unambiguous spec-evaluation case the runtime can't
2917            // disambiguate; reject up-front.
2918            let wp_names: std::collections::HashSet<String> =
2919                workload_params.keys().cloned().collect();
2920            t.validate_iter_var_uniqueness(&wp_names)?;
2921            // SRD-83 follow-up — load-time authoring lints: every
2922            // `errors:` router spec must parse (bad verbs fail the
2923            // load, not the first runtime error), a router without a
2924            // catch-all rule warns, and `metric()` families in
2925            // stop/gate predicates are checked against the instrument
2926            // namespace (an unregistered family reads 0.0 silently).
2927            for w in crate::workload_lint::lint_workload(
2928                &workload.stop_when,
2929                phases.iter().map(|(k, v)| (k.as_str(), v)),
2930            )? {
2931                crate::diag!(crate::observer::LogLevel::Warn, "{w}");
2932            }
2933            // SRD-13d Phase 6 — extend the scope tree with
2934            // op-template children of every Phase node so the
2935            // op tier is visible to the elision classifier
2936            // and downstream diagnostics.
2937            t.extend_with_op_templates(&phases);
2938            // SRD-13d Phase 3 — workload-init scope-elision
2939            // pre-walk. Reads `HasGkMatter` on each AST node
2940            // and marks the corresponding scope-tree node
2941            // `materialised` (own kernel) or elided (binds
2942            // through parent). Conservative predicate today
2943            // (Definitions ⇒ materialise without hash-subset
2944            // refinement); Phase 6 tightens it.
2945            //
2946            // Scoped fields rather than `&workload` because
2947            // `workload.ops` was moved earlier in this fn —
2948            // the classifier reads only bindings + params +
2949            // phases anyway.
2950            let classify_inputs = crate::scope_elision::ClassifyInputs {
2951                bindings: &workload.bindings,
2952                params: &workload.params,
2953                phases: &phases,
2954            };
2955            crate::scope_elision::classify_and_mark(&mut t, &classify_inputs);
2956            std::sync::Arc::new(t)
2957        };
2958
2959        // dryrun=kernels: register the ride-along visitor BEFORE
2960        // the install loop so every install_kernel call (root
2961        // workload kernel + per-scope kernels in DFS pre-order)
2962        // streams its polydat source to stdout. Cleared after
2963        // the install loop runs (see the matching short-circuit
2964        // a few hundred lines below).
2965        if params.get("dryrun").map(|s| s.as_str()) == Some("kernels") {
2966            print_kernel_dump_header();
2967            crate::scope_tree::set_kernel_install_visitor(Some(Box::new(|node, _idx, kernel| {
2968                print_kernel_for_scope(node, kernel);
2969            })));
2970        }
2971
2972        // Install the workload-params module on the session node
2973        // (the workload root's parent) so identity chains
2974        // (`ScopeTree::ancestor_kernels` → the SRD-44/SRD-77
2975        // provenance hashes) include the module whose const
2976        // slots carry every param VALUE. The workload kernel is
2977        // built as a subscope of this module; installing it here
2978        // records that same relationship on the tree. Nearest-
2979        // ancestor kernel lookups are unaffected — the workload
2980        // root always has its own kernel, so walks stop there.
2981        scope_tree.install_kernel(scope_tree.root, std::sync::Arc::new(params_kernel));
2982
2983        // Install the canonical workload kernel (SRD 18b §"Iter
2984        // vars as scope outputs"). After this, intermediate
2985        // scopes (for_each, for_combinations, …) install their
2986        // own kernels in DFS pre-order below — each one's
2987        // synthesis reads its parent's manifest via the standard
2988        // Polydat API on the parent's installed kernel.
2989        scope_tree.install_kernel(scope_tree.workload_root_idx(), workload_canonical_kernel);
2990
2991        // M3.2: install per-scope kernels for for_each /
2992        // for_combinations nodes. Each kernel re-exports its
2993        // iteration variables and any referenced inherited
2994        // values as outputs (`const x := x` passthrough), so
2995        // children's standard `materialize_wiring_from_outer(parent)`
2996        // chains inheritance through arbitrary nesting depth
2997        // — no caller-side scope-tree walking for name
2998        // resolution at runtime.
2999        let workload_dir_owned: Option<std::path::PathBuf> = workload_dir.map(|p| p.to_path_buf());
3000        // M3.4b: scope kinds get categorized for synthesis.
3001        // For-comprehensions (ForEach, ForCombinations,
3002        // ForEachUnion) carry tuple iteration vars; do-loops
3003        // (DoWhile, DoUntil) carry an optional counter +
3004        // condition expression. Both produce installed kernels
3005        // that the unified dispatch_comprehension reads from.
3006        // reason: function-local, short-lived spec list built once per
3007        // install pass; the `OpTemplate`/`ParsedOp` variant dominates the
3008        // size, but boxing it would ripple `Box::new` + deref across every
3009        // construction and destructuring match arm below for no real gain
3010        // on a vector that is consumed immediately.
3011        #[allow(clippy::large_enum_variant)]
3012        enum InstallSpec {
3013            ForComprehension {
3014                idx: crate::scope_tree::ScopeNodeIdx,
3015                iter_vars: Vec<String>,
3016                spec_exprs: Vec<String>,
3017                /// SRD-13f Push E: phase-level `bindings:` folded
3018                /// into the for_each scope kernel when the phase
3019                /// declares both `for_each:` AND `bindings:`. The
3020                /// single install at the phase node materializes
3021                /// one kernel carrying both the iter-var
3022                /// declarations AND the phase-level bindings.
3023                /// Empty for pure-comprehension scope nodes
3024                /// (scenario-level `for_each:`) and for phase
3025                /// nodes without own bindings.
3026                phase_bindings: nmbrs_workload::model::BindingsDef,
3027            },
3028            DoLoop {
3029                idx: crate::scope_tree::ScopeNodeIdx,
3030                counter: Option<String>,
3031                condition: String,
3032            },
3033            /// SRD-13d Phase 9 — install a kernel for an
3034            /// op-template scope that classified as
3035            /// `materialised`. Flattened op-templates
3036            /// (`materialised == false`) get no install spec;
3037            /// their dispensers reach the parent kernel via
3038            /// `nearest_materialised`.
3039            OpTemplate {
3040                idx: crate::scope_tree::ScopeNodeIdx,
3041                op: nmbrs_workload::model::ParsedOp,
3042            },
3043            /// SRD-13d Phase 9 — install a phase-scope kernel
3044            /// for a phase that declares its own `bindings:`
3045            /// block (and no `for_each:` — that case is owned
3046            /// by the for_each install spec at the same node).
3047            /// Phases without bindings AND without for_each
3048            /// emit no install spec; the closure-lifetime
3049            /// kernel reference is the parent's by walker
3050            /// fall-through.
3051            /// Phase-scope kernel install for phases declaring
3052            /// their own `bindings:` block (and no `for_each:` —
3053            /// that case is owned by the for_each install spec
3054            /// at the same node). Also covers scenario-tree
3055            /// `bindings:` nodes (and the `set:` sugar that
3056            /// lowers to them) — the synthesizer is identical
3057            /// for both: parent-cascaded externs + the body's
3058            /// authored matter.
3059            Bindings {
3060                idx: crate::scope_tree::ScopeNodeIdx,
3061                bindings: nmbrs_workload::model::BindingsDef,
3062            },
3063        }
3064        let install_specs: Vec<InstallSpec> = scope_tree
3065            .iter_dfs()
3066            .filter_map(|(idx, node)| match &node.kind {
3067                crate::scope_tree::ScopeKind::Comprehension { comprehension } => {
3068                    // Representative iter_vars + spec_exprs for
3069                    // synthesis: dedup'd by var name. Walks the
3070                    // algebra AST directly via coordinate_specs
3071                    // — same dedup semantics the legacy
3072                    // scalar_bindings/Union-flatten path
3073                    // produced.
3074                    let pairs = comprehension.coordinate_specs();
3075                    let vars: Vec<String> = pairs.iter().map(|(v, _)| v.clone()).collect();
3076                    let specs: Vec<String> = pairs.iter().map(|(_, e)| e.clone()).collect();
3077                    Some(InstallSpec::ForComprehension {
3078                        idx,
3079                        iter_vars: vars,
3080                        spec_exprs: specs,
3081                        // Scope-tree Comprehension nodes (scenario-
3082                        // level `for_each:`) carry no phase-level
3083                        // bindings; the wrapping phase has its own
3084                        // scope-tree node and its own install spec
3085                        // (PhaseBindings or another ForComprehension).
3086                        phase_bindings: nmbrs_workload::model::BindingsDef::default(),
3087                    })
3088                }
3089                crate::scope_tree::ScopeKind::DoWhile { condition, counter } => {
3090                    Some(InstallSpec::DoLoop {
3091                        idx,
3092                        counter: counter.clone(),
3093                        condition: condition.clone(),
3094                    })
3095                }
3096                crate::scope_tree::ScopeKind::DoUntil { condition, counter } => {
3097                    Some(InstallSpec::DoLoop {
3098                        idx,
3099                        counter: counter.clone(),
3100                        condition: condition.clone(),
3101                    })
3102                }
3103                crate::scope_tree::ScopeKind::Phase { name } => {
3104                    // Phase-scope kernel installation, matter-gated
3105                    // per SRD-13d / SRD-67. Three cases:
3106                    //
3107                    //   1. Phase declares `for_each:` — treat as
3108                    //      a single-clause tuple comprehension.
3109                    //      The for_each scope owns the phase
3110                    //      node's kernel; phase `bindings:` (if
3111                    //      also present) need to fold into that
3112                    //      scope's matter (deferred — the legacy
3113                    //      parser-merge path keeps the bindings
3114                    //      reachable via op-bindings until the
3115                    //      for_each-with-bindings synthesizer
3116                    //      lands).
3117                    //
3118                    //   2. Phase declares only `bindings:` — own
3119                    //      subscope from those bindings layered
3120                    //      over the parent kernel.
3121                    //
3122                    //   3. Neither — no install spec; phase
3123                    //      scope's closure inherits the parent's
3124                    //      kernel reference via the walker's
3125                    //      fall-through (the matter-gated
3126                    //      pass-through).
3127                    let phase = phases.get(name.as_str())?;
3128                    if let Some(spec) = phase.for_each.as_ref() {
3129                        if !phase.metrics.is_empty() {
3130                            // Phase-level `metrics:` + phase-level
3131                            // `for_each:` isn't supported in the
3132                            // initial ship: the for_each scope
3133                            // synthesiser doesn't yet thread the
3134                            // metric-binding augmentation through, and
3135                            // the per-iteration completion-pull
3136                            // semantics want their own design pass.
3137                            // Reject loudly rather than silently
3138                            // dropping the metrics.
3139                            crate::diag!(
3140                                crate::observer::LogLevel::Error,
3141                                "phase '{name}': phase-level `metrics:` + phase-level \
3142                                 `for_each:` is not supported yet. Move the for_each to \
3143                                 scenario-tree level (so each iteration is its own phase \
3144                                 activation, each with its own metrics), or drop one. \
3145                                 Phase will be skipped.",
3146                            );
3147                            return None;
3148                        }
3149                        if phase.poll.is_some() {
3150                            // SRD-75: phase-poll + phase-level
3151                            // for_each isn't supported in the
3152                            // initial ship. The for_each scope
3153                            // synthesizer doesn't yet thread the
3154                            // poll augmentation through, and the
3155                            // combination's semantics
3156                            // (iterate-and-synchronize-each-cell?
3157                            // iterate-while-synchronizing?) wants
3158                            // its own design pass. Reject loudly.
3159                            crate::diag!(
3160                                crate::observer::LogLevel::Error,
3161                                "phase '{name}': `poll:` + phase-level `for_each:` is not \
3162                                 supported in the initial ship of SRD-75. Move the for_each \
3163                                 to scenario-tree level (so each iter is its own phase \
3164                                 activation), or drop one of the two. Phase will be skipped.",
3165                            );
3166                            return None;
3167                        }
3168                        // Delegate the for_each grammar to polydat (the
3169                        // single owner): `parse_inline` handles single- AND
3170                        // multi-clause, and `coordinate_specs()` yields the
3171                        // per-clause (var, spec) pairs — identical to the
3172                        // scenario-level path above. A single-clause spec
3173                        // yields exactly one pair, preserving prior behaviour.
3174                        let comp = match polydat::iteration::comprehension::spec::parse_inline(spec)
3175                        {
3176                            Ok(c) => c,
3177                            Err(e) => {
3178                                crate::diag!(
3179                                    crate::observer::LogLevel::Error,
3180                                    "phase '{name}' for_each '{spec}': {e}"
3181                                );
3182                                return None;
3183                            }
3184                        };
3185                        let pairs = comp.coordinate_specs();
3186                        let iter_vars: Vec<String> = pairs.iter().map(|(v, _)| v.clone()).collect();
3187                        let spec_exprs: Vec<String> =
3188                            pairs.iter().map(|(_, e)| e.clone()).collect();
3189                        // SRD-13f Push E: phases declaring both `for_each:`
3190                        // and `bindings:` fold the bindings into the for_each
3191                        // scope kernel (one kernel, one install). Pure-for_each
3192                        // phases pass an empty `BindingsDef` (no-op).
3193                        //
3194                        // Route through the SAME phase-scope synthesis the
3195                        // non-for_each branch uses, so phase-level `metrics:` /
3196                        // `poll:` and an inline `optimize.objective` (SRD-86)
3197                        // are folded into the for_each kernel too — not just the
3198                        // author's raw `bindings:`. The synthesizer returns the
3199                        // raw bindings unchanged when there is nothing to add,
3200                        // so plain for_each phases are unaffected.
3201                        let phase_bindings =
3202                            match crate::scope::synthesize_phase_scope_bindings(phase) {
3203                                Ok(b) => b,
3204                                Err(e) => {
3205                                    crate::diag!(
3206                                        crate::observer::LogLevel::Error,
3207                                        "phase '{name}': phase-scope synthesis: {e}"
3208                                    );
3209                                    return None;
3210                                }
3211                            };
3212                        Some(InstallSpec::ForComprehension {
3213                            idx,
3214                            iter_vars,
3215                            spec_exprs,
3216                            phase_bindings,
3217                        })
3218                    } else {
3219                        // SRD-75: when the phase declares `poll:`,
3220                        // synthesise capture-as-shared-cell
3221                        // declarations + the `__poll_until`
3222                        // predicate binding into the phase scope's
3223                        // bindings, even when the phase has no
3224                        // author-declared `bindings:` of its own.
3225                        // The synthesised bindings flow through the
3226                        // same `build_phase_scope_kernel` path as
3227                        // any other phase-level bindings; phase-
3228                        // poll has no synthesizer-specific code
3229                        // path.
3230                        let synth = match crate::scope::synthesize_phase_scope_bindings(phase) {
3231                            Ok(b) => b,
3232                            Err(e) => {
3233                                crate::diag!(
3234                                    crate::observer::LogLevel::Error,
3235                                    "phase '{name}': SRD-75 phase-poll synthesis: {e}",
3236                                );
3237                                return None;
3238                            }
3239                        };
3240                        if !synth.is_empty() {
3241                            Some(InstallSpec::Bindings {
3242                                idx,
3243                                bindings: synth,
3244                            })
3245                        } else {
3246                            None
3247                        }
3248                    }
3249                }
3250                crate::scope_tree::ScopeKind::OpTemplate { name } => {
3251                    // SRD-13d Phase 9: install a per-op kernel
3252                    // ONLY for materialised op-templates. The
3253                    // scope-elision pre-walk already set the
3254                    // mark; we just gate on it here.
3255                    if node.materialised != Some(true) {
3256                        return None;
3257                    }
3258                    // Find the ParsedOp by walking up to the
3259                    // OWNING phase first, then resolving by name
3260                    // within that phase. Two phases can both
3261                    // declare an op named e.g. `select_ann` with
3262                    // very different bodies; a flat
3263                    // `phases.values().flat_map(|p| p.ops.iter())
3264                    // .find(...)` would pick whichever phase the
3265                    // HashMap iterator yielded first, silently
3266                    // compiling pvs_query's body into ann_query's
3267                    // op-template kernel (and vice versa).
3268                    let owning_phase: Option<&str> = {
3269                        let mut cursor = scope_tree.nodes[idx].parent;
3270                        let mut found: Option<&str> = None;
3271                        while let Some(p) = cursor {
3272                            if let crate::scope_tree::ScopeKind::Phase { name: pname } =
3273                                &scope_tree.nodes[p].kind
3274                            {
3275                                found = Some(pname.as_str());
3276                                break;
3277                            }
3278                            cursor = scope_tree.nodes[p].parent;
3279                        }
3280                        found
3281                    };
3282                    owning_phase
3283                        .and_then(|pname| phases.get(pname))
3284                        .and_then(|phase| phase.ops.iter().find(|op| op.name == *name))
3285                        .cloned()
3286                        .map(|op| InstallSpec::OpTemplate { idx, op })
3287                }
3288                crate::scope_tree::ScopeKind::Bindings { source } => {
3289                    // Scenario-tree `bindings:` block (also the
3290                    // canonical lowered form of `set:` sugar)
3291                    // installs through the same synthesizer
3292                    // phases use for their own `bindings:`. The
3293                    // body source compiles into a scope kernel
3294                    // that publishes its `final`/`init`/cycle
3295                    // bindings as outputs; descendants read
3296                    // those through the canonical scope chain
3297                    // (no HashMap merges, no side-channel
3298                    // resolvers). Shadowing of upstream names is
3299                    // enforced by the local-final transit-
3300                    // suppression rule in
3301                    // `materialize_wiring_from_outer` — uniform
3302                    // with every other scope.
3303                    Some(InstallSpec::Bindings {
3304                        idx,
3305                        bindings: nmbrs_workload::model::BindingsDef::PolydatSource(source.clone()),
3306                    })
3307                }
3308                _ => None,
3309            })
3310            .collect();
3311
3312        for install_spec in install_specs {
3313            let idx = match &install_spec {
3314                InstallSpec::ForComprehension { idx, .. } => *idx,
3315                InstallSpec::DoLoop { idx, .. } => *idx,
3316                InstallSpec::OpTemplate { idx, .. } => *idx,
3317                InstallSpec::Bindings { idx, .. } => *idx,
3318            };
3319            // Nearest installed ancestor — skips Scenario /
3320            // IncludedScenario nodes that don't install kernels
3321            // (those are pass-through structural).
3322            let parent_kernel = {
3323                let mut cursor = scope_tree.nodes[idx].parent;
3324                let mut found: Option<std::sync::Arc<crate::scope_kernel::ScopeKernel>> = None;
3325                while let Some(p) = cursor {
3326                    if let Some(k) = scope_tree.nodes[p].cached_kernel.get() {
3327                        found = Some(k.clone());
3328                        break;
3329                    }
3330                    cursor = scope_tree.nodes[p].parent;
3331                }
3332                found.expect("workload root always has an installed kernel")
3333            };
3334            let parent_manifest = extract_manifest(parent_kernel.program());
3335            let context = format!("scope idx {idx} ({})", scope_tree.nodes[idx].kind.label(),);
3336
3337            let result = match install_spec {
3338                InstallSpec::ForComprehension {
3339                    iter_vars,
3340                    spec_exprs,
3341                    phase_bindings,
3342                    ..
3343                } => {
3344                    let bindings: Vec<(String, String)> = iter_vars
3345                        .iter()
3346                        .cloned()
3347                        .zip(spec_exprs.iter().cloned())
3348                        .collect();
3349                    // SRD-13f Push E: translate phase-level
3350                    // `bindings:` into the Polydat source the
3351                    // for_each synthesiser folds in. PolydatSource
3352                    // form passes verbatim; Map form serialises
3353                    // to `name := expr\n` lines.
3354                    let phase_bindings_source = match phase_bindings {
3355                        nmbrs_workload::model::BindingsDef::PolydatSource(s)
3356                            if !s.trim().is_empty() =>
3357                        {
3358                            Some(s)
3359                        }
3360                        nmbrs_workload::model::BindingsDef::Map(m) if !m.is_empty() => {
3361                            let mut out = String::new();
3362                            for (name, expr) in &m {
3363                                out.push_str(&format!("{name} := {expr}\n"));
3364                            }
3365                            Some(out)
3366                        }
3367                        _ => None,
3368                    };
3369                    crate::scope_synth::build_for_each_scope_kernel(
3370                        &bindings,
3371                        &parent_manifest,
3372                        &parent_kernel,
3373                        &workload_params,
3374                        polydat_lib_paths.clone(),
3375                        workload_dir_owned.as_deref(),
3376                        strict,
3377                        &context,
3378                        phase_bindings_source.as_deref(),
3379                    )
3380                }
3381                InstallSpec::DoLoop {
3382                    counter, condition, ..
3383                } => crate::scope::build_do_loop_scope_kernel(
3384                    counter.as_deref(),
3385                    &condition,
3386                    &parent_manifest,
3387                    &parent_kernel,
3388                    &workload_params,
3389                    polydat_lib_paths.clone(),
3390                    workload_dir_owned.as_deref(),
3391                    strict,
3392                    &context,
3393                ),
3394                InstallSpec::OpTemplate { op, .. } => {
3395                    // SRD-13d Phase 9 — synthesize the op-
3396                    // template kernel layered over the parent.
3397                    // Includes op-level bindings + cascaded
3398                    // parent externs; materialize_wiring_from_outer chains
3399                    // values in at runtime.
3400                    // The scope module stays on the node for the fiber
3401                    // engine's per-op images (`crate::fiber_engine`).
3402                    crate::scope::build_op_template_scope_kernel(
3403                        &op,
3404                        &parent_manifest,
3405                        &parent_kernel,
3406                        &workload_params,
3407                        polydat_lib_paths.clone(),
3408                        workload_dir_owned.as_deref(),
3409                        strict,
3410                        kernel_opt,
3411                        &context,
3412                    )
3413                }
3414                InstallSpec::Bindings { bindings, .. } => {
3415                    // Single install path for both phase-level
3416                    // `bindings:` and scenario-tree-level
3417                    // `bindings:` (including the `set:` sugar
3418                    // form that lowers to it). The synthesizer
3419                    // cascades workload params + parent
3420                    // outputs/inputs as externs and appends the
3421                    // body verbatim; Polydat handles workload-param
3422                    // interpolation and expression evaluation
3423                    // at compile time. Lexical shadowing of an
3424                    // upstream `final NAME` by the body's own
3425                    // `const NAME := …` is enforced by the
3426                    // local-final transit-suppression rule in
3427                    // `materialize_wiring_from_outer`.
3428                    crate::scope::build_phase_scope_kernel(
3429                        &bindings,
3430                        &parent_manifest,
3431                        &parent_kernel,
3432                        &workload_params,
3433                        polydat_lib_paths.clone(),
3434                        workload_dir_owned.as_deref(),
3435                        strict,
3436                        &context,
3437                    )
3438                }
3439            };
3440
3441            match result {
3442                Ok(kernel) => {
3443                    let _ = scope_tree.install_kernel(idx, std::sync::Arc::new(kernel));
3444                }
3445                Err(e) => {
3446                    // Kernel synthesis failure is a hard error
3447                    // regardless of strict mode: a phase whose GK
3448                    // source doesn't compile literally cannot run.
3449                    // Letting the walk continue past the failure
3450                    // only delays the bad news — the phase will
3451                    // fail mid-run with a less helpful diagnostic
3452                    // (or, worse, run with stale / partial
3453                    // kernels installed for sibling scopes). The
3454                    // earlier "warn-and-continue" behavior dates
3455                    // from before strict mode existed; with the
3456                    // strict-mode behavior being the only sane
3457                    // default, the non-strict branch was
3458                    // effectively a footgun that turned compile
3459                    // errors into silent partial runs.
3460                    return Err(format!("scope kernel synthesis failed: {e}"));
3461                }
3462            }
3463        }
3464
3465        crate::diag!(
3466            crate::observer::LogLevel::Info,
3467            "scenario '{scenario_name}':\n{}",
3468            format_scenario_tree(&scenario_nodes, &phases)
3469        );
3470
3471        // Observer is passed from the caller (default: StderrObserver).
3472
3473        // ─── Unified walker: structural pre-map pass ─────────────────
3474        //
3475        // Per SRD 18b §"Single Walker Contract", there is ONE walker
3476        // function (`crate::executor::execute_tree`). It runs twice
3477        // here: first at depth=Phase to populate the scene tree (so
3478        // resume_plan / declare_scene_tree_phases / pre_map_pending_uses
3479        // can read the populated tree), then again at the configured
3480        // depth to actually execute. SceneTree::push is idempotent
3481        // by `(parent, kind, name)` so the second pass re-encounters
3482        // every node from the first without duplicating.
3483        //
3484        // The pre-map ExecCtx uses stub post-pre-map fields
3485        // (checkpoint_writer = None, fresh resume_plan, fresh
3486        // resource_pool); they're updated to the real values after
3487        // pre-map produces the tree.
3488        let schedule_spec = std::sync::Arc::new(match params.get("schedule") {
3489            Some(s) => crate::scheduler::ScheduleSpec::parse(s)
3490                .map_err(|e| format!("schedule= param: {e}"))?,
3491            None => crate::scheduler::ScheduleSpec::default_serial(),
3492        });
3493        // `&str` → `&'static str` so the activity config can
3494        // carry the mode label across thread boundaries
3495        // without lifetime gymnastics. Every mode the resolver
3496        // above produces must appear here, otherwise the
3497        // wrapper-install path silently sees `None` and
3498        // DRYRUN never installs.
3499        let dry_run_static: Option<&'static str> = match dry_run {
3500            Some("silent") => Some("silent"),
3501            Some("fields") => Some("fields"),
3502            Some("cycle") => Some("cycle"),
3503            Some("op") => Some("op"),
3504            _ => None,
3505        };
3506
3507        // phases=<pattern> filter (bareword / glob / regex). When
3508        // unset, every phase runs. When set, the planner's
3509        // scenario-tree walker skips phase activations whose name
3510        // doesn't match AND elides scope subtrees with no
3511        // matching descendant.
3512        let phase_filter: Option<Arc<crate::phase_filter::PhasePattern>> = match params
3513            .get("phases")
3514            .map(|s| s.as_str())
3515            .filter(|s| !s.is_empty())
3516        {
3517            None => None,
3518            Some(src) => {
3519                let pat = crate::phase_filter::PhasePattern::parse(src)
3520                    .map_err(|e| format!("phases= param: {e}"))?;
3521                crate::diag!(
3522                    crate::observer::LogLevel::Info,
3523                    "phases=<filter>: pattern '{src}' ({}{})",
3524                    if pat.negated() { "negated " } else { "" },
3525                    pat.dialect().as_str()
3526                );
3527                Some(Arc::new(pat))
3528            }
3529        };
3530        let resource_pool = Arc::new(crate::resource_pool::ResourcePool::new());
3531        // SRD-104 — point the resource bridge every kernel tree resolves
3532        // through at this session's pool, so kernel nodes can reach a live
3533        // pool-owned resource (e.g. a CQL session handle) by fingerprint via
3534        // their tree's resource scope. The pool stays the definitive owner.
3535        crate::resource_pool::install_accessor(&resource_pool);
3536        let initial_scene_tree_path = vec![crate::checkpoint::PathSegment::Scenario(
3537            scenario_name.to_string(),
3538        )];
3539        // SRD-82 — the session root error policy. Every shell resolves
3540        // its own from this (inherit or derive); equal configs share
3541        // one instance, parsed once per session.
3542        let root_error_policy = crate::error_policy::ErrorPolicy::root(
3543            crate::error_policy::PolicyConfig::new(error_spec.clone(), error_rate_max),
3544        );
3545        // SRD-83 — build the workload execution shell (SRD-82's
3546        // outermost shell). Its stop conditions are the workload's
3547        // `stop_when:` declarations whose `each:` names the workload
3548        // itself (`self`/`workload`), compiled once against the
3549        // workload root's cached kernel — the same native-scope binding
3550        // every other shell uses, never a conjured root. The remaining
3551        // `each: phase` declarations fan out to the per-phase activity
3552        // build (see `executor.rs`); the unfiltered list rides on
3553        // `ExecCtx.workload_stop_when` for that gathering.
3554        //
3555        // The error-rate breach stays a per-phase concern (each phase
3556        // already trips on its own `error_rate_max`), so no default
3557        // error-rate condition is installed at the workload aggregate.
3558        let workload_shell = {
3559            use nmbrs_workload::model::ScopeLevel;
3560            // SRD-82 Part 3/6 — the scenario-graph default `*Failed:stop`:
3561            // any child phase whose outcome is Failed halts the remaining
3562            // walk and records `Interrupted + Failed` (a fault). Expressed
3563            // as the SRD-83 stop condition `children_failed > 0` with a
3564            // `fail` effect, so it rides the same workload-shell mechanism
3565            // as declared conditions and reaches concurrent / cross-subtree
3566            // siblings the local `Err` cascade can't. First in the list →
3567            // a failed child trips it before any declared graceful rule.
3568            let mut conditions: Vec<crate::stop_conditions::StopConditionDecl> =
3569                vec![crate::stop_conditions::StopConditionDecl {
3570                    when: "children_failed > 0".to_string(),
3571                    effect: crate::phase_outcome::Outcome::failed(),
3572                    reason: None,
3573                    target: crate::stop_conditions::StopScope::Workload,
3574                    // The default stop-on-error drains cooperatively.
3575                    cancel_ops: false,
3576                }];
3577            // Declared workload-level conditions (`each ∋ self|workload`).
3578            // A declared trip defaults to a graceful `stop`
3579            // (Interrupted+Succeeded): nothing failed, later phases are
3580            // deliberately skipped.
3581            conditions.extend(
3582                workload
3583                    .stop_when
3584                    .iter()
3585                    .filter(|c| {
3586                        c.each
3587                            .iter()
3588                            .any(|l| matches!(l, ScopeLevel::SelfScope | ScopeLevel::Workload))
3589                    })
3590                    .map(|c| crate::stop_conditions::StopConditionDecl {
3591                        // Same `{param}` interpolation as phase-level stop_when
3592                        // (executor build_activity_config_for_phase) so a workload
3593                        // breaker threshold can be a modular workload param.
3594                        when: expand_workload_params(&c.when, &workload_params),
3595                        effect: crate::stop_conditions::StopConditionDecl::effect_from_str(
3596                            c.effect.as_deref(),
3597                            crate::phase_outcome::Outcome::interrupted(),
3598                        ),
3599                        reason: None,
3600                        // Detected at the workload shell; `at:` (default =
3601                        // innermost of `per:`/`each:`, here `workload`) selects
3602                        // the action scope.
3603                        target: crate::executor::resolve_stop_scope(c.at, &c.each),
3604                        // `action: abort` → cancel in-flight ops at the trip site.
3605                        cancel_ops: crate::stop_conditions::StopConditionDecl::action_cancels_ops(
3606                            c.effect.as_deref(),
3607                        ),
3608                    }),
3609            );
3610            let set = match scope_tree.nodes[scope_tree.workload_root_idx()]
3611                .cached_kernel
3612                .get()
3613            {
3614                Some(root_kernel) => crate::stop_conditions::StopConditionSet::build_for_phase(
3615                    root_kernel,
3616                    &conditions,
3617                )
3618                .unwrap_or_else(|e| {
3619                    crate::diag!(
3620                        crate::observer::LogLevel::Error,
3621                        "workload stop-condition compile failed: {e}"
3622                    );
3623                    crate::stop_conditions::StopConditionSet::empty()
3624                }),
3625                _ => crate::stop_conditions::StopConditionSet::empty(),
3626            };
3627            std::sync::Arc::new(crate::workload_shell::WorkloadShell::new(set))
3628        };
3629
3630        // SRD-71 P3 — phase-scoped CLI parameter overrides
3631        // (`<phase-pattern>.<param>=<value>`). Parsed from the raw
3632        // args (parse_params skips dotted keys), validated against
3633        // the declared phase names so a never-matching pattern is
3634        // a startup error instead of a silent no-op.
3635        let phase_param_overrides =
3636            std::sync::Arc::new(crate::phase_params::parse_overrides(&args)?);
3637        crate::phase_params::validate_against_phases(
3638            &phase_param_overrides,
3639            phases.keys().map(|s| s.as_str()),
3640        )?;
3641
3642        let mut exec_ctx = crate::executor::ExecCtx {
3643            phases: phases.clone(),
3644            optimize_objective: None,
3645            optimize_objective_value: None,
3646            optimize_servo: None,
3647            phase_param_overrides,
3648            workload_shell,
3649            workload_stop_when: workload.stop_when.clone(),
3650            daemon_stop: None,
3651            workload_readouts: workload_readouts.clone(),
3652            cli_readout_override: cli_readout_override.clone(),
3653            workload_params: workload_params.clone(),
3654            wrappers_override: workload_wrappers_override.clone(),
3655            wrap_default_order: cli_wrap_default_order.clone(),
3656            workload_scope: builder.source_kernel().clone(),
3657            polydat_lib_paths: polydat_lib_paths.clone(),
3658            workload_dir: workload_dir.map(|p| p.to_path_buf()),
3659            strict,
3660            driver: driver.clone(),
3661            merged_params: merged_params.clone(),
3662            dry_run: dry_run_static,
3663            phase_filter: phase_filter.clone(),
3664            refine_plan: refine_plan.clone(),
3665            diag: {
3666                let mut d = diag.clone();
3667                d.depth = ExecDepth::Phase;
3668                d
3669            },
3670            // The pre-map pass walks at depth=Phase but is NOT
3671            // execution: the structural-only sentinel that fires
3672            // `set_phase_running` + `_completed` in the walker
3673            // (intended for the dryrun=phase summary) is
3674            // suppressed via this flag so the TUI's scene tree
3675            // doesn't start life with every phase already
3676            // Completed. Flipped back to false at line ~2675
3677            // before the real execution pass.
3678            pre_map_only: true,
3679            seq_type,
3680            concurrency,
3681            rate,
3682            error_spec: error_spec.clone(),
3683            tries,
3684            error_rate_max,
3685            error_policy: root_error_policy,
3686            session_id: session_id.clone(),
3687            exec_id,
3688            workload_name: execution.workload.clone(),
3689            label_stack: Vec::new(),
3690            // SRD-88 §2 — phase/activity components attach under the
3691            // EXECUTION component (which declares `exec_id` +
3692            // `workload`), not the session root. The session root
3693            // is the shared `session=<id>` ancestor above it.
3694            session_component: execution.component.clone(),
3695            cadence_reporter: cadence_reporter.clone(),
3696            stop_handle: stop_handle.clone(),
3697            observer: observer.clone(),
3698            scope_tree: scope_tree.clone(),
3699            schedule_spec: schedule_spec.clone(),
3700            current_parent_kernel: scope_tree.nodes[scope_tree.workload_root_idx()]
3701                .cached_kernel
3702                .get()
3703                .cloned(),
3704            workload_source: workload_file.as_ref().and_then(|path| {
3705                workload_source_text.as_ref().map(|text| {
3706                    std::sync::Arc::new(crate::executor::WorkloadSource {
3707                        path: path.clone(),
3708                        text: text.clone(),
3709                    })
3710                })
3711            }),
3712            // Stub post-pre-map fields: replaced after the pre-map
3713            // walk populates the scene tree. Pre-map walks at depth
3714            // Phase, so no run_phase / run_do_loop / checkpoint
3715            // events fire — the stubs are not consulted.
3716            checkpoint_writer: None,
3717            resume_plan: std::sync::Arc::new(crate::checkpoint::ResumePlan::fresh()),
3718            sqlite_reporter: sqlite_reporter.clone(),
3719            resource_pool: resource_pool.clone(),
3720            scene_tree_parent_id: 0,
3721            scene_tree_path: initial_scene_tree_path.clone(),
3722            current_scope_idx: 0,
3723        };
3724
3725        // One Walker: seed the scope cursor at the scenario layer (the single
3726        // child of the workload root) so the top-level scenario nodes resolve
3727        // positionally against its children, not by AST match.
3728        exec_ctx.current_scope_idx = exec_ctx.scope_tree.scenario_root_idx();
3729
3730        // Install empty SceneTree global; the walker populates it.
3731        crate::scene_tree::install_global(crate::scene_tree::SceneTree::new());
3732
3733        // Pre-map structural pass. Errors propagate in strict mode
3734        // (SRD-15 §"Empty Iteration Sources"); otherwise the walker
3735        // logs and continues — downstream code handles the partial
3736        // / empty tree.
3737        let pre_map_result = crate::executor::execute_tree(&mut exec_ctx, &scenario_nodes).await;
3738        let pre_mapped_tree = match pre_map_result {
3739            Ok(()) => {
3740                let tree = crate::scene_tree::current();
3741                if let Some(ref t) = tree {
3742                    observer.scenario_pre_mapped(t);
3743                }
3744                tree
3745            }
3746            Err(e) if strict => return Err(e),
3747            Err(e) => {
3748                crate::diag!(
3749                    crate::observer::LogLevel::Warn,
3750                    "pre-map walker failed (scope hierarchy will be flat in summaries / TUI): {e}"
3751                );
3752                None
3753            }
3754        };
3755
3756        // dryrun=kernels short-circuit: pre-map already ran;
3757        // the install-kernel visitor (registered above before
3758        // execute_tree) streamed each scope's polydat source
3759        // to stdout as the walk encountered it. Print the
3760        // legend + exit cleanly.
3761        if params.get("dryrun").map(|s| s.as_str()) == Some("kernels") {
3762            print_kernel_dump_legend();
3763            crate::scope_tree::set_kernel_install_visitor(None);
3764            return Ok(());
3765        }
3766
3767        // --- Checkpoint writer + resume plan (SRD-44 / SRD-44a) ---
3768        //
3769        // The writer file lives at `<session-dir>/checkpoint.jsonl`
3770        // — an append-only JSONL event log per SRD-44a. Resume from
3771        // an explicit prior session is wired through the
3772        // `--resume <session>` / `--resume-latest` CLI surface
3773        // (see runner CLI parsing); for a fresh session the writer
3774        // starts empty and the plan reruns everything.
3775        // SRD-88 — the writer + resume doc are SESSION-tier (created
3776        // once in `SessionHost::setup`, holding the single resume lock).
3777        // This execution shares them; it derives its own resume plan
3778        // below from `saved_doc` + its pre-map.
3779        let checkpoint_writer = host.checkpoint_writer.clone();
3780        let saved_doc = host.saved_doc.clone();
3781        let invocation = saved_doc.as_ref().map(|d| d.invocation + 1).unwrap_or(1);
3782
3783        // End-of-run notices: drops on success OR error path.
3784        //
3785        //  - Resume hint: when checkpoint state shows
3786        //    incomplete idempotent phases (SRD-44), advise the
3787        //    operator how to resume.
3788        //  - Keep-purge forecast: when the next new session
3789        //    would auto-purge sessions under the keep cap
3790        //    (SRD-45), let the operator know how many and how
3791        //    to disable.
3792        let parent_for_keep_check = if let Some(p) = session.output_dir.parent() {
3793            p.to_path_buf()
3794        } else {
3795            crate::session::default_sessions_root()
3796        };
3797        let session_keep = crate::session::resolve_session_dir(&args).session_keep;
3798        struct EndOfRunNoticeGuard {
3799            writer: std::sync::Arc<crate::checkpoint::CheckpointWriter>,
3800            parent: std::path::PathBuf,
3801            keep_cap: usize,
3802        }
3803        impl Drop for EndOfRunNoticeGuard {
3804            fn drop(&mut self) {
3805                if let Some(hint) = self.writer.resume_hint() {
3806                    // Through the observer, one line per log call —
3807                    // NOT a raw eprintln!: this drop can fire while
3808                    // the TUI still holds the terminal in raw mode,
3809                    // where a bare `\n` does not return the carriage
3810                    // and a stderr write bypasses the render sink —
3811                    // each line then starts at the previous line's
3812                    // end column (the end-of-session staircase,
3813                    // observed 2026-08-05). The log path is owned by
3814                    // the surface channel (SRD-87) in both TUI and
3815                    // plain modes, so it renders correctly in each.
3816                    for line in hint.lines() {
3817                        crate::diag!(crate::observer::LogLevel::Info, "{line}");
3818                    }
3819                }
3820                let n = crate::session::forecast_keep_purge(&self.parent, self.keep_cap);
3821                if n > 0 {
3822                    crate::diag!(
3823                        crate::observer::LogLevel::Info,
3824                        "the next new nmbrs session will auto-purge {n} prior session \
3825                         director{plural} under {} due to --session-keep={cap}. \
3826                         To disable: --session-keep=0 (or NMBRS_SESSION_KEEP=0). \
3827                         To raise the cap: --session-keep=<bigger>.",
3828                        self.parent.display(),
3829                        plural = if n == 1 { "y" } else { "ies" },
3830                        cap = self.keep_cap,
3831                    );
3832                }
3833            }
3834        }
3835        let _eor_notice_guard = EndOfRunNoticeGuard {
3836            writer: checkpoint_writer.clone(),
3837            parent: parent_for_keep_check,
3838            keep_cap: session_keep,
3839        };
3840        let resume_plan =
3841            if let (Some(saved), Some(tree)) = (saved_doc.as_ref(), pre_mapped_tree.as_ref()) {
3842                let candidates =
3843                    crate::checkpoint::scene_tree_resume_candidates(tree, &scope_tree, &phases);
3844                std::sync::Arc::new(crate::checkpoint::ResumePlan::from_checkpoint(
3845                    saved,
3846                    &candidates,
3847                    &workload_params,
3848                ))
3849            } else {
3850                std::sync::Arc::new(crate::checkpoint::ResumePlan::fresh())
3851            };
3852
3853        // Declare every pre-mapped phase into the writer so a
3854        // future resume can tell "didn't run yet" from "wasn't
3855        // planned". Idempotent — re-declaring an entry the
3856        // writer already restored from disk is a no-op.
3857        if let Some(tree) = pre_mapped_tree.as_ref() {
3858            crate::checkpoint::declare_scene_tree_phases(&checkpoint_writer, tree, &phases);
3859        }
3860
3861        if resume_plan.is_resume {
3862            let skip = resume_plan.skip_count();
3863            let mismatch = resume_plan.mismatch_count();
3864            let cursor = resume_plan.cursor_resume_count();
3865            crate::diag!(
3866                crate::observer::LogLevel::Info,
3867                "resume: invocation #{invocation} — \
3868                 {skip} skip, {mismatch} mismatched, {cursor} cursor-resume"
3869            );
3870        }
3871
3872        // SRD-35 Push D: seed the resource pool's per-key
3873        // `pending_uses` counter before any phase runs. The
3874        // walker is a pure read of the pre-mapped tree +
3875        // session-level params; it doesn't instantiate any
3876        // adapter or open any resource. After this, the pool
3877        // can close `Shared`/`PerScenario` entries the moment
3878        // their last predicted phase detaches, instead of
3879        // holding them until session end.
3880        if let Some(tree) = pre_mapped_tree.as_ref() {
3881            crate::resource_pool::pre_map_pending_uses(
3882                &resource_pool,
3883                tree,
3884                &phases,
3885                &driver,
3886                &merged_params,
3887            )?;
3888        }
3889
3890        // ─── Unified walker: execution pass ──────────────────────────
3891        //
3892        // Update the post-pre-map fields on the same `exec_ctx`
3893        // used for the pre-map pass: real `checkpoint_writer`,
3894        // resolved `resume_plan`, restored execution depth. Per
3895        // SRD 18b §"Single Walker Contract" point 1, this is the
3896        // SAME walker function — `execute_tree` — invoked again at
3897        // the configured depth. SceneTree::push is idempotent so
3898        // every node the pre-map pass pushed is reused.
3899        exec_ctx.checkpoint_writer = Some(checkpoint_writer.clone());
3900        exec_ctx.resume_plan = resume_plan.clone();
3901        exec_ctx.diag = diag.clone();
3902        exec_ctx.scene_tree_parent_id = 0;
3903        exec_ctx.scene_tree_path = initial_scene_tree_path.clone();
3904        // One Walker: seed at the scenario layer (see the pre-map seed above).
3905        exec_ctx.current_scope_idx = exec_ctx.scope_tree.scenario_root_idx();
3906        // Pre-map pass is done — the real execution starts now.
3907        // dryrun=phase still walks at depth=Phase but with this
3908        // flag false, so the sentinel set_phase_completed in the
3909        // walker fires as the dryrun=phase summary needs.
3910        exec_ctx.pre_map_only = false;
3911
3912        let scheduler = crate::scheduler::build(&schedule_spec);
3913        let scheduler_result = scheduler.run(&mut exec_ctx, &scenario_nodes).await;
3914
3915        // SRD-35: drain the resource pool at session end.
3916        // `Shared`/`PerScenario` entries intentionally stay alive
3917        // across phases (the whole reason the pool exists), so
3918        // this is the close trigger that releases their network
3919        // resources. Runs even if the scenario errored out —
3920        // half-open clusters would otherwise leak FDs into the
3921        // next session in TUI / `metrics watch` host processes.
3922        exec_ctx.resource_pool.shutdown().await;
3923        // SRD-93 stage 6 — a ladder-driven interrupt (level 1/2)
3924        // unwinds the walk as an `Err`, which the `?` below would
3925        // propagate PAST the SRD-77 row close-out at the end of this
3926        // function — leaving `disposition` NULL, the marker reserved
3927        // for genuinely unclean exits (force-exit, panic, SIGKILL). A
3928        // cooperative drain IS a clean shutdown: stamp the row with
3929        // the scene tree's computed disposition (interrupted / failed
3930        // / …) before the error propagates. `update_execution_end`
3931        // keys on `ended_at_nanos IS NULL`, so the normal-completion
3932        // stamp below stays a no-op after this one.
3933        if scheduler_result.is_err() {
3934            close_execution_row(&sqlite_reporter, &session_id, exec_id);
3935        }
3936        scheduler_result?;
3937
3938        // Workload-end lifecycle boundary: every phase in the
3939        // scenario has completed. Individual phase paths already
3940        // closed themselves at phase-end, but any workload-level
3941        // ingests (e.g. aggregate metrics the tree code emits at
3942        // scope scope rather than phase scope) still need a flush.
3943        // In phased mode the workload's label set is the session
3944        // root — there's no intermediate `activity=...` label —
3945        // so we close at the session root.
3946        cadence_reporter.close_path(&Labels::of("session", &session.id));
3947
3948        // SRD-13d Phase 7 — `dryrun=dispenser` scope-elision
3949        // summary. Phase walk has just completed; scope tree
3950        // carries final `materialised` / `logical_name` marks
3951        // (set by the workload-load classifier). Dump now so the
3952        // diagnostic surfaces phase-init artifacts (registered
3953        // metrics, adapter map_op calls) in the same run. Used
3954        // to fire for `Op` depth; since the auto-bump now lifts
3955        // `dryrun=op` to `Cycle` (full cycle execution with
3956        // wrapper short-circuit), the scope-elision surface
3957        // moved to `dryrun=dispenser` — the explicit "build
3958        // every dispenser but don't run cycles" mode.
3959        if diag.depth == ExecDepth::Dispenser {
3960            let mut out = std::io::stdout();
3961            if let Err(e) = render_scope_elision_summary(&scope_tree, &mut out) {
3962                crate::diag!(
3963                    crate::observer::LogLevel::Warn,
3964                    "warning: rendering scope-elision summary: {e}"
3965                );
3966            }
3967        }
3968
3969        // The run reached its end boundary: every fallible step is
3970        // behind us (the epilogue after this block is teardown
3971        // only). Tell the checkpoint writer HERE, as the block's
3972        // last statement — `_eor_notice_guard` drops when this
3973        // block closes, and its resume_hint must read
3974        // declared-but-never-started phases as excluded-by-
3975        // predicate rather than left-behind (SRD-44a; see
3976        // resume_hint). Error `?` returns above skip this, so a
3977        // cut-short run still advises resuming pending phases.
3978        checkpoint_writer.mark_run_reached_end();
3979    }
3980
3981    // Session-end lifecycle boundary. Close the session root path
3982    // for any aggregate windows that were ingested at session level
3983    // (rare today, but the boundary must be explicit — otherwise
3984    // session-level aggregates would only flush during
3985    // `shutdown_flush` at the very end, after all the per-subscriber
3986    // teardown logic had already started).
3987    cadence_reporter.close_path(&Labels::of("session", &session.id));
3988
3989    // SRD-88 — flush THIS execution's windows into the store so the
3990    // summaries below see complete data, without tearing down the
3991    // session-shared cadence reporter.
3992    cadence_reporter
3993        .quiesce(std::time::Duration::from_secs(30))
3994        .await;
3995
3996    // SRD-63 Push 9a: fire `EventType::SessionEnd` once after
3997    // the cadence shutdown but before `run_finished()`.
3998    // Both branches (phased + single-activity) converge
3999    // here, so a single fire covers every run shape.
4000    {
4001        let session_ctx = crate::readout_context::LifecycleContext {
4002            event: crate::lifecycle::EventType::SessionEnd,
4003            subject_name: session.id.clone(),
4004            subject_labels: String::new(),
4005            depth_indent: String::new(),
4006            use_color: crate::observer::use_color(),
4007            stick_reattached: String::new(),
4008        };
4009        crate::readout_context::fire_lifecycle(
4010            crate::lifecycle::EventType::SessionEnd,
4011            &workload_readouts,
4012            None,
4013            &session_ctx,
4014            Some(&sqlite_reporter),
4015        );
4016    }
4017
4018    observer.run_finished();
4019
4020    if dry_run.is_some() {
4021        crate::diag!(crate::observer::LogLevel::Info, "dry-run complete.");
4022    } else {
4023        crate::diag!(crate::observer::LogLevel::Info, "done.");
4024    }
4025
4026    // Build the active set of named summaries.
4027    //
4028    // Precedence:
4029    //   - CLI `summary=<spec>` wins outright — produces a single
4030    //     ad-hoc summary under the synthetic name `default`,
4031    //     overriding any workload-declared map. Matches prior
4032    //     CLI behavior.
4033    //   - Otherwise the workload's `summary:` map (and the
4034    //     `summary.yaml` sidecar fallback already merged into
4035    //     `workload_summaries` above) is used as-is.
4036    //
4037    // An empty map means "no summary at end of run" — same as
4038    // the legacy "no `summary:` field" case.
4039    let active_summaries: HashMap<String, nmbrs_workload::model::SummaryConfig> =
4040        if let Some(cli_summary) = merged_params.get("summary") {
4041            let mut m = HashMap::new();
4042            m.insert(
4043                "default".into(),
4044                nmbrs_workload::model::SummaryConfig::parse(cli_summary),
4045            );
4046            m
4047        } else {
4048            workload_summaries.clone()
4049        };
4050
4051    // SRD-46 output routing for the in-run summary, by item name.
4052    //
4053    // A CLI `summary=<spec>` is an explicit operator request —
4054    // they typed it, so it still echoes to the terminal. A
4055    // workload-declared table goes where its `to:` says, and one
4056    // that declared nothing goes to the session directory ONLY.
4057    // stdout is never implied for automatic rendering: a run's
4058    // stdout is its op output, and a summary carries wall-clock
4059    // values that would make that output differ run to run.
4060    let summary_destinations: HashMap<String, Vec<nmbrs_workload::report::Destination>> = {
4061        use nmbrs_workload::report::Destination as D;
4062        if merged_params.contains_key("summary") {
4063            let mut m = HashMap::new();
4064            m.insert("default".to_string(), vec![D::SessionDir, D::Stdout]);
4065            m
4066        } else {
4067            workload_report
4068                .items()
4069                .filter(|i| matches!(i.kind, nmbrs_workload::report::Kind::Table))
4070                .map(|i| {
4071                    (
4072                        i.name.clone(),
4073                        i.style
4074                            .destinations
4075                            .clone()
4076                            .unwrap_or_else(|| vec![D::SessionDir]),
4077                    )
4078                })
4079                .collect()
4080        }
4081    };
4082
4083    // SRD-46 Details auto-injection: persist run-wide context
4084    // (end time, phase + scenario counts, adapter, …) into
4085    // session_metadata regardless of whether the workload
4086    // declared a `report:` block. Post-run hooks read this to
4087    // build the auto-injected Details section that lands at
4088    // the top of every output markdown file.
4089    if let Ok(mut guard) = sqlite_reporter.lock()
4090        && let Some(ref mut reporter) = *guard
4091    {
4092        let end_time = std::time::SystemTime::now()
4093            .duration_since(std::time::UNIX_EPOCH)
4094            .map(|d| d.as_secs())
4095            .unwrap_or(0);
4096        let sid = session.id.clone();
4097        let exec_id = execution.exec_id;
4098        reporter.set_execution_metadata(&sid, exec_id, "end_time", &end_time.to_string());
4099        reporter.set_execution_metadata(&sid, exec_id, "phase_count", &phases.len().to_string());
4100        reporter.set_execution_metadata(
4101            &sid,
4102            exec_id,
4103            "scenario_count",
4104            &scenarios.len().to_string(),
4105        );
4106        if let Some(wf) = workload_file.as_deref() {
4107            reporter.set_execution_metadata(&sid, exec_id, "workload_file", wf);
4108        }
4109        reporter.set_execution_metadata(&sid, exec_id, "adapter", &driver);
4110    }
4111
4112    if !active_summaries.is_empty() {
4113        // Summary report always comes from SQLite — the
4114        // durable record. The in-memory store exists for GK
4115        // access and reactive control, not for reporting.
4116        if let Ok(mut guard) = sqlite_reporter.lock()
4117            && let Some(ref mut reporter) = *guard
4118        {
4119            // Persist every report item (SRD-46) under
4120            // `report.<name>` keys. Value carries the kind
4121            // keyword (`plot ...` / `table ...`) followed
4122            // by an optional `label "..."` line and then
4123            // the spec body — same shape the report parser
4124            // ingests, so the db-fallback path in
4125            // `nmbrs report` round-trips through the same
4126            // parser the workload uses.
4127            let sid = session.id.clone();
4128            let exec_id = execution.exec_id;
4129            for item in workload_report.items() {
4130                // Single emission point: the workload-side
4131                // serializer. The db-fallback path in
4132                // `nmbrs report` parses this value back
4133                // through `parse_persisted_item`, which
4134                // uses the same grammar — round-trip safe.
4135                let value = item.to_yaml_directive_string();
4136                reporter.set_execution_metadata(
4137                    &sid,
4138                    exec_id,
4139                    &format!("report.{}", item.name),
4140                    &value,
4141                );
4142            }
4143
4144            // Stable ordering for consistent output across
4145            // runs (HashMap iteration is non-deterministic).
4146            let mut names: Vec<&String> = active_summaries.keys().collect();
4147            names.sort();
4148            for name in names {
4149                let cfg = &active_summaries[name];
4150                let (basename, format) =
4151                    nmbrs_metrics::reporters::sqlite::derive_name_and_format(name);
4152                // SRD-77 — the in-run summary is naturally
4153                // scoped to the current execution; qualifier
4154                // narrows to this run's exec_id so a refine
4155                // doesn't render rows from prior runs.
4156                let report_config = report_config_from_summary(cfg, Some(exec_id));
4157                let rendered = reporter.format_summary_with_format(&report_config, &format);
4158                if rendered.is_empty() {
4159                    continue;
4160                }
4161                // SRD-46 routing for this item. Undeclared ⇒
4162                // session directory only.
4163                let dests = summary_destinations
4164                    .get(name.as_str())
4165                    .cloned()
4166                    .unwrap_or_else(|| vec![nmbrs_workload::report::Destination::SessionDir]);
4167                let to_session = dests.contains(&nmbrs_workload::report::Destination::SessionDir);
4168                let to_stdout = dests.contains(&nmbrs_workload::report::Destination::Stdout);
4169                let to_stderr = dests.contains(&nmbrs_workload::report::Destination::Stderr);
4170
4171                let filename = format!("{basename}_summary.{format}");
4172                let summary_path = session.output_dir.join(&filename);
4173                if to_session {
4174                    if let Err(e) = std::fs::write(&summary_path, &rendered) {
4175                        crate::diag!(
4176                            crate::observer::LogLevel::Warn,
4177                            "warning: failed to write summary to {}: {e}",
4178                            summary_path.display()
4179                        );
4180                    } else {
4181                        crate::diag!(
4182                            crate::observer::LogLevel::Info,
4183                            "summary: {}",
4184                            summary_path.display()
4185                        );
4186                    }
4187                }
4188                // Inline print only when the observer is
4189                // not suppressing stderr — i.e. we're in
4190                // tui=off mode and the user can see stdout
4191                // right now. In TUI mode the alternate
4192                // screen is up, so `print!()` here would
4193                // get buffered behind the TUI rendering and
4194                // discarded on teardown. The persona reads
4195                // the *_summary.* files and prints them
4196                // post-shutdown (see `crates/nmbrs/src/run.rs`).
4197                if to_stderr {
4198                    eprint!("{rendered}");
4199                }
4200                if to_stdout {
4201                    // In TUI mode the alternate screen is up, so an
4202                    // inline `print!` would be buffered behind the
4203                    // TUI rendering and discarded on teardown.
4204                    // Defer it to a file the post-run printer
4205                    // flushes once the terminal is back in cooked
4206                    // mode. Routing is decided HERE either way —
4207                    // the post-run printer no longer infers "goes
4208                    // to stdout" from the presence of an artifact.
4209                    if observer.suppresses_stderr() {
4210                        let deferred = session.output_dir.join(DEFERRED_STDOUT_FILE);
4211                        if let Err(e) = std::fs::OpenOptions::new()
4212                            .create(true)
4213                            .append(true)
4214                            .open(&deferred)
4215                            .and_then(|mut f| {
4216                                std::io::Write::write_all(&mut f, rendered.as_bytes())
4217                            })
4218                        {
4219                            crate::diag!(
4220                                crate::observer::LogLevel::Warn,
4221                                "warning: failed to defer summary stdout to {}: {e}",
4222                                deferred.display()
4223                            );
4224                        }
4225                    } else {
4226                        print!("{rendered}");
4227                    }
4228                }
4229            }
4230        }
4231    }
4232
4233    // Refresh convenience symlinks at the logs/ root so
4234    //   logs/metrics.db, logs/summary.md, logs/session.log
4235    // always resolve to this session's artifacts. `logs/latest` (a
4236    // symlink to the whole session dir) is created by Session::new;
4237    // these are per-file counterparts for direct tool access like
4238    // `sqlite3 logs/metrics.db` or `tail -f logs/session.log`.
4239    refresh_latest_file_links(session);
4240
4241    // dryrun=controls: every phase has now been constructed (at
4242    // depth=Phase the executor stops before cycles but still
4243    // attaches components and declares controls). Walk the
4244    // session tree and dump the catalog.
4245    if diag.list_controls {
4246        let mut out = std::io::stdout();
4247        if let Err(e) = render_controls_tree(&session.component, &mut out) {
4248            crate::diag!(
4249                crate::observer::LogLevel::Warn,
4250                "warning: rendering controls: {e}"
4251            );
4252        }
4253    }
4254
4255    // SRD-77 / SRD-93 stage 6 — close out the executions row with
4256    // the computed disposition + end timestamp. Both clean-exit
4257    // paths stamp it: normal completion here, and a ladder-driven
4258    // interrupt at the walk-error site above (which then propagates
4259    // out before reaching this line). Only genuinely unclean exits
4260    // (force-exit, panic, SIGKILL) leave `ended_at_nanos` NULL,
4261    // which the read side surfaces as "execution in flight /
4262    // unclean exit" distinct from a recorded outcome.
4263    close_execution_row(&sqlite_reporter, &session_id, exec_id);
4264
4265    // WAL consolidation runs from the RAII shutdown guard
4266    // bound at the top of this function (`_sqlite_shutdown_guard`).
4267    // The guard's Drop fires reliably across normal return,
4268    // `?` error propagation, and first-Ctrl-C cooperative
4269    // shutdown — every path Rust unwinds through. Second
4270    // Ctrl-C → `process::exit` is the only skip path,
4271    // matching the documented force-exit semantic in
4272    // `session_signals`.
4273
4274    Ok(())
4275}
4276
4277/// SRD-77 / SRD-93 stage 6 — close the in-flight executions row with
4278/// the scene tree's session disposition + an end timestamp. Idempotent
4279/// (`update_execution_end` keys on `ended_at_nanos IS NULL`), so the
4280/// interrupt-path caller and the normal-completion caller compose:
4281/// whichever runs first wins, the other is a no-op.
4282fn close_execution_row(
4283    sqlite_reporter: &std::sync::Arc<
4284        std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>,
4285    >,
4286    session_id: &str,
4287    exec_id: u64,
4288) {
4289    let disposition =
4290        crate::scene_tree::with_global(|t| t.session_disposition().label()).unwrap_or("UNKNOWN");
4291    let ended_at_nanos = std::time::SystemTime::now()
4292        .duration_since(std::time::UNIX_EPOCH)
4293        .map(|d| d.as_nanos() as i64)
4294        .unwrap_or(0);
4295    if let Ok(mut g) = sqlite_reporter.lock()
4296        && let Some(r) = g.as_mut()
4297    {
4298        r.update_execution_end(session_id, exec_id, ended_at_nanos, disposition);
4299    }
4300}
4301
4302/// Core runner: set up the shared session host, run one execution, tear down.
4303/// Diagnostic mode is controlled by the `dryrun=` param.
4304async fn run_impl(
4305    args: &[String],
4306    observer: Arc<dyn crate::observer::RunObserver>,
4307) -> Result<(), String> {
4308    let host = SessionHost::setup(args, observer.clone())?;
4309    let result = run_execution(&host, args, observer).await;
4310    host.shutdown().await;
4311    result
4312}
4313
4314/// SRD-88 — one execution's spec for [`run_executions`]: the workload
4315/// CLI args, the observer that captures its lifecycle/log, and an optional
4316/// per-execution output channel (SRD-87 buckets). `channel = None` falls back
4317/// to the process-global channel; in-process example verification passes a
4318/// `CaptureChannel` so each execution's op stdout is captured separately.
4319pub struct ExecutionSpec {
4320    pub args: Vec<String>,
4321    pub observer: Arc<dyn crate::observer::RunObserver>,
4322    pub channel: Option<Arc<dyn crate::output_channel::OutputChannel>>,
4323}
4324
4325/// SRD-88 — run N executions CONCURRENTLY in one process, all sharing
4326/// ONE session, at most `max_concurrent` in flight. The session
4327/// (`SessionHost`: dir / stores / cadence + scheduler services) is set
4328/// up ONCE and torn down ONCE, after every execution. Each execution
4329/// loads + runs its own workload, derives its own `Execution`
4330/// (distinct allocated `exec_id`) under the shared session component,
4331/// flushes its metrics into the shared store via
4332/// [`CadenceReporter::quiesce`](nmbrs_metrics::cadence_reporter::CadenceReporter::quiesce)
4333/// without tearing the reporter down, and routes its lifecycle/log
4334/// through its own observer (a scoped
4335/// [`ExecutionContext`](crate::execution_context::ExecutionContext)). Results
4336/// come back in input order.
4337///
4338/// `max_concurrent == 1` is the sequential case — the SAME harness, no
4339/// separate path (SRD-02 "One Concurrency Path").
4340pub async fn run_executions(
4341    session_args: &[String],
4342    session_observer: Arc<dyn crate::observer::RunObserver>,
4343    specs: Vec<ExecutionSpec>,
4344    max_concurrent: usize,
4345) -> Result<Vec<Result<(), String>>, String> {
4346    let host = std::sync::Arc::new(SessionHost::setup(session_args, session_observer)?);
4347    let sem = std::sync::Arc::new(tokio::sync::Semaphore::new(max_concurrent.max(1)));
4348    let futs = specs.into_iter().map(|spec| {
4349        let host = host.clone();
4350        let sem = sem.clone();
4351        async move {
4352            // Bound in-flight executions; permit held for the whole run.
4353            let _permit = sem.acquire().await.expect("semaphore not closed");
4354            // Scope this execution's context — a distinct allocated
4355            // `exec_id` + its own observer (+ optional output channel) — so
4356            // deeply-nested fibers, op-output routing, and `run_execution`'s
4357            // exec-identity all resolve to THIS execution.
4358            let ctx = match spec.channel.clone() {
4359                Some(ch) => crate::execution_context::ExecutionContext::with_observer_and_channel(
4360                    spec.observer.clone(),
4361                    ch,
4362                ),
4363                None => {
4364                    crate::execution_context::ExecutionContext::with_observer(spec.observer.clone())
4365                }
4366            };
4367            crate::execution_context::scope(ctx, run_execution(&host, &spec.args, spec.observer))
4368                .await
4369        }
4370    });
4371    let results = futures::future::join_all(futs).await;
4372    // Session teardown — once, after every execution completed (so the
4373    // host is now the sole owner).
4374    match std::sync::Arc::try_unwrap(host) {
4375        Ok(h) => h.shutdown().await,
4376        Err(_) => crate::diag!(
4377            crate::observer::LogLevel::Warn,
4378            "run_executions: session host still referenced at teardown; \
4379             scheduler/WAL will close on drop"
4380        ),
4381    }
4382    Ok(results)
4383}
4384
4385/// Point per-file symlinks under `logs/` at the latest session's
4386/// artifacts. Silently skips files that don't exist (e.g. summary.md
4387/// when no `summary:` was declared). Replaces any existing symlink.
4388///
4389/// Targets route through `logs/latest` (which `Session::new` points
4390/// at the actual session dir) so the convenience links stay
4391/// consistent with `latest`. Skipped entirely when the session
4392/// lives outside `logs/` — `--session-path /tmp/x` is an explicit
4393/// redirect and shouldn't hijack the user's `logs/` symlinks.
4394fn refresh_latest_file_links(session: &crate::session::Session) {
4395    let logs_dir = std::path::Path::new("logs");
4396    // Mirror the gate in `Session::new` — keep these convenience
4397    // links and `logs/latest` synchronized: either both update or
4398    // neither does.
4399    if !crate::session::target_is_under(logs_dir, &session.output_dir) {
4400        return;
4401    }
4402    for file in ["metrics.db", "summary.md", "session.log"] {
4403        let target = session.output_dir.join(file);
4404        if !target.exists() {
4405            continue;
4406        }
4407        let link = logs_dir.join(file);
4408        // Remove any existing entry (symlink or regular file) so we can
4409        // recreate the link. If this fails because nothing's there,
4410        // that's fine.
4411        let _ = std::fs::remove_file(&link);
4412        let rel_target = std::path::Path::new("latest").join(file);
4413        if let Err(e) = crate::session::symlink_any(&rel_target, &link) {
4414            crate::diag!(
4415                crate::observer::LogLevel::Warn,
4416                "warning: failed to link {} → {}: {e}",
4417                link.display(),
4418                rel_target.display()
4419            );
4420        }
4421    }
4422}
4423
4424/// Create an adapter from inventory registrations.
4425///
4426/// `dryrun=cycle` does NOT substitute the adapter here — it means
4427/// "construct a fully-executable cycle path, then suppress only
4428/// the outbound `execute()` at cycle time." The real adapter is
4429/// always created (connecting, preparing statements, gathering
4430/// metadata); the outermost `DryRunWrapper` handles the runtime
4431/// short-circuit. See `nmbrs_runtime::wrappers::DryRunWrapper`.
4432pub async fn create_adapter(
4433    driver: &str,
4434    params: &HashMap<String, String>,
4435) -> Result<Arc<dyn crate::adapter::DriverAdapter>, String> {
4436    let reg = find_adapter_registration(driver)
4437        .ok_or_else(|| crate::adapter::unknown_adapter_error(driver))?;
4438    (reg.create)(params.clone()).await
4439}
4440
4441/// Run an activity without its own capture thread.
4442///
4443/// All metrics flow through the session-level scheduler →
4444/// `CadenceReporter` → `MetricsQuery`. This function just runs the
4445/// activity to completion; lifecycle flush (final delta +
4446/// validation metrics) is handled by the caller (executor).
4447/// Streaming print: one header line for the `dryrun=kernels`
4448/// dump, fired before any kernel installs.
4449fn print_kernel_dump_header() {
4450    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
4451    let (bold, reset) = if is_tty {
4452        ("\x1b[1m", "\x1b[0m")
4453    } else {
4454        ("", "")
4455    };
4456    println!();
4457    println!("{bold}Polydat Scope Kernels{reset}");
4458    println!("{bold}═════════════════════{reset}");
4459    println!();
4460}
4461
4462/// Streaming per-scope visitor callback. Prints the scope's
4463/// logical name + the polydat source the kernel was compiled
4464/// from, indented by the scope's depth.
4465fn print_kernel_for_scope(
4466    node: &crate::scope_tree::ScopeNode,
4467    kernel: &crate::scope_kernel::ScopeKernel,
4468) {
4469    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
4470    let (bold, dim, reset, cyan, magenta, green) = if is_tty {
4471        (
4472            "\x1b[1m", "\x1b[2m", "\x1b[0m", "\x1b[36m", "\x1b[35m", "\x1b[32m",
4473        )
4474    } else {
4475        ("", "", "", "", "", "")
4476    };
4477
4478    let logical = if node.logical_name.is_empty() {
4479        "<unnamed scope>".to_string()
4480    } else {
4481        node.logical_name.clone()
4482    };
4483    let depth_indent = " ".repeat(node.depth);
4484    println!(
4485        "{depth_indent}{green}●{reset} {bold}{cyan}{logical}{reset} \
4486              {dim}(depth={}, kind={:?}){reset}",
4487        node.depth, node.kind
4488    );
4489    let source = kernel.program().source().trim_end();
4490    if source.is_empty() {
4491        println!("{depth_indent}  {dim}(empty kernel — no own bindings){reset}");
4492    } else {
4493        for line in source.lines() {
4494            println!("{depth_indent}  {magenta}│{reset} {line}");
4495        }
4496    }
4497    println!();
4498}
4499
4500/// Footer for the `dryrun=kernels` dump (legend + spacing).
4501fn print_kernel_dump_legend() {
4502    let is_tty = std::io::IsTerminal::is_terminal(&std::io::stdout());
4503    let (dim, reset, green) = if is_tty {
4504        ("\x1b[2m", "\x1b[0m", "\x1b[32m")
4505    } else {
4506        ("", "", "")
4507    };
4508    println!(
4509        "  {dim}Legend: {green}●{reset}{dim} kernel installed at this scope. \
4510              Flattened scopes (those that inherit a parent's kernel) emit no entry.{reset}"
4511    );
4512    println!();
4513}
4514
4515pub async fn run_activity_simple(
4516    activity: Activity,
4517    adapters: std::collections::HashMap<String, Arc<dyn crate::adapter::DriverAdapter>>,
4518    default_adapter: &str,
4519    op_builder: Arc<crate::synthesis::OpBuilder>,
4520) -> bool {
4521    activity
4522        .run_with_adapters(adapters, default_adapter, op_builder)
4523        .await
4524}
4525
4526/// Adapter that delegates to an `Arc<Mutex<Option<SqliteReporter>>>`.
4527///
4528/// Allows the SQLite reporter to be registered on the scheduler while
4529/// also being accessible for summary queries after the scheduler stops.
4530struct MutexReporter(
4531    std::sync::Arc<std::sync::Mutex<Option<nmbrs_metrics::reporters::sqlite::SqliteReporter>>>,
4532);
4533
4534impl Reporter for MutexReporter {
4535    fn report(&mut self, snapshot: &nmbrs_metrics::snapshot::MetricSet) {
4536        if let Ok(mut guard) = self.0.lock()
4537            && let Some(ref mut r) = *guard
4538        {
4539            Reporter::report(r, snapshot);
4540        }
4541    }
4542
4543    fn flush(&mut self) {
4544        if let Ok(mut guard) = self.0.lock()
4545            && let Some(ref mut r) = *guard
4546        {
4547            Reporter::flush(r);
4548        }
4549    }
4550}
4551
4552/// Wrapper to make `Box<dyn Reporter>` usable with `add_reporter(impl Reporter)`.
4553struct BoxedReporter(Box<dyn Reporter>);
4554impl Reporter for BoxedReporter {
4555    fn report(&mut self, snapshot: &nmbrs_metrics::snapshot::MetricSet) {
4556        self.0.report(snapshot);
4557    }
4558    fn flush(&mut self) {
4559        self.0.flush();
4560    }
4561}
4562
4563// =========================================================================
4564// Helpers
4565// =========================================================================
4566
4567/// Expand `{key}` workload param placeholders in a string.
4568pub fn expand_workload_params(s: &str, params: &HashMap<String, String>) -> String {
4569    let mut result = s.to_string();
4570    for (key, value) in params {
4571        let placeholder = format!("{{{key}}}");
4572        if result.contains(&placeholder) {
4573            result = result.replace(&placeholder, value);
4574        }
4575    }
4576    result
4577}
4578
4579/// Collected param references from a workload, separating direct
4580/// `{name}` references from composite-name templates like
4581/// `{k_{k}_limits}` whose ground form depends on a runtime
4582/// substitution.
4583///
4584/// Used by the workload param validator to recognize that a
4585/// declared param like `k_1_limits` is genuinely referenced
4586/// when the workload uses `{k_{k}_limits}` and `k` ranges over
4587/// values including `1`.
4588#[derive(Default)]
4589struct ParamRefs {
4590    /// Names that appeared as `{name}` curly-brace placeholders.
4591    /// These MUST resolve to a declared param, runner-known
4592    /// param, adapter-registered param, or scenario-tree
4593    /// iter-var — anything else is a typo or missing
4594    /// declaration and the validator surfaces it as an error.
4595    placeholders: std::collections::HashSet<String>,
4596    /// Placeholders that appeared in scenario-tree `for_each` /
4597    /// `for_combinations` / DoWhile-condition text. These get
4598    /// resolved at runtime by the comprehension interpolator
4599    /// (which emits a `<path>:<line>:<col>:` error on failure);
4600    /// the strict "must-resolve-now" validator skips them so the
4601    /// more-specific runtime diagnostic wins. They still count
4602    /// as references for the "declared but unreferenced" check
4603    /// — a workload param used only in a `for_each` spec is
4604    /// genuinely consumed by the workload, just at runtime.
4605    runtime_only_placeholders: std::collections::HashSet<String>,
4606    /// Bare identifiers harvested from `if:` / `delay:`
4607    /// expression bodies. These may be wire names (referencing
4608    /// values bound via Polydat source) rather than workload params,
4609    /// so they participate in the "declared but unreferenced"
4610    /// check (as references) but NOT in the "referenced but
4611    /// undeclared" check (since wire names legitimately live
4612    /// outside the workload's param surface).
4613    expression_idents: std::collections::HashSet<String>,
4614    /// Composite templates: the literal body of a `{...}` whose
4615    /// inner content contained nested `{...}`. Stored verbatim
4616    /// (e.g. `"k_{k}_limits"`); validation checks each declared
4617    /// param name against these templates by replacing each
4618    /// inner `{NAME}` with a word-character wildcard.
4619    templates: Vec<String>,
4620}
4621
4622impl ParamRefs {
4623    /// Does `param` appear as a reference anywhere — placeholder,
4624    /// runtime-only placeholder, expression ident, or composite
4625    /// template? Used by the existing "declared but unreferenced"
4626    /// validator.
4627    fn contains(&self, param: &str) -> bool {
4628        if self.placeholders.contains(param) {
4629            return true;
4630        }
4631        if self.runtime_only_placeholders.contains(param) {
4632            return true;
4633        }
4634        if self.expression_idents.contains(param) {
4635            return true;
4636        }
4637        self.templates
4638            .iter()
4639            .any(|tpl| template_matches(tpl, param))
4640    }
4641}
4642
4643/// Match a declared param name against a composite-name template.
4644///
4645/// `template` is the body of a `{...}` reference whose content
4646/// included nested `{...}` substitutions — e.g. `k_{k}_limits`.
4647/// Each inner `{NAME}` matches one or more word characters
4648/// (`[A-Za-z0-9_]+`); the surrounding literal chars must match
4649/// exactly. Returns `true` iff `param` exactly matches the
4650/// template's ground form for some substitution of the inner
4651/// names.
4652fn template_matches(template: &str, param: &str) -> bool {
4653    let t = template.as_bytes();
4654    let p = param.as_bytes();
4655    let mut ti = 0;
4656    let mut pi = 0;
4657    while ti < t.len() {
4658        if t[ti] == b'{' {
4659            // Skip past the inner {...}. The template body
4660            // doesn't nest deeper than one level in practice
4661            // (composed names like `{k_{k}_limits}` don't
4662            // contain `{a_{b}_c}` recursively); a simple
4663            // first-`}` lookup suffices.
4664            let close = match template[ti + 1..].find('}') {
4665                Some(n) => ti + 1 + n,
4666                None => return false, // malformed template
4667            };
4668            // Determine where the template's literal context
4669            // resumes after the inner placeholder.
4670            let next_lit = close + 1;
4671            // The next literal char (or end-of-template) bounds
4672            // how far the wildcard can consume.
4673            if next_lit >= t.len() {
4674                // Wildcard must consume the rest of `param`,
4675                // and that suffix must be at least one word char.
4676                if pi >= p.len() {
4677                    return false;
4678                }
4679                return p[pi..]
4680                    .iter()
4681                    .all(|b| b.is_ascii_alphanumeric() || *b == b'_');
4682            }
4683            let stop = t[next_lit];
4684            // Greedy-match word chars in param up to the next
4685            // literal in template.
4686            let mut consumed = 0;
4687            while pi + consumed < p.len() && p[pi + consumed] != stop {
4688                let b = p[pi + consumed];
4689                if !(b.is_ascii_alphanumeric() || b == b'_') {
4690                    return false;
4691                }
4692                consumed += 1;
4693            }
4694            if consumed == 0 {
4695                return false;
4696            } // wildcard requires ≥1 char
4697            pi += consumed;
4698            ti = next_lit;
4699        } else {
4700            // Literal char: must match.
4701            if pi >= p.len() || p[pi] != t[ti] {
4702                return false;
4703            }
4704            ti += 1;
4705            pi += 1;
4706        }
4707    }
4708    pi == p.len()
4709}
4710
4711/// Scan a string for `{name}` references and `{composite_{x}_name}`
4712/// templates, accumulating into `refs`.
4713///
4714/// Plain `{name}` placeholders (where the body is a single
4715/// identifier — alphanumerics + underscore, leading non-digit)
4716/// are recorded as direct references. A `{...}` whose body
4717/// contains nested `{...}` is recorded as a template; the inner
4718/// leaf names are also recorded as direct references because
4719/// they're the substitution inputs (e.g. `{k_{k}_limits}`
4720/// records the template `k_{k}_limits` AND the direct ref `k`).
4721/// Walk a `serde_json::Value` and call [`scan_param_refs`] on
4722/// every string leaf. Used by [`collect_param_references`] to
4723/// reach `{name}` references nested inside structured
4724/// `params:` blocks (e.g. `relevancy: { expected: "{ground_truth}" }`).
4725fn scan_json_for_refs(v: &serde_json::Value, refs: &mut ParamRefs) {
4726    match v {
4727        serde_json::Value::String(s) => scan_param_refs(s, refs),
4728        serde_json::Value::Array(a) => {
4729            for item in a {
4730                scan_json_for_refs(item, refs);
4731            }
4732        }
4733        serde_json::Value::Object(m) => {
4734            for item in m.values() {
4735                scan_json_for_refs(item, refs);
4736            }
4737        }
4738        _ => {} // numbers, booleans, null — no string content
4739    }
4740}
4741
4742fn scan_param_refs(text: &str, refs: &mut ParamRefs) {
4743    let bytes = text.as_bytes();
4744    let mut i = 0;
4745    while i < bytes.len() {
4746        if bytes[i] != b'{' {
4747            i += 1;
4748            continue;
4749        }
4750        // Find the matching `}`, balancing nested `{`s.
4751        let body_start = i + 1;
4752        let mut depth = 1;
4753        let mut j = body_start;
4754        while j < bytes.len() && depth > 0 {
4755            match bytes[j] {
4756                b'{' => depth += 1,
4757                b'}' => depth -= 1,
4758                _ => {}
4759            }
4760            if depth == 0 {
4761                break;
4762            }
4763            j += 1;
4764        }
4765        if depth != 0 {
4766            // Unmatched `{` — bail, treat as literal.
4767            break;
4768        }
4769        let body = &text[body_start..j];
4770        if body.contains('{') {
4771            // Composite template (e.g. `k_{k}_limits`).
4772            refs.templates.push(body.to_string());
4773            // Recurse into the body to pick up the inner leaf
4774            // names as direct references.
4775            scan_param_refs(body, refs);
4776        } else if !body.is_empty()
4777            && body.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
4778            && !body.bytes().next().unwrap().is_ascii_digit()
4779        {
4780            // Plain `{name}` — curly-brace placeholder. MUST
4781            // resolve to a declared / known / iter-var name;
4782            // the new validator surfaces an error if it doesn't.
4783            refs.placeholders.insert(body.to_string());
4784        } else {
4785            // Inline Polydat expression body, e.g.
4786            // `{is_one_of(cassandra_dialect, "vendor")}` or
4787            // `{:=mod(hash(cycle), 100):=}`. Walk the body,
4788            // collect identifier-shaped tokens that aren't
4789            // inside string literals — those are Polydat name
4790            // references which may resolve to workload params.
4791            // Over-collecting (function names, Polydat stdlib
4792            // identifiers) is harmless — the validator's
4793            // membership test below uses the workload's own
4794            // declared params as the universe of interest.
4795            //
4796            // These land in `expression_idents` (not
4797            // `placeholders`) because they may legitimately
4798            // resolve to Polydat wire names rather than workload
4799            // params; the "declared but unreferenced" check
4800            // still consults them via `ParamRefs::contains`,
4801            // but the new "referenced but undeclared" check
4802            // only scrutinises `placeholders`.
4803            scan_expression_idents(body, &mut refs.expression_idents);
4804        }
4805        i = j + 1;
4806    }
4807}
4808
4809/// Walk a GK-expression body (no surrounding `{}`) and add any
4810/// identifier-shaped tokens to `out`. Skips identifiers nested
4811/// inside `"..."` or `'...'` string literals — those are CQL /
4812/// regex / display strings, not name references. Recognises
4813/// backslash escapes inside string literals.
4814///
4815/// This is best-effort: it doesn't honor Polydat lexer subtleties
4816/// (numeric suffixes, raw strings, etc.). For the unused-param
4817/// check in `runner.rs::collect_param_references` the goal is
4818/// "does the param name appear anywhere we'd evaluate it" — a
4819/// loose match is correct because false positives only mean
4820/// "param is considered used when it might not have been",
4821/// which is the safer failure mode.
4822fn scan_expression_idents(body: &str, out: &mut std::collections::HashSet<String>) {
4823    let bytes = body.as_bytes();
4824    let mut i = 0;
4825    while i < bytes.len() {
4826        let b = bytes[i];
4827        // Skip `//` line comments — checked BEFORE the string-literal
4828        // scan below, because an apostrophe in comment prose (`hasn't`,
4829        // `don't`) would otherwise be read as an unterminated string
4830        // delimiter and swallow every identifier to end-of-input,
4831        // falsely flagging a later-referenced param as unused.
4832        if b == b'/' && i + 1 < bytes.len() && bytes[i + 1] == b'/' {
4833            i += 2;
4834            while i < bytes.len() && bytes[i] != b'\n' {
4835                i += 1;
4836            }
4837            continue;
4838        }
4839        // Skip string literals.
4840        if b == b'"' || b == b'\'' {
4841            let quote = b;
4842            i += 1;
4843            while i < bytes.len() {
4844                if bytes[i] == b'\\' && i + 1 < bytes.len() {
4845                    i += 2;
4846                    continue;
4847                }
4848                if bytes[i] == quote {
4849                    i += 1;
4850                    break;
4851                }
4852                i += 1;
4853            }
4854            continue;
4855        }
4856        // Identifier start: ASCII letter or underscore.
4857        if b.is_ascii_alphabetic() || b == b'_' {
4858            let start = i;
4859            while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
4860                i += 1;
4861            }
4862            let ident = &body[start..i];
4863            // Skip the few literals the Polydat lexer also recognises
4864            // — they're definitely not param names.
4865            if ident != "true" && ident != "false" {
4866                out.insert(ident.to_string());
4867            }
4868            continue;
4869        }
4870        i += 1;
4871    }
4872}
4873
4874/// Collect all `{name}` param references from a workload's ops,
4875/// phases, bindings, and scenario tree. Returns both direct
4876/// refs and composite templates so the validator can recognize
4877/// dynamic-name-composition references like `{k_{k}_limits}`.
4878fn collect_param_references(workload: &nmbrs_workload::model::Workload) -> ParamRefs {
4879    let mut refs = ParamRefs::default();
4880
4881    // Local helper so every op-bearing scope (top-level + per-
4882    // phase) hits the same set of fields. Critically this
4883    // includes the *core* fields the parser hoists out of the
4884    // op map — `if:` (condition), `delay:`, and the
4885    // serde_json values inside `params:`. Missing any of those
4886    // produced false positives on the unused-param check
4887    // (e.g. `if: '{is_one_of(cassandra_dialect, "vendor")}'`
4888    // landed in `condition` rather than `op.op`, so the
4889    // workload param `cassandra_dialect` looked unreferenced).
4890    fn scan_op(op: &nmbrs_workload::model::ParsedOp, refs: &mut ParamRefs) {
4891        for value in op.op.values() {
4892            if let serde_json::Value::String(s) = value {
4893                scan_param_refs(s, refs);
4894            }
4895        }
4896        // `if:` and `delay:` accept either `{name}` placeholders
4897        // (caught by `scan_param_refs`) or bare wire names like
4898        // `delay: think_time`. Walk both shapes — the bare-ident
4899        // pass mirrors what `scope.rs` Step 3/6 do for the same
4900        // fields, so a workload param consumed only via a bare
4901        // delay/condition reference doesn't trip the unused-param
4902        // validator.
4903        if let Some(s) = &op.condition {
4904            scan_param_refs(s, refs);
4905            scan_expression_idents(s, &mut refs.expression_idents);
4906        }
4907        if let Some(spec) = &op.delay {
4908            for name in spec.names() {
4909                scan_param_refs(name, refs);
4910                scan_expression_idents(name, &mut refs.expression_idents);
4911            }
4912        }
4913        // `params:` values can be strings, numbers, nested
4914        // maps (e.g. `relevancy: { actual: key, expected: …}`).
4915        // Walk the JSON recursively so anything stringy gets
4916        // scanned regardless of nesting depth.
4917        //
4918        // `gutter:` is exempt: its templates resolve at RUNTIME
4919        // (wires first, then status-metric aggregates like
4920        // `{recall}` / `{latency_p50}` which have no workload
4921        // declaration), and an unresolved name degrades to
4922        // visible literal text in the cell — never a silent
4923        // failure this validator needs to preempt.
4924        for (k, v) in op.params.iter() {
4925            if k == "gutter" {
4926                continue;
4927            }
4928            scan_json_for_refs(v, refs);
4929        }
4930        // Evaluation blocks reference WIRES by bare identifier
4931        // (`relevancy: { k: suite_k, expected: ground_truth }`) —
4932        // the same shapes `scope.rs` resolves at wrap-time
4933        // through the op-template kernel. Harvest them as
4934        // expression idents so a param consumed only as an
4935        // evaluation bound doesn't trip the unused-param check.
4936        // (Before this, such workloads only validated by ACCIDENT:
4937        // any `{{…}}` inline expression elsewhere in the merged
4938        // doc registered a composite template that wildcard-
4939        // matched every declared param.)
4940        let evaluation_wire_refs = [
4941            (
4942                "relevancy",
4943                &["actual", "expected", "k", "r", "admitted"][..],
4944            ),
4945            (crate::admission::PARAM, crate::admission::WIRE_KEYS),
4946        ];
4947        for (block, keys) in evaluation_wire_refs {
4948            if let Some(rel) = op.params.get(block).and_then(|v| v.as_object()) {
4949                for key in keys {
4950                    if let Some(s) = rel.get(*key).and_then(|v| v.as_str()) {
4951                        scan_expression_idents(s, &mut refs.expression_idents);
4952                    }
4953                }
4954            }
4955        }
4956        match &op.bindings {
4957            nmbrs_workload::model::BindingsDef::PolydatSource(s) => {
4958                // Two reference shapes inside Polydat source:
4959                //   - `{name}` placeholders inside string literals
4960                //     (resolved by Polydat string-interpolation against
4961                //     `const` bindings),
4962                //   - bare identifier references in Polydat expressions
4963                //     (e.g. `row := char_buf(..., cols)` — `cols`
4964                //     resolves directly to its `const` binding).
4965                // The unused-param validator must recognise both
4966                // or it falsely flags params that the workload
4967                // legitimately consumes via the bare path.
4968                scan_param_refs(s, refs);
4969                scan_expression_idents(s, &mut refs.expression_idents);
4970            }
4971            nmbrs_workload::model::BindingsDef::Map(m) => {
4972                for v in m.values() {
4973                    scan_param_refs(v, refs);
4974                }
4975            }
4976        }
4977    }
4978
4979    // Scan top-level ops
4980    for op in &workload.ops {
4981        scan_op(op, &mut refs);
4982    }
4983
4984    // SRD-13f Push D: workload-level `bindings:` are no longer
4985    // folded into ops at YAML parse time — they live on
4986    // `workload.bindings` and reach descendants via the GK
4987    // kernel chain. The unused-param validator must scan them
4988    // directly here, otherwise a workload param consumed only
4989    // from workload-level bindings (`row := char_buf(..., cols)`)
4990    // looks unreferenced.
4991    match &workload.bindings {
4992        nmbrs_workload::model::BindingsDef::PolydatSource(s) => {
4993            scan_param_refs(s, &mut refs);
4994            scan_expression_idents(s, &mut refs.expression_idents);
4995        }
4996        nmbrs_workload::model::BindingsDef::Map(m) => {
4997            for v in m.values() {
4998                scan_param_refs(v, &mut refs);
4999            }
5000        }
5001    }
5002
5003    // SRD-83 — workload-level `stop_when:` predicates: `{param}` interpolation
5004    // only (same as phase-level), so a param used only by a workload breaker
5005    // counts as referenced.
5006    for c in &workload.stop_when {
5007        scan_param_refs(&c.when, &mut refs);
5008    }
5009
5010    // Scan phases
5011    for phase in workload.phases.values() {
5012        if let Some(s) = &phase.cycles {
5013            scan_param_refs(s, &mut refs);
5014        }
5015        // SRD-83 (C3) governance `timeout:` and SRD-75 `interval:`
5016        // resolve `{param}` at phase setup — documented reference
5017        // sites the collector must count (before this, workloads
5018        // using them only validated via the accidental composite-
5019        // template wildcard).
5020        if let Some(s) = &phase.timeout {
5021            scan_param_refs(s, &mut refs);
5022        }
5023        if let Some(s) = &phase.interval {
5024            scan_param_refs(s, &mut refs);
5025        }
5026        if let Some(s) = &phase.concurrency {
5027            scan_param_refs(s, &mut refs);
5028        }
5029        if let Some(s) = &phase.for_each {
5030            scan_param_refs(s, &mut refs);
5031        }
5032        // Phase `rate:` and the SRD-75 poll bounds carry `{param}`
5033        // references resolved at the phase gather (the `timeout:`
5034        // discipline) — documented reference sites the collector
5035        // must count. The poll predicate additionally consumes
5036        // bare identifiers (params/wires) like `continue_if`.
5037        if let Some(s) = &phase.rate {
5038            scan_param_refs(s, &mut refs);
5039        }
5040        if let Some(poll) = &phase.poll {
5041            scan_expression_idents(&poll.until, &mut refs.expression_idents);
5042            for s in [&poll.interval_ms, &poll.timeout_ms, &poll.max_error_retries]
5043                .into_iter()
5044                .flatten()
5045            {
5046                scan_param_refs(s, &mut refs);
5047            }
5048        }
5049        // SRD-13f Push D parallel: phase-level `bindings:` also
5050        // sit on their own scope post-Push-D; scan for param
5051        // refs so a phase-binding-only consumer doesn't falsely
5052        // trip the unused-param check.
5053        match &phase.bindings {
5054            nmbrs_workload::model::BindingsDef::PolydatSource(s) => {
5055                scan_param_refs(s, &mut refs);
5056                scan_expression_idents(s, &mut refs.expression_idents);
5057            }
5058            nmbrs_workload::model::BindingsDef::Map(m) => {
5059                for v in m.values() {
5060                    scan_param_refs(v, &mut refs);
5061                }
5062            }
5063        }
5064        // SRD-83 / SRD-101 — breaker predicates can consume a workload param,
5065        // but by DIFFERENT mechanisms, so scan each for the shape it actually
5066        // supports (a param used in the UNsupported shape stays flagged):
5067        //   - `stop_when` substitutes `{param}` before its predicate compiles;
5068        //     its bound scope can't resolve a bare param wire → `{param}` only.
5069        //   - `continue_if` resolves BARE wires through its for_iteration
5070        //     scope-walk (inherited consts/params) → bare idents only.
5071        for c in &phase.stop_when {
5072            scan_param_refs(&c.when, &mut refs);
5073        }
5074        if let Some(ci) = &phase.continue_if {
5075            scan_expression_idents(&ci.when, &mut refs.expression_idents);
5076        }
5077        for op in &phase.ops {
5078            scan_op(op, &mut refs);
5079        }
5080    }
5081
5082    // Scan scenario tree — every node kind contributes its
5083    // `{...}`-bearing fields. DoWhile/DoUntil contribute their
5084    // condition text; ForEach/ForCombinations/ForEachUnion
5085    // contribute their iteration specs.
5086    //
5087    // Scenario-tree `{name}` placeholders are runtime-interpolated
5088    // against the outer iter-var scope (the comprehension's
5089    // enclosing for-each, plus workload params). An unresolved
5090    // placeholder there surfaces a `path:line:col:` runtime error
5091    // through the interpolation pipeline — the early
5092    // workload-level "undeclared placeholder" check would steal
5093    // that diagnostic with a less specific error. So we route
5094    // these refs through a side-channel that contributes to the
5095    // declared-but-unreferenced check (workload params used only
5096    // in for_each text are still counted as referenced) but NOT
5097    // to `refs.placeholders` (which drives the strict
5098    // "must-resolve-now" guard).
5099    fn scan_scenario_nodes(nodes: &[nmbrs_workload::model::ScenarioNode], refs: &mut ParamRefs) {
5100        for node in nodes {
5101            match node {
5102                nmbrs_workload::model::ScenarioNode::Phase(_) => {}
5103                nmbrs_workload::model::ScenarioNode::Comprehension {
5104                    comprehension,
5105                    children,
5106                    ..
5107                } => {
5108                    // Grammar-based source-reference extraction.
5109                    // A comprehension clause `eh in eh_values`
5110                    // carries `eh_values` as a *bare* source
5111                    // reference (a `Generator`/`WorkloadParamList`
5112                    // spec), and `(v) in (concat(foo))` carries
5113                    // `foo` inside a function call. Byte-scanning
5114                    // for `{name}` misses both. `referenced_source_names`
5115                    // parses each spec with the Polydat expression
5116                    // grammar (via `polydat::dsl::refs`) and returns
5117                    // the free names structurally. These resolve at
5118                    // runtime, so they count as references (for the
5119                    // declared-but-unreferenced check) but bypass
5120                    // the strict undeclared-placeholder guard.
5121                    //
5122                    // A dynamic param-list reference like
5123                    // `limit in {k_{k}_limits}` surfaces as the
5124                    // composite name `k_{k}_limits` (the inner
5125                    // `{k}` is an iter-var hole filled at runtime).
5126                    // Route composite names — those still carrying
5127                    // a `{` — into `templates` so the structured
5128                    // `template_matches` name-composition grammar
5129                    // resolves them against `k_10_limits` /
5130                    // `k_100_limits` / …; plain names go to the
5131                    // runtime-placeholder set.
5132                    for name in comprehension.referenced_source_names() {
5133                        if name.contains('{') {
5134                            refs.templates.push(name);
5135                        } else {
5136                            refs.runtime_only_placeholders.insert(name);
5137                        }
5138                    }
5139                    // The names above are the ones a SOURCE reads as a
5140                    // reference. A param is also consumed by a `{name}`
5141                    // inside a quoted literal element
5142                    // (`src in ["{data_dir}/x"]`), inside a composite
5143                    // name within a quoted string, and by the `where:`
5144                    // predicate, none of which a source's free names
5145                    // include. Scan every string the comprehension tree
5146                    // holds (source specs, literal elements, predicates)
5147                    // for placeholders; they resolve at runtime, like the
5148                    // rest of the comprehension. The tree's serialized
5149                    // form reaches all of them, where its canonical text
5150                    // does not exist for every shape.
5151                    let mut deferred = ParamRefs::default();
5152                    if let Ok(tree) = serde_json::to_value(comprehension) {
5153                        scan_json_for_refs(&tree, &mut deferred);
5154                    }
5155                    refs.runtime_only_placeholders.extend(deferred.placeholders);
5156                    refs.templates.extend(deferred.templates);
5157                    scan_scenario_nodes(children, refs);
5158                }
5159                nmbrs_workload::model::ScenarioNode::DoWhile {
5160                    condition,
5161                    children,
5162                    ..
5163                }
5164                | nmbrs_workload::model::ScenarioNode::DoUntil {
5165                    condition,
5166                    children,
5167                    ..
5168                } => {
5169                    scan_param_refs(condition, refs);
5170                    scan_scenario_nodes(children, refs);
5171                }
5172                nmbrs_workload::model::ScenarioNode::IncludedScenario { children, .. } => {
5173                    scan_scenario_nodes(children, refs);
5174                }
5175                nmbrs_workload::model::ScenarioNode::Bindings { source, children } => {
5176                    // Scenario-tree `bindings:` (and the `set:`
5177                    // sugar form) carries Polydat matter text. Scan
5178                    // the body for `{name}` placeholders and
5179                    // bare identifiers and route through
5180                    // `runtime_only_placeholders` so a param
5181                    // referenced only by a bindings body still
5182                    // counts as referenced, without tripping the
5183                    // strict undeclared-placeholder guard (the
5184                    // body is resolved at kernel build time,
5185                    // not at op-template substitution).
5186                    let mut deferred = ParamRefs::default();
5187                    scan_param_refs(source, &mut deferred);
5188                    refs.runtime_only_placeholders.extend(deferred.placeholders);
5189                    refs.expression_idents.extend(deferred.expression_idents);
5190                    refs.templates.extend(deferred.templates);
5191                    scan_scenario_nodes(children, refs);
5192                }
5193            }
5194        }
5195    }
5196    for nodes in workload.scenarios.values() {
5197        scan_scenario_nodes(nodes, &mut refs);
5198    }
5199
5200    refs
5201}
5202
5203/// Collect every iter-var name introduced by a `for_each:` /
5204/// `for_combinations:` clause anywhere in the scenario tree.
5205///
5206/// These names become legitimate `{name}` placeholders inside
5207/// phases reached via that for-clause — the runner binds them
5208/// fresh per iteration through the workload kernel's
5209/// scope-coordinate mechanism. The "referenced but undeclared"
5210/// validator consults this set so it doesn't false-positive on
5211/// `{k}` / `{limit}` / `{profile}` references that are clearly
5212/// satisfied by an enclosing `for_each: "k in …, limit in …,
5213/// profile in …"`.
5214///
5215/// Walks every scenario in the workload (the union — any
5216/// scenario the operator might invoke), so the validator
5217/// remains correct regardless of which `scenario=` argument
5218/// the operator passes on the CLI.
5219fn collect_iter_var_names(
5220    workload: &nmbrs_workload::model::Workload,
5221) -> std::collections::HashSet<String> {
5222    let mut out = std::collections::HashSet::new();
5223    for nodes in workload.scenarios.values() {
5224        for node in nodes {
5225            collect_iter_vars_recursive(node, &mut out);
5226        }
5227    }
5228    // Phase-level `for_each:` declarations also introduce iter-vars
5229    // — `phases.X.for_each: "k in 1, 2, 3"` lets the phase's ops
5230    // reference `{k}`. The scenario walker doesn't traverse phase
5231    // bodies, so harvest from each phase's `for_each` clause too.
5232    for phase in workload.phases.values() {
5233        if let Some(text) = phase.for_each.as_deref()
5234            && let Ok(comp) =
5235                polydat::iteration::comprehension::spec::parse_comprehension_algebra(text)
5236        {
5237            for name in comp.coordinate_names() {
5238                out.insert(name.to_string());
5239            }
5240        }
5241    }
5242    out
5243}
5244
5245fn collect_iter_vars_recursive(
5246    node: &nmbrs_workload::model::ScenarioNode,
5247    out: &mut std::collections::HashSet<String>,
5248) {
5249    use nmbrs_workload::model::ScenarioNode::*;
5250    match node {
5251        Phase(_) => {}
5252        Comprehension {
5253            comprehension,
5254            children,
5255            ..
5256        } => {
5257            for name in comprehension.coordinate_names() {
5258                out.insert(name.to_string());
5259            }
5260            for child in children {
5261                collect_iter_vars_recursive(child, out);
5262            }
5263        }
5264        DoWhile {
5265            children, counter, ..
5266        }
5267        | DoUntil {
5268            children, counter, ..
5269        } => {
5270            // `counter:` introduces a bare iteration index name
5271            // that's legitimately referenceable inside the loop
5272            // body, even though there's no `for_each` clause.
5273            if let Some(c) = counter {
5274                out.insert(c.clone());
5275            }
5276            for child in children {
5277                collect_iter_vars_recursive(child, out);
5278            }
5279        }
5280        IncludedScenario { children, .. } => {
5281            for child in children {
5282                collect_iter_vars_recursive(child, out);
5283            }
5284        }
5285        // Scenario-tree `bindings:` (and `set:` sugar) doesn't
5286        // introduce an iter-var; it publishes a scope-local
5287        // binding layer. Just walk children.
5288        Bindings { children, .. } => {
5289            for child in children {
5290                collect_iter_vars_recursive(child, out);
5291            }
5292        }
5293    }
5294}
5295
5296/// Collect every binding LHS name (wire output) declared in GK
5297/// source anywhere in the workload — top-level `bindings:`,
5298/// per-phase `bindings:`, and per-op `bindings:`.
5299///
5300/// These names become legitimate `{name}` placeholders inside
5301/// op text (op-template `prepared:` / `raw:` strings get
5302/// `{wire}` interpolated to the wire's value at cycle time, just
5303/// like workload params get expanded earlier in the pipeline).
5304/// The "referenced but undeclared" validator consults this set so
5305/// it doesn't false-positive on `{query_vector}` / `{dim}` /
5306/// `{ground_truth}` references that are clearly satisfied by an
5307/// enclosing `bindings:` block.
5308///
5309/// Scanner is line-based and recognises six shapes:
5310///   * `input NAME[: TYPE]` — kernel input slot (bare form)
5311///   * `input (NAME[: TYPE], ...)` — kernel input slot (tuple form)
5312///   * `const NAME := …`     — init binding (eager, once per scope)
5313///   * `cursor NAME = …`   — cursor declaration
5314///   * `shared NAME := …`  — shared output (cross-scope cell)
5315///   * `const NAME := …`   — final binding
5316///   * `NAME := …`         — ordinary `:=` output binding
5317///
5318/// The collector also mirrors the workload-root kernel's auto-input
5319/// behaviour (see `bindings.rs::compile_workload_kernel`): when no
5320/// Polydat source anywhere in the workload declares any `input` slot,
5321/// the runtime injects `input cycle: u64` so `{cycle}` resolves at
5322/// op-template substitution time. Reflecting that injection in the
5323/// validator allow-set prevents false-positive rejection of
5324/// `{cycle}` placeholders in workloads with no explicit `bindings:`
5325/// block (e.g. inline `op="tick={cycle}"`).
5326fn collect_polydat_binding_names(
5327    workload: &nmbrs_workload::model::Workload,
5328) -> std::collections::HashSet<String> {
5329    let mut out = std::collections::HashSet::new();
5330    use nmbrs_workload::model::BindingsDef;
5331
5332    let mut any_input_decl = false;
5333    let mut scan_bindings =
5334        |bindings: &BindingsDef, sink: &mut std::collections::HashSet<String>| {
5335            match bindings {
5336                BindingsDef::PolydatSource(s) => {
5337                    scan_polydat_binding_lhs(sink, s);
5338                    if s.lines().any(|l| l.trim_start().starts_with("input ")) {
5339                        any_input_decl = true;
5340                    }
5341                }
5342                BindingsDef::Map(m) => {
5343                    // Legacy nosqlbench-style chains (`Hash(); Mod(...)`)
5344                    // are translated into Polydat bindings at runtime by
5345                    // `compile_bindings_with_opts`; the keys of the map
5346                    // become the wire names those translations produce.
5347                    // The validator's allow-set must reflect those names
5348                    // so referencing `{user_id}` in op text — where
5349                    // `user_id: Hash(); Mod(...)` is the binding key —
5350                    // doesn't trip the undeclared-placeholder guard.
5351                    for name in m.keys() {
5352                        sink.insert(name.clone());
5353                    }
5354                }
5355            }
5356        };
5357
5358    scan_bindings(&workload.bindings, &mut out);
5359    // Top-level `workload.ops` carry their own `bindings:` blocks
5360    // in inline-mode workloads (the inline parser puts
5361    // synthesised `__inline_N := <expr>` lines there). Without
5362    // walking this collection, the validator misses every
5363    // inline-rewrite-generated wire name.
5364    for op in &workload.ops {
5365        scan_bindings(&op.bindings, &mut out);
5366    }
5367    for phase in workload.phases.values() {
5368        scan_bindings(&phase.bindings, &mut out);
5369        for op in &phase.ops {
5370            scan_bindings(&op.bindings, &mut out);
5371        }
5372    }
5373
5374    // Runtime mirror: workload-root kernel auto-injects
5375    // `input cycle: u64` when no `input` line is declared anywhere.
5376    // Surface that injection to the validator.
5377    if !any_input_decl {
5378        out.insert("cycle".to_string());
5379    }
5380    out
5381}
5382
5383/// One occurrence of an invalid `{name}` placeholder inside a
5384/// Polydat expression context. The `location` describes which source
5385/// block in the workload (e.g. `"phase 'ann_query' bindings"`),
5386/// and the `placeholder` is the literal body that appeared inside
5387/// the offending `{...}` — kept verbatim so the error formatter
5388/// can locate the exact YAML line by substring search.
5389#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
5390struct PolydatBraceFinding {
5391    location: String,
5392    placeholder: String,
5393}
5394
5395/// Collect every `{name}` placeholder that appears inside a GK
5396/// source context but OUTSIDE a string literal — these will
5397/// always fail Polydat compile because `{...}` isn't valid expression
5398/// syntax. Each finding names the workload block it came from
5399/// so the error formatter can point at the offending site.
5400///
5401/// Walks every Polydat source in the workload: top-level `bindings:`,
5402/// per-phase `bindings:`, per-op `bindings:`.
5403fn collect_polydat_brace_refs(
5404    workload: &nmbrs_workload::model::Workload,
5405) -> Vec<PolydatBraceFinding> {
5406    use nmbrs_workload::model::BindingsDef;
5407    let mut out: Vec<PolydatBraceFinding> = Vec::new();
5408    // Braces are no longer categorically invalid in Polydat: the block form of
5409    // conditional selection (`if <cond> { a } else { b }`) uses them. So a brace is
5410    // only evidence of a stray YAML placeholder when the source ALSO fails to parse.
5411    // Gating on parseability keeps this check doing its actual job — converting a
5412    // cryptic "expected expression, got LBrace" into a message that names the file,
5413    // line and placeholder — without rejecting valid if-expressions.
5414    let mut push_refs = |loc: &str, source: &str| {
5415        let parses = polydat::dsl::lexer::lex(source)
5416            .ok()
5417            .and_then(|toks| polydat::dsl::parser::parse(toks).ok())
5418            .is_some();
5419        if parses {
5420            return;
5421        }
5422        for name in scan_polydat_braced_refs(source) {
5423            out.push(PolydatBraceFinding {
5424                location: loc.to_string(),
5425                placeholder: name,
5426            });
5427        }
5428    };
5429    if let BindingsDef::PolydatSource(s) = &workload.bindings {
5430        push_refs("workload `bindings:`", s);
5431    }
5432    for (phase_name, phase) in &workload.phases {
5433        if let BindingsDef::PolydatSource(s) = &phase.bindings {
5434            push_refs(&format!("phase '{phase_name}' bindings"), s);
5435        }
5436        for op in &phase.ops {
5437            if let BindingsDef::PolydatSource(s) = &op.bindings {
5438                push_refs(&format!("phase '{phase_name}' op-bindings"), s);
5439            }
5440        }
5441    }
5442    out
5443}
5444
5445/// Scan the raw YAML source for the first line that contains
5446/// the given placeholder text (with surrounding braces).
5447/// Returns the 1-based line number when found, `None` otherwise.
5448///
5449/// Used to upgrade the GK-brace validator's error message from
5450/// "phase 'foo' bindings" to a file:line locator the operator
5451/// can click on or jump to. Works because YAML block scalars
5452/// (`|` / `>`) preserve the body verbatim; the offending
5453/// `{name}` substring appears in the file exactly as the
5454/// validator captured it.
5455///
5456/// Falls back to `None` on the rare cases where the literal
5457/// also appears in an unrelated comment or string — the
5458/// validator's caller treats that as "give the location but
5459/// no line number." The substring is namespaced enough
5460/// (`{name}` with curly braces) that collisions are unlikely
5461/// in practice.
5462fn find_yaml_line_for_brace(yaml_source: &str, placeholder: &str) -> Option<usize> {
5463    let needle = format!("{{{placeholder}}}");
5464    yaml_source
5465        .lines()
5466        .enumerate()
5467        .find(|(_, line)| line.contains(&needle))
5468        .map(|(idx, _)| idx + 1)
5469}
5470
5471/// Scan Polydat source for `{name}` placeholders that appear OUTSIDE
5472/// string literals and OUTSIDE comments. Inside `"..."` or
5473/// `'...'` (with backslash escapes), `{...}` is part of the
5474/// string and gets handled by runtime interpolation — leave it
5475/// alone. Lines starting with `#` (and content after `#` on any
5476/// line) are comments — also skipped.
5477fn scan_polydat_braced_refs(source: &str) -> Vec<String> {
5478    let bytes = source.as_bytes();
5479    let mut out: Vec<String> = Vec::new();
5480    let mut i = 0;
5481    while i < bytes.len() {
5482        let b = bytes[i];
5483        // Line comment — skip to next newline.
5484        if b == b'#' {
5485            while i < bytes.len() && bytes[i] != b'\n' {
5486                i += 1;
5487            }
5488            continue;
5489        }
5490        // String literal — skip past the closing quote.
5491        if b == b'"' || b == b'\'' {
5492            let quote = b;
5493            i += 1;
5494            while i < bytes.len() {
5495                if bytes[i] == b'\\' && i + 1 < bytes.len() {
5496                    i += 2;
5497                    continue;
5498                }
5499                if bytes[i] == quote {
5500                    i += 1;
5501                    break;
5502                }
5503                i += 1;
5504            }
5505            continue;
5506        }
5507        // Outside any string — `{` opens a brace placeholder.
5508        if b == b'{' {
5509            // Find the matching `}`, allowing one level of
5510            // nesting for composite forms like `{k_{k}_limits}`.
5511            // We only need the OUTER body for the error message
5512            // — the inner placeholders are also wrong but the
5513            // outer is what the operator sees.
5514            let start = i + 1;
5515            let mut depth = 1;
5516            let mut j = start;
5517            while j < bytes.len() && depth > 0 {
5518                match bytes[j] {
5519                    b'{' => depth += 1,
5520                    b'}' => depth -= 1,
5521                    _ => {}
5522                }
5523                if depth == 0 {
5524                    break;
5525                }
5526                j += 1;
5527            }
5528            if depth == 0 && j > start {
5529                let body = &source[start..j];
5530                // Trim whitespace; ignore obviously-empty bodies.
5531                let trimmed = body.trim();
5532                if !trimmed.is_empty() {
5533                    out.push(trimmed.to_string());
5534                }
5535                i = j + 1;
5536                continue;
5537            }
5538            // Unmatched `{` — let the Polydat parser handle it with
5539            // its own error; don't double-report.
5540            break;
5541        }
5542        i += 1;
5543    }
5544    out
5545}
5546
5547/// Line-by-line scan of Polydat source for locally-bound names —
5548/// `cursor NAME = …`, `shared NAME := …`, `const NAME := …`,
5549/// `volatile NAME := …`, bare `NAME := …` assignments, and
5550/// `input NAME[: TYPE]` / `input (NAME[: TYPE], ...)` declarations.
5551/// Skips comments and blank lines. Lines that don't match any of
5552/// these shapes (function-call statements, comments, expression
5553/// continuations) are ignored.
5554fn scan_polydat_binding_lhs(out: &mut std::collections::HashSet<String>, source: &str) {
5555    for raw_line in source.lines() {
5556        let line = raw_line.trim();
5557        if line.is_empty() || line.starts_with('#') {
5558            continue;
5559        }
5560        // `input` declarations: collect declared slot names without
5561        // requiring an `=` / `:=` suffix. Both bare (`input cycle: u64`)
5562        // and tuple (`input (cycle: u64, q: f64)`) forms are handled.
5563        if let Some(rest) = line.strip_prefix("input ") {
5564            scan_input_decl_names(out, rest.trim());
5565            continue;
5566        }
5567        // `extern` declarations (`extern name: type [= default]`,
5568        // `extern (a: u64, b: f64)`) declare wire names just like
5569        // `input` — same `name: type` shape. Without this, a
5570        // `{name}` placeholder referencing an extern-declared wire
5571        // (e.g. a same-op capture target) trips the
5572        // undeclared-placeholder guard.
5573        if let Some(rest) = line.strip_prefix("extern ") {
5574            scan_input_decl_names(out, rest.trim());
5575            continue;
5576        }
5577        // Strip leading modifier (`const `, `cursor `, `shared `,
5578        // `volatile `); body is what follows. Modifiers can be
5579        // combined in a few cases (e.g. `shared const`,
5580        // `shared volatile`), so loop until no recognised prefix
5581        // remains.
5582        let mut body = line;
5583        loop {
5584            let stripped = body
5585                .strip_prefix("const ")
5586                .or_else(|| body.strip_prefix("cursor "))
5587                .or_else(|| body.strip_prefix("shared "))
5588                .or_else(|| body.strip_prefix("volatile "));
5589            match stripped {
5590                Some(rest) => body = rest,
5591                None => break,
5592            }
5593        }
5594        // Tuple-destructure LHS: `(a, b, c) := <expr>`. Each
5595        // identifier inside the parens becomes a separate
5596        // declared name. Used by multi-output stdlib nodes
5597        // (e.g. `(y, mo, d, h, mi, s, ms) := date_components(0)`)
5598        // and any other binding that unpacks multiple outputs.
5599        if body.starts_with('(') {
5600            if let Some(close) = body.find(')') {
5601                let after = body[close + 1..].trim_start();
5602                if after.starts_with(":=") || after.starts_with('=') {
5603                    for raw in body[1..close].split(',') {
5604                        let name = raw.trim();
5605                        if !name.is_empty() {
5606                            out.insert(name.to_string());
5607                        }
5608                    }
5609                }
5610            }
5611            continue;
5612        }
5613        // Pull the leading identifier.
5614        let bytes = body.as_bytes();
5615        let mut i = 0;
5616        while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
5617            i += 1;
5618        }
5619        if i == 0 {
5620            continue;
5621        }
5622        // What follows the identifier? Skip whitespace.
5623        let mut j = i;
5624        while j < bytes.len() && bytes[j].is_ascii_whitespace() {
5625            j += 1;
5626        }
5627        // Must be `=` (init/cursor) or `:=` (assignment); reject
5628        // anything else (function calls, expressions starting
5629        // with an ident, etc.).
5630        let is_binding = bytes.get(j) == Some(&b'=')
5631            || (bytes.get(j) == Some(&b':') && bytes.get(j + 1) == Some(&b'='));
5632        if is_binding {
5633            out.insert(body[..i].to_string());
5634            continue;
5635        }
5636        // Typed cell form: `name: type := default` (e.g.
5637        // `shared sstables: u64 := 0`). The `:` here is a type
5638        // annotation, not `:=` — skip the type token and accept
5639        // iff an assignment follows it. Without this arm, typed
5640        // shared/volatile declarations were invisible to the
5641        // undeclared-placeholder validator and any `{name}`
5642        // reference to one tripped a false positive.
5643        if bytes.get(j) == Some(&b':') {
5644            let rest = body[j + 1..].trim_start();
5645            let te = rest
5646                .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
5647                .unwrap_or(rest.len());
5648            if te > 0 {
5649                let after_ty = rest[te..].trim_start();
5650                if after_ty.starts_with(":=") || after_ty.starts_with('=') {
5651                    out.insert(body[..i].to_string());
5652                }
5653            }
5654        }
5655    }
5656}
5657
5658/// Parse the name(s) out of an `input` declaration body (the text
5659/// after the `input ` keyword has been stripped).
5660///
5661/// Accepts both surface forms:
5662/// - `cycle` / `cycle: u64`        → inserts `cycle`
5663/// - `(a: u64, b: f64, ...)`        → inserts each declared name
5664///
5665/// Mirrors `parse_input_decl` in the Polydat parser; this is a
5666/// lightweight scanner used by scope-elision to register
5667/// locally-bound names without re-running the full lexer/parser.
5668fn scan_input_decl_names(out: &mut std::collections::HashSet<String>, body: &str) {
5669    let body = body.trim();
5670    if let Some(inner) = body.strip_prefix('(').and_then(|s| s.strip_suffix(')')) {
5671        for part in inner.split(',') {
5672            let name = part.trim().split(':').next().unwrap_or("").trim();
5673            if !name.is_empty() {
5674                out.insert(name.to_string());
5675            }
5676        }
5677        return;
5678    }
5679    let name = body.split(':').next().unwrap_or("").trim();
5680    if !name.is_empty() {
5681        out.insert(name.to_string());
5682    }
5683}
5684
5685/// Resolve a scenario name to a list of phase names.
5686fn resolve_scenario(
5687    scenarios: &HashMap<String, Vec<nmbrs_workload::model::ScenarioNode>>,
5688    phase_order: &[String],
5689    name: &str,
5690) -> Result<Vec<nmbrs_workload::model::ScenarioNode>, String> {
5691    if let Some(nodes) = scenarios.get(name) {
5692        return Ok(nodes.clone());
5693    }
5694    if name == "default" && !phase_order.is_empty() {
5695        return Ok(phase_order
5696            .iter()
5697            .map(|n| nmbrs_workload::model::ScenarioNode::Phase(n.clone()))
5698            .collect());
5699    }
5700    Err(format!("scenario '{name}' not found"))
5701}
5702
5703/// Format a scenario tree for display — one construct per line,
5704/// nested with two-space indent per level. Phases include their
5705/// declared `cycles:` and `concurrency:` config when available
5706/// from the workload's phase map so the operator can see the
5707/// run shape at a glance.
5708///
5709/// Example output for the full_cql_vector fulltest scenario:
5710///
5711/// ```text
5712/// scenario 'test_oracles'
5713///   for_each profile in matching_profiles('{dataset}', '{oracles_prefix}')
5714///     for_each table in vec_{profile}
5715///       teardown                          (cycles: 1, concurrency: 1)
5716///       schema                            (cycles: 1, concurrency: 1)
5717///       rampup
5718///       jolokia_flush
5719///       for_combinations [k, limit] in {k_values}, {k_{k}_limits}
5720///         ann_query                       (concurrency: {query_concurrency})
5721/// scenario 'test_fknn'
5722///   ...
5723/// ```
5724///
5725/// The replaced LISP-shaped one-liner had bracket nesting that
5726/// scaled badly past two levels and required mental parsing to
5727/// see the loop structure.
5728fn format_scenario_tree(
5729    nodes: &[nmbrs_workload::model::ScenarioNode],
5730    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
5731) -> String {
5732    let mut out = String::new();
5733    format_scenario_nodes(nodes, phases, 0, &mut out);
5734    // Trim trailing newline so the runner's log call doesn't
5735    // emit a double-blank line.
5736    if out.ends_with('\n') {
5737        out.pop();
5738    }
5739    out
5740}
5741
5742/// Render a multi-coord comprehension's `[vars] in [specs]`
5743/// in two column-aligned lines. Column `i` is padded to the
5744/// widest of `vars[i]` and `specs[i]` so corresponding entries
5745/// stack vertically:
5746///
5747/// ```text
5748/// for [sm,          mnc,          bw,          eh,           alf_label]
5749///  in [{sm_values}, {mnc_values}, {bw_values}, {eh_values}, concat({alf_label_values})]
5750/// ```
5751///
5752/// `for ` and ` in ` are 4 chars (padding `in` with a leading
5753/// space) so the `[` brackets and every column thereafter
5754/// share the same vertical line. Color highlights the
5755/// keywords when the active terminal supports it; on a
5756/// piped/no-color stderr the output stays plain.
5757///
5758/// `indent_prefix` is the per-depth indent at the call site
5759/// — applied to the second line so it sits at the same depth
5760/// as the first.
5761fn format_for_combinations(pairs: &[(String, String)], indent_prefix: &str, color: bool) -> String {
5762    let kw_open = if color { "\x1b[1;36m" } else { "" };
5763    let kw_close = if color { "\x1b[0m" } else { "" };
5764    let bracket_open = if color { "\x1b[2m" } else { "" };
5765    let bracket_close = if color { "\x1b[0m" } else { "" };
5766
5767    let widths: Vec<usize> = pairs
5768        .iter()
5769        .map(|(v, s)| v.chars().count().max(s.chars().count()))
5770        .collect();
5771
5772    let pad = |entry: &str, idx: usize, last: bool| -> String {
5773        // Last column gets no trailing comma + no padding —
5774        // the closing `]` lands flush against the final token.
5775        if last {
5776            entry.to_string()
5777        } else {
5778            // `<entry>,` then pad to `widths[idx] + 1` so the
5779            // next column begins at a constant offset.
5780            let with_comma = format!("{entry},");
5781            let width_target = widths[idx] + 1; // +1 for the comma
5782            let visible = with_comma.chars().count();
5783            if visible >= width_target {
5784                with_comma
5785            } else {
5786                format!("{with_comma}{:<pad$}", "", pad = width_target - visible)
5787            }
5788        }
5789    };
5790
5791    let last_idx = pairs.len().saturating_sub(1);
5792    let vars_line: String = pairs
5793        .iter()
5794        .enumerate()
5795        .map(|(i, (v, _))| pad(v, i, i == last_idx))
5796        .collect::<Vec<_>>()
5797        .join(" ");
5798    let specs_line: String = pairs
5799        .iter()
5800        .enumerate()
5801        .map(|(i, (_, s))| pad(s, i, i == last_idx))
5802        .collect::<Vec<_>>()
5803        .join(" ");
5804
5805    format!(
5806        "{kw_open}for{kw_close} {bracket_open}[{bracket_close}{vars_line}{bracket_open}]{bracket_close}\n\
5807         {indent_prefix} {kw_open}in{kw_close} {bracket_open}[{bracket_close}{specs_line}{bracket_open}]{bracket_close}"
5808    )
5809}
5810
5811fn format_scenario_nodes(
5812    nodes: &[nmbrs_workload::model::ScenarioNode],
5813    phases: &std::collections::HashMap<String, nmbrs_workload::model::WorkloadPhase>,
5814    depth: usize,
5815    out: &mut String,
5816) {
5817    use nmbrs_workload::model::ScenarioNode::*;
5818    let indent = " ".repeat(depth);
5819    for node in nodes {
5820        match node {
5821            Phase(name) => {
5822                let suffix = phases
5823                    .get(name)
5824                    .map(format_phase_config_suffix)
5825                    .unwrap_or_default();
5826                if suffix.is_empty() {
5827                    out.push_str(&format!("{indent}{name}\n"));
5828                } else {
5829                    // Pad name to a fixed column so the
5830                    // `(cycles:..., concurrency:...)` chip lines
5831                    // up across consecutive phases. 32 chars
5832                    // covers the typical phase names; longer
5833                    // names just push past the column without
5834                    // breaking layout.
5835                    out.push_str(&format!("{indent}{name:<32} {suffix}\n",));
5836                }
5837            }
5838            Comprehension {
5839                comprehension,
5840                children,
5841                ..
5842            } => {
5843                // Algebra-native display: walk the AST once to
5844                // detect Union vs flat, then format. Matches
5845                // the scope_tree::label_for_comprehension shape
5846                // at one level of detail finer (includes the
5847                // spec_expr for non-Union shapes).
5848                use polydat::iteration::comprehension::Comprehension as Comp;
5849                // Peel outer Order/Filter for structural detection.
5850                let mut body = comprehension;
5851                while let Comp::Order { child, .. } | Comp::Filter { child, .. } = body {
5852                    body = child;
5853                }
5854                let header = match body {
5855                    Comp::Union { children } => {
5856                        let names = comprehension.coordinate_names().join(", ");
5857                        format!("for_each_union [{}] ({} sub-spaces)", names, children.len())
5858                    }
5859                    _ => {
5860                        let pairs = comprehension.coordinate_specs();
5861                        if pairs.len() == 1 {
5862                            let (var, spec) = &pairs[0];
5863                            format!("for_each {var} in {spec}")
5864                        } else {
5865                            // Two-line column-aligned form for
5866                            // multi-coord comprehensions: variable
5867                            // names on the first line, source
5868                            // expressions on the second, each
5869                            // column padded to its widest
5870                            // (var, spec) pair so the columns
5871                            // line up vertically. Keywords
5872                            // `for` / ` in` are right-aligned
5873                            // so the `[` brackets land in the
5874                            // same column.
5875                            format_for_combinations(&pairs, &indent, crate::observer::use_color())
5876                        }
5877                    }
5878                };
5879                out.push_str(&format!("{indent}{header}\n"));
5880                format_scenario_nodes(children, phases, depth + 1, out);
5881            }
5882            DoWhile {
5883                condition,
5884                counter,
5885                children,
5886            } => {
5887                let ctr = counter
5888                    .as_deref()
5889                    .map(|c| format!(" (counter={c})"))
5890                    .unwrap_or_default();
5891                out.push_str(&format!("{indent}do_while '{condition}'{ctr}\n"));
5892                format_scenario_nodes(children, phases, depth + 1, out);
5893            }
5894            DoUntil {
5895                condition,
5896                counter,
5897                children,
5898            } => {
5899                let ctr = counter
5900                    .as_deref()
5901                    .map(|c| format!(" (counter={c})"))
5902                    .unwrap_or_default();
5903                out.push_str(&format!("{indent}do_until '{condition}'{ctr}\n"));
5904                format_scenario_nodes(children, phases, depth + 1, out);
5905            }
5906            IncludedScenario { name, children } => {
5907                out.push_str(&format!("{indent}scenario '{name}'\n"));
5908                format_scenario_nodes(children, phases, depth + 1, out);
5909            }
5910            Bindings { source, children } => {
5911                // First non-empty line of the source as a one-
5912                // line summary in the scenario-tree dump. Long
5913                // bodies stay readable in the YAML; the
5914                // hierarchical view just teases the binding.
5915                let summary = source
5916                    .lines()
5917                    .map(str::trim)
5918                    .find(|l| !l.is_empty())
5919                    .unwrap_or("");
5920                if source.lines().filter(|l| !l.trim().is_empty()).count() > 1 {
5921                    out.push_str(&format!("{indent}bindings: {summary} …\n"));
5922                } else {
5923                    out.push_str(&format!("{indent}bindings: {summary}\n"));
5924                }
5925                format_scenario_nodes(children, phases, depth + 1, out);
5926            }
5927        }
5928    }
5929}
5930
5931/// Render the `(cycles: X, concurrency: Y)` suffix for a phase
5932/// line in the scenario-tree summary. Includes only the fields
5933/// that the phase actually declared — phases that inherit the
5934/// runtime defaults skip the chip entirely so the tree line
5935/// stays uncluttered. Strings are shown verbatim (including
5936/// `{name}` placeholders) so the operator sees the workload's
5937/// declared intent rather than a runtime-evaluated number.
5938fn format_phase_config_suffix(phase: &nmbrs_workload::model::WorkloadPhase) -> String {
5939    let mut parts: Vec<String> = Vec::new();
5940    if let Some(c) = phase.cycles.as_deref()
5941        && !c.is_empty()
5942    {
5943        parts.push(format!("cycles: {c}"));
5944    }
5945    if let Some(c) = phase.concurrency.as_deref()
5946        && !c.is_empty()
5947    {
5948        parts.push(format!("concurrency: {c}"));
5949    }
5950    if parts.is_empty() {
5951        String::new()
5952    } else {
5953        format!("({})", parts.join(", "))
5954    }
5955}
5956
5957/// Bind an implementation into the blueprint its `implements:` names
5958/// (SRD-108), returning the bound workload: the blueprint, with the
5959/// implementation's op bodies, params, scenarios and report folded in.
5960///
5961/// `workload_file` is the implementation's own identity: its path, or
5962/// its catalog name when `is_bundled`. The blueprint reference
5963/// resolves relative to it, as an `extends:` target does.
5964fn bind_into_declared_blueprint(
5965    implementation: nmbrs_workload::model::Workload,
5966    target: &str,
5967    workload_file: Option<&str>,
5968    is_bundled: bool,
5969    params: &HashMap<String, String>,
5970) -> Result<nmbrs_workload::model::Workload, String> {
5971    let base_dir = (!is_bundled)
5972        .then(|| {
5973            workload_file
5974                .map(std::path::Path::new)
5975                .and_then(|p| p.parent().map(|d| d.to_path_buf()))
5976        })
5977        .flatten();
5978    let bundled_origin = is_bundled.then_some(workload_file).flatten();
5979    let (mut blueprint, blueprint_id) =
5980        load_secondary_workload(target, params, base_dir.as_deref(), bundled_origin)?;
5981    crate::diag!(
5982        crate::observer::LogLevel::Info,
5983        "implements: binding '{}' into blueprint '{blueprint_id}'",
5984        workload_file.unwrap_or("<inline>")
5985    );
5986    nmbrs_workload::implements::bind_implementation(&mut blueprint, implementation)
5987        .map_err(|e| format!("implements binding: {e}"))?;
5988    Ok(blueprint)
5989}
5990
5991/// Load the workload file at `path` as a run of it would: its
5992/// `extends:` chain merged and, when it is an implementation, bound
5993/// into its blueprint (SRD-108). Every command that reads a workload's
5994/// model reads this, so `nmbrs report workload=<impl>` sees the report
5995/// the run of that file rendered.
5996pub fn load_bound_workload_from_path(
5997    path: &std::path::Path,
5998    params: &HashMap<String, String>,
5999) -> Result<nmbrs_workload::model::Workload, String> {
6000    let workload = nmbrs_workload::parse::parse_workload_from_path(path, params)?;
6001    match workload.implements.clone() {
6002        Some(target) => {
6003            let file = path.to_string_lossy();
6004            bind_into_declared_blueprint(workload, &target, Some(file.as_ref()), false, params)
6005        }
6006        None => Ok(workload),
6007    }
6008}
6009
6010/// SRD-108 Part B — load a secondary workload document (an
6011/// `implements:` target, or the `impl=` module) through the same
6012/// resolution the primary `workload=` uses: local file first,
6013/// then the bundled catalog. Returns the parsed workload plus its
6014/// canonical identity string (canonicalized path, or catalog
6015/// name) for target-matching.
6016fn load_secondary_workload(
6017    reference: &str,
6018    params: &HashMap<String, String>,
6019    base_dir: Option<&std::path::Path>,
6020    bundled_origin: Option<&str>,
6021) -> Result<(nmbrs_workload::model::Workload, String), String> {
6022    match resolve_secondary_ref(reference, base_dir, bundled_origin)? {
6023        ResolvedWorkload::Path(path) => {
6024            let workload = nmbrs_workload::parse::parse_workload_from_path(
6025                std::path::Path::new(&path),
6026                params,
6027            )
6028            .map_err(|e| format!("parse workload '{path}': {e}"))?;
6029            Ok((workload, canonical_identity(&path)))
6030        }
6031        ResolvedWorkload::Bundled(bundled) => {
6032            let (merged, res_warnings) =
6033                nmbrs_workload::extends::load_and_merge_bundled(bundled)
6034                    .map_err(|e| format!("bundled workload `{}`: {e}", bundled.name))?;
6035            let mut workload = nmbrs_workload::parse::parse_workload(&merged, params)
6036                .map_err(|e| format!("parse bundled workload `{}`: {e}", bundled.name))?;
6037            workload.resolution_warnings.extend(res_warnings);
6038            Ok((workload, bundled.name.to_string()))
6039        }
6040    }
6041}
6042
6043/// Resolve a workload reference to its canonical identity WITHOUT
6044/// parsing it — used to compare an `implements:` target against
6045/// the invoked `workload=`.
6046fn workload_ref_identity(
6047    reference: &str,
6048    base_dir: Option<&std::path::Path>,
6049    bundled_origin: Option<&str>,
6050) -> Result<String, String> {
6051    match resolve_secondary_ref(reference, base_dir, bundled_origin)? {
6052        ResolvedWorkload::Path(path) => Ok(canonical_identity(&path)),
6053        ResolvedWorkload::Bundled(bundled) => Ok(bundled.name.to_string()),
6054    }
6055}
6056
6057/// SRD-109 Part 2 — resolve a driver manifest by name: local
6058/// `drivers/<name>/driver.yaml` under the cwd first, then the
6059/// bundled catalog entry `drivers/<name>/driver`. Both at once
6060/// FAVORS the local manifest (SRD-85 nearest-first) with a
6061/// logged warning naming both — shadowing is allowed but never
6062/// silent. Returns the manifest plus the resolved LIBRARY
6063/// reference: a file path for a local manifest, a catalog name
6064/// for a bundled one. An error when neither exists.
6065fn resolve_driver_manifest(
6066    name: &str,
6067) -> Result<(nmbrs_workload::drivers::DriverManifest, String), String> {
6068    let local_path = std::path::Path::new("drivers")
6069        .join(name)
6070        .join("driver.yaml");
6071    let catalog_name = format!("drivers/{name}/driver");
6072    let bundled = nmbrs_workload::catalog::lookup(&catalog_name);
6073    match (local_path.is_file(), bundled) {
6074        (true, Some(_)) => {
6075            crate::observer::log_tagged(
6076                crate::observer::LogLevel::Warn,
6077                crate::observer::EventTag::in_flight(crate::observer::EventCategory::Resolution),
6078                &format!(
6079                    "resolve: driver '{name}' matches multiple resources — local \
6080                 manifest {} AND bundled driver `{catalog_name}` — using the \
6081                 local manifest (filesystem-first). Same-named resources in \
6082                 multiple places invite confusion: prefer a unique name.",
6083                    local_path.display()
6084                ),
6085            );
6086            let source = std::fs::read_to_string(&local_path)
6087                .map_err(|e| format!("read driver manifest {}: {e}", local_path.display()))?;
6088            let manifest = nmbrs_workload::drivers::parse_driver_manifest(
6089                &source,
6090                &local_path.display().to_string(),
6091            )?;
6092            verify_driver_identity(&manifest, name)?;
6093            let dir = local_path.parent().expect("manifest path has a parent");
6094            let library_ref = resolve_driver_library_local(dir, &manifest.library)?;
6095            Ok((manifest, library_ref))
6096        }
6097        (true, None) => {
6098            let source = std::fs::read_to_string(&local_path)
6099                .map_err(|e| format!("read driver manifest {}: {e}", local_path.display()))?;
6100            let manifest = nmbrs_workload::drivers::parse_driver_manifest(
6101                &source,
6102                &local_path.display().to_string(),
6103            )?;
6104            verify_driver_identity(&manifest, name)?;
6105            let dir = local_path.parent().expect("manifest path has a parent");
6106            let library_ref = resolve_driver_library_local(dir, &manifest.library)?;
6107            Ok((manifest, library_ref))
6108        }
6109        (false, Some(entry)) => {
6110            let manifest =
6111                nmbrs_workload::drivers::parse_driver_manifest(entry.source, &catalog_name)?;
6112            verify_driver_identity(&manifest, name)?;
6113            let stem = manifest
6114                .library
6115                .strip_suffix(".yaml")
6116                .or_else(|| manifest.library.strip_suffix(".yml"))
6117                .unwrap_or(&manifest.library);
6118            let library_ref = format!("drivers/{name}/{stem}");
6119            Ok((manifest, library_ref))
6120        }
6121        (false, None) => Err(unknown_driver_error(name)),
6122    }
6123}
6124
6125/// `driver=<name>` names a driver manifest, and none is called
6126/// `name`. The error lists the manifests that exist, and points an
6127/// adapter name at `adapter=`, since `driver=` never selects one.
6128fn unknown_driver_error(name: &str) -> String {
6129    let known = nmbrs_workload::drivers::manifest_names();
6130    let adapter_hint = if crate::adapter::find_adapter_registration(name).is_some() {
6131        format!(" '{name}' is an adapter; select it with `adapter={name}`.")
6132    } else {
6133        String::new()
6134    };
6135    format!(
6136        "driver={name}: no driver manifest named '{name}' (looked for \
6137         ./drivers/{name}/driver.yaml and the bundled drivers/{name}/driver).\
6138         {adapter_hint} Known drivers: [{}]",
6139        known.join(", ")
6140    )
6141}
6142
6143/// A manifest must be named for the directory it lives in — a
6144/// mismatch is a packaging bug surfaced at load, not a silent
6145/// re-route.
6146fn verify_driver_identity(
6147    manifest: &nmbrs_workload::drivers::DriverManifest,
6148    name: &str,
6149) -> Result<(), String> {
6150    if manifest.driver != name {
6151        return Err(format!(
6152            "driver manifest for '{name}' declares `driver: {}` — the \
6153             manifest must be named for its directory",
6154            manifest.driver
6155        ));
6156    }
6157    Ok(())
6158}
6159
6160/// Resolve a local manifest's `library:` reference beside the
6161/// manifest: as written first, then with `.yaml` appended.
6162fn resolve_driver_library_local(dir: &std::path::Path, library: &str) -> Result<String, String> {
6163    let as_written = dir.join(library);
6164    if as_written.is_file() {
6165        return Ok(as_written.display().to_string());
6166    }
6167    let with_ext = dir.join(format!("{library}.yaml"));
6168    if with_ext.is_file() {
6169        return Ok(with_ext.display().to_string());
6170    }
6171    Err(format!(
6172        "driver manifest {}: library '{library}' not found beside the manifest",
6173        dir.display()
6174    ))
6175}
6176
6177/// Apply a resolved driver manifest to the invocation params:
6178/// the library lands as `workload=` (no workload given) or
6179/// `impl=` (a blueprint was invoked); the backing adapter and the
6180/// manifest's default params fill only ABSENT keys, so the CLI
6181/// always wins and the defaults still overlay the library's own
6182/// declared params (this map is the CLI overlay layer).
6183fn apply_driver_manifest(
6184    params: &mut HashMap<String, String>,
6185    driver_name: &str,
6186    manifest: nmbrs_workload::drivers::DriverManifest,
6187    library_ref: String,
6188    workload_given: bool,
6189) -> Result<(), String> {
6190    if params.contains_key("impl") {
6191        return Err(format!(
6192            "driver={driver_name} supplies the implementation library \
6193             ('{}') — impl= conflicts; pass one or the other",
6194            manifest.library
6195        ));
6196    }
6197    if workload_given {
6198        params.insert("impl".into(), library_ref.clone());
6199    } else {
6200        params.insert("workload".into(), library_ref.clone());
6201    }
6202    params
6203        .entry("adapter".to_string())
6204        .or_insert_with(|| manifest.adapter.clone());
6205    for (k, v) in &manifest.default_params {
6206        params.entry(k.clone()).or_insert_with(|| v.clone());
6207    }
6208    crate::diag!(
6209        crate::observer::LogLevel::Info,
6210        "driver: {driver_name} → adapter={}, library={library_ref}",
6211        manifest.adapter
6212    );
6213    Ok(())
6214}
6215
6216/// Resolve a secondary workload reference the way `extends:`
6217/// targets resolve: relative to the REFERRING DOCUMENT's
6218/// directory first (when one exists on disk), then the standard
6219/// cwd-local + bundled-catalog path. Without the base-dir leg, an
6220/// `implements: ./blueprint.yaml` inside a file would only resolve
6221/// when the invoking cwd happens to be the file's directory.
6222fn resolve_secondary_ref(
6223    reference: &str,
6224    base_dir: Option<&std::path::Path>,
6225    bundled_origin: Option<&str>,
6226) -> Result<ResolvedWorkload, String> {
6227    // SRD-85 nearest-first: every candidate is enumerated and the
6228    // nearest wins — the logical filesystem location is favored
6229    // over the embedded catalog BY DEFAULT (a fresh checkout must
6230    // never be silently shadowed by a stale binary's catalog).
6231    // Multiple matches are a warnable condition, logged with every
6232    // candidate named; never a hard error and never silent.
6233    let pinned = reference.starts_with("./") || reference.starts_with("../");
6234
6235    // 1. The referring document's own directory (nearest).
6236    let origin_file: Option<String> = base_dir
6237        .map(|dir| dir.join(reference))
6238        .filter(|c| c.is_file())
6239        .map(|c| c.display().to_string());
6240
6241    // A `./`-pinned reference that resolves beside its referring
6242    // FILE is explicit — no enumeration, no warning.
6243    if pinned
6244        && base_dir.is_some()
6245        && let Some(file) = origin_file
6246    {
6247        return Ok(ResolvedWorkload::Path(file));
6248    }
6249
6250    // 2. The cwd's logical layout (exact path, extension probing,
6251    //    cwd `workloads/`).
6252    let cwd_file: Option<String> = resolve_workload_file(reference).filter(|p| {
6253        // Dedupe against the origin-dir candidate.
6254        origin_file.as_deref().map(canonical_identity) != Some(canonical_identity(p))
6255    });
6256
6257    // 3. The bundled catalog: exact name, then the sibling idiom —
6258    //    the referring bundled document's namespace — then the bare
6259    //    stem (extension and `./` stripped: files reference siblings
6260    //    by filename, catalog names carry none).
6261    let stem = reference
6262        .strip_suffix(".yaml")
6263        .or_else(|| reference.strip_suffix(".yml"))
6264        .unwrap_or(reference);
6265    let stem = stem.strip_prefix("./").unwrap_or(stem);
6266    let ns_stem = bundled_origin
6267        .and_then(|o| o.rsplit_once('/'))
6268        .map(|(ns, _)| format!("{ns}/{stem}"));
6269    let bundled: Option<&'static nmbrs_workload::catalog::BundledWorkload> =
6270        nmbrs_workload::catalog::lookup(reference)
6271            .or_else(|| ns_stem.as_deref().and_then(nmbrs_workload::catalog::lookup))
6272            .or_else(|| nmbrs_workload::catalog::lookup(stem));
6273
6274    let mut names: Vec<String> = Vec::new();
6275    if let Some(p) = &origin_file {
6276        names.push(format!("file {p} (beside the referring document)"));
6277    }
6278    if let Some(p) = &cwd_file {
6279        names.push(format!("local file {p}"));
6280    }
6281    if let Some(b) = bundled {
6282        names.push(format!("bundled workload `{}`", b.name));
6283    }
6284
6285    if names.len() > 1 {
6286        crate::observer::log_tagged(
6287            crate::observer::LogLevel::Warn,
6288            crate::observer::EventTag::in_flight(crate::observer::EventCategory::Resolution),
6289            &format!(
6290                "resolve: reference '{reference}' matches multiple resources — {} — \
6291             using the nearest ({}). Same-named resources in multiple places \
6292             invite confusion: prefer a unique name, or pin the intent with a \
6293             `./` path / full catalog name.",
6294                names.join(" AND "),
6295                names[0]
6296            ),
6297        );
6298    }
6299
6300    if let Some(p) = origin_file {
6301        return Ok(ResolvedWorkload::Path(p));
6302    }
6303    if let Some(p) = cwd_file {
6304        return Ok(ResolvedWorkload::Path(p));
6305    }
6306    if let Some(b) = bundled {
6307        return Ok(ResolvedWorkload::Bundled(b));
6308    }
6309    Err(format!(
6310        "workload not found: '{reference}'. Not a local file, and no bundled \
6311         workload by that name — `nmbrs describe workloads` lists what this \
6312         binary carries.{}",
6313        nmbrs_workload::suggest::did_you_mean(&nmbrs_workload::suggest::suggest_workloads(
6314            reference
6315        )),
6316    ))
6317}
6318
6319/// Canonicalize a workload file path for identity comparison;
6320/// bundled names pass through unchanged (they contain no path
6321/// separators that resolve).
6322fn canonical_identity(reference: &str) -> String {
6323    std::fs::canonicalize(reference)
6324        .map(|p| p.display().to_string())
6325        .unwrap_or_else(|_| reference.to_string())
6326}
6327
6328/// SRD-106 Part 3 — light pre-read of the workload's merged YAML
6329/// for the top-level `stick_session:` flag. Runs BEFORE session
6330/// construction (the full workload parse happens after the session
6331/// exists, so it cannot inform session resolution). Resolution
6332/// mirrors the execution path — local file first, then the bundled
6333/// catalog — and `extends:` chains merge before the peek, so a
6334/// suite base declaring `stick_session: true` reaches derived
6335/// workloads. Any failure answers `None`; the full parse surfaces
6336/// the real error with proper context.
6337fn peek_stick_session(params: &HashMap<String, String>, args: &[String]) -> Option<bool> {
6338    if params.contains_key("op") {
6339        return None; // inline workloads carry no header
6340    }
6341    let workload_raw = params.get("workload").cloned().or_else(|| {
6342        args.iter()
6343            .find(|a| a.ends_with(".yaml") || a.ends_with(".yml"))
6344            .cloned()
6345    })?;
6346    // Pre-probe only (stick_session peek): resolution warnings
6347    // are dropped here — the authoritative load that follows
6348    // surfaces the identical warnings itself.
6349    let merged = match resolve_workload(&workload_raw).ok()? {
6350        ResolvedWorkload::Path(p) => {
6351            nmbrs_workload::extends::load_and_merge(std::path::Path::new(&p))
6352                .ok()?
6353                .0
6354        }
6355        ResolvedWorkload::Bundled(b) => nmbrs_workload::extends::load_and_merge_bundled(b).ok()?.0,
6356    };
6357    let doc: serde_yaml::Value = serde_yaml::from_str(&merged).ok()?;
6358    doc.get("stick_session")?.as_bool()
6359}
6360
6361/// Resolve a workload file path from a bare name.
6362/// Tries: as-is, with .yaml/.yml extension, then under workloads/.
6363/// SRD-85 resolution result: a local file path or a bundled
6364/// catalog entry.
6365pub enum ResolvedWorkload {
6366    Path(String),
6367    Bundled(&'static nmbrs_workload::catalog::BundledWorkload),
6368}
6369
6370/// Resolve a `workload=` value per SRD-85 nearest-first: local
6371/// files first (exact path, extension probing, cwd `workloads/`),
6372/// then the bundled catalog by exact name. A name that resolves
6373/// both ways FAVORS the logical filesystem location and logs a
6374/// warning naming both — shadowing is allowed but never silent.
6375/// `./`-prefixed paths pin the local reading without a warning.
6376pub fn resolve_workload(name: &str) -> Result<ResolvedWorkload, String> {
6377    let local = resolve_workload_file(name);
6378    let bundled = nmbrs_workload::catalog::lookup(name);
6379    match (local, bundled) {
6380        (Some(local_path), Some(b)) => {
6381            if !name.starts_with("./") && !name.starts_with("../") {
6382                crate::observer::log_tagged(
6383                    crate::observer::LogLevel::Warn,
6384                    crate::observer::EventTag::in_flight(
6385                        crate::observer::EventCategory::Resolution,
6386                    ),
6387                    &format!(
6388                        "resolve: workload '{name}' matches multiple resources — \
6389                     local file {local_path} AND bundled workload `{}` — using \
6390                     the local file (filesystem-first). Same-named resources in \
6391                     multiple places invite confusion: prefer a unique name, or \
6392                     pin the intent with a `./` path.",
6393                        b.name
6394                    ),
6395                );
6396            }
6397            Ok(ResolvedWorkload::Path(local_path))
6398        }
6399        (Some(local_path), None) => Ok(ResolvedWorkload::Path(local_path)),
6400        (None, Some(b)) => Ok(ResolvedWorkload::Bundled(b)),
6401        (None, None) => Err(format!(
6402            "workload not found: '{name}'. Not a local file, and no bundled \
6403             workload by that name — `nmbrs describe workloads` lists what \
6404             this binary carries.{}",
6405            nmbrs_workload::suggest::did_you_mean(&nmbrs_workload::suggest::suggest_workloads(
6406                name
6407            ),)
6408        )),
6409    }
6410}
6411
6412fn resolve_workload_file(name: &str) -> Option<String> {
6413    let p = std::path::Path::new(name);
6414    if p.exists() {
6415        return Some(name.to_string());
6416    }
6417
6418    // Already has yaml extension — no further search
6419    if name.ends_with(".yaml") || name.ends_with(".yml") {
6420        // Try under workloads/
6421        let under = format!("workloads/{name}");
6422        if std::path::Path::new(&under).exists() {
6423            return Some(under);
6424        }
6425        return None;
6426    }
6427
6428    // Try adding extensions
6429    for ext in [".yaml", ".yml"] {
6430        let with_ext = format!("{name}{ext}");
6431        if std::path::Path::new(&with_ext).exists() {
6432            return Some(with_ext);
6433        }
6434    }
6435
6436    // Try under workloads/
6437    for ext in ["", ".yaml", ".yml"] {
6438        let under = format!("workloads/{name}{ext}");
6439        if std::path::Path::new(&under).exists() {
6440            return Some(under);
6441        }
6442    }
6443
6444    None
6445}
6446
6447/// Normalize args: detect scenario shorthand where a bare word after
6448/// the workload file becomes `scenario=<name>`.
6449///
6450/// The auto-promotion has to skip the **values** of space-form
6451/// flags (`--session-path X`, `--readout Y`, etc.) — otherwise
6452/// the path or value gets misread as a scenario name and ends up
6453/// as `scenario=<path>`, which downstream code then materialises
6454/// as a literal directory at `<cwd>/scenario=<path>` (the
6455/// orphaned-dir bug we hit earlier). Use the same list
6456/// [`parse_params`] uses so the two surfaces agree on which
6457/// flags consume their next token.
6458pub fn normalize_args(args: &[String]) -> Vec<String> {
6459    // Spec-derived value-taking flags (installed at startup); the
6460    // session-flag fallback applies for library/test drivers.
6461    let value_flags = known_value_flags();
6462
6463    let mut result = Vec::new();
6464    let mut workload_seen = false;
6465    let mut scenario_set = false;
6466    let mut iter = args.iter().peekable();
6467    while let Some(arg) = iter.next() {
6468        // Pass through space-form flag + its value as a unit.
6469        // Equals-form (`--session-path=X`) is one token and
6470        // skips this branch.
6471        if value_flags.iter().any(|f| *f == arg) {
6472            result.push(arg.clone());
6473            if let Some(next) = iter.next() {
6474                result.push(next.clone());
6475            }
6476            continue;
6477        }
6478        if !workload_seen
6479            && (arg.ends_with(".yaml") || arg.ends_with(".yml") || arg.contains("workload="))
6480        {
6481            workload_seen = true;
6482            result.push(arg.clone());
6483        } else if workload_seen && !scenario_set && !arg.contains('=') && !arg.starts_with('-') {
6484            result.push(format!("scenario={arg}"));
6485            scenario_set = true;
6486        } else {
6487            result.push(arg.clone());
6488        }
6489    }
6490    result
6491}
6492
6493/// Bare flags accepted by the runner — these don't follow the
6494/// `key=value` shape but are otherwise recognized. Centralized
6495/// here so [`parse_params`] doesn't reject them and any consumer
6496/// can re-check the raw `args` for them.
6497const RECOGNIZED_BARE_FLAGS: &[&str] = &[
6498    "--strict",             // SRD-15 strict-mode toggle.
6499    "--resume-latest",      // SRD-44: resume from logs/latest.
6500    "--force-retry-failed", // SRD-44: prepend retry,warn to errors.
6501    "--refine",             // SRD-77: enable refine-mode skip-plan loading.
6502];
6503
6504/// Strip a single layer of matching outer quotes (single or
6505/// double) from a string slice. Idempotent for un-quoted input.
6506///
6507/// Per SRD 71 §"CLI parsing — quote elision": this lets wrapper
6508/// scripts forwarding `"$@"`, or `key="value"` constructions
6509/// that double-passed through a shell, parse the same as their
6510/// bare equivalents. Backtick and other quote-like characters
6511/// are deliberately not handled — they carry shell-evaluation
6512/// semantics that don't survive into our argv.
6513pub(crate) fn elide_outer_quotes(s: &str) -> &str {
6514    let bytes = s.as_bytes();
6515    if bytes.len() < 2 {
6516        return s;
6517    }
6518    let first = bytes[0];
6519    let last = bytes[bytes.len() - 1];
6520    if (first == b'\'' || first == b'"') && first == last {
6521        &s[1..s.len() - 1]
6522    } else {
6523        s
6524    }
6525}
6526
6527/// The error for a CLI argument whose key is no known parameter. `parse_params`
6528/// strips leading dashes, so `--x=1` and `x=1` both arrive as the key `x`; the
6529/// message names the argument as the operator wrote it. A dashed argument is
6530/// reported as a flag and matched against the known flags (a retired spelling
6531/// names its replacement); a bare `key=value` is matched against the known
6532/// parameters.
6533fn unrecognized_param_error(args: &[String], key: &str, known_params: &[&str]) -> String {
6534    let dashed = args.iter().find_map(|a| {
6535        let a = elide_outer_quotes(a);
6536        let name = a.split('=').next().unwrap_or(a);
6537        (name.starts_with('-') && name.trim_start_matches('-') == key).then_some(name)
6538    });
6539    match dashed {
6540        Some(flag) => {
6541            let suggestion = crate::session::retired_flag_replacement(flag).or_else(|| {
6542                let flags = known_flags();
6543                crate::suggest::closest_match(flag, flags.iter().copied())
6544            });
6545            match suggestion {
6546                Some(s) => format!("unrecognized flag '{flag}'. Did you mean '{s}'?"),
6547                None => format!("unrecognized flag '{flag}'"),
6548            }
6549        }
6550        None => match crate::suggest::closest_match(key, known_params.iter().copied()) {
6551            Some(s) => format!("unrecognized parameter '{key}='. Did you mean '{s}='?"),
6552            None => format!("unrecognized parameter '{key}='"),
6553        },
6554    }
6555}
6556
6557/// Flags consumed by `crate::session::resolve_session_dir` at startup.
6558/// They appear in raw `args` but shouldn't reach the per-key params map.
6559/// Both equals-form (`--session-path=/path`) and space-form
6560/// (`--session-path /path`) are recognised; the space-form value is
6561/// silently absorbed. Shared by [`parse_params`] and
6562/// [`detect_conflicting_duplicate_params`] so they treat these args
6563/// identically.
6564const SESSION_DIR_FLAGS: &[&str] = &[
6565    // Umbrella flag (kv-list).
6566    "--session",
6567    // Per-key long-form flags.
6568    "--session-name",
6569    "--session-path",
6570    "--session-reuse",
6571    "--session-keep",
6572    "--session-shelflife",
6573    // SRD-63 §8: `--readout=<body>` overrides the workload's
6574    // `on_update` binding for the run. Resolved by
6575    // `crate::session::resolve_flag` at runner-init; consumed here so
6576    // the value doesn't bleed into the workload params map.
6577    "--readout",
6578];
6579
6580/// Reject a `key=value` run param supplied more than once with
6581/// *conflicting* values. These params collapse into a map (last value
6582/// wins — see [`parse_params`]), which silently discards an earlier
6583/// value: e.g. `scenario=reset scenario=idx_sweep` drops `reset` and
6584/// runs `idx_sweep`. A repeat with an IDENTICAL value is harmless and
6585/// allowed (re-passing the same value shouldn't break a script); a
6586/// conflicting repeat is an ambiguous instruction, so it's rejected and
6587/// surfaced rather than silently last-wins ("Never Ignore Silently").
6588///
6589/// Mirrors `parse_params`'s arg walk: session-dir flags (own resolver)
6590/// and dotted phase-scoped overrides (`<phase>.<param>=`, a separate
6591/// namespace) are skipped, and the same quote elision is applied so
6592/// `scenario=x` and `scenario='x'` compare equal.
6593pub fn detect_conflicting_duplicate_params(args: &[String]) -> Result<(), String> {
6594    let mut seen: HashMap<String, String> = HashMap::new();
6595    let mut iter = args.iter().peekable();
6596    while let Some(arg) = iter.next() {
6597        // Session-dir flags: consumed by the startup hook, absorb the
6598        // space-form value so it isn't mistaken for a param.
6599        if known_value_flags()
6600            .iter()
6601            .any(|p| arg == p || arg.starts_with(&format!("{p}=")))
6602        {
6603            if !arg.contains('=') {
6604                let _consumed = iter.next();
6605            }
6606            continue;
6607        }
6608        let unquoted = elide_outer_quotes(arg.as_str());
6609        let stripped = unquoted.trim_start_matches('-');
6610        let Some(eq_pos) = stripped.find('=') else {
6611            continue;
6612        };
6613        let key = stripped[..eq_pos].to_string();
6614        // Dotted (non-path) keys are SRD-71 phase-scoped overrides — a
6615        // separate namespace — skipped here as in `parse_params`.
6616        if key.contains('.') && !key.contains('/') && !key.contains('\\') {
6617            continue;
6618        }
6619        let value = elide_outer_quotes(&stripped[eq_pos + 1..]).to_string();
6620        match seen.get(&key) {
6621            Some(prev) if *prev != value => {
6622                return Err(format!(
6623                    "parameter '{key}' specified more than once with conflicting \
6624                     values ('{prev}' and '{value}') — pass it exactly once"
6625                ));
6626            }
6627            Some(_) => {} // identical repeat — harmless, allow.
6628            None => {
6629                seen.insert(key, value);
6630            }
6631        }
6632    }
6633    Ok(())
6634}
6635
6636/// Parse `key=value` pairs from command line args.
6637///
6638/// Quote handling (SRD 71): if the whole arg or just the value
6639/// portion is wrapped in matching `'…'` / `"…"` quotes, those
6640/// quotes are stripped. So `cursor=0..53%`, `cursor='0..53%'`,
6641/// `cursor="0..53%"`, `'cursor=0..53%'`, and `"cursor=0..53%"`
6642/// all parse to the same `(name="cursor", value="0..53%")`
6643/// pair. The first `=` still splits name from value, so values
6644/// containing `=` retain everything after the first split.
6645pub fn parse_params(args: &[String]) -> HashMap<String, String> {
6646    let mut params = HashMap::new();
6647    let mut iter = args.iter().peekable();
6648    while let Some(arg) = iter.next() {
6649        // Session-dir flags (consumed by the startup hook,
6650        // not stored in params).
6651        if known_value_flags()
6652            .iter()
6653            .any(|p| arg == p || arg.starts_with(&format!("{p}=")))
6654        {
6655            if !arg.contains('=') {
6656                let _consumed = iter.next();
6657            }
6658            continue;
6659        }
6660
6661        // Quote elision (SRD 71): strip matching outer quotes
6662        // from the whole arg first — handles `'key=value'` and
6663        // `"key=value"` — then again from the value portion
6664        // after the `=` split — handles `key='value'` and
6665        // `key="value"`.
6666        let unquoted = elide_outer_quotes(arg.as_str());
6667        // Strip leading dashes: --dryrun=phase,wiring → dryrun=phase,wiring
6668        let stripped = unquoted.trim_start_matches('-');
6669        if let Some(eq_pos) = stripped.find('=') {
6670            let key = stripped[..eq_pos].to_string();
6671            // Dotted keys (without path separators) are SRD-71
6672            // phase-scoped overrides (`<phase-pattern>.<param>=`),
6673            // parsed by `crate::phase_params::parse_overrides` —
6674            // not workload params.
6675            if key.contains('.') && !key.contains('/') && !key.contains('\\') {
6676                continue;
6677            }
6678            let value = elide_outer_quotes(&stripped[eq_pos + 1..]).to_string();
6679            params.insert(key, value);
6680        } else if arg.ends_with(".yaml") || arg.ends_with(".yml") {
6681            // Workload file path — handled elsewhere
6682        } else if is_recognized_bare_flag(arg.as_str()) || arg.starts_with("--polydat-lib=") {
6683            // Bare runner flag — consumed elsewhere via `args`
6684            // scan (e.g. `--strict`, `--polydat-lib=path`).
6685        } else {
6686            crate::diag!(
6687                crate::observer::LogLevel::Error,
6688                "error: unrecognized argument '{arg}'. Expected key=value format."
6689            );
6690            std::process::exit(1);
6691        }
6692    }
6693    params
6694}
6695
6696/// Overlay CLI `key=value` params onto a base set, CLI winning on
6697/// conflict. The single precedence rule for the whole run — applied to
6698/// the session-tier effective params ([`effective_params`]) and to the
6699/// execution's workload params identically, so "CLI overrides the
6700/// workload" means the same thing everywhere.
6701fn overlay_cli_params(
6702    mut base: HashMap<String, String>,
6703    cli: &HashMap<String, String>,
6704) -> HashMap<String, String> {
6705    for (k, v) in cli {
6706        // Coerce the CLI value to the type already inferred for this key
6707        // (the declared default, resolved by `parse_workload`), so a
6708        // suffixed override like `max_size=10m` re-applies as a number
6709        // rather than overwriting the coerced value with raw text. Keys
6710        // with no declared default (ad-hoc CLI params) pass through.
6711        let coerced = match base.get(k) {
6712            Some(existing) => nmbrs_workload::magnitude::coerce_param_override(existing, v),
6713            None => v.clone(),
6714        };
6715        base.insert(k.clone(), coerced);
6716    }
6717    base
6718}
6719
6720/// The run's **effective parameters**: the workload's declared top-level
6721/// `params:` (extends-merged) as the base, with CLI `key=value` args
6722/// overlaid on top (CLI wins). This is the single consolidated param set —
6723/// the same one whether a setting is declared in the workload or passed on
6724/// the command line — used for session-tier services (metrics cadence,
6725/// push reporters, per-instance metrics) and console-ownership detection
6726/// alike. The per-execution path reaches the same result by overlaying CLI
6727/// onto the fully-parsed `workload.params` (see `run_execution`).
6728///
6729/// The workload reference is taken from `workload=` or a bare `.yaml`/`.yml`
6730/// positional; an unresolvable/absent workload contributes no base params
6731/// (the real load error, if any, surfaces later in the execution).
6732pub fn effective_params(args: &[String]) -> HashMap<String, String> {
6733    let cli = parse_params(args);
6734    let workload_ref = cli.get("workload").cloned().or_else(|| {
6735        args.iter()
6736            .find(|a| (a.ends_with(".yaml") || a.ends_with(".yml")) && !a.contains('='))
6737            .cloned()
6738    });
6739    let base = workload_ref
6740        .as_deref()
6741        .and_then(nmbrs_workload::verify::declared_params)
6742        .unwrap_or_default();
6743    overlay_cli_params(base, &cli)
6744}
6745
6746/// Param keys that configure the **session-tier** services — one value per
6747/// session, shared by every execution under it. Executions that declare
6748/// different values for any of these cannot share a session; a multi-
6749/// execution harness must group by them and set up one session per group
6750/// (see [`session_param_signature`]). `metrics_cadence` is the load-bearing
6751/// case: it fixes the cadence the optimizer settle detector samples, so
6752/// workloads wanting a sub-second cadence must run in their own session.
6753pub const SESSION_PARAMS: &[&str] = &["metrics_cadence"];
6754
6755/// The session-grouping signature for a workload reference: its declared
6756/// values (following `extends:`) for the [`SESSION_PARAMS`], sorted.
6757/// Workloads with equal signatures can share one session; differing ones
6758/// must not. Empty signature = "the default session is fine".
6759pub fn session_param_signature(reference: &str) -> Vec<(String, String)> {
6760    let declared = nmbrs_workload::verify::declared_params(reference).unwrap_or_default();
6761    let mut sig: Vec<(String, String)> = SESSION_PARAMS
6762        .iter()
6763        .filter_map(|k| declared.get(*k).map(|v| ((*k).to_string(), v.clone())))
6764        .collect();
6765    sig.sort();
6766    sig
6767}
6768
6769/// Resolve the metrics base interval + cadence ladder from the run's
6770/// effective params. A `metrics_cadence` param (workload or CLI, e.g.
6771/// `100ms` / `200ms`) sets the FINEST cadence — the pulse the SRD-86
6772/// optimizer settle detector samples — and the scheduler base interval, so
6773/// a windowed objective settles in a fraction of the default 1 s-cadence
6774/// wall-clock. A standard coarse ladder (1s/10s/30s/1m/5m) is layered above
6775/// it (keeping a 1 s rung bounds the fan-in from a sub-second floor). Absent
6776/// the param, this is the unchanged default: a 1 s base with the observer's
6777/// declared cadences (or [`Cadences::defaults`]).
6778fn resolve_cadence_config(
6779    params: &HashMap<String, String>,
6780    observer: &Arc<dyn crate::observer::RunObserver>,
6781) -> Result<(std::time::Duration, nmbrs_metrics::cadence::Cadences), String> {
6782    use std::time::Duration;
6783    let Some(raw) = params.get("metrics_cadence") else {
6784        let cadences = observer
6785            .cadences()
6786            .unwrap_or_else(nmbrs_metrics::cadence::Cadences::defaults);
6787        return Ok((Duration::from_secs(1), cadences));
6788    };
6789    let floor = nmbrs_metrics::cadence::parse_duration(raw).ok_or_else(|| {
6790        format!("metrics_cadence: invalid duration `{raw}` (use e.g. `100ms`, `200ms`, `1s`)")
6791    })?;
6792    if floor.is_zero() {
6793        return Err("metrics_cadence: must be greater than zero".to_string());
6794    }
6795    let mut layers = vec![floor];
6796    for secs in [1u64, 10, 30, 60, 300] {
6797        let d = Duration::from_secs(secs);
6798        if d > floor {
6799            layers.push(d);
6800        }
6801    }
6802    let cadences = nmbrs_metrics::cadence::Cadences::new(&layers)
6803        .map_err(|e| format!("metrics_cadence `{raw}`: cannot build a cadence ladder: {e:?}"))?;
6804    Ok((floor, cadences))
6805}
6806
6807/// Collect every occurrence of a repeatable flag (e.g.
6808/// `--trace=<spec>` or `trace=<spec>`) from a raw arg list.
6809/// Returns the values in order of appearance — `parse_params`
6810/// collapses repeats into a HashMap, so this is the escape
6811/// hatch for repeatable args.
6812///
6813/// Accepts both `--name=value` and `name=value` shapes for
6814/// symmetry with the rest of nmbrs's arg surface.
6815pub fn collect_repeated_flag(args: &[String], name: &str) -> Vec<String> {
6816    let mut out = Vec::new();
6817    let mut iter = args.iter().peekable();
6818    let long_eq = format!("--{name}=");
6819    let bare_eq = format!("{name}=");
6820    while let Some(arg) = iter.next() {
6821        let unquoted = elide_outer_quotes(arg.as_str());
6822        if let Some(v) = unquoted.strip_prefix(&long_eq) {
6823            out.push(elide_outer_quotes(v).to_string());
6824        } else if let Some(v) = unquoted.strip_prefix(&bare_eq) {
6825            out.push(elide_outer_quotes(v).to_string());
6826        } else if unquoted == format!("--{name}")
6827            && let Some(v) = iter.next()
6828        {
6829            out.push(elide_outer_quotes(v.as_str()).to_string());
6830        }
6831    }
6832    out
6833}
6834
6835/// Parse a cycle count that may have suffixes: K, M, B.
6836pub fn parse_count(s: &str) -> Option<u64> {
6837    let s = s.trim().to_uppercase();
6838    if let Some(n) = s.strip_suffix('K') {
6839        n.trim().parse::<u64>().ok().map(|v| v * 1_000)
6840    } else if let Some(n) = s.strip_suffix('M') {
6841        n.trim().parse::<u64>().ok().map(|v| v * 1_000_000)
6842    } else if let Some(n) = s.strip_suffix('B') {
6843        n.trim().parse::<u64>().ok().map(|v| v * 1_000_000_000)
6844    } else {
6845        s.parse().ok()
6846    }
6847}
6848
6849// =========================================================================
6850// Polydat Scope Composition (sysref 16)
6851// =========================================================================
6852
6853// `ManifestEntry` and `extract_manifest` now live in
6854// `polydat::kernel`. Re-exported here so existing
6855// `crate::runner::extract_manifest` / `ManifestEntry` callers
6856// keep working — pure compatibility shim.
6857pub use polydat::kernel::{ManifestEntry, extract_manifest};
6858
6859#[cfg(test)]
6860mod tests {
6861    use super::*;
6862
6863    // ── parse_params quote elision (SRD 71) ──────────────────
6864
6865    fn pp(args: &[&str]) -> HashMap<String, String> {
6866        parse_params(&args.iter().map(|s| s.to_string()).collect::<Vec<_>>())
6867    }
6868
6869    #[test]
6870    fn parse_params_bare_unchanged() {
6871        let m = pp(&["cursor=0..53%"]);
6872        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6873    }
6874
6875    #[test]
6876    fn parse_params_value_single_quoted_stripped() {
6877        let m = pp(&["cursor='0..53%'"]);
6878        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6879    }
6880
6881    #[test]
6882    fn parse_params_value_double_quoted_stripped() {
6883        let m = pp(&["cursor=\"0..53%\""]);
6884        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6885    }
6886
6887    #[test]
6888    fn parse_params_whole_arg_single_quoted_stripped() {
6889        let m = pp(&["'cursor=0..53%'"]);
6890        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6891    }
6892
6893    #[test]
6894    fn parse_params_whole_arg_double_quoted_stripped() {
6895        let m = pp(&["\"cursor=0..53%\""]);
6896        assert_eq!(m.get("cursor").map(String::as_str), Some("0..53%"));
6897    }
6898
6899    #[test]
6900    fn parse_params_bracket_value_with_quotes() {
6901        let m = pp(&["cursor='[0..53%)'"]);
6902        assert_eq!(m.get("cursor").map(String::as_str), Some("[0..53%)"));
6903    }
6904
6905    #[test]
6906    fn parse_params_mismatched_quotes_not_stripped() {
6907        let m = pp(&["cursor='0..53%\""]);
6908        // First char `'`, last char `"` — no matching pair.
6909        assert_eq!(m.get("cursor").map(String::as_str), Some("'0..53%\""));
6910    }
6911
6912    fn dup(args: &[&str]) -> Result<(), String> {
6913        let owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();
6914        detect_conflicting_duplicate_params(&owned)
6915    }
6916
6917    #[test]
6918    fn duplicate_conflicting_scenario_is_rejected() {
6919        let err = dup(&["workload=x.yaml", "scenario=reset", "scenario=idx_sweep"]).unwrap_err();
6920        assert!(
6921            err.contains("scenario") && err.contains("reset") && err.contains("idx_sweep"),
6922            "expected a conflicting-duplicate error naming both values, got: {err}"
6923        );
6924    }
6925
6926    #[test]
6927    fn duplicate_identical_value_is_allowed() {
6928        // Re-passing the same value is harmless.
6929        assert!(dup(&["scenario=idx_sweep", "scenario=idx_sweep"]).is_ok());
6930    }
6931
6932    #[test]
6933    fn distinct_params_are_allowed() {
6934        assert!(dup(&["workload=x.yaml", "scenario=reset", "cycles=10", "host=h"]).is_ok());
6935    }
6936
6937    #[test]
6938    fn conflicting_duplicate_any_param_is_rejected() {
6939        // The guard is general — not just `scenario=`.
6940        assert!(dup(&["cycles=10", "cycles=20"]).is_err());
6941    }
6942
6943    #[test]
6944    fn duplicate_check_elides_quotes_before_comparing() {
6945        // `scenario=reset` and `scenario='reset'` are the SAME value.
6946        assert!(dup(&["scenario=reset", "scenario='reset'"]).is_ok());
6947        // …but genuinely different quoted values still conflict.
6948        assert!(dup(&["scenario='reset'", "scenario=\"idx_sweep\""]).is_err());
6949    }
6950
6951    /// A dashed argument is reported as the flag the operator wrote, and a
6952    /// retired spelling names its replacement rather than whatever edit
6953    /// distance finds nearest. A bare `key=value` stays a parameter.
6954    #[test]
6955    fn unrecognized_argument_error_matches_its_shape() {
6956        let args = vec!["--sessions-max=5".to_string()];
6957        assert_eq!(
6958            unrecognized_param_error(&args, "sessions-max", &["cycles"]),
6959            "unrecognized flag '--sessions-max'. Did you mean '--session-keep'?"
6960        );
6961        let args = vec!["cyclse=5".to_string()];
6962        assert_eq!(
6963            unrecognized_param_error(&args, "cyclse", &["cycles"]),
6964            "unrecognized parameter 'cyclse='. Did you mean 'cycles='?"
6965        );
6966    }
6967
6968    #[test]
6969    fn duplicate_check_skips_session_flags_and_dotted_overrides() {
6970        // Session-dir flags are consumed by their own resolver; dotted
6971        // keys are phase-scoped overrides — neither participates here.
6972        assert!(dup(&["--session-path", "/a", "--session-path", "/b"]).is_ok());
6973        assert!(dup(&["phase1.cycles=10", "phase2.cycles=20"]).is_ok());
6974    }
6975
6976    #[test]
6977    fn parse_params_equals_in_value_preserved() {
6978        // `key='a=b'` → name=`key`, value=`a=b`.
6979        let m = pp(&["key='a=b'"]);
6980        assert_eq!(m.get("key").map(String::as_str), Some("a=b"));
6981    }
6982
6983    #[test]
6984    fn parse_params_multiple_params_independent() {
6985        let m = pp(&["dataset=example", "cursor='0..1%'", "concurrency=\"100\""]);
6986        assert_eq!(m.get("dataset").map(String::as_str), Some("example"));
6987        assert_eq!(m.get("cursor").map(String::as_str), Some("0..1%"));
6988        assert_eq!(m.get("concurrency").map(String::as_str), Some("100"));
6989    }
6990
6991    // ── Polydat binding-LHS-name scanner ──────────────────────────
6992
6993    fn scan_to_set(src: &str) -> std::collections::HashSet<String> {
6994        let mut out = std::collections::HashSet::new();
6995        scan_polydat_binding_lhs(&mut out, src);
6996        out
6997    }
6998
6999    // ── scan_polydat_braced_refs: invalid `{...}` outside strings ─
7000
7001    #[test]
7002    fn polydat_brace_guard_allows_valid_if_block() {
7003        // Block-form conditional selection uses braces legitimately. The guard must
7004        // not flag it, because the source parses.
7005        let src = "extern segments: u64 = 0\nmean := if segments > 0 { 100 } else { 0 }\n";
7006        let parses = polydat::dsl::lexer::lex(src)
7007            .ok()
7008            .and_then(|t| polydat::dsl::parser::parse(t).ok())
7009            .is_some();
7010        assert!(parses, "if-block source must parse: {src}");
7011    }
7012
7013    #[test]
7014    fn polydat_brace_guard_still_catches_stray_placeholder() {
7015        // A YAML placeholder in expression position does NOT parse, so the guard
7016        // still fires and still names the placeholder.
7017        let src = "const passes := multiples_at_least({min_query_cycles}, base)\n";
7018        let parses = polydat::dsl::lexer::lex(src)
7019            .ok()
7020            .and_then(|t| polydat::dsl::parser::parse(t).ok())
7021            .is_some();
7022        assert!(!parses, "stray placeholder must fail to parse");
7023        let refs = scan_polydat_braced_refs(src);
7024        assert!(refs.iter().any(|r| r == "min_query_cycles"), "got {refs:?}");
7025    }
7026
7027    #[test]
7028    fn scan_polydat_braced_refs_flags_expression_position_braces() {
7029        // The user's case: `{name}` outside any string literal,
7030        // sitting where Polydat expects an expression. Always invalid.
7031        let refs = scan_polydat_braced_refs(
7032            "const passes := multiples_at_least({min_query_cycles}, base)\n",
7033        );
7034        assert_eq!(refs, vec!["min_query_cycles".to_string()]);
7035    }
7036
7037    #[test]
7038    fn scan_polydat_braced_refs_ignores_braces_inside_double_quotes() {
7039        // Inside `"…"` braces are valid — either workload-param
7040        // interp (if the runtime expanded the string earlier) or
7041        // Polydat string interpolation (parser turns it into printf).
7042        // Either way, scan_polydat_braced_refs must NOT flag them.
7043        let refs = scan_polydat_braced_refs(
7044            "const prebuffered := dataset_prebuffer(\"{dataset}:{profile}\")\n",
7045        );
7046        assert!(
7047            refs.is_empty(),
7048            "must not flag `{{dataset}}` / `{{profile}}` inside string \
7049             literal — string interpolation handles them, got {refs:?}"
7050        );
7051    }
7052
7053    #[test]
7054    fn scan_polydat_braced_refs_ignores_braces_inside_single_quotes() {
7055        let refs = scan_polydat_braced_refs("tag := assert_eq(actual, '{expected}')\n");
7056        assert!(
7057            refs.is_empty(),
7058            "single-quoted strings get the same treatment: {refs:?}"
7059        );
7060    }
7061
7062    #[test]
7063    fn scan_polydat_braced_refs_handles_escaped_quotes_in_strings() {
7064        // `"foo \"with brace {x}\" bar"` — the inner `{x}` is
7065        // inside a string the whole way through; backslash-escape
7066        // must not be treated as the end of the string.
7067        let refs = scan_polydat_braced_refs("x := concat(\"prefix \\\"{embedded}\\\" suffix\")\n");
7068        assert!(refs.is_empty(), "escaped quotes inside strings: {refs:?}");
7069    }
7070
7071    #[test]
7072    fn scan_polydat_braced_refs_ignores_comments() {
7073        let refs = scan_polydat_braced_refs(
7074            "# this is a comment with {fake} placeholder\n\
7075             const real := 1\n",
7076        );
7077        assert!(
7078            refs.is_empty(),
7079            "`{{fake}}` inside a comment must not be flagged: {refs:?}"
7080        );
7081    }
7082
7083    #[test]
7084    fn scan_polydat_braced_refs_catches_multiple_invalid_braces() {
7085        let refs = scan_polydat_braced_refs(
7086            "a := foo({x}, {y})\n\
7087             b := bar({z})\n",
7088        );
7089        // Order is source order; uniqueness isn't enforced here
7090        // (the validator caller dedups before reporting).
7091        assert_eq!(
7092            refs,
7093            vec!["x".to_string(), "y".to_string(), "z".to_string(),]
7094        );
7095    }
7096
7097    #[test]
7098    fn scan_polydat_braced_refs_handles_mixed_string_and_expression_braces() {
7099        // `{inside}` is in a string (OK); `{outside}` is in
7100        // expression position (flagged).
7101        let refs = scan_polydat_braced_refs("x := concat(\"foo {inside}\", {outside})\n");
7102        assert_eq!(refs, vec!["outside".to_string()]);
7103    }
7104
7105    // ── Polydat binding-LHS-name scanner ──────────────────────────
7106
7107    #[test]
7108    fn scan_polydat_binding_lhs_handles_typed_cell_form() {
7109        // `shared name: type := default` — the type annotation sits
7110        // between the name and the assignment; the scanner must still
7111        // collect the name (undeclared-placeholder false-positive fix).
7112        let mut out = std::collections::HashSet::new();
7113        scan_polydat_binding_lhs(
7114            &mut out,
7115            "shared sstables: u64 := 0\nshared measured: f64 := 1.0\nplain := 2\n",
7116        );
7117        assert!(out.contains("sstables"), "{out:?}");
7118        assert!(out.contains("measured"), "{out:?}");
7119        assert!(out.contains("plain"), "{out:?}");
7120    }
7121
7122    #[test]
7123    fn scan_polydat_binding_lhs_handles_tuple_destructure() {
7124        // Multi-output stdlib calls bind multiple names via
7125        // tuple destructure: `(a, b, c) := func(...)`. The
7126        // scanner must register every name on the LHS so the
7127        // placeholder validator doesn't false-flag downstream
7128        // `{a}` / `{b}` references.
7129        let names = scan_to_set("(y, mo, d, h, mi, s, ms) := date_components(0)\n");
7130        for expected in ["y", "mo", "d", "h", "mi", "s", "ms"] {
7131            assert!(
7132                names.contains(expected),
7133                "tuple-LHS scanner missed `{expected}` — got {names:?}"
7134            );
7135        }
7136    }
7137
7138    #[test]
7139    fn scan_polydat_binding_lhs_finds_all_recognised_shapes() {
7140        // Validates the wire-name scanner picks up every shape:
7141        // init / cursor / shared / final modifier-prefixed
7142        // bindings, plus bare `NAME := …` assignments.
7143        let names = scan_to_set(
7144            "const prebuffered := dataset_prebuffer(\"foo\")\n\
7145             cursor q = range(0, 100)\n\
7146             query_vector := query_vector_at(prebuffered, q)\n\
7147             shared query_passes := set_or_get(query_passes, 7)\n\
7148             const tag := \"label_00\"\n",
7149        );
7150        for expected in ["prebuffered", "q", "query_vector", "query_passes", "tag"] {
7151            assert!(
7152                names.contains(expected),
7153                "scanner missed `{expected}` — got {names:?}"
7154            );
7155        }
7156    }
7157
7158    #[test]
7159    fn scan_polydat_binding_lhs_skips_comments_and_blank_lines() {
7160        let names = scan_to_set(
7161            "# comment\n\
7162             \n\
7163             const real_binding := 1\n\
7164             # another comment\n",
7165        );
7166        assert_eq!(names.len(), 1);
7167        assert!(names.contains("real_binding"));
7168    }
7169
7170    #[test]
7171    fn scan_polydat_binding_lhs_ignores_non_binding_lines() {
7172        // Expression-call statements and continuation lines must
7173        // not introduce phantom wires.
7174        let names = scan_to_set(
7175            "foo(1, 2)\n\
7176             bar.baz\n\
7177             const real := 1\n",
7178        );
7179        assert_eq!(names.len(), 1);
7180        assert!(names.contains("real"));
7181    }
7182
7183    #[test]
7184    fn scan_polydat_binding_lhs_picks_up_input_decl_bare() {
7185        let names = scan_to_set("input cycle: u64\nx := hash(cycle)\n");
7186        assert!(names.contains("cycle"));
7187        assert!(names.contains("x"));
7188    }
7189
7190    #[test]
7191    fn scan_polydat_binding_lhs_picks_up_input_decl_untyped() {
7192        let names = scan_to_set("input cycle\n");
7193        assert!(names.contains("cycle"));
7194    }
7195
7196    #[test]
7197    fn scan_polydat_binding_lhs_picks_up_input_decl_tuple() {
7198        let names = scan_to_set("input (cycle: u64, q: f64)\n");
7199        assert!(names.contains("cycle"));
7200        assert!(names.contains("q"));
7201    }
7202
7203    #[test]
7204    fn scan_polydat_binding_lhs_picks_up_extern_decl() {
7205        // `extern name: type [= default]` declares a wire just like
7206        // `input` — a same-op capture target referenced via `{name}`
7207        // must not trip the undeclared-placeholder guard.
7208        let names = scan_to_set(
7209            "extern active_compactions: u64 = 0\n\
7210             extern completion_ratio: f64 = 0.0\n\
7211             extern (a: u64, b: f64)\n",
7212        );
7213        assert!(names.contains("active_compactions"));
7214        assert!(names.contains("completion_ratio"));
7215        assert!(names.contains("a"));
7216        assert!(names.contains("b"));
7217    }
7218
7219    #[test]
7220    fn parse_dryrun_controls_sets_list_flag() {
7221        let cfg = DiagnosticConfig::parse("controls");
7222        assert!(cfg.list_controls);
7223        // Implies phase depth so the runner exits before any
7224        // cycle-time work.
7225        assert_eq!(cfg.depth, ExecDepth::Phase);
7226    }
7227
7228    #[test]
7229    fn parse_dryrun_controls_combines_with_other_flags() {
7230        let cfg = DiagnosticConfig::parse("controls,labels");
7231        assert!(cfg.list_controls);
7232        assert!(cfg.show_labels);
7233    }
7234
7235    #[test]
7236    fn parse_dryrun_unknown_flag_does_not_set_controls() {
7237        let cfg = DiagnosticConfig::parse("phase,bogus");
7238        assert!(!cfg.list_controls);
7239    }
7240
7241    // ── SRD-13d Phase 7 — `dryrun=op` ──
7242
7243    #[test]
7244    fn parse_dryrun_op_sets_op_depth() {
7245        let cfg = DiagnosticConfig::parse("op");
7246        assert_eq!(cfg.depth, ExecDepth::Op);
7247    }
7248
7249    #[test]
7250    fn parse_dryrun_phase_still_sets_phase_depth() {
7251        let cfg = DiagnosticConfig::parse("phase");
7252        assert_eq!(cfg.depth, ExecDepth::Phase);
7253    }
7254
7255    #[test]
7256    fn parse_dryrun_cycle_still_sets_cycle_depth() {
7257        let cfg = DiagnosticConfig::parse("cycle");
7258        assert_eq!(cfg.depth, ExecDepth::Cycle);
7259    }
7260
7261    #[test]
7262    fn parse_dryrun_op_combines_with_wiring_flag() {
7263        let cfg = DiagnosticConfig::parse("op,wiring");
7264        assert_eq!(cfg.depth, ExecDepth::Op);
7265        assert!(cfg.show_wiring);
7266    }
7267
7268    #[test]
7269    fn parse_dryrun_wiring_alone_bumps_depth_to_op() {
7270        // `wiring` needs depth >= Op for kernels to exist; a bare
7271        // `dryrun=wiring` must auto-bump so it produces output
7272        // instead of silently doing nothing at depth=Phase.
7273        let cfg = DiagnosticConfig::parse("wiring");
7274        assert_eq!(cfg.depth, ExecDepth::Op);
7275        assert!(cfg.show_wiring);
7276    }
7277
7278    #[test]
7279    fn parse_dryrun_wiring_does_not_override_explicit_depth() {
7280        // Explicit phase depth wins; `wiring` is then a no-op
7281        // (no kernels to render at phase depth) — the user gets
7282        // what they asked for rather than a silent bump.
7283        let cfg = DiagnosticConfig::parse("phase,wiring");
7284        assert_eq!(cfg.depth, ExecDepth::Phase);
7285        assert!(cfg.show_wiring);
7286    }
7287
7288    #[test]
7289    fn exec_depth_ordering_matches_srd_13d() {
7290        // `Phase` is the shallowest stop, `Full` is the deepest;
7291        // `Op` sits between `Phase` and `Cycle`. Depth-gating
7292        // sites read this ordering as `< Cycle` ⇒ "skip cycles".
7293        assert!(ExecDepth::Phase < ExecDepth::Op);
7294        assert!(ExecDepth::Op < ExecDepth::Cycle);
7295        assert!(ExecDepth::Cycle < ExecDepth::Full);
7296        // The transitive should hold (it would be a derive
7297        // bug if it didn't, but assert it for documentation).
7298        assert!(ExecDepth::Phase < ExecDepth::Cycle);
7299        assert!(ExecDepth::Op < ExecDepth::Full);
7300    }
7301
7302    #[test]
7303    fn exec_depth_phase_and_op_short_circuit_before_cycles() {
7304        // The executor's per-phase early-exit fires when
7305        // `depth < Cycle`. Both Phase and Op satisfy that;
7306        // Cycle and Full do not.
7307        assert!(ExecDepth::Phase < ExecDepth::Cycle);
7308        assert!(ExecDepth::Op < ExecDepth::Cycle);
7309        assert!((ExecDepth::Cycle >= ExecDepth::Cycle));
7310        assert!((ExecDepth::Full >= ExecDepth::Cycle));
7311    }
7312
7313    #[test]
7314    fn render_scope_elision_summary_shows_materialised_and_elides_to() {
7315        use nmbrs_workload::model::{BindingsDef, ScenarioNode, WorkloadPhase};
7316        use std::collections::HashMap;
7317
7318        let phase = WorkloadPhase {
7319            key_metrics: Vec::new(),
7320            dimensions: Default::default(),
7321            cycles: None,
7322            concurrency: None,
7323            rate: None,
7324            daemon: false,
7325            adapter: None,
7326            errors: None,
7327            tries: None,
7328            tries_backoff: None,
7329            interval: None,
7330            repeat: None,
7331            error_rate_max: None,
7332            timeout: None,
7333            stop_when: Vec::new(),
7334            throttle: None,
7335            continue_if: None,
7336            tags: None,
7337            ops: vec![],
7338            for_each: None,
7339            loop_scope: None,
7340            iter_scope: None,
7341            checkpoint: None,
7342            status_metrics: vec![],
7343            metrics: Default::default(),
7344            bindings: BindingsDef::default(),
7345            poll: None,
7346            optimize: None,
7347        };
7348        let mut phases = HashMap::new();
7349        phases.insert("predict".to_string(), phase);
7350        let mut tree = crate::scope_tree::ScopeTree::build(
7351            "default",
7352            &[ScenarioNode::Phase("predict".into())],
7353        );
7354        // Conservative classifier: empty workload + empty
7355        // phase ⇒ scenario and phase elide into root.
7356        let inputs = crate::scope_elision::ClassifyInputs {
7357            bindings: &BindingsDef::default(),
7358            params: &HashMap::new(),
7359            phases: &phases,
7360        };
7361        crate::scope_elision::classify_and_mark(&mut tree, &inputs);
7362
7363        let mut buf: Vec<u8> = Vec::new();
7364        render_scope_elision_summary(&tree, &mut buf).unwrap();
7365        let s = String::from_utf8(buf).unwrap();
7366
7367        assert!(s.contains("scope elision summary"), "missing header: {s}");
7368        // Workload root materialises always (SRD-13d §5.1).
7369        assert!(
7370            s.contains("workload") && s.contains("materialised=true"),
7371            "expected materialised=true line for workload root: {s}"
7372        );
7373        // Scenario + phase elide into the workload root.
7374        assert!(
7375            s.contains("elides-to=workload"),
7376            "expected elides-to=workload for empty phase: {s}"
7377        );
7378        assert!(
7379            s.contains("workload.scenario.default"),
7380            "expected scenario logical name: {s}"
7381        );
7382        assert!(
7383            s.contains("workload.scenario.default.phase.predict"),
7384            "expected phase logical name: {s}"
7385        );
7386    }
7387
7388    #[test]
7389    fn render_controls_tree_empty_session_writes_placeholder() {
7390        let root = nmbrs_metrics::component::Component::root(
7391            nmbrs_metrics::labels::Labels::of("session", "t"),
7392            std::collections::HashMap::new(),
7393        );
7394        let mut buf: Vec<u8> = Vec::new();
7395        render_controls_tree(&root, &mut buf).unwrap();
7396        let s = String::from_utf8(buf).unwrap();
7397        assert!(s.contains("no controls declared"), "got: {s}");
7398    }
7399
7400    #[test]
7401    fn render_controls_tree_lists_session_root_controls() {
7402        let root = nmbrs_metrics::component::Component::root(
7403            nmbrs_metrics::labels::Labels::of("session", "t"),
7404            std::collections::HashMap::new(),
7405        );
7406        root.read().unwrap().controls().declare(
7407            nmbrs_metrics::controls::ControlBuilder::new("log_level", 1u32)
7408                .reify_as_gauge(|v| Some(*v as f64))
7409                .branch_scope(nmbrs_metrics::controls::BranchScope::Subtree)
7410                .from_f64(|v| Ok(v as u32))
7411                .final_at_scope("session_root")
7412                .build(),
7413        );
7414
7415        let mut buf: Vec<u8> = Vec::new();
7416        render_controls_tree(&root, &mut buf).unwrap();
7417        let s = String::from_utf8(buf).unwrap();
7418        assert!(s.contains("log_level"), "missing name: {s}");
7419        assert!(s.contains("scope=subtree"), "missing scope: {s}");
7420        assert!(
7421            s.contains("final@session_root"),
7422            "missing final marker: {s}"
7423        );
7424        assert!(s.contains("f64-writable"), "missing write surface: {s}");
7425    }
7426
7427    // ── Regression: --session-path value not auto-promoted to scenario= ──
7428    //
7429    // Bug shape (caught by user during Phase C live exercise):
7430    // `nmbrs run wl.yaml cycles=2 --session-path X` was rewritten to
7431    // `nmbrs run wl.yaml cycles=2 --session-path scenario=X` because
7432    // `normalize_args` walked tokens flat and saw `X` as a bare
7433    // post-workload positional. Symptom: a literal directory at
7434    // `<cwd>/scenario=X` was created. The fix peeks for value-taking
7435    // flags so the value passes through unchanged.
7436
7437    fn s(v: &[&str]) -> Vec<String> {
7438        v.iter().map(|x| x.to_string()).collect()
7439    }
7440
7441    #[test]
7442    fn normalize_args_session_path_space_form_value_passes_through() {
7443        let out = normalize_args(&s(&[
7444            "wl.yaml",
7445            "cycles=2",
7446            "--session-path",
7447            "target/test-tmp/foo/session",
7448        ]));
7449        // The path arg must NOT be turned into `scenario=...`.
7450        assert!(
7451            !out.iter().any(|a| a.starts_with("scenario=")),
7452            "scenario= auto-promotion fired on a flag value: {out:?}"
7453        );
7454        assert_eq!(
7455            out,
7456            s(&[
7457                "wl.yaml",
7458                "cycles=2",
7459                "--session-path",
7460                "target/test-tmp/foo/session",
7461            ])
7462        );
7463    }
7464
7465    #[test]
7466    fn normalize_args_session_path_equals_form_unchanged() {
7467        let out = normalize_args(&s(&[
7468            "wl.yaml",
7469            "--session-path=target/test-tmp/foo/session",
7470        ]));
7471        assert_eq!(
7472            out,
7473            s(&["wl.yaml", "--session-path=target/test-tmp/foo/session",])
7474        );
7475    }
7476
7477    #[test]
7478    fn normalize_args_real_scenario_positional_still_promotes() {
7479        // The original feature: bare-word scenario shorthand.
7480        // Must keep working when no value-flag interferes.
7481        let out = normalize_args(&s(&["wl.yaml", "myscenario", "cycles=2"]));
7482        assert_eq!(out, s(&["wl.yaml", "scenario=myscenario", "cycles=2",]));
7483    }
7484
7485    #[test]
7486    fn normalize_args_scenario_after_session_path_still_promotes() {
7487        // After a value-flag pair, the next free positional is
7488        // still eligible for scenario= promotion. This confirms
7489        // the bookkeeping survives the look-ahead.
7490        let out = normalize_args(&s(&["wl.yaml", "--session-path", "/tmp/x", "myscenario"]));
7491        assert_eq!(
7492            out,
7493            s(&["wl.yaml", "--session-path", "/tmp/x", "scenario=myscenario",])
7494        );
7495    }
7496
7497    #[test]
7498    fn normalize_args_readout_value_passes_through() {
7499        let out = normalize_args(&s(&["wl.yaml", "--readout", "throughput ok_pct"]));
7500        assert!(
7501            !out.iter().any(|a| a.starts_with("scenario=")),
7502            "readout body misread as scenario: {out:?}"
7503        );
7504    }
7505
7506    /// `format_for_combinations` lays out vars and specs in
7507    /// column-aligned pairs. Each column is padded to the
7508    /// widest of its (var, spec) so corresponding entries
7509    /// stack vertically. The `color = false` argument forces
7510    /// the no-ANSI branch so the assertion can pattern-match
7511    /// the raw text — no dependency on the process's ambient
7512    /// TTY / `NO_COLOR` state (which `observer::use_color()`
7513    /// caches process-wide on first call and can't be undone
7514    /// per-test).
7515    #[test]
7516    fn format_for_combinations_aligns_columns() {
7517        let pairs = vec![
7518            ("sm".to_string(), "{sm_values}".to_string()),
7519            ("mnc".to_string(), "{mnc_values}".to_string()),
7520            (
7521                "alf_label".to_string(),
7522                "concat({alf_label_values})".to_string(),
7523            ),
7524        ];
7525        let out = format_for_combinations(&pairs, "", false);
7526        let lines: Vec<&str> = out.split('\n').collect();
7527        assert_eq!(lines.len(), 2, "MUST produce exactly 2 lines: {out:?}");
7528        assert!(
7529            lines[0].starts_with("for ["),
7530            "first line MUST start with `for [`: {:?}",
7531            lines[0]
7532        );
7533        assert!(
7534            lines[1].starts_with(" in ["),
7535            "second line MUST start with ` in [`: {:?}",
7536            lines[1]
7537        );
7538        // Bracket columns align: the `[` after `for` and the
7539        // `[` after `in ` should be at the same column index.
7540        let l0_bracket = lines[0].find('[').unwrap();
7541        let l1_bracket = lines[1].find('[').unwrap();
7542        assert_eq!(
7543            l0_bracket, l1_bracket,
7544            "`[` brackets MUST align: line0={l0_bracket}, line1={l1_bracket}"
7545        );
7546        // Column alignment: the comma after `sm,` on line 0
7547        // sits at the same column as the comma after the
7548        // `{sm_values},` on line 1 — except padded so that
7549        // `mnc` on line 0 starts at the same column as
7550        // `{mnc_values}` on line 1.
7551        let mnc_pos = lines[0].find("mnc").unwrap();
7552        let mnc_values_pos = lines[1].find("{mnc_values}").unwrap();
7553        assert_eq!(
7554            mnc_pos, mnc_values_pos,
7555            "column 2 MUST align: `mnc`@{mnc_pos} vs `{{mnc_values}}`@{mnc_values_pos}\n{out}"
7556        );
7557        let alf_pos = lines[0].find("alf_label").unwrap();
7558        let alf_concat_pos = lines[1].find("concat(").unwrap();
7559        assert_eq!(
7560            alf_pos, alf_concat_pos,
7561            "column 3 MUST align: `alf_label`@{alf_pos} vs `concat(...)`@{alf_concat_pos}\n{out}"
7562        );
7563        // Closing brackets present on both lines.
7564        assert!(lines[0].ends_with(']'));
7565        assert!(lines[1].ends_with(']'));
7566    }
7567}