Skip to main content

nmbrs_workload/
report.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Unified `report:` block — plots and tables under one schema.
5//!
6//! See SRD-46 (`docs/SRD/46_reports.md`) for the authoritative
7//! design. This module owns:
8//!
9//! - The data model: [`Report`] / [`ReportGroup`] / [`ReportItem`]
10//!   / [`Kind`] / [`Style`].
11//! - The directive-string tokenizer that splits a group's body
12//!   into items keyed by leading `plot <name>` / `table <name>`.
13//! - The JSON sub-block parser for `series ... {…}` style
14//!   overrides (strict JSON only — relies on the existing rule
15//!   that Polydat `{...}` is unambiguously not JSON).
16//! - Style cascade helpers: `defaults` at workload root,
17//!   `defaults` at group level, then per-item directives.
18//!
19//! The crate is parser-only. Renderers in `crates/nmbrs/src/plot_metrics.rs`
20//! and the corresponding table renderer consume `ReportItem.body`
21//! plus the resolved [`Style`] — they don't touch the raw YAML
22//! again.
23
24use serde::{Deserialize, Serialize};
25use std::collections::HashSet;
26
27pub mod vocab;
28pub use vocab::{
29    AGG_FNS, ALL_DIRECTIVES, AXIS_SCALES, Directive, DirectiveTarget, KindMask, LINE_STYLES,
30    MARKER_SHAPES, PALETTE_NAMES, ValueProvider, YamlForm, cli_flags_for, directive_by_cli_flag,
31    directive_by_yaml_keyword, directives_for,
32};
33
34/// Top-level `report:` block.
35#[derive(Debug, Clone, Default, Serialize, Deserialize)]
36pub struct Report {
37    /// Cross-cutting style + metadata defaults declared via the
38    /// reserved `defaults:` mapping. Cascade into every group.
39    #[serde(default)]
40    pub defaults: Style,
41    /// Groups in YAML declaration order. Each group's name becomes
42    /// a markdown section heading; items render in body order.
43    #[serde(default)]
44    pub groups: Vec<ReportGroup>,
45}
46
47impl Report {
48    /// Iterate every item across every group in declaration order.
49    pub fn items(&self) -> impl Iterator<Item = &ReportItem> {
50        self.groups.iter().flat_map(|g| g.items.iter())
51    }
52
53    /// Find an item by canonical name. Returns the first match in
54    /// declaration order. Names should be unique within a `Report`
55    /// (collisions are caught at parse time).
56    pub fn find(&self, name: &str) -> Option<&ReportItem> {
57        self.items().find(|i| i.name == name)
58    }
59
60    /// Resolve the effective style for one item, walking the
61    /// cascade: report defaults → group defaults → item directives.
62    pub fn effective_style(&self, group: &ReportGroup, item: &ReportItem) -> Style {
63        let mut s = self.defaults.clone();
64        s.merge_from(&group.defaults);
65        s.merge_from(&item.style);
66        s
67    }
68}
69
70/// One named container in `report:`. Holds zero or more items
71/// plus group-level defaults.
72#[derive(Debug, Clone, Default, Serialize, Deserialize)]
73pub struct ReportGroup {
74    /// YAML key the group was declared under (e.g.
75    /// `recall_block`). Used as the markdown section heading.
76    pub name: String,
77    /// Group-level style defaults (from `defaults <directives>`
78    /// lines at the start of the group body). Cascade into every
79    /// item in this group.
80    #[serde(default)]
81    pub defaults: Style,
82    /// Items declared in this group, in body declaration order.
83    #[serde(default)]
84    pub items: Vec<ReportItem>,
85}
86
87/// One renderable report item — either a plot or a table.
88#[derive(Debug, Clone, Default, Serialize, Deserialize)]
89pub struct ReportItem {
90    /// `plot` or `table`.
91    pub kind: Kind,
92    /// Canonical name (the token after `plot` / `table`).
93    pub name: String,
94    /// Display label (`label "..."`). Falls back to a prettified
95    /// form of `name` when absent.
96    #[serde(default)]
97    pub label: Option<String>,
98    /// Output-filename stem (`as <stem>`). When absent, default
99    /// is `plot_<name>` / `table_<name>` derived at render time.
100    #[serde(default)]
101    pub as_stem: Option<String>,
102    /// Per-item style overrides parsed from the directive body.
103    #[serde(default)]
104    pub style: Style,
105    /// Raw spec body — the directive lines following the
106    /// `<kind> <name>` line, with `as`/`label`/style directives
107    /// stripped out (they live on the [`ReportItem`] / [`Style`]
108    /// fields). Renderers parse this exactly the way they parse
109    /// the legacy CLI spec strings.
110    #[serde(default)]
111    pub body: String,
112    /// Output file this item flows into when the markdown
113    /// assembler runs. `None` ⇒ default `summary.md`. Set by a
114    /// preceding `file <filename>` directive in the same group.
115    /// Resolved at parse time so consumers don't need to walk
116    /// the group order.
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub target_file: Option<String>,
119    /// Declaration ordinal across the whole `report:` block,
120    /// stamped by [`parse_report`] and persisted as an
121    /// `order <n>` directive line, so a db-sourced render
122    /// (`report.<name>` metadata rows, which iterate in key
123    /// order) can restore declaration order. `serde(skip)`:
124    /// positional metadata derived at parse, not document
125    /// content.
126    #[serde(skip)]
127    pub order: Option<usize>,
128    /// Plot-only directive: when `true`, the renderer
129    /// emits a companion table immediately after the plot
130    /// in the same markdown file, sharing the plot's
131    /// underlying query data. The companion table reuses
132    /// the plot's name with a `_table` suffix for its
133    /// anchor and figure-numbering slot, so users can
134    /// link to either view independently.
135    ///
136    /// Set via `with-table: true` in the plot's body.
137    /// No-op for `Kind::Table` and other non-plot items.
138    /// Default `false` — plots without an explicit toggle
139    /// keep their existing single-image behaviour.
140    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
141    pub with_table: bool,
142    /// Plot-only directive: when non-empty, the renderer
143    /// emits one companion table per distinct value tuple
144    /// of the listed label keys. Each table is filtered to
145    /// rows whose labels match that tuple, and gets its own
146    /// markdown section / standalone file named with the
147    /// tuple values appended.
148    ///
149    /// Set via `with-tables: [label1, label2, …]` in the
150    /// plot body. Independent of (and composes with)
151    /// `with-table: true` — the singular form still emits
152    /// a single un-faceted table when set.
153    #[serde(default, skip_serializing_if = "Vec::is_empty")]
154    pub with_tables: Vec<String>,
155}
156
157/// Kind discriminator. Identifies which renderer owns the item.
158///
159/// `Plot` and `Table` are figures — they carry data and get a
160/// figure number. `Text` is markdown prose; `File` is a scope
161/// directive that switches subsequent items' output file.
162/// `Details` is an auto-injected session-context block (the
163/// runner emits one to every target markdown file at end-of-
164/// run; users can also declare it explicitly to control its
165/// position). Only Plot and Table participate in figure
166/// numbering.
167#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
168#[serde(rename_all = "lowercase")]
169#[derive(Default)]
170pub enum Kind {
171    #[default]
172    Plot,
173    Table,
174    Text,
175    File,
176    Details,
177}
178
179impl Kind {
180    pub fn as_str(&self) -> &'static str {
181        match self {
182            Kind::Plot => "plot",
183            Kind::Table => "table",
184            Kind::Text => "text",
185            Kind::File => "file",
186            Kind::Details => "details",
187        }
188    }
189
190    /// True for kinds that contribute a figure to the report
191    /// (plot, table). Used by the figure-numbering pass.
192    pub fn is_figure(&self) -> bool {
193        matches!(self, Kind::Plot | Kind::Table)
194    }
195}
196
197/// SRD-46 output destination for a rendered report item.
198///
199/// The set is declared with `to <dest>[, <dest>…]` and rides the
200/// style cascade (report defaults → group defaults → item), so a
201/// whole report can be routed in one line. An inner declaration
202/// REPLACES an outer one rather than unioning with it — routing
203/// you can't take back would make the outer default a trap.
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205#[serde(rename_all = "lowercase")]
206pub enum Destination {
207    /// The session directory: standalone artifact + markdown
208    /// upsert. The default when nothing is declared.
209    SessionDir,
210    /// The console form on stdout. Never implied — see
211    /// [`vocab::DESTINATION_NAMES`].
212    Stdout,
213    /// The console form on stderr.
214    Stderr,
215    /// Render nothing.
216    None,
217}
218
219impl Destination {
220    /// Parse one destination name — exactly one of
221    /// [`vocab::DESTINATION_NAMES`], case-sensitive.
222    pub fn parse(s: &str) -> Option<Self> {
223        Some(match s.trim() {
224            "sessiondir" => Self::SessionDir,
225            "stdout" => Self::Stdout,
226            "stderr" => Self::Stderr,
227            "none" => Self::None,
228            _ => return None,
229        })
230    }
231
232    /// Retired destination spellings and the name that replaced
233    /// each; an error names the replacement, never accepts it.
234    fn retired_replacement(s: &str) -> Option<&'static str> {
235        match s {
236            "session" | "session_dir" => Some("sessiondir"),
237            "off" => Some("none"),
238            _ => None,
239        }
240    }
241
242    pub fn as_str(self) -> &'static str {
243        match self {
244            Self::SessionDir => "sessiondir",
245            Self::Stdout => "stdout",
246            Self::Stderr => "stderr",
247            Self::None => "none",
248        }
249    }
250
251    /// Parse a comma- (or whitespace-) separated destination
252    /// list. `none` anywhere in the list wins outright: it is a
253    /// suppression, not a peer.
254    pub fn parse_list(s: &str) -> Result<Vec<Self>, String> {
255        let mut out: Vec<Self> = Vec::new();
256        for tok in s.split([',', ' ', '\t']).filter(|t| !t.trim().is_empty()) {
257            let tok = tok.trim();
258            let d = Self::parse(tok).ok_or_else(|| match Self::retired_replacement(tok) {
259                Some(canonical) => format!("destination '{tok}' — write '{canonical}'"),
260                None => format!(
261                    "unknown destination '{tok}' — expected one of: {}",
262                    vocab::DESTINATION_NAMES.join(", ")
263                ),
264            })?;
265            if !out.contains(&d) {
266                out.push(d);
267            }
268        }
269        // `none` suppresses delivery; beside a real destination it
270        // would silently cancel it, so the mix is an error.
271        if out.contains(&Self::None) && out.len() > 1 {
272            return Err("`to: none` suppresses delivery and can't be combined with \
273                 other destinations — write `none` alone, or drop it"
274                .to_string());
275        }
276        if out.is_empty() {
277            return Err(format!(
278                "`to` needs at least one destination — expected one of: {}",
279                vocab::DESTINATION_NAMES.join(", ")
280            ));
281        }
282        Ok(out)
283    }
284}
285
286/// Style and figure-metadata bag. Every field optional; cascade
287/// is "first non-`None` wins outer-to-inner".
288#[derive(Debug, Clone, Default, Serialize, Deserialize)]
289pub struct Style {
290    /// Palette name or numeric index (`"wong"`, `"3"`).
291    #[serde(default, skip_serializing_if = "Option::is_none")]
292    pub palette: Option<String>,
293    /// Line-dash style: `solid`, `dashed`, `dotted`, `dashdot`,
294    /// `none`.
295    #[serde(default, skip_serializing_if = "Option::is_none")]
296    pub line: Option<String>,
297    /// Stroke width in pixels.
298    #[serde(default, skip_serializing_if = "Option::is_none")]
299    pub width: Option<f32>,
300    /// Marker shape: `none`, `circle`, `square`, `triangle`,
301    /// `diamond`, `plus`, `cross`.
302    #[serde(default, skip_serializing_if = "Option::is_none")]
303    pub marker: Option<String>,
304    /// Marker radius in pixels.
305    #[serde(default, skip_serializing_if = "Option::is_none")]
306    pub size: Option<f32>,
307    /// Hex color override (`#RRGGBB`).
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    pub color: Option<String>,
310    /// Figure width in pixels.
311    #[serde(default, skip_serializing_if = "Option::is_none")]
312    pub figure_width: Option<u32>,
313    /// Figure height in pixels.
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    pub figure_height: Option<u32>,
316    /// Per-series JSON sub-block overrides keyed by the
317    /// `<key>=<value>` discriminator after the `series` directive.
318    /// Values are arbitrary JSON objects; renderers consume the
319    /// fields they recognise.
320    #[serde(default, skip_serializing_if = "Vec::is_empty")]
321    pub series: Vec<SeriesOverride>,
322    /// SRD-46 output routing (`to stdout, sessiondir`). `None`
323    /// means "not declared at this level" — the cascade keeps
324    /// looking outward, and the render entry point supplies the
325    /// default when nothing declared it anywhere.
326    #[serde(default, skip_serializing_if = "Option::is_none")]
327    pub destinations: Option<Vec<Destination>>,
328}
329
330/// One `series <key>=<value> {...}` directive.
331#[derive(Debug, Clone, Serialize, Deserialize)]
332pub struct SeriesOverride {
333    /// Discriminator key (e.g. `profile`).
334    pub key: String,
335    /// Discriminator value (e.g. `hnsw`).
336    pub value: String,
337    /// Style overrides — strict JSON object verbatim, parsed
338    /// into a Style at apply time.
339    pub style: Style,
340}
341
342impl ReportItem {
343    /// Render this item back to its canonical YAML directive
344    /// form — the same string shape the workload-YAML parser
345    /// in `parse_group` consumes. Round-trips:
346    /// `parse_group(... item.to_yaml_directive_string() ...) == item`.
347    ///
348    /// The output is one or more lines:
349    ///
350    /// ```text
351    /// plot <name>
352    ///   as <stem>
353    ///   label "<label>"
354    ///   palette=<v>
355    ///   line=<v> width=<n> marker=<v> size=<n> color=<#hex>
356    ///   <body lines verbatim>
357    ///   series <key>=<val> {<json>}
358    /// ```
359    ///
360    /// Order matches [`vocab::ALL_DIRECTIVES`] so the
361    /// round-trip is stable. Style fields that are `None` are
362    /// omitted; the body is appended verbatim (it carries the
363    /// renderer-consumed `over` / `by` / `where` / `agg` /
364    /// `xlabel` / etc. lines).
365    pub fn to_yaml_directive_string(&self) -> String {
366        let mut out = String::new();
367        // Header line: `<kind> <name>`. `Details` items also
368        // round-trip; `File` directives use their target stem
369        // as the "name" (a `file <stem>` line).
370        out.push_str(self.kind.as_str());
371        out.push(' ');
372        out.push_str(&self.name);
373        // Text headers need the trailing colon: it is the parser's
374        // "named" signal (a bare `text <word>` line is the legacy
375        // anonymous single-line body form). Without it the
376        // round-trip anonymized the item and leaked the name into
377        // the rendered prose.
378        if matches!(self.kind, Kind::Text) {
379            out.push(':');
380        }
381        out.push('\n');
382
383        // `as <stem>` and `label "<text>"` come first when
384        // present — the reader expects identity directives
385        // before the per-renderer body.
386        if let Some(stem) = &self.as_stem {
387            out.push_str("  as ");
388            out.push_str(stem);
389            out.push('\n');
390        }
391        if let Some(label) = &self.label {
392            out.push_str("  label \"");
393            out.push_str(&label.replace('\\', "\\\\").replace('"', "\\\""));
394            out.push_str("\"\n");
395        }
396        if let Some(target) = &self.target_file {
397            out.push_str("  target ");
398            out.push_str(target);
399            out.push('\n');
400        }
401        // Routing travels with the item so a persisted item
402        // replayed by `nmbrs report` lands where it was declared
403        // to land, not where the replaying command defaults.
404        if let Some(dests) = &self.style.destinations {
405            out.push_str("  to ");
406            out.push_str(
407                &dests
408                    .iter()
409                    .map(|d| d.as_str())
410                    .collect::<Vec<_>>()
411                    .join(", "),
412            );
413            out.push('\n');
414        }
415        if let Some(order) = self.order {
416            out.push_str("  order ");
417            out.push_str(&order.to_string());
418            out.push('\n');
419        }
420        if self.with_table {
421            out.push_str("  with-table true\n");
422        }
423        if !self.with_tables.is_empty() {
424            out.push_str("  with-tables [");
425            out.push_str(&self.with_tables.join(", "));
426            out.push_str("]\n");
427        }
428
429        // Style scalars in declaration order from the vocab
430        // registry. Each is `<key>=<value>` on its own line —
431        // matches the existing parser's `apply_one_style_kv`
432        // contract.
433        for line in self.style.scalar_directive_lines() {
434            out.push_str("  ");
435            out.push_str(&line);
436            out.push('\n');
437        }
438
439        // Body lines (over / by / where / agg / xlabel / etc.)
440        // are passed through verbatim. The body is already in
441        // the canonical form the renderer expects.
442        if !self.body.trim().is_empty() {
443            for line in self.body.split('\n') {
444                if line.trim().is_empty() {
445                    continue;
446                }
447                out.push_str("  ");
448                out.push_str(line.trim_start());
449                out.push('\n');
450            }
451        }
452
453        // Per-series sub-blocks. Use the brace-free directive
454        // form (`series profile=hnsw line=dashed`) when only
455        // simple key=value scalars are involved; fall back to
456        // the JSON form for completeness when the series style
457        // carries series-style fields that don't survive the
458        // simple form (today they all do, but reserved for
459        // future extension).
460        for s in &self.style.series {
461            out.push_str("  style ");
462            out.push_str(&s.key);
463            out.push('=');
464            out.push_str(&s.value);
465            for line in s.style.scalar_directive_lines() {
466                out.push(' ');
467                out.push_str(&line);
468            }
469            out.push('\n');
470        }
471
472        out
473    }
474}
475
476impl Style {
477    /// Render the scalar (non-series) fields of this style
478    /// as a list of `key=value` directive lines, in the
479    /// canonical [`vocab::ALL_DIRECTIVES`] order. Used by
480    /// [`ReportItem::to_yaml_directive_string`] and by
481    /// the `series` sub-block renderer.
482    ///
483    /// `None` fields are skipped; only fields whose vocab
484    /// `target` is [`vocab::DirectiveTarget::StyleField`]
485    /// are emitted.
486    pub fn scalar_directive_lines(&self) -> Vec<String> {
487        let mut out = Vec::new();
488        for d in vocab::ALL_DIRECTIVES {
489            if !matches!(d.target, vocab::DirectiveTarget::StyleField) {
490                continue;
491            }
492            let value: Option<String> = match d.yaml_directive {
493                "palette" => self.palette.clone(),
494                "line" => self.line.clone(),
495                "width" => self.width.map(|v| v.to_string()),
496                "marker" => self.marker.clone(),
497                "size" => self.size.map(|v| v.to_string()),
498                "color" => self.color.clone(),
499                "figure_width" => self.figure_width.map(|v| v.to_string()),
500                "figure_height" => self.figure_height.map(|v| v.to_string()),
501                _ => None,
502            };
503            if let Some(v) = value {
504                out.push(format!("{}={}", d.yaml_directive, v));
505            }
506        }
507        out
508    }
509
510    /// Merge `other` into `self`: every `Some(_)` field in `other`
511    /// overrides the corresponding field in `self`. Used to walk
512    /// the cascade outer → inner.
513    pub fn merge_from(&mut self, other: &Style) {
514        if other.palette.is_some() {
515            self.palette = other.palette.clone();
516        }
517        if other.line.is_some() {
518            self.line = other.line.clone();
519        }
520        if other.width.is_some() {
521            self.width = other.width;
522        }
523        if other.marker.is_some() {
524            self.marker = other.marker.clone();
525        }
526        if other.size.is_some() {
527            self.size = other.size;
528        }
529        if other.color.is_some() {
530            self.color = other.color.clone();
531        }
532        if other.figure_width.is_some() {
533            self.figure_width = other.figure_width;
534        }
535        if other.figure_height.is_some() {
536            self.figure_height = other.figure_height;
537        }
538        if !other.series.is_empty() {
539            for s in &other.series {
540                self.series
541                    .retain(|t| !(t.key == s.key && t.value == s.value));
542                self.series.push(s.clone());
543            }
544        }
545        // Routing REPLACES rather than unions: an item declaring
546        // `to stdout` means stdout, not "stdout on top of
547        // whatever the group defaulted to".
548        if other.destinations.is_some() {
549            self.destinations = other.destinations.clone();
550        }
551    }
552
553    /// The declared destination set, or `default_to` when no
554    /// level of the cascade declared one. Callers pass the
555    /// default their entry point implies — files-only for
556    /// automatic end-of-run rendering, files+stdout for an
557    /// explicit `nmbrs report` invocation.
558    pub fn destinations_or(&self, default_to: &[Destination]) -> Vec<Destination> {
559        match &self.destinations {
560            Some(d) => d.clone(),
561            None => default_to.to_vec(),
562        }
563    }
564}
565
566// ---------------------------------------------------------------------------
567// Parsing
568// ---------------------------------------------------------------------------
569
570/// Reserved directive keywords. Used to:
571/// (1) reject group child keys that collide with directive names
572///     (warn / error in strict mode),
573/// (2) detect when a directive line is the start of a new item
574///     (`plot`, `table`) vs a continuation directive.
575const STYLE_DIRECTIVE_KEYWORDS: &[&str] = &[
576    "palette",
577    "line",
578    "width",
579    "marker",
580    "size",
581    "color",
582    "figure_width",
583    "figure_height",
584    "style",
585    "label",
586    "as",
587    "to",
588];
589
590const ITEM_KIND_KEYWORDS: &[&str] = &["plot", "table", "text", "file"];
591
592const ALL_RESERVED_DIRECTIVES: &[&str] = &[
593    "defaults",
594    "plot",
595    "table",
596    "text",
597    "file",
598    "palette",
599    "line",
600    "width",
601    "marker",
602    "size",
603    "color",
604    "figure_width",
605    "figure_height",
606    "style",
607    "label",
608    "as",
609    "to",
610];
611
612/// Parse a `report:` value (a YAML mapping) into a [`Report`].
613///
614/// Errors describe the offending input precisely; warnings (e.g.
615/// empty groups, kind-mismatched directives) are collected
616/// alongside so callers can decide whether to surface or promote
617/// to errors under strict mode.
618pub fn parse_report(value: &serde_json::Value) -> Result<ParsedReport, String> {
619    let map = value
620        .as_object()
621        .ok_or_else(|| "report: must be a mapping".to_string())?;
622
623    let mut report = Report::default();
624    let mut warnings: Vec<String> = Vec::new();
625    let mut seen_names: HashSet<String> = HashSet::new();
626    // Global counter for anonymous text item naming so the
627    // round-trip identity (`report.<name>` keys) stays unique
628    // across the whole document, not just within one group.
629    let mut text_counter: usize = 0;
630
631    for (key, v) in map {
632        let key: &str = key.as_str();
633        if key == "defaults" {
634            report.defaults =
635                parse_style_mapping(v).map_err(|e| format!("report.defaults: {e}"))?;
636            continue;
637        }
638        if STYLE_DIRECTIVE_KEYWORDS.contains(&key) {
639            warnings.push(format!(
640                "report.{key}: bare directive keyword used as a group name; \
641                 nest under `defaults:` to set as a default, or rename the group"
642            ));
643        }
644
645        let body = match v {
646            serde_json::Value::String(s) => s.clone(),
647            serde_json::Value::Null => String::new(),
648            _ => {
649                return Err(format!(
650                    "report.{key}: must be a string (single-line or block scalar) \
651                 of directive lines starting with `plot` / `table`"
652                ));
653            }
654        };
655
656        let group = parse_group(key, &body, &mut warnings, &mut text_counter)?;
657        for it in &group.items {
658            if !seen_names.insert(it.name.clone()) {
659                return Err(format!(
660                    "duplicate report item name '{}' (within scope: workload root)",
661                    it.name
662                ));
663            }
664        }
665        if group.items.is_empty() {
666            warnings.push(format!(
667                "report.{key}: empty group (no `plot` or `table` items)"
668            ));
669        }
670        report.groups.push(group);
671    }
672
673    // Stamp the declaration ordinal across the whole block. The
674    // persisted form (`order <n>`) carries it through the db so
675    // `nmbrs report` renders items in declaration order even when
676    // the metadata rows iterate alphabetically by key.
677    let mut ordinal: usize = 0;
678    for group in &mut report.groups {
679        for item in &mut group.items {
680            item.order = Some(ordinal);
681            ordinal += 1;
682        }
683    }
684
685    Ok(ParsedReport { report, warnings })
686}
687
688/// Result of parsing a `report:` block. Warnings are non-fatal
689/// in normal mode; callers running under SRD-15 strict mode
690/// should promote them to errors.
691#[derive(Debug, Clone, Default)]
692pub struct ParsedReport {
693    pub report: Report,
694    pub warnings: Vec<String>,
695}
696
697/// Parse a single persisted-form report item — header line
698/// (`<kind> <name>`) followed by indented directive lines, as
699/// produced by [`ReportItem::to_yaml_directive_string`]. Used by
700/// the session-db fallback path in `nmbrs report` so the
701/// directive-form knowledge lives in one place.
702pub fn parse_persisted_item(body: &str) -> Result<ReportItem, String> {
703    let mut warnings: Vec<String> = Vec::new();
704    let mut text_counter: usize = 0;
705    let group = parse_group("__persisted__", body, &mut warnings, &mut text_counter)?;
706    group
707        .items
708        .into_iter()
709        .next()
710        .ok_or_else(|| "persisted report item body did not yield any item".to_string())
711}
712
713fn parse_group(
714    name: &str,
715    body: &str,
716    warnings: &mut Vec<String>,
717    text_counter: &mut usize,
718) -> Result<ReportGroup, String> {
719    let mut group = ReportGroup {
720        name: name.to_string(),
721        ..Default::default()
722    };
723    let mut current: Option<PartialItem> = None;
724    // Active output file scope (set by a `file <filename>` line).
725    // Items declared after a `file` directive inherit this until
726    // the next `file` directive in the same group.
727    let mut current_file: Option<String> = None;
728
729    let emit = |partial: PartialItem,
730                target_file: &Option<String>,
731                group: &mut ReportGroup,
732                warnings: &mut Vec<String>|
733     -> Result<(), String> {
734        let mut item = partial.finalize(warnings)?;
735        if item.target_file.is_none() {
736            item.target_file = target_file.clone();
737        }
738        group.items.push(item);
739        Ok(())
740    };
741
742    for (lineno, raw_line) in body.lines().enumerate() {
743        // Strip `#` line comments (SRD-46) before parsing —
744        // honours quoted strings so `label "see #1 above"`
745        // survives.
746        let stripped = strip_line_comment(raw_line);
747        let line = stripped.trim();
748        if line.is_empty() {
749            continue;
750        }
751        let line_no = lineno + 1;
752
753        // `defaults <directives>` — group-level defaults. Only
754        // valid before any item starts (since otherwise the
755        // intent is ambiguous: do they apply to subsequent items
756        // only? to all items? we pick "before-first-item" so
757        // there's exactly one place defaults can land).
758        if let Some(rest) = strip_directive_keyword(line, "defaults") {
759            if current.is_some() {
760                return Err(format!(
761                    "report.{name}:{line_no}: `defaults` must precede the first \
762                     item in the group"
763                ));
764            }
765            apply_directives_to_style(rest, &mut group.defaults, name, line_no)?;
766            continue;
767        }
768
769        // `<kind> <args>` — start of new item.
770        if let Some((kind, rest)) = strip_kind_keyword(line) {
771            if let Some(prev) = current.take() {
772                emit(prev, &current_file, &mut group, warnings)?;
773            }
774            match kind {
775                Kind::Plot | Kind::Table => {
776                    let mut tokens = rest.splitn(2, char::is_whitespace);
777                    let raw_item_name =
778                        tokens.next().filter(|s| !s.is_empty()).ok_or_else(|| {
779                            format!(
780                                "report.{name}:{line_no}: `{}` must be followed by a name",
781                                kind.as_str()
782                            )
783                        })?;
784                    // Allow trailing `:` on the block header
785                    // (`plot recall_vs_qps:`) for visual parity with
786                    // the body's `name: value` directives. The
787                    // colon is a delimiter — strip it before the
788                    // reserved-keyword check so `plot text:` still
789                    // sees the name as `text`.
790                    let item_name = raw_item_name.strip_suffix(':').unwrap_or(raw_item_name);
791                    if item_name.is_empty() {
792                        return Err(format!(
793                            "report.{name}:{line_no}: `{}` must be followed by a name",
794                            kind.as_str()
795                        ));
796                    }
797                    if ALL_RESERVED_DIRECTIVES.contains(&item_name) {
798                        return Err(format!(
799                            "report.{name}:{line_no}: item name '{item_name}' \
800                             collides with a reserved directive keyword"
801                        ));
802                    }
803                    let trailing = tokens.next().unwrap_or("");
804                    let mut p = PartialItem::new(kind, item_name, name.to_string(), line_no);
805                    if !trailing.trim().is_empty() {
806                        p.directives.push(trailing.to_string());
807                    }
808                    current = Some(p);
809                }
810                Kind::Text => {
811                    // Three surface forms for a `text` block:
812                    //   text <body>                              — anonymous, body on this line
813                    //   text <name>[:]                           — named, body on continuation lines
814                    //   text <name> as "<label>"[:]              — named + alias for the markdown heading
815                    //
816                    // The trailing `:` (per the new uniform
817                    // `name: value` style) is decorative and
818                    // gets stripped before the name is captured.
819                    // A bare `text` with no first token degrades
820                    // to the anonymous auto-name form, preserving
821                    // the legacy single-line shape.
822                    let rest = rest.trim();
823                    // Strip the trailing block-header colon from
824                    // the WHOLE line before tokenising, so it
825                    // doesn't get sucked into the `as "..."`
826                    // alias as `"...":`.
827                    let body = rest.strip_suffix(':').unwrap_or(rest).trim_end();
828                    let header_has_colon = body.len() < rest.len();
829                    let mut tokens = body.splitn(2, char::is_whitespace);
830                    let first = tokens.next().unwrap_or("").trim();
831                    let after = tokens.next().unwrap_or("").trim();
832                    // Decide between named and anonymous. A `text`
833                    // block is named only when the author opted in
834                    // with a positive signal:
835                    //   - a trailing `:` on the header line, or
836                    //   - an `as "<label>"` clause.
837                    // A bare `text <word>` line stays anonymous —
838                    // it's the legacy "single-line text body"
839                    // shape (preserves `text First` / `text Second`
840                    // auto-numbering tests + workloads in the wild).
841                    let has_as_alias = strip_directive_keyword(after, "as").is_some();
842                    let looks_named = !first.is_empty()
843                        && is_bare_text_name(first)
844                        && (header_has_colon || has_as_alias);
845                    let (item_name, alias) = if looks_named {
846                        let alias = strip_directive_keyword(after, "as").map(parse_quoted_or_bare);
847                        (first.to_string(), alias)
848                    } else {
849                        // Anonymous — auto-name globally so the
850                        // persistence round-trip keeps unique
851                        // `report.<name>` keys.
852                        *text_counter += 1;
853                        let auto = format!("text_{:03}", *text_counter);
854                        (auto, None)
855                    };
856                    let mut p = PartialItem::new(Kind::Text, &item_name, name.to_string(), line_no);
857                    if let Some(label) = alias {
858                        p.directives.push(format!("label {label}"));
859                    } else if !looks_named && !rest.is_empty() {
860                        // Anonymous: keep the original-line body
861                        // as a directive (legacy shape).
862                        p.directives.push(rest.to_string());
863                    }
864                    current = Some(p);
865                }
866                Kind::File => {
867                    // `file <filename> [as <label>]` — switches
868                    // the active output file. The directive is
869                    // also persisted as a Kind::File item so the
870                    // listing surface can show it; no body
871                    // attaches.
872                    let mut tokens = rest.splitn(2, char::is_whitespace);
873                    let filename = tokens
874                        .next()
875                        .filter(|s| !s.is_empty())
876                        .ok_or_else(|| {
877                            format!(
878                                "report.{name}:{line_no}: `file` must be followed by a filename"
879                            )
880                        })?
881                        .to_string();
882                    let trailing = tokens.next().unwrap_or("");
883                    let mut p = PartialItem::new(Kind::File, &filename, name.to_string(), line_no);
884                    // Honor optional `as '<label>'` on the same
885                    // line (passed through to finalize via the
886                    // directive list — the `label` extractor
887                    // already understands quoted strings).
888                    if !trailing.trim().is_empty() {
889                        // Translate `as 'X'` → `label X` so the
890                        // existing label extractor handles it.
891                        let trailing = trailing.trim();
892                        if let Some(rest) = strip_directive_keyword(trailing, "as") {
893                            p.directives.push(format!("label {rest}"));
894                        } else {
895                            p.directives.push(trailing.to_string());
896                        }
897                    }
898                    current_file = Some(filename);
899                    current = Some(p);
900                }
901                Kind::Details => {
902                    // Auto-injected at end-of-run; explicit
903                    // `details` declarations are accepted so the
904                    // author can pin position. Body is whatever
905                    // the assembler decides — usually empty
906                    // when declared explicitly (the runtime
907                    // fills it in).
908                    let mut p =
909                        PartialItem::new(Kind::Details, "details", name.to_string(), line_no);
910                    if !rest.trim().is_empty() {
911                        p.directives.push(rest.to_string());
912                    }
913                    current = Some(p);
914                }
915            }
916            continue;
917        }
918
919        // Continuation directive line for the current item.
920        match current.as_mut() {
921            Some(p) => p.directives.push(line.to_string()),
922            None => {
923                return Err(format!(
924                    "report.{name}:{line_no}: directive `{line}` precedes any \
925                 kind keyword (plot / table / text / file)"
926                ));
927            }
928        }
929    }
930
931    if let Some(p) = current.take() {
932        emit(p, &current_file, &mut group, warnings)?;
933    }
934    Ok(group)
935}
936
937struct PartialItem {
938    kind: Kind,
939    name: String,
940    group: String,
941    line_no: usize,
942    directives: Vec<String>,
943}
944
945impl PartialItem {
946    fn new(kind: Kind, name: &str, group: String, line_no: usize) -> Self {
947        Self {
948            kind,
949            name: name.to_string(),
950            group,
951            line_no,
952            directives: Vec::new(),
953        }
954    }
955
956    /// Pull `label` / `as` / style directives out of the directive
957    /// body. Anything else is left in `body` for the kind-specific
958    /// renderer to consume.
959    fn finalize(self, warnings: &mut Vec<String>) -> Result<ReportItem, String> {
960        let mut item = ReportItem {
961            kind: self.kind,
962            name: self.name.clone(),
963            label: None,
964            as_stem: None,
965            style: Style::default(),
966            body: String::new(),
967            target_file: None,
968            order: None,
969            with_table: false,
970            with_tables: Vec::new(),
971        };
972
973        // Text items: body is verbatim markdown. Pull out a
974        // leading `label "..."` line if present (so the heading
975        // can carry a title) plus the identity directives the
976        // persisted round-trip emits — `target <file>` (only when
977        // the remainder is a single token, so prose that happens
978        // to start with the word stays prose) and `order <n>`
979        // (only when the remainder is a number). Every other
980        // line stays as prose. Style / series / `as` directives
981        // don't apply to text — preserved in body if the user
982        // wrote them (most likely they meant prose).
983        if matches!(self.kind, Kind::Text) {
984            let mut body_lines: Vec<String> = Vec::new();
985            for line in &self.directives {
986                let trimmed = line.trim();
987                if trimmed.is_empty() {
988                    body_lines.push(String::new());
989                    continue;
990                }
991                if let Some(rest) = strip_directive_keyword(trimmed, "label") {
992                    item.label = Some(parse_quoted_or_bare(rest));
993                    continue;
994                }
995                if let Some(rest) = strip_directive_keyword(trimmed, "to") {
996                    item.style.destinations = Some(
997                        Destination::parse_list(rest)
998                            .map_err(|e| format!("text '{}': {e}", self.name))?,
999                    );
1000                    continue;
1001                }
1002                if let Some(rest) = strip_directive_keyword(trimmed, "target") {
1003                    let rest = rest.trim();
1004                    if !rest.is_empty() && !rest.contains(char::is_whitespace) {
1005                        item.target_file = Some(rest.to_string());
1006                        continue;
1007                    }
1008                }
1009                if let Some(rest) = strip_directive_keyword(trimmed, "order")
1010                    && let Ok(n) = rest.trim().parse::<usize>()
1011                {
1012                    item.order = Some(n);
1013                    continue;
1014                }
1015                body_lines.push(line.clone());
1016            }
1017            item.body = body_lines.join("\n");
1018            return Ok(item);
1019        }
1020
1021        let mut residual: Vec<String> = Vec::new();
1022        for line in &self.directives {
1023            let line = line.trim();
1024            if line.is_empty() {
1025                continue;
1026            }
1027
1028            if let Some(rest) = strip_directive_keyword(line, "label") {
1029                item.label = Some(parse_quoted_or_bare(rest));
1030                continue;
1031            }
1032            if let Some(rest) = strip_directive_keyword(line, "to") {
1033                item.style.destinations = Some(
1034                    Destination::parse_list(rest)
1035                        .map_err(|e| format!("{} '{}': {e}", self.kind.as_str(), self.name))?,
1036                );
1037                continue;
1038            }
1039            if let Some(rest) = strip_directive_keyword(line, "as") {
1040                item.as_stem = Some(rest.trim().to_string());
1041                continue;
1042            }
1043            // `target <filename>` — per-item override that pins
1044            // the output markdown file independently of any
1045            // surrounding `file <filename>` scope. Used by the
1046            // persisted form (runner emits it for every item so
1047            // the round-trip through the db preserves the
1048            // target the workload's `file` scope assigned).
1049            if let Some(rest) = strip_directive_keyword(line, "target") {
1050                item.target_file = Some(rest.trim().to_string());
1051                continue;
1052            }
1053            // `order <n>` — declaration ordinal, emitted by the
1054            // persisted form so db-sourced renders keep the
1055            // workload's declaration order.
1056            if let Some(rest) = strip_directive_keyword(line, "order")
1057                && let Ok(n) = rest.trim().parse::<usize>()
1058            {
1059                item.order = Some(n);
1060                continue;
1061            }
1062            // `with-tables: [label1, label2, …]` — plot-only
1063            // multi-table fan-out. Emits one companion
1064            // table per distinct value tuple of the listed
1065            // labels. Comes before `with-table` matching so
1066            // the plural form isn't shadowed by the
1067            // prefix-trimmed singular.
1068            if let Some(rest) = strip_directive_keyword(line, "with-tables") {
1069                let trimmed = rest.trim().trim_matches(':').trim();
1070                let inner = trimmed.strip_prefix('[')
1071                    .and_then(|s| s.strip_suffix(']'))
1072                    .ok_or_else(|| format!(
1073                        "report.{}:{} `with-tables`: expected `[label1, label2, …]`, got `{trimmed}`",
1074                        self.group, self.line_no,
1075                    ))?;
1076                let labels: Vec<String> = inner
1077                    .split(',')
1078                    .map(|s| s.trim().trim_matches('"').trim_matches('\'').to_string())
1079                    .filter(|s| !s.is_empty())
1080                    .collect();
1081                if labels.is_empty() {
1082                    return Err(format!(
1083                        "report.{}:{} `with-tables`: list is empty — drop the directive \
1084                         or list one or more label keys",
1085                        self.group, self.line_no,
1086                    ));
1087                }
1088                if !matches!(self.kind, Kind::Plot) {
1089                    warnings.push(format!(
1090                        "report.{}:{} item '{}' uses `with-tables` but is a {}; \
1091                         only plots can have a faceted companion table.",
1092                        self.group,
1093                        self.line_no,
1094                        item.name,
1095                        item.kind.as_str(),
1096                    ));
1097                } else {
1098                    item.with_tables = labels;
1099                }
1100                continue;
1101            }
1102            // `with-table: true|false` — plot-only flag
1103            // that asks the renderer to emit a companion
1104            // table immediately after the plot, sharing
1105            // the plot's underlying query data. SRD-46
1106            // §"Table-from-plot". Accepted-but-warned for
1107            // non-plot items.
1108            if let Some(rest) = strip_directive_keyword(line, "with-table") {
1109                let v = rest.trim().trim_matches(':').trim();
1110                item.with_table = crate::boolean::parse_bool("with-table", v)
1111                    .map_err(|e| format!("report.{}:{} {e}", self.group, self.line_no))?;
1112                if item.with_table && !matches!(self.kind, Kind::Plot) {
1113                    warnings.push(format!(
1114                        "report.{}:{} item '{}' uses `with-table` but is a {}; \
1115                         only plots can have a companion table.",
1116                        self.group,
1117                        self.line_no,
1118                        item.name,
1119                        item.kind.as_str(),
1120                    ));
1121                    item.with_table = false;
1122                }
1123                continue;
1124            }
1125            if let Some(rest) = strip_directive_keyword(line, "style") {
1126                let so = parse_series_override(rest).map_err(|e| {
1127                    format!("report.{}:{} `style`: {}", self.group, self.line_no, e,)
1128                })?;
1129                item.style.series.push(so);
1130                continue;
1131            }
1132
1133            if let Some(applied) = try_apply_style_directives(line, &mut item.style)? {
1134                if !applied {
1135                    residual.push(line.to_string());
1136                } else {
1137                    // Per-item directive that doesn't apply to the
1138                    // item's kind: warn (SRD-46 strict-mode hook).
1139                    if !style_directive_applies_to_kind(line, item.kind) {
1140                        warnings.push(format!(
1141                            "report.{}:{} item '{}' is a {} but uses \
1142                             directive `{}`, which has no effect on this kind",
1143                            self.group,
1144                            self.line_no,
1145                            item.name,
1146                            item.kind.as_str(),
1147                            line
1148                        ));
1149                    }
1150                }
1151                continue;
1152            }
1153
1154            residual.push(line.to_string());
1155        }
1156        item.body = residual.join("\n");
1157        Ok(item)
1158    }
1159}
1160
1161fn strip_directive_keyword<'a>(line: &'a str, kw: &str) -> Option<&'a str> {
1162    let line = line.trim_start();
1163    if let Some(rest) = line.strip_prefix(kw) {
1164        let next = rest.chars().next();
1165        if next.is_none()
1166            || next == Some(' ')
1167            || next == Some('\t')
1168            || next == Some('=')
1169            || next == Some(':')
1170        {
1171            return Some(rest.trim_start_matches([' ', '\t', '=', ':']));
1172        }
1173    }
1174    None
1175}
1176
1177fn strip_kind_keyword(line: &str) -> Option<(Kind, &str)> {
1178    for kw in ITEM_KIND_KEYWORDS {
1179        if let Some(rest) = line.strip_prefix(kw)
1180            && let Some(next) = rest.chars().next()
1181            && next.is_whitespace()
1182        {
1183            let kind = match *kw {
1184                "plot" => Kind::Plot,
1185                "table" => Kind::Table,
1186                "text" => Kind::Text,
1187                "file" => Kind::File,
1188                _ => unreachable!(),
1189            };
1190            return Some((kind, rest.trim_start()));
1191        }
1192    }
1193    None
1194}
1195
1196/// `true` when `s` is a bare identifier-shaped token suitable to
1197/// use as the name of a `text <name>` block — `[A-Za-z_][A-Za-z0-9_-]*`.
1198/// Falls back to anonymous-text auto-naming when the first token
1199/// has whitespace, punctuation, or starts with a digit; that's
1200/// the legacy single-line `text <body>` shape.
1201fn is_bare_text_name(s: &str) -> bool {
1202    let mut chars = s.chars();
1203    match chars.next() {
1204        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
1205        _ => return false,
1206    }
1207    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
1208}
1209
1210fn parse_quoted_or_bare(s: &str) -> String {
1211    let s = s.trim();
1212    if let Some(stripped) = s.strip_prefix('"').and_then(|x| x.strip_suffix('"')) {
1213        return stripped.to_string();
1214    }
1215    if let Some(stripped) = s.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')) {
1216        return stripped.to_string();
1217    }
1218    s.to_string()
1219}
1220
1221/// Apply style directives from a single line (any combination
1222/// of `key=value` pairs separated by whitespace or commas) to
1223/// the given Style. Returns `Ok(Some(true))` if every token on
1224/// the line was a recognized style directive, `Ok(Some(false))`
1225/// if some tokens belonged to the kind-specific spec body, or
1226/// `Ok(None)` if the line doesn't look like a style directive
1227/// line at all (no `=` and no leading style keyword).
1228fn try_apply_style_directives(line: &str, style: &mut Style) -> Result<Option<bool>, String> {
1229    if !line.contains('=') && !line_starts_with_any(line, STYLE_DIRECTIVE_KEYWORDS) {
1230        return Ok(None);
1231    }
1232    let mut all_consumed = true;
1233    for token in tokenize_directive_line(line) {
1234        if let Some((k, v)) = token.split_once('=') {
1235            if STYLE_DIRECTIVE_KEYWORDS.contains(&k) {
1236                apply_one_style_kv(k, v, style)?;
1237            } else {
1238                all_consumed = false;
1239            }
1240        } else if STYLE_DIRECTIVE_KEYWORDS.contains(&token.as_str()) {
1241            // Bare keyword without value — not yet meaningful.
1242            return Err(format!("style directive `{token}` requires a value"));
1243        } else {
1244            all_consumed = false;
1245        }
1246    }
1247    Ok(Some(all_consumed))
1248}
1249
1250fn apply_one_style_kv(k: &str, v: &str, style: &mut Style) -> Result<(), String> {
1251    let v = v.trim().trim_matches('"').trim_matches('\'');
1252    match k {
1253        "palette" => style.palette = Some(v.to_string()),
1254        "line" => style.line = Some(v.to_string()),
1255        "width" => {
1256            style.width = Some(
1257                v.parse()
1258                    .map_err(|_| format!("`width={v}` is not a number"))?,
1259            )
1260        }
1261        "marker" => style.marker = Some(v.to_string()),
1262        "size" => {
1263            style.size = Some(
1264                v.parse()
1265                    .map_err(|_| format!("`size={v}` is not a number"))?,
1266            )
1267        }
1268        "color" => style.color = Some(v.to_string()),
1269        "figure_width" => {
1270            style.figure_width = Some(
1271                v.parse()
1272                    .map_err(|_| format!("`figure_width={v}` is not an integer"))?,
1273            )
1274        }
1275        "figure_height" => {
1276            style.figure_height = Some(
1277                v.parse()
1278                    .map_err(|_| format!("`figure_height={v}` is not an integer"))?,
1279            )
1280        }
1281        // Routing, not cosmetics — but it cascades through the
1282        // same `defaults:` mapping, so it is applied here.
1283        "to" => style.destinations = Some(Destination::parse_list(v)?),
1284        _ => return Err(format!("unknown style directive `{k}`")),
1285    }
1286    Ok(())
1287}
1288
1289fn tokenize_directive_line(line: &str) -> Vec<String> {
1290    // Split on whitespace and commas at depth 0. Quoted values
1291    // stay together. No JSON braces here — those are only inside
1292    // `series` sub-blocks and parsed separately.
1293    let mut out: Vec<String> = Vec::new();
1294    let mut cur = String::new();
1295    let mut quote: Option<char> = None;
1296    for ch in line.chars() {
1297        match quote {
1298            Some(q) if ch == q => {
1299                quote = None;
1300                cur.push(ch);
1301            }
1302            Some(_) => cur.push(ch),
1303            None => match ch {
1304                '"' | '\'' => {
1305                    quote = Some(ch);
1306                    cur.push(ch);
1307                }
1308                ' ' | '\t' | ',' => {
1309                    if !cur.is_empty() {
1310                        out.push(std::mem::take(&mut cur));
1311                    }
1312                }
1313                _ => cur.push(ch),
1314            },
1315        }
1316    }
1317    if !cur.is_empty() {
1318        out.push(cur);
1319    }
1320    out
1321}
1322
1323fn line_starts_with_any(line: &str, kws: &[&str]) -> bool {
1324    let trimmed = line.trim_start();
1325    kws.iter().any(|kw| {
1326        trimmed.starts_with(kw)
1327            && trimmed
1328                .as_bytes()
1329                .get(kw.len())
1330                .is_none_or(|c| matches!(*c, b' ' | b'\t' | b'='))
1331    })
1332}
1333
1334fn style_directive_applies_to_kind(line: &str, kind: Kind) -> bool {
1335    let head = tokenize_directive_line(line)
1336        .first()
1337        .map(|s| {
1338            s.split_once('=')
1339                .map(|(k, _)| k.to_string())
1340                .unwrap_or_else(|| s.clone())
1341        })
1342        .unwrap_or_default();
1343    !matches!(
1344        (kind, head.as_str()),
1345        (Kind::Table, "line" | "width" | "marker" | "size")
1346    )
1347}
1348
1349fn parse_series_override(s: &str) -> Result<SeriesOverride, String> {
1350    // Shape: `<key>=<value> {<json>}`, `<key>=<value> <directives>`,
1351    // or the colon-separator form `<key>=<value>:<directives>` (same
1352    // shape the plot DSL's --style flag accepts; lets workload
1353    // authors write `style phase=pvs_query:line=dotted` without
1354    // having to remember which directive uses which separator).
1355    let s = s.trim();
1356    // Try `:` first when it appears before any whitespace — that's
1357    // the colon-form. Otherwise the head ends at the first
1358    // whitespace boundary as before.
1359    let first_colon = s.find(':');
1360    let first_ws = s.find(char::is_whitespace);
1361    let split_at = match (first_colon, first_ws) {
1362        (Some(c), Some(w)) if c < w => Some((c, 1)), // colon wins
1363        (Some(c), None) => Some((c, 1)),
1364        (_, Some(w)) => Some((w, 1)),
1365        (None, None) => None,
1366    };
1367    let (head, rest) = match split_at {
1368        Some((idx, n)) => (&s[..idx], s[idx + n..].trim_start()),
1369        None => (s, ""),
1370    };
1371    let (key, value) = head
1372        .split_once('=')
1373        .ok_or_else(|| format!("series discriminator must be <key>=<value>, got `{head}`"))?;
1374
1375    let mut style = Style::default();
1376    let rest = rest.trim();
1377
1378    if rest.starts_with('{') {
1379        // JSON sub-block — strict.
1380        if !rest.ends_with('}') {
1381            return Err("JSON sub-block must close with `}` on the same line".to_string());
1382        }
1383        let json: serde_json::Value =
1384            serde_json::from_str(rest).map_err(|e| format!("JSON sub-block parse error: {e}"))?;
1385        apply_json_to_style(&json, &mut style)?;
1386    } else if !rest.is_empty() {
1387        // Brace-free directive form.
1388        try_apply_style_directives(rest, &mut style)?;
1389    }
1390
1391    Ok(SeriesOverride {
1392        key: key.trim().to_string(),
1393        value: value
1394            .trim()
1395            .trim_matches('"')
1396            .trim_matches('\'')
1397            .to_string(),
1398        style,
1399    })
1400}
1401
1402fn apply_json_to_style(v: &serde_json::Value, style: &mut Style) -> Result<(), String> {
1403    let map = v
1404        .as_object()
1405        .ok_or_else(|| "series JSON sub-block must be an object".to_string())?;
1406    for (k, val) in map {
1407        let v_str = match val {
1408            serde_json::Value::String(s) => s.clone(),
1409            serde_json::Value::Number(n) => n.to_string(),
1410            serde_json::Value::Bool(b) => b.to_string(),
1411            _ => {
1412                return Err(format!(
1413                    "series JSON sub-block: value for `{k}` must be a string, number, or bool"
1414                ));
1415            }
1416        };
1417        apply_one_style_kv(k, &v_str, style)?;
1418    }
1419    Ok(())
1420}
1421
1422fn apply_directives_to_style(
1423    line: &str,
1424    style: &mut Style,
1425    group: &str,
1426    line_no: usize,
1427) -> Result<(), String> {
1428    match try_apply_style_directives(line, style) {
1429        Ok(_) => Ok(()),
1430        Err(e) => Err(format!("report.{group}:{line_no}: {e}")),
1431    }
1432}
1433
1434/// Strip a `#` line comment from one source line. A `#` starts
1435/// a comment only when it is at line start or preceded by
1436/// whitespace — so hex colors (`#117733`) and JSON sub-blocks
1437/// (`{"color": "#fff"}`) are unaffected. Quoted strings are
1438/// honoured so `label "see #1 above"` keeps its `#`.
1439fn strip_line_comment(line: &str) -> &str {
1440    let mut quote: Option<char> = None;
1441    let mut prev_ws = true; // start-of-line counts as whitespace boundary
1442    for (i, ch) in line.char_indices() {
1443        match quote {
1444            Some(q) if ch == q => {
1445                quote = None;
1446                prev_ws = false;
1447            }
1448            Some(_) => {
1449                prev_ws = false;
1450            }
1451            None => match ch {
1452                '"' | '\'' => {
1453                    quote = Some(ch);
1454                    prev_ws = false;
1455                }
1456                '#' if prev_ws => return &line[..i],
1457                c if c.is_whitespace() => {
1458                    prev_ws = true;
1459                }
1460                _ => {
1461                    prev_ws = false;
1462                }
1463            },
1464        }
1465    }
1466    line
1467}
1468
1469fn parse_style_mapping(v: &serde_json::Value) -> Result<Style, String> {
1470    let map = v
1471        .as_object()
1472        .ok_or_else(|| "must be a mapping of style directives".to_string())?;
1473    let mut style = Style::default();
1474    for (key, val) in map {
1475        let key = key.as_str();
1476        let value: String = match val {
1477            serde_json::Value::String(s) => s.clone(),
1478            serde_json::Value::Number(n) => n.to_string(),
1479            serde_json::Value::Bool(b) => b.to_string(),
1480            serde_json::Value::Null => continue,
1481            _ => {
1482                return Err(format!(
1483                    "value for `{key}` must be a scalar (string, number, or bool)"
1484                ));
1485            }
1486        };
1487        apply_one_style_kv(key, &value, &mut style)?;
1488    }
1489    Ok(style)
1490}
1491
1492#[cfg(test)]
1493mod tests {
1494    use super::*;
1495
1496    fn parse(yaml: &str) -> ParsedReport {
1497        let v: serde_json::Value = serde_yaml::from_str(yaml).unwrap();
1498        parse_report(&v).unwrap()
1499    }
1500
1501    #[test]
1502    fn single_plot_minimal() {
1503        let p = parse(
1504            r#"
1505recall_block: |
1506  plot recall_at_k10
1507    over limit by profile
1508    label "Recall@10 vs k limit"
1509"#,
1510        );
1511        assert_eq!(p.report.groups.len(), 1);
1512        let g = &p.report.groups[0];
1513        assert_eq!(g.name, "recall_block");
1514        assert_eq!(g.items.len(), 1);
1515        let item = &g.items[0];
1516        assert_eq!(item.kind, Kind::Plot);
1517        assert_eq!(item.name, "recall_at_k10");
1518        assert_eq!(item.label.as_deref(), Some("Recall@10 vs k limit"));
1519        assert!(item.body.contains("over limit"));
1520    }
1521
1522    #[test]
1523    fn defaults_at_root_and_group() {
1524        let p = parse(
1525            r#"
1526defaults:
1527  palette: wong
1528  width: 1024
1529
1530recall_block: |
1531  defaults palette=tol_muted
1532  plot recall_at_k10 over limit
1533"#,
1534        );
1535        assert_eq!(p.report.defaults.palette.as_deref(), Some("wong"));
1536        assert_eq!(p.report.defaults.width, Some(1024.0));
1537        let g = &p.report.groups[0];
1538        assert_eq!(g.defaults.palette.as_deref(), Some("tol_muted"));
1539        // Item-level inherits via merge_from at apply time.
1540        let s = p.report.effective_style(g, &g.items[0]);
1541        assert_eq!(s.palette.as_deref(), Some("tol_muted"));
1542        assert_eq!(s.width, Some(1024.0));
1543    }
1544
1545    #[test]
1546    fn plots_and_tables_in_one_group() {
1547        let p = parse(
1548            r#"
1549combo: |
1550  plot recall_at_k10 over limit
1551  table recall_summary metric=recall@.* group_by=profile
1552"#,
1553        );
1554        let items = &p.report.groups[0].items;
1555        assert_eq!(items.len(), 2);
1556        assert_eq!(items[0].kind, Kind::Plot);
1557        assert_eq!(items[0].name, "recall_at_k10");
1558        assert_eq!(items[1].kind, Kind::Table);
1559        assert_eq!(items[1].name, "recall_summary");
1560    }
1561
1562    #[test]
1563    fn style_json_sub_block() {
1564        let p = parse(
1565            r#"
1566g: |
1567  plot p1 over x
1568    style profile=hnsw {"line": "dashed", "marker": "triangle"}
1569"#,
1570        );
1571        let item = &p.report.groups[0].items[0];
1572        assert_eq!(item.style.series.len(), 1);
1573        let so = &item.style.series[0];
1574        assert_eq!(so.key, "profile");
1575        assert_eq!(so.value, "hnsw");
1576        assert_eq!(so.style.line.as_deref(), Some("dashed"));
1577        assert_eq!(so.style.marker.as_deref(), Some("triangle"));
1578    }
1579
1580    #[test]
1581    fn style_directive_form() {
1582        let p = parse(
1583            r#"
1584g: |
1585  plot p1 over x
1586    style profile=ivf line=dotted color=#117733
1587"#,
1588        );
1589        let so = &p.report.groups[0].items[0].style.series[0];
1590        assert_eq!(so.value, "ivf");
1591        assert_eq!(so.style.line.as_deref(), Some("dotted"));
1592        assert_eq!(so.style.color.as_deref(), Some("#117733"));
1593    }
1594
1595    #[test]
1596    fn duplicate_name_is_error() {
1597        let v: serde_json::Value = serde_yaml::from_str(
1598            r#"
1599g1: "plot dup over x"
1600g2: "plot dup over y"
1601"#,
1602        )
1603        .unwrap();
1604        assert!(parse_report(&v).is_err());
1605    }
1606
1607    #[test]
1608    fn empty_group_warns() {
1609        let p = parse(
1610            r#"
1611empty_block: ""
1612"#,
1613        );
1614        assert_eq!(p.report.groups.len(), 1);
1615        assert!(p.warnings.iter().any(|w| w.contains("empty_block")));
1616    }
1617
1618    #[test]
1619    fn persisted_text_item_round_trips_name_target_and_order() {
1620        // The full text-identity round trip: named text with a
1621        // heading label, a file target, and a declaration
1622        // ordinal must come back from the persisted form with
1623        // NOTHING leaked into the prose body. (Before this, the
1624        // header lost its named signal — the name and `target`
1625        // line rendered as prose and the section fell back to
1626        // summary.md.)
1627        let item = ReportItem {
1628            kind: Kind::Text,
1629            name: "key_metrics_overview".to_string(),
1630            label: Some("Overview".to_string()),
1631            target_file: Some("key_metrics.md".to_string()),
1632            order: Some(3),
1633            body: "First prose line.\ntarget audience is prose, not a directive.".to_string(),
1634            ..Default::default()
1635        };
1636        let persisted = item.to_yaml_directive_string();
1637        let back = parse_persisted_item(&persisted).expect("round-trip parse");
1638        assert_eq!(back.kind, Kind::Text);
1639        assert_eq!(back.name, "key_metrics_overview");
1640        assert_eq!(back.label.as_deref(), Some("Overview"));
1641        assert_eq!(back.target_file.as_deref(), Some("key_metrics.md"));
1642        assert_eq!(back.order, Some(3));
1643        // Prose survives verbatim — including a line that merely
1644        // STARTS with the word `target` (multi-token ⇒ prose).
1645        assert_eq!(back.body, item.body);
1646    }
1647
1648    #[test]
1649    fn destination_list_parses_spellings_and_rejects_junk() {
1650        use Destination::*;
1651        assert_eq!(Destination::parse_list("stdout").unwrap(), vec![Stdout]);
1652        // Comma, whitespace, and mixed separators all work.
1653        assert_eq!(
1654            Destination::parse_list("stdout, sessiondir").unwrap(),
1655            vec![Stdout, SessionDir]
1656        );
1657        assert_eq!(
1658            Destination::parse_list("sessiondir stderr").unwrap(),
1659            vec![SessionDir, Stderr]
1660        );
1661        // Retired spellings and case variants are errors naming the
1662        // canonical word.
1663        for (retired, canonical) in [
1664            ("session", "sessiondir"),
1665            ("session_dir", "sessiondir"),
1666            ("off", "none"),
1667        ] {
1668            let err = Destination::parse_list(retired).unwrap_err();
1669            assert!(err.contains(&format!("write '{canonical}'")), "{err}");
1670        }
1671        assert!(Destination::parse_list("STDOUT").is_err());
1672        // Duplicates collapse rather than double-delivering.
1673        assert_eq!(
1674            Destination::parse_list("stdout,stdout").unwrap(),
1675            vec![Stdout]
1676        );
1677        // `none` is a suppression, not a peer: alone it suppresses;
1678        // beside a real destination it is an error, not a silent win.
1679        assert_eq!(Destination::parse_list("none").unwrap(), vec![None]);
1680        assert!(Destination::parse_list("stdout, none, sessiondir").is_err());
1681        // An unknown destination names the vocabulary.
1682        let err = Destination::parse_list("syslog").unwrap_err();
1683        assert!(err.contains("syslog"), "{err}");
1684        assert!(err.contains("sessiondir"), "names the vocabulary: {err}");
1685        // An empty list is an error, not a silent no-op.
1686        assert!(Destination::parse_list("  ").is_err());
1687    }
1688
1689    #[test]
1690    fn to_directive_parses_and_cascades_replacing_outer() {
1691        let yaml: serde_json::Value = serde_yaml::from_str(
1692            r#"
1693defaults:
1694  to: sessiondir
1695routed: |
1696  table alpha:
1697    to stdout
1698    query: v: avg(x)
1699  table beta:
1700    query: v: avg(y)
1701"#,
1702        )
1703        .expect("yaml");
1704        let parsed = parse_report(&yaml).expect("parse report");
1705        let group = &parsed.report.groups[0];
1706        let alpha = parsed.report.find("alpha").expect("alpha");
1707        let beta = parsed.report.find("beta").expect("beta");
1708
1709        // The item declaration REPLACES the report default rather
1710        // than unioning with it — `to stdout` means stdout, not
1711        // "stdout on top of sessiondir".
1712        assert_eq!(
1713            parsed.report.effective_style(group, alpha).destinations,
1714            Some(vec![Destination::Stdout])
1715        );
1716        // An item that declared nothing inherits the cascade.
1717        assert_eq!(
1718            parsed.report.effective_style(group, beta).destinations,
1719            Some(vec![Destination::SessionDir])
1720        );
1721    }
1722
1723    #[test]
1724    fn undeclared_routing_stays_none_so_the_caller_supplies_the_default() {
1725        // Nothing anywhere in the cascade declared `to`, so the
1726        // parsed style carries `None` — the render entry point
1727        // decides, and the two entry points differ (files-only for
1728        // the automatic run-end render, files+stdout for an
1729        // explicit `nmbrs report`).
1730        let yaml: serde_json::Value = serde_yaml::from_str(
1731            r#"
1732plain: |
1733  table alpha:
1734    query: v: avg(x)
1735"#,
1736        )
1737        .expect("yaml");
1738        let parsed = parse_report(&yaml).expect("parse report");
1739        let group = &parsed.report.groups[0];
1740        let alpha = parsed.report.find("alpha").expect("alpha");
1741        assert_eq!(
1742            parsed.report.effective_style(group, alpha).destinations,
1743            Option::None
1744        );
1745        assert_eq!(
1746            parsed
1747                .report
1748                .effective_style(group, alpha)
1749                .destinations_or(&[Destination::SessionDir]),
1750            vec![Destination::SessionDir]
1751        );
1752    }
1753
1754    #[test]
1755    fn routing_round_trips_through_the_persisted_form() {
1756        // `to` must survive the db round-trip, or an item replayed
1757        // by `nmbrs report` would land where the replaying command
1758        // defaults instead of where it was declared.
1759        let yaml: serde_json::Value = serde_yaml::from_str(
1760            r#"
1761routed: |
1762  table alpha:
1763    to stdout, sessiondir
1764    query: v: avg(x)
1765"#,
1766        )
1767        .expect("yaml");
1768        let parsed = parse_report(&yaml).expect("parse report");
1769        let item = parsed.report.find("alpha").expect("alpha");
1770        let persisted = item.to_yaml_directive_string();
1771        assert!(
1772            persisted.contains("to stdout, sessiondir"),
1773            "persisted form carries routing: {persisted}"
1774        );
1775        let back = parse_persisted_item(&persisted).expect("round-trip");
1776        assert_eq!(
1777            back.style.destinations,
1778            Some(vec![Destination::Stdout, Destination::SessionDir])
1779        );
1780    }
1781
1782    #[test]
1783    fn parse_report_stamps_declaration_ordinals() {
1784        let yaml: serde_json::Value = serde_yaml::from_str(
1785            r#"
1786section_a: |
1787  table alpha:
1788    query: v: avg(x)
1789  text zeta as "Z":
1790   prose
1791section_b: |
1792  table beta:
1793    query: v: avg(y)
1794"#,
1795        )
1796        .expect("yaml");
1797        let parsed = parse_report(&yaml).expect("parse report");
1798        let orders: Vec<(String, Option<usize>)> = parsed
1799            .report
1800            .items()
1801            .map(|i| (i.name.clone(), i.order))
1802            .collect();
1803        assert_eq!(
1804            orders,
1805            vec![
1806                ("alpha".to_string(), Some(0)),
1807                ("zeta".to_string(), Some(1)),
1808                ("beta".to_string(), Some(2)),
1809            ]
1810        );
1811    }
1812
1813    #[test]
1814    fn parse_persisted_item_strips_with_table_from_body() {
1815        // Verbatim shape produced by `to_yaml_directive_string`
1816        // and written to `session_metadata.report.<name>`.
1817        // Lines start at column 0 (no indentation in the
1818        // persisted form). The plot must survive a round-trip
1819        // with `with_table=true` and no `with-table` line in
1820        // the body.
1821        let body = "plot recall_1_mean
1822label \"ALL 1-recall@R, oracles & PVS\"
1823target oracles_report.md
1824legend: bottom-right
1825x: r
1826y1: avg(recall_mean{k=\"1\"}) by (k,r)
1827y-ranges: [[0.0,1.0]]
1828with-table: true";
1829        let item = parse_persisted_item(body).expect("parse_persisted_item should succeed");
1830        assert_eq!(item.name, "recall_1_mean");
1831        assert!(item.with_table, "with_table should be set");
1832        assert!(
1833            !item.body.contains("with-table"),
1834            "body should not contain with-table line; got: {:?}",
1835            item.body,
1836        );
1837    }
1838
1839    #[test]
1840    fn with_table_colon_form_consumed_not_in_body() {
1841        // Regression: the YAML colon form `with-table: true` used
1842        // to fall through `strip_directive_keyword` (which only
1843        // accepted space/tab/`=` separators), leaving the line in
1844        // `item.body`. The plot renderer then saw it as an
1845        // unknown directive and failed every plot it touched.
1846        let p = parse(
1847            r#"
1848g: |
1849  plot p1
1850    over limit
1851    with-table: true
1852"#,
1853        );
1854        let item = &p.report.groups[0].items[0];
1855        assert!(item.with_table, "with-table flag should be set");
1856        assert!(
1857            !item.body.contains("with-table"),
1858            "with-table line should be stripped from body, got: {:?}",
1859            item.body,
1860        );
1861    }
1862
1863    #[test]
1864    fn unknown_directive_falls_into_body() {
1865        let p = parse(
1866            r#"
1867g: |
1868  plot p1
1869    over limit
1870    where dataset=example
1871    custom_directive=foo
1872"#,
1873        );
1874        let item = &p.report.groups[0].items[0];
1875        assert!(item.body.contains("over limit"));
1876        assert!(item.body.contains("custom_directive=foo"));
1877    }
1878
1879    #[test]
1880    fn label_with_quotes() {
1881        let p = parse(
1882            r#"
1883g: |
1884  plot p1 over x
1885    label 'p99 latency'
1886"#,
1887        );
1888        assert_eq!(
1889            p.report.groups[0].items[0].label.as_deref(),
1890            Some("p99 latency")
1891        );
1892    }
1893
1894    #[test]
1895    fn item_name_collides_with_directive_keyword_errors() {
1896        let v: serde_json::Value = serde_yaml::from_str(
1897            r#"
1898g: "plot palette over x"
1899"#,
1900        )
1901        .unwrap();
1902        assert!(parse_report(&v).is_err());
1903    }
1904
1905    #[test]
1906    fn declaration_order_preserved_across_groups() {
1907        let p = parse(
1908            r#"
1909zzz_block: "plot z over x"
1910aaa_block: "plot a over x"
1911mmm_block: "plot m over x"
1912"#,
1913        );
1914        let names: Vec<_> = p.report.groups.iter().map(|g| g.name.clone()).collect();
1915        assert_eq!(names, vec!["zzz_block", "aaa_block", "mmm_block"]);
1916    }
1917
1918    #[test]
1919    fn style_cascade_root_to_item() {
1920        let p = parse(
1921            r#"
1922defaults:
1923  palette: wong
1924  width: 1024
1925
1926g: |
1927  defaults palette=tol_muted
1928  plot p1 over x
1929    palette=ibm
1930"#,
1931        );
1932        let g = &p.report.groups[0];
1933        let item = &g.items[0];
1934        let s = p.report.effective_style(g, item);
1935        assert_eq!(s.palette.as_deref(), Some("ibm"));
1936        assert_eq!(s.width, Some(1024.0));
1937    }
1938
1939    #[test]
1940    fn text_kind_keeps_body_verbatim() {
1941        let p = parse(
1942            r#"
1943intro: |
1944  text Welcome to the report.
1945   Multi-line prose continues here
1946   with arbitrary text.
1947"#,
1948        );
1949        let item = &p.report.groups[0].items[0];
1950        assert_eq!(item.kind, Kind::Text);
1951        assert_eq!(item.name, "text_001");
1952        assert!(item.body.contains("Welcome to the report"));
1953        assert!(item.body.contains("arbitrary text"));
1954    }
1955
1956    #[test]
1957    fn file_directive_scopes_following_items() {
1958        let p = parse(
1959            r#"
1960sections: |
1961  file my_report.md as 'Markdown Report'
1962    text Intro paragraph
1963    plot recall_at_k10 over limit
1964    table summary metric=recall@.* group_by=p
1965"#,
1966        );
1967        let items = &p.report.groups[0].items;
1968        assert_eq!(items.len(), 4);
1969        assert_eq!(items[0].kind, Kind::File);
1970        assert_eq!(items[0].name, "my_report.md");
1971        assert_eq!(items[0].label.as_deref(), Some("Markdown Report"));
1972        // Subsequent items inherit the file as target.
1973        for it in &items[1..] {
1974            assert_eq!(
1975                it.target_file.as_deref(),
1976                Some("my_report.md"),
1977                "item {} should target my_report.md, got {:?}",
1978                it.name,
1979                it.target_file
1980            );
1981        }
1982    }
1983
1984    #[test]
1985    fn file_switch_resets_scope() {
1986        let p = parse(
1987            r#"
1988two_files: |
1989  file alpha.md as 'Alpha'
1990    plot p1 over x
1991  file beta.md
1992    plot p2 over y
1993"#,
1994        );
1995        let items = &p.report.groups[0].items;
1996        // Items 0=file alpha, 1=plot p1 (alpha), 2=file beta, 3=plot p2 (beta)
1997        assert_eq!(items[0].name, "alpha.md");
1998        assert_eq!(items[1].target_file.as_deref(), Some("alpha.md"));
1999        assert_eq!(items[2].name, "beta.md");
2000        assert_eq!(items[3].target_file.as_deref(), Some("beta.md"));
2001    }
2002
2003    #[test]
2004    fn items_before_any_file_have_no_target() {
2005        let p = parse(
2006            r#"
2007mixed: |
2008  plot orphan over x
2009  file r.md
2010    plot inside over x
2011"#,
2012        );
2013        let items = &p.report.groups[0].items;
2014        assert_eq!(items[0].name, "orphan");
2015        assert_eq!(items[0].target_file, None);
2016        assert_eq!(items[2].name, "inside");
2017        assert_eq!(items[2].target_file.as_deref(), Some("r.md"));
2018    }
2019
2020    #[test]
2021    fn hash_line_comments_stripped() {
2022        let p = parse(
2023            r#"
2024g: |
2025  # comment line — ignored
2026  plot p1   # trailing comment
2027    over limit  # also stripped
2028    label "Mean recall"  # don't strip inside quotes
2029"#,
2030        );
2031        let item = &p.report.groups[0].items[0];
2032        assert_eq!(item.kind, Kind::Plot);
2033        assert_eq!(item.name, "p1");
2034        assert!(
2035            item.body.contains("over limit"),
2036            "body kept: {:?}",
2037            item.body
2038        );
2039        assert!(
2040            !item.body.contains("trailing"),
2041            "comment leaked: {:?}",
2042            item.body
2043        );
2044        assert_eq!(item.label.as_deref(), Some("Mean recall"));
2045    }
2046
2047    #[test]
2048    fn auto_text_names_unique_across_document() {
2049        let p = parse(
2050            r#"
2051g1: |
2052  text First
2053  text Second
2054g2: |
2055  text Third
2056"#,
2057        );
2058        let g1 = &p.report.groups[0];
2059        assert_eq!(g1.items[0].name, "text_001");
2060        assert_eq!(g1.items[1].name, "text_002");
2061        // Counter is global, not per-group, so persistence keys
2062        // (`report.<name>`) stay unique.
2063        let g2 = &p.report.groups[1];
2064        assert_eq!(g2.items[0].name, "text_003");
2065    }
2066
2067    #[test]
2068    fn label_directive_strips_quotes() {
2069        let p = parse(
2070            r#"
2071g: |
2072  plot p1 over x
2073    label "My label"
2074  plot p2 over x
2075    label 'Another'
2076"#,
2077        );
2078        let items = &p.report.groups[0].items;
2079        assert_eq!(items[0].label.as_deref(), Some("My label"));
2080        assert_eq!(items[1].label.as_deref(), Some("Another"));
2081    }
2082
2083    // ------------------------------------------------------------------
2084    // Round-trip emitter — Phase A SRD-64 contract test
2085    // ------------------------------------------------------------------
2086    //
2087    // For every report-grammar shape we accept, the emitter
2088    // must produce a string that re-parses to an equal AST.
2089    // That's the contract that lets `--add` write the same
2090    // grammar back to YAML faithfully.
2091
2092    fn round_trip_via_group(item: &ReportItem) -> ReportItem {
2093        let group_body = item.to_yaml_directive_string();
2094        let yaml = format!(
2095            "g: |\n{}",
2096            group_body
2097                .lines()
2098                .map(|l| format!("  {l}"))
2099                .collect::<Vec<_>>()
2100                .join("\n")
2101        );
2102        let parsed = parse(&yaml);
2103        assert_eq!(
2104            parsed.report.groups.len(),
2105            1,
2106            "round-trip should yield one group, got: {parsed:#?}"
2107        );
2108        let items = &parsed.report.groups[0].items;
2109        assert_eq!(
2110            items.len(),
2111            1,
2112            "round-trip should yield one item, got: {items:#?}"
2113        );
2114        items[0].clone()
2115    }
2116
2117    fn assert_round_trip_eq(item: ReportItem) {
2118        let recovered = round_trip_via_group(&item);
2119        // Compare individual fields for clearer diffs on failure.
2120        assert_eq!(recovered.kind, item.kind);
2121        assert_eq!(recovered.name, item.name);
2122        assert_eq!(recovered.label, item.label);
2123        assert_eq!(recovered.as_stem, item.as_stem);
2124        assert_eq!(recovered.style.palette, item.style.palette);
2125        assert_eq!(recovered.style.line, item.style.line);
2126        assert_eq!(recovered.style.width, item.style.width);
2127        assert_eq!(recovered.style.marker, item.style.marker);
2128        assert_eq!(recovered.style.size, item.style.size);
2129        assert_eq!(recovered.style.color, item.style.color);
2130        assert_eq!(recovered.style.figure_width, item.style.figure_width);
2131        assert_eq!(recovered.style.figure_height, item.style.figure_height);
2132        assert_eq!(recovered.style.series.len(), item.style.series.len());
2133        for (a, b) in recovered.style.series.iter().zip(&item.style.series) {
2134            assert_eq!(a.key, b.key);
2135            assert_eq!(a.value, b.value);
2136        }
2137        // Body comparison is whitespace-tolerant: the emitter
2138        // re-indents to canonical 2-space, the parser strips
2139        // leading whitespace anyway.
2140        let normalize = |s: &str| {
2141            s.split('\n')
2142                .map(|l| l.trim())
2143                .filter(|l| !l.is_empty())
2144                .collect::<Vec<_>>()
2145                .join("\n")
2146        };
2147        assert_eq!(normalize(&recovered.body), normalize(&item.body));
2148    }
2149
2150    #[test]
2151    fn round_trip_minimal_plot() {
2152        let item = ReportItem {
2153            kind: Kind::Plot,
2154            name: "demo".to_string(),
2155            body: "over cycle\nmetric=throughput".to_string(),
2156            ..Default::default()
2157        };
2158        assert_round_trip_eq(item);
2159    }
2160
2161    #[test]
2162    fn round_trip_plot_with_label_and_palette() {
2163        let mut item = ReportItem {
2164            kind: Kind::Plot,
2165            name: "recall".to_string(),
2166            label: Some("Recall@10".to_string()),
2167            body: "over limit\nby profile".to_string(),
2168            ..Default::default()
2169        };
2170        item.style.palette = Some("wong".to_string());
2171        assert_round_trip_eq(item);
2172    }
2173
2174    #[test]
2175    fn round_trip_plot_full_style() {
2176        let mut item = ReportItem {
2177            kind: Kind::Plot,
2178            name: "full".to_string(),
2179            label: Some("Full".to_string()),
2180            as_stem: Some("plot_full".to_string()),
2181            body: "over limit\nby profile\nwhere dataset=example\nagg=mean".to_string(),
2182            ..Default::default()
2183        };
2184        item.style.palette = Some("tol_muted".to_string());
2185        item.style.line = Some("dashed".to_string());
2186        item.style.width = Some(2.0);
2187        item.style.marker = Some("circle".to_string());
2188        item.style.size = Some(4.0);
2189        item.style.color = Some("#117733".to_string());
2190        item.style.figure_width = Some(800);
2191        item.style.figure_height = Some(600);
2192        assert_round_trip_eq(item);
2193    }
2194
2195    #[test]
2196    fn round_trip_table() {
2197        let mut item = ReportItem {
2198            kind: Kind::Table,
2199            name: "summary".to_string(),
2200            label: Some("Summary".to_string()),
2201            body: "metric=recall@.*\ngroup_by=profile".to_string(),
2202            ..Default::default()
2203        };
2204        item.style.palette = Some("wong".to_string());
2205        assert_round_trip_eq(item);
2206    }
2207
2208    #[test]
2209    fn round_trip_with_series_overrides() {
2210        let mut item = ReportItem {
2211            kind: Kind::Plot,
2212            name: "perseries".to_string(),
2213            body: "over limit\nby profile".to_string(),
2214            ..Default::default()
2215        };
2216        let s1 = Style {
2217            line: Some("dashed".to_string()),
2218            marker: Some("triangle".to_string()),
2219            ..Default::default()
2220        };
2221        item.style.series.push(SeriesOverride {
2222            key: "profile".to_string(),
2223            value: "hnsw".to_string(),
2224            style: s1,
2225        });
2226        let s2 = Style {
2227            line: Some("solid".to_string()),
2228            ..Default::default()
2229        };
2230        item.style.series.push(SeriesOverride {
2231            key: "profile".to_string(),
2232            value: "ivf".to_string(),
2233            style: s2,
2234        });
2235        let recovered = round_trip_via_group(&item);
2236        assert_eq!(recovered.style.series.len(), 2);
2237        assert_eq!(recovered.style.series[0].key, "profile");
2238        assert_eq!(recovered.style.series[0].value, "hnsw");
2239        assert_eq!(
2240            recovered.style.series[0].style.line.as_deref(),
2241            Some("dashed")
2242        );
2243        assert_eq!(
2244            recovered.style.series[0].style.marker.as_deref(),
2245            Some("triangle")
2246        );
2247        assert_eq!(recovered.style.series[1].value, "ivf");
2248        assert_eq!(
2249            recovered.style.series[1].style.line.as_deref(),
2250            Some("solid")
2251        );
2252    }
2253
2254    #[test]
2255    fn round_trip_label_with_internal_quotes_is_escaped() {
2256        let item = ReportItem {
2257            kind: Kind::Plot,
2258            name: "tricky".to_string(),
2259            label: Some(r#"He said "hi""#.to_string()),
2260            body: "over cycle".to_string(),
2261            ..Default::default()
2262        };
2263        // The emitter must escape the inner quotes so the
2264        // parser sees a single label string. (The parser today
2265        // strips outer quotes only; if it doesn't honour the
2266        // escape, the test catches that as a real bug to fix.)
2267        let group_body = item.to_yaml_directive_string();
2268        assert!(
2269            group_body.contains(r#"label "He said \"hi\"""#),
2270            "emitter should escape inner quotes; got:\n{group_body}"
2271        );
2272    }
2273
2274    #[test]
2275    fn emitter_orders_directives_canonically() {
2276        // `as` comes before `label`; identity before style;
2277        // style (scalar fields) before body; body before
2278        // per-series style overrides. This is the canonical
2279        // order from vocab::ALL_DIRECTIVES so the round-trip
2280        // stays stable.
2281        let mut item = ReportItem {
2282            kind: Kind::Plot,
2283            name: "ordered".to_string(),
2284            label: Some("L".to_string()),
2285            as_stem: Some("S".to_string()),
2286            body: "over cycle".to_string(),
2287            ..Default::default()
2288        };
2289        item.style.palette = Some("wong".to_string());
2290        item.style.series.push(SeriesOverride {
2291            key: "k".to_string(),
2292            value: "v".to_string(),
2293            style: Style::default(),
2294        });
2295        let s = item.to_yaml_directive_string();
2296        let pos = |needle: &str| {
2297            s.find(needle)
2298                .unwrap_or_else(|| panic!("missing {needle} in:\n{s}"))
2299        };
2300        let pos_as = pos("as S");
2301        let pos_label = pos("label \"L\"");
2302        let pos_style = pos("palette=wong");
2303        let pos_body = pos("over cycle");
2304        let pos_per_series = pos("style k=v");
2305        assert!(pos_as < pos_label, "as before label");
2306        assert!(pos_label < pos_style, "label before style");
2307        assert!(pos_style < pos_body, "style before body");
2308        assert!(
2309            pos_body < pos_per_series,
2310            "body before per-series style overrides"
2311        );
2312    }
2313}