Skip to main content

arb/
spec.rs

1//! Interpreter: command tree -> a `Spec`. Recognizes the widget verbs,
2//! `source .x { … }` whose body compiles to a query pipeline (see `query`), and
3//! the `.x <- in` bind shorthand. Unknown widget verbs are ignored so specs stay
4//! forward-compatible.
5
6use std::collections::BTreeMap;
7use std::sync::Arc;
8use std::time::Duration;
9
10use regex::Regex;
11
12use crate::actor::ActorDef;
13use crate::ast::{Arg, Command};
14use crate::query::{FieldSel, QueryOp};
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum WidgetKind {
18    Text,
19    Tail,
20    List,
21    Gauge,
22    Bars,
23    Histo,
24    Spark,
25    Chart,
26    Table,
27    Tabs,
28    Block,
29    Frame,
30    /// A thin single-line progress bar (ratatui `LineGauge`) — a compact `gauge`
31    /// for tight grid cells. Same scalar source + `-max` as `gauge`.
32    LineGauge,
33    /// A braille scatter/line plot (ratatui `Canvas`) of a numeric series — a
34    /// higher-resolution `chart` drawn with braille dots. `-mode line|points`.
35    Scatter,
36    /// A block-bar sparkline (ratatui `Sparkline`) of the numeric series — the
37    /// classic fixed-height bar sparkline (distinct from `spark`'s braille line).
38    Sparkline,
39    /// A braille world map (ratatui `Canvas` + `Map`) plotting `lon lat` points
40    /// parsed from the stream — geo scatter (IP geolocation, GPS traces). `-res
41    /// high|low`.
42    Map,
43    /// A month calendar (ratatui `Monthly`) for the current month, highlighting
44    /// days that appear as `YYYY-MM-DD` in the stream (activity by day).
45    Calendar,
46    /// A level-colored log tail: like `tail`, but each line is tinted by its log
47    /// level (ERROR/WARN/INFO/DEBUG) detected in the text — theme-aware.
48    LogView,
49    /// A heatmap grid (GitHub-contribution-style): the numeric series laid out as
50    /// colored cells, each cell's shade scaled from the value across the palette.
51    Heatmap,
52    /// A treemap (slice-and-dice): `tally`/`count_by` pairs as proportional
53    /// labeled rectangles filling the pane, colored across the palette.
54    Treemap,
55    /// A Gantt/timeline: `label start end` lines drawn as horizontal bars on a
56    /// shared time axis (min start → max end).
57    Gantt,
58    /// A diff-colored view: each line tinted by its leading char — `+` add (green),
59    /// `-` remove (red), `@` hunk (accent) — for `git diff`/patch streams.
60    Diff,
61    /// The ratatui logo (braille wordmark), centered — a decorative splash.
62    Logo,
63    /// A blank spacer (ratatui `Clear`) — occupies a grid cell without drawing, to
64    /// open space in a layout.
65    Blank,
66    /// A horizontal (or `-dir vertical`) divider rule in the theme accent.
67    Rule,
68    /// An in-dashboard selection list over its own `source` (per-widget), with a
69    /// moveable cursor. Its highlighted row is published as the control value
70    /// `.<path>.sel`, readable from `where`/`apply`/`tell`/`ask` (SPEC §14). E.g.
71    /// `ps aux | arb` with `sel .ps { in }` exposes `.ps.sel` = the current row.
72    Sel,
73    /// An editable text field. Its live value is bound into pipelines via
74    /// `apply .name` (parse the value as a query pipeline) — the megafilter/map.
75    Input,
76    /// An interactive fuzzy-select list over the stream (the fzf surface as a
77    /// widget). Its presence puts the TUI in select mode: type to fuzzy-filter,
78    /// arrows/Ctrl-N/P move the cursor, Tab marks, Enter emits the picked lines.
79    /// `-prompt`/`-header` opts set the prompt line and a header above the list.
80    Select,
81    /// A text box whose value drives `where match(.name)` / `apply` — a labelled
82    /// filter control (a specialised `input`).
83    Filter,
84    /// A multi-select of candidate values (`-opts {a b c}`, else distinct stream
85    /// `-field` values). Its value is the comma-joined selected set for
86    /// `where <field> in .name`.
87    Facet,
88    /// A numeric control (`-min`/`-max`/`-step`) whose value drives
89    /// `where <field> < .name`; arrows/`+`/`-` adjust it.
90    Slider,
91    /// A boolean toggle (`-label`); its value is `"1"`/`"0"`.
92    Check,
93}
94
95impl WidgetKind {
96    pub(crate) fn from(verb: &str) -> Option<WidgetKind> {
97        Some(match verb {
98            "text" => WidgetKind::Text,
99            "tail" => WidgetKind::Tail,
100            "list" => WidgetKind::List,
101            "gauge" => WidgetKind::Gauge,
102            "bars" => WidgetKind::Bars,
103            "histo" => WidgetKind::Histo,
104            "spark" => WidgetKind::Spark,
105            "chart" => WidgetKind::Chart,
106            "table" => WidgetKind::Table,
107            "tabs" => WidgetKind::Tabs,
108            "block" => WidgetKind::Block,
109            "frame" => WidgetKind::Frame,
110            "linegauge" => WidgetKind::LineGauge,
111            "scatter" => WidgetKind::Scatter,
112            "sparkline" => WidgetKind::Sparkline,
113            "map" => WidgetKind::Map,
114            "calendar" => WidgetKind::Calendar,
115            "logview" => WidgetKind::LogView,
116            "heatmap" => WidgetKind::Heatmap,
117            "treemap" => WidgetKind::Treemap,
118            "gantt" => WidgetKind::Gantt,
119            "diff" => WidgetKind::Diff,
120            "logo" => WidgetKind::Logo,
121            "clear" | "blank" | "spacer" => WidgetKind::Blank,
122            "rule" | "divider" => WidgetKind::Rule,
123            "sel" => WidgetKind::Sel,
124            "input" => WidgetKind::Input,
125            "select" => WidgetKind::Select,
126            "filter" => WidgetKind::Filter,
127            "facet" => WidgetKind::Facet,
128            "slider" => WidgetKind::Slider,
129            "check" => WidgetKind::Check,
130            _ => return None,
131        })
132    }
133
134    pub fn label(&self) -> &'static str {
135        match self {
136            WidgetKind::Text => "text",
137            WidgetKind::Tail => "tail",
138            WidgetKind::List => "list",
139            WidgetKind::Gauge => "gauge",
140            WidgetKind::Bars => "bars",
141            WidgetKind::Histo => "histo",
142            WidgetKind::Spark => "spark",
143            WidgetKind::Chart => "chart",
144            WidgetKind::Table => "table",
145            WidgetKind::Tabs => "tabs",
146            WidgetKind::Block => "block",
147            WidgetKind::Frame => "frame",
148            WidgetKind::LineGauge => "linegauge",
149            WidgetKind::Scatter => "scatter",
150            WidgetKind::Sparkline => "sparkline",
151            WidgetKind::Map => "map",
152            WidgetKind::Calendar => "calendar",
153            WidgetKind::LogView => "logview",
154            WidgetKind::Heatmap => "heatmap",
155            WidgetKind::Treemap => "treemap",
156            WidgetKind::Gantt => "gantt",
157            WidgetKind::Diff => "diff",
158            WidgetKind::Logo => "logo",
159            WidgetKind::Blank => "clear",
160            WidgetKind::Rule => "rule",
161            WidgetKind::Sel => "sel",
162            WidgetKind::Input => "input",
163            WidgetKind::Select => "select",
164            WidgetKind::Filter => "filter",
165            WidgetKind::Facet => "facet",
166            WidgetKind::Slider => "slider",
167            WidgetKind::Check => "check",
168        }
169    }
170
171    /// Whether this kind is an interactive control (value lives in the input
172    /// registry and drives `apply`/`where … .name`), not a stream view.
173    pub fn is_control(&self) -> bool {
174        matches!(
175            self,
176            WidgetKind::Input
177                | WidgetKind::Filter
178                | WidgetKind::Facet
179                | WidgetKind::Slider
180                | WidgetKind::Check
181                | WidgetKind::Sel
182        )
183    }
184}
185
186/// A data source: reads stdin, then applies a query pipeline.
187#[derive(Debug, Clone)]
188pub struct Source {
189    pub pipeline: Vec<QueryOp>,
190}
191
192#[derive(Debug, Clone)]
193pub struct Widget {
194    pub path: String,
195    pub kind: WidgetKind,
196    pub opts: BTreeMap<String, String>,
197    pub source: Option<Source>,
198    /// Optional search-key pipeline (`search .name { … }`), for a `select`
199    /// widget: the fuzzy match runs against this derived key while the row still
200    /// shows/emits the `source` display. fzf `--nth`, but pipeline-general (search
201    /// a column, a lowercased key, an extracted field). `None` = search display.
202    pub search: Option<Vec<QueryOp>>,
203    /// Grid cell `(row, col)` set by a `grid` command; `None` = auto-stacked.
204    pub grid: Option<(usize, usize)>,
205    /// Grid span `(rows, cols)` from `grid -rowspan`/`-colspan` (`-span` = colspan);
206    /// `(1, 1)` = a single cell. Lets a chart span multiple cells while gauges take one.
207    pub span: (usize, usize),
208}
209
210/// A key binding: a control key that triggers a [`BindAction`] in the TUI.
211/// Declared `bind C-<letter> <action>` — the arb-native way to drive the spec's
212/// own state from the keyboard (set a control, quit), foundation for reactions.
213#[derive(Debug, Clone)]
214pub struct Bind {
215    /// The raw control byte (e.g. Ctrl-U = 0x15).
216    pub key: u8,
217    pub action: BindAction,
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub enum BindAction {
222    /// Set an `input .name` widget's value — with `out { … apply .name }` this
223    /// reshapes the live pipe on a keystroke (a keyboard-driven megafilter/map).
224    SetInput { name: String, value: String },
225    /// Quit the TUI.
226    Quit,
227    /// Ring the terminal bell (write 0x07 after the next draw).
228    Beep,
229    /// Flash a message in the status bar for a few seconds.
230    Alert(String),
231    /// Tint a widget's border/accent for a few seconds. `widget` is the path
232    /// without the leading dot; `color` is a color name (green/red/…).
233    Flash { widget: String, color: String },
234    /// Run a shell command, fire-and-forget (never waits, never blocks the loop).
235    Exec(String),
236    /// Write text to a `spawn -pty` child's stdin — the Expect `send`. No-op
237    /// unless the stream source is a PTY. Include `\n` to submit a line.
238    Send(String),
239    /// `tell REF MSG(args)` — post a message to a session actor/pool, fire-and-
240    /// forget (SPEC §15). `call` is the raw `MSG(args)` text, parsed + evaluated
241    /// (with live control substitution) when the action fires.
242    ActorTell { refname: String, call: String },
243    /// `ask .CTRL REF MSG(args)` — ask a session actor/pool and store the reply
244    /// into control `ctrl` (so a widget bound to it shows the result).
245    ActorAsk {
246        ctrl: String,
247        refname: String,
248        call: String,
249    },
250    /// Run several actions in order (block form `{ alert "x"; beep }`).
251    Seq(Vec<BindAction>),
252}
253
254/// A mouse trigger for a `bind <…> ACTION` (Tk-style events). Extensible; only
255/// `Click` (any button press) ships today.
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub enum MouseTrigger {
258    Click,
259}
260
261/// Parse a key spec to its raw byte. Accepts control-key forms (`C-u`, `c-u`,
262/// `^u`) and the Tk named keys `<Enter>`/`<Esc>`/`<Tab>` and `<Key-X>` (a single
263/// letter). Only these forms bind, so a bind never shadows plain filter typing.
264pub fn parse_key(spec: &str) -> Option<u8> {
265    match spec {
266        "<Enter>" | "<Return>" => return Some(0x0d),
267        "<Esc>" | "<Escape>" => return Some(0x1b),
268        "<Tab>" => return Some(0x09),
269        _ => {}
270    }
271    // `<Key-x>` -> the literal letter byte.
272    if let Some(inner) = spec.strip_prefix("<Key-").and_then(|s| s.strip_suffix('>')) {
273        let ch = inner.chars().next()?;
274        if inner.chars().count() == 1 && ch.is_ascii_alphabetic() {
275            return Some(ch as u8);
276        }
277        return None;
278    }
279    let letter = spec
280        .strip_prefix("C-")
281        .or_else(|| spec.strip_prefix("c-"))
282        .or_else(|| spec.strip_prefix('^'))?;
283    let ch = letter.chars().next()?;
284    if letter.chars().count() != 1 || !ch.is_ascii_alphabetic() {
285        return None;
286    }
287    Some((ch.to_ascii_uppercase() as u8) & 0x1f)
288}
289
290/// Parse a `Ns`/`Nms`/`Nm` duration literal (SPEC §3) into a `Duration`.
291/// `ms` is matched before the bare `s` so `500ms` is not read as `500` seconds.
292pub fn parse_duration(s: &str) -> Option<Duration> {
293    let s = s.trim();
294    if let Some(n) = s.strip_suffix("ms") {
295        return n.trim().parse::<u64>().ok().map(Duration::from_millis);
296    }
297    if let Some(n) = s.strip_suffix('s') {
298        return n.trim().parse::<f64>().ok().map(Duration::from_secs_f64);
299    }
300    if let Some(n) = s.strip_suffix('m') {
301        return n
302            .trim()
303            .parse::<f64>()
304            .ok()
305            .map(|m| Duration::from_secs_f64(m * 60.0));
306    }
307    None
308}
309
310/// An event-driven reaction: when a stream line matches `pattern`, fire `action`.
311/// Declared `expect /regex/ <action>` — the "react" half of Expect. Reuses
312/// [`BindAction`], so a matching line can set a control or quit.
313#[derive(Debug, Clone)]
314pub struct Expect {
315    pub pattern: Regex,
316    pub action: BindAction,
317}
318
319/// An idle reaction (SPEC §13): when the input stream produces no new line for
320/// `dur`, fire `action`. Latched once per idle span, re-armed on the next line.
321/// Reuses [`BindAction`] exactly like [`Expect`], so `timeout 5s quit` works.
322#[derive(Debug, Clone)]
323pub struct Timeout {
324    pub dur: Duration,
325    pub action: BindAction,
326}
327
328/// Parse an action clause (`set .name VALUE…` | `quit`) shared by `bind` and
329/// `expect`. `params` is the args AFTER the action verb.
330fn parse_action(verb: &str, params: &[Arg]) -> Result<BindAction, String> {
331    // The space-joined string params (used by alert/exec/set values).
332    let joined = || {
333        params
334            .iter()
335            .filter_map(Arg::as_str)
336            .collect::<Vec<_>>()
337            .join(" ")
338    };
339    match verb {
340        "quit" => Ok(BindAction::Quit),
341        "beep" => Ok(BindAction::Beep),
342        "alert" => Ok(BindAction::Alert(joined())),
343        "exec" => {
344            let cmd = joined();
345            if cmd.is_empty() {
346                return Err("exec: missing command".into());
347            }
348            Ok(BindAction::Exec(cmd))
349        }
350        "send" => {
351            let text = joined();
352            if text.is_empty() {
353                return Err("send: missing text".into());
354            }
355            // The lexer already turns `\n`/`\t` in a quoted string into the real
356            // char, and (like Expect) `send` never auto-appends — so `send "y\n"`
357            // submits a line, `send "y"` leaves the cursor on the same line.
358            Ok(BindAction::Send(text))
359        }
360        "flash" => {
361            let widget = params
362                .first()
363                .and_then(Arg::as_str)
364                .ok_or("flash: missing widget (.name)")?;
365            let widget = widget.strip_prefix('.').unwrap_or(widget).to_string();
366            let color = params
367                .get(1)
368                .and_then(Arg::as_str)
369                .unwrap_or("yellow")
370                .to_string();
371            Ok(BindAction::Flash { widget, color })
372        }
373        "set" => {
374            let name = params
375                .first()
376                .and_then(Arg::as_str)
377                .ok_or("set: missing input name (.name)")?;
378            let name = name.strip_prefix('.').unwrap_or(name).to_string();
379            let value = params[1..]
380                .iter()
381                .filter_map(Arg::as_str)
382                .collect::<Vec<_>>()
383                .join(" ");
384            Ok(BindAction::SetInput { name, value })
385        }
386        "tell" => {
387            // `tell REF MSG(args)` — the message tell of the actor system (§15).
388            // `send` stays the Expect PTY action; `tell` avoids the collision.
389            let refname = params
390                .first()
391                .and_then(Arg::as_str)
392                .ok_or("tell: expected `tell REF MSG(args)`")?
393                .to_string();
394            let call = params[1..]
395                .iter()
396                .filter_map(Arg::as_str)
397                .collect::<Vec<_>>()
398                .join(" ");
399            if call.trim().is_empty() {
400                return Err("tell: missing message (`tell REF MSG(args)`)".into());
401            }
402            // Validate the call shape now so a typo is a build error, not silent.
403            crate::actor::parse_call(&call)?;
404            Ok(BindAction::ActorTell { refname, call })
405        }
406        "ask" => {
407            // `ask .CTRL REF MSG(args)` — ask a ref, store the reply into control CTRL.
408            let ctrl = params
409                .first()
410                .and_then(Arg::as_str)
411                .ok_or("ask: expected `ask .CTRL REF MSG(args)`")?;
412            let ctrl = ctrl.strip_prefix('.').unwrap_or(ctrl).to_string();
413            let refname = params
414                .get(1)
415                .and_then(Arg::as_str)
416                .ok_or("ask: missing ref (`ask .CTRL REF MSG(args)`)")?
417                .to_string();
418            let call = params[2..]
419                .iter()
420                .filter_map(Arg::as_str)
421                .collect::<Vec<_>>()
422                .join(" ");
423            if call.trim().is_empty() {
424                return Err("ask: missing message (`ask .CTRL REF MSG(args)`)".into());
425            }
426            crate::actor::parse_call(&call)?;
427            Ok(BindAction::ActorAsk {
428                ctrl,
429                refname,
430                call,
431            })
432        }
433        other => Err(format!(
434            "unknown action `{other}` (set | quit | beep | alert | flash | exec | tell | ask)"
435        )),
436    }
437}
438
439/// Parse a `spawn NAME = ACTOR(init)` or `pool NAME = ACTOR * N` binding into a
440/// [`crate::actor::RefDecl`]. `verb` is `spawn`/`pool`; the actor must already be
441/// declared. Both forms share `NAME = RHS`; a `pool` (or `RHS` with `* N`) sets
442/// the pool width.
443fn parse_actor_ref(
444    verb: &str,
445    args: &[Arg],
446    actors: &BTreeMap<String, Arc<ActorDef>>,
447) -> Result<crate::actor::RefDecl, String> {
448    let name = args
449        .first()
450        .and_then(Arg::as_str)
451        .ok_or_else(|| format!("{verb}: expected `{verb} NAME = ACTOR…`"))?
452        .to_string();
453    if args.get(1).and_then(Arg::as_str) != Some("=") {
454        return Err(format!("{verb}: expected `=` (`{verb} NAME = ACTOR…`)"));
455    }
456    // RHS: `ACTOR(init)` and/or `* N`, joined so spaces don't matter.
457    let rhs = args[2..]
458        .iter()
459        .filter_map(Arg::as_str)
460        .collect::<Vec<_>>()
461        .join(" ");
462    if rhs.trim().is_empty() {
463        return Err(format!("{verb}: missing actor (`{verb} {name} = ACTOR…`)"));
464    }
465    // Split off a `* N` pool width (from the verb or the RHS).
466    let (head, pool) = match rhs.split_once('*') {
467        Some((h, n)) => {
468            let n = n
469                .trim()
470                .parse::<usize>()
471                .map_err(|_| format!("{verb}: `* {}` is not a pool size", n.trim()))?;
472            (h.trim().to_string(), Some(n.min(1024)))
473        }
474        None => (rhs.trim().to_string(), None),
475    };
476    // `pool NAME = ACTOR` (no explicit `* N`) still means a pool — default width
477    // is filled in at spawn time (one per hardware thread) via `pool: Some(0)`.
478    let pool = match (verb, pool) {
479        (_, Some(n)) => Some(n),
480        ("pool", None) => Some(0),
481        _ => None,
482    };
483    // `head` is `ACTOR(init)` — reuse the actor-call splitter for name + init.
484    let (actor, init_exprs) = crate::actor::parse_call(&head)?;
485    if !actors.contains_key(&actor) {
486        return Err(format!(
487            "{verb}: no actor named `{actor}` in scope (declare `actor {actor}(state) {{ … }}` first)"
488        ));
489    }
490    // Initial state is a constant expression evaluated now (`worker(3)` -> 3).
491    let init = match init_exprs.as_slice() {
492        [] => 0.0,
493        [e] => crate::expr::eval(e, 0.0).unwrap_or(0.0),
494        _ => return Err(format!("{verb}: `{actor}(…)` takes a single init value")),
495    };
496    Ok(crate::actor::RefDecl {
497        name,
498        actor,
499        init,
500        pool,
501        restart: true,
502    })
503}
504
505/// Apply a `supervise NAME { on crash { restart | stop } }` policy to an already-
506/// declared ref: `stop` turns off respawn (fail-stop), `restart` (the default)
507/// leaves it on.
508fn apply_supervise(args: &[Arg], refs: &mut [crate::actor::RefDecl]) -> Result<(), String> {
509    let name = args
510        .first()
511        .and_then(Arg::as_str)
512        .ok_or("supervise: expected `supervise NAME { on crash { restart | stop } }`")?;
513    let body = match args.get(1) {
514        Some(Arg::Block(b)) => b,
515        _ => return Err("supervise: expected `{ on crash { restart | stop } }`".into()),
516    };
517    let decl = refs
518        .iter_mut()
519        .find(|r| r.name == name)
520        .ok_or_else(|| format!("supervise: no ref named `{name}` (spawn/pool it first)"))?;
521    for clause in body {
522        if clause.name != "on" || clause.args.first().and_then(Arg::as_str) != Some("crash") {
523            return Err("supervise: only `on crash { … }` is supported".into());
524        }
525        let policy = match clause.args.get(1) {
526            Some(Arg::Block(b)) => b
527                .first()
528                .map(|c| c.name.as_str())
529                .ok_or("supervise: `on crash { }` needs `restart` or `stop`")?,
530            _ => return Err("supervise: `on crash` needs a `{ restart | stop }` body".into()),
531        };
532        match policy {
533            "restart" => decl.restart = true,
534            "stop" => decl.restart = false,
535            other => {
536                return Err(format!(
537                    "supervise: unknown crash policy `{other}` (restart | stop)"
538                ))
539            }
540        }
541    }
542    Ok(())
543}
544
545/// Parse a block-form action body (`{ alert "x"; beep; flash .w red }`) into a
546/// `Seq` — each top-level command is one action, run in order.
547fn parse_action_block(cmds: &[Command]) -> Result<BindAction, String> {
548    let actions = cmds
549        .iter()
550        .map(|c| parse_action(&c.name, &c.args))
551        .collect::<Result<Vec<_>, _>>()?;
552    Ok(BindAction::Seq(actions))
553}
554
555/// Parse the action clause of a `bind`/`expect`: either a `{ … }` block (→ Seq)
556/// or the single-line `verb params…` form. `rest` is the args after the key/regex.
557fn parse_bind_or_expect_action(rest: &[Arg]) -> Result<BindAction, String> {
558    match rest.first() {
559        Some(Arg::Block(cmds)) => parse_action_block(cmds),
560        Some(_) => {
561            let verb = rest[0].as_str().unwrap_or("");
562            parse_action(verb, &rest[1..])
563        }
564        None => Err("missing action (set | quit | beep | alert | flash | exec | { … })".into()),
565    }
566}
567
568#[derive(Debug, Default)]
569pub struct Spec {
570    pub widgets: Vec<Widget>,
571    /// Downstream output pipeline (`out { … }`): applied to the stream and
572    /// written to stdout, so arb can *modify* a pipe, not just visualize it.
573    pub out: Option<Vec<QueryOp>>,
574    /// Key bindings (`bind C-<letter> <action>`).
575    pub binds: Vec<Bind>,
576    /// Event-driven reactions (`expect /re/ <action>`).
577    pub expects: Vec<Expect>,
578    /// Idle reactions (`timeout Ns <action>`).
579    pub timeouts: Vec<Timeout>,
580    /// Mouse reactions (`bind <Click> <action>`).
581    pub mouse_binds: Vec<(MouseTrigger, BindAction)>,
582    /// Terminal-resize reactions (`bind <Resize> <action>`).
583    pub resize_binds: Vec<BindAction>,
584    /// Input-source command (`spawn CMD` / `spawn { CMD }`, SPEC §7): arb
585    /// launches CMD via `sh -c` and feeds its stdout into the stream in place of
586    /// stdin (fire-and-forget; child detached, dies with arb). CLI `--run` wins
587    /// if both are given. The interactive `send`/PTY react leg + `.ps.sel`
588    /// selection widget are deferred. `None` = read stdin.
589    pub spawn: Option<String>,
590    /// Input-source file (`< FILE`, SPEC §7): read FILE as the stream in place
591    /// of stdin. Folded into the producer as `cat -- FILE` in main. Mutually
592    /// exclusive with `spawn` (and `--run`). `None` = read stdin.
593    pub source_file: Option<String>,
594    /// Poll source (`! CMD every Ns`, SPEC §7): re-run CMD via `sh -c` every
595    /// interval, feeding each run's stdout into the stream. The interactive/serve
596    /// loop runs in a background thread; the headless path runs CMD once (a
597    /// reducer over an endless source can't terminate). `None` = read stdin.
598    pub poll: Option<(String, Duration)>,
599    /// In-language unit tests (`test "NAME" { given …; run { … }; want … }`):
600    /// feed sample lines through a query pipeline and assert the output. Run
601    /// headlessly by `arb --test`; ignored by every other mode.
602    pub tests: Vec<TestCase>,
603    /// `spawn -pty CMD`: run the spawn command on a pseudo-terminal (so it acts
604    /// interactive) and keep a writer to its stdin for the `send` action. Only
605    /// meaningful with `spawn` set and in the interactive TUI.
606    pub spawn_pty: bool,
607    /// `actor NAME(state) { on MSG { … } }` declarations, by name. A `via NAME`
608    /// pipeline op resolves against this registry at build time (SPEC §15).
609    pub actors: BTreeMap<String, Arc<ActorDef>>,
610    /// `spawn NAME = ACTOR(init)` / `pool NAME = ACTOR * N` session bindings, in
611    /// declaration order. The TUI spawns these once at startup; `tell`/`ask` bind
612    /// actions drive them (SPEC §15).
613    pub actor_refs: Vec<crate::actor::RefDecl>,
614    /// `rows "1 2 1"` — the grid's row track sizes (`None` = uniform). A track is
615    /// `N` (fixed cells), `N%` (percentage), or `N*`/`*` (weight, proportional).
616    pub row_tracks: Option<Vec<Track>>,
617    /// `cols "20 * 2*"` — the grid's column track sizes (`None` = uniform).
618    pub col_tracks: Option<Vec<Track>>,
619    /// `gap N` — blank cells between grid rows/columns (default 0).
620    pub gap: u16,
621    /// `layout horizontal|vertical` — the no-grid auto-tile direction (default
622    /// vertical). Ignored once any widget declares a grid cell.
623    pub flow: Flow,
624    /// `theme NAME` / `theme custom c1..c6` — the active color palette (one of the
625    /// 31 built-ins or a custom 6-index palette). `None` = no directive: `main`
626    /// resolves the default (`--theme` → `~/.arb` config → baked `neon-sprawl`).
627    pub theme: Option<crate::theme::Palette>,
628    /// `theme off`/`none` — opt out of theming to the classic cyan scheme; stops
629    /// `main` from applying the config/baked default.
630    pub theme_off: bool,
631}
632
633/// A layout track size (a grid row/column). Maps to a ratatui `Constraint`.
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub enum Track {
636    /// `N` — a fixed cell count (`Constraint::Length`).
637    Length(u16),
638    /// `N%` — a percentage of the axis (`Constraint::Percentage`).
639    Percentage(u16),
640    /// `N*` / `*` — a proportional weight; remaining space splits by weight
641    /// (`Constraint::Fill`). Bare `*` is weight 1.
642    Fill(u16),
643}
644
645/// The auto-tile direction when no widget declares a grid cell.
646#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
647pub enum Flow {
648    #[default]
649    Vertical,
650    Horizontal,
651}
652
653/// Parse a track spec (`"1 2 1"` / `"20c * 2*"`) into a track list. A **bare
654/// integer is a proportional weight** (`1 2 1` = a 1:2:1 split — the common case);
655/// `N*` / `*` is the same explicit weight; `N%` is a percentage of the axis; and
656/// `Nc` is a fixed cell count. Empty/invalid tokens are an error.
657pub fn parse_tracks(spec: &str) -> Result<Vec<Track>, String> {
658    let mut out = Vec::new();
659    for tok in spec.split_whitespace() {
660        let track = if let Some(pct) = tok.strip_suffix('%') {
661            Track::Percentage(
662                pct.parse::<u16>()
663                    .map_err(|_| format!("track: bad percentage `{tok}`"))?
664                    .min(100),
665            )
666        } else if let Some(cells) = tok.strip_suffix('c') {
667            Track::Length(
668                cells
669                    .parse::<u16>()
670                    .map_err(|_| format!("track: bad cell count `{tok}`"))?,
671            )
672        } else {
673            // Bare `N`, `N*`, or `*` — a proportional weight (`*` = 1).
674            let w = tok.strip_suffix('*').unwrap_or(tok);
675            let weight = if w.is_empty() {
676                1
677            } else {
678                w.parse::<u16>()
679                    .map_err(|_| format!("track: bad weight `{tok}` (use N, N%, N*, or Nc)"))?
680                    .max(1)
681            };
682            Track::Fill(weight)
683        };
684        out.push(track);
685    }
686    if out.is_empty() {
687        return Err("track spec is empty".into());
688    }
689    Ok(out)
690}
691
692/// One in-language test case: feed `given` lines through the `run` pipeline
693/// (`ops`) and assert the flattened output equals `want`. Purely headless —
694/// evaluated via [`crate::query::eval`], the same path the widgets use.
695#[derive(Debug, Clone)]
696pub struct TestCase {
697    pub name: String,
698    pub given: Vec<String>,
699    pub ops: Vec<QueryOp>,
700    pub want: Vec<String>,
701}
702
703/// True if any single-stream input source (`spawn`/`< file`/`! poll`) is already
704/// set — only one may feed the stream.
705fn stream_source_set(s: &Spec) -> bool {
706    s.spawn.is_some() || s.source_file.is_some() || s.poll.is_some()
707}
708
709/// Build a `Spec` from a parsed command tree.
710pub fn build(cmds: &[Command]) -> Result<Spec, crate::err::SpecError> {
711    let mut spec = Spec::default();
712    build_into(&mut spec, cmds, 0)?;
713    Ok(spec)
714}
715
716/// Resolve `apply .name` placeholders against live `input` widget values: each
717/// `Apply(name)` is replaced by the query pipeline parsed from that input's
718/// current text (empty/invalid → dropped). Called every render frame so a
719/// before/after transform pane updates as the user edits the input.
720pub fn resolve_pipeline(
721    ops: &[QueryOp],
722    inputs: &std::collections::HashMap<String, String>,
723) -> Vec<QueryOp> {
724    // Resolve a control name to its live numeric value (empty/non-numeric -> None)
725    // or its raw string value (for `match`/`in .set` string predicates).
726    let num = |n: &str| -> Option<f64> { inputs.get(n).and_then(|v| v.trim().parse::<f64>().ok()) };
727    let strv = |n: &str| -> Option<String> { inputs.get(n).cloned() };
728    let mut out = Vec::with_capacity(ops.len());
729    for op in ops {
730        match op {
731            QueryOp::Apply(name) => {
732                if let Some(val) = inputs.get(name).filter(|v| !v.trim().is_empty()) {
733                    // Parse the input text as a pipeline body (prefix `in;` so it
734                    // is a valid source body) and splice its ops in.
735                    // A live `apply` input is typed at render time, before any
736                    // actor is in scope — `via` there resolves against an empty
737                    // registry (unknown-actor errors just drop the transform).
738                    if let Ok(cmds) = crate::parser::parse(&format!("in; {val}")) {
739                        if let Ok(sub) = pipeline_from_body(&cmds, &BTreeMap::new()) {
740                            out.extend(sub);
741                        }
742                    }
743                }
744            }
745            // `where lat < .th` (numeric) / `where match(.q)` / `where lvl in .lv`
746            // (string). Numeric controls must all resolve or the filter is dropped
747            // (unset threshold = no filter); string controls with an empty value
748            // simply match everything, so they never force a drop.
749            QueryOp::Where(e) => {
750                let (mut nums, mut strs) = (Vec::new(), Vec::new());
751                crate::expr::control_names_typed(e, &mut nums, &mut strs);
752                if nums.is_empty() && strs.is_empty() {
753                    out.push(op.clone());
754                } else if nums.iter().all(|n| num(n).is_some()) {
755                    out.push(QueryOp::Where(crate::expr::substitute_controls(
756                        e, &num, &strv,
757                    )));
758                }
759                // else: a numeric control is unset -> drop this `where`.
760            }
761            // `map(x * .k)`: substitute resolvable controls; an unresolved one
762            // stays a control (-> NaN) rather than dropping the transform.
763            QueryOp::Map(e) => {
764                out.push(QueryOp::Map(crate::expr::substitute_controls(
765                    e, &num, &strv,
766                )));
767            }
768            other => out.push(other.clone()),
769        }
770    }
771    out
772}
773
774// ---- `import X as Y` namespacing ------------------------------------------
775// A module built into a fresh sub-Spec has its render-time NAME references
776// (widget paths, `apply`, control refs, `set`/`flash` targets) prefixed with the
777// alias, then merged in. Intra-module by-path refs (source/search/grid/configure)
778// already resolved during the fresh build, so only these string names remain.
779
780/// Namespace a control/input name: `cpu` -> `g.cpu`.
781fn prefix_name(name: &str, ns: &str) -> String {
782    format!("{ns}.{name}")
783}
784
785/// Namespace `apply`/`where`/`map`/`calc` references in a query pipeline.
786fn prefix_pipeline(ops: &mut [QueryOp], ns: &str) {
787    for op in ops {
788        match op {
789            QueryOp::Apply(n) => *n = prefix_name(n, ns),
790            QueryOp::Where(e) | QueryOp::Map(e) | QueryOp::Calc(e) => {
791                crate::expr::prefix_controls(e, ns)
792            }
793            _ => {}
794        }
795    }
796}
797
798/// Namespace the widget/control names an action targets.
799fn prefix_action(a: &mut BindAction, ns: &str) {
800    match a {
801        BindAction::SetInput { name, .. } => *name = prefix_name(name, ns),
802        BindAction::Flash { widget, .. } => *widget = prefix_name(widget, ns),
803        // A module's `tell`/`ask` targets its own (now-namespaced) ref; `ask` also
804        // writes a namespaced control.
805        BindAction::ActorTell { refname, .. } => *refname = prefix_name(refname, ns),
806        BindAction::ActorAsk { ctrl, refname, .. } => {
807            *ctrl = prefix_name(ctrl, ns);
808            *refname = prefix_name(refname, ns);
809        }
810        BindAction::Seq(v) => v.iter_mut().for_each(|x| prefix_action(x, ns)),
811        _ => {}
812    }
813}
814
815/// Prefix every render-time name in a freshly-built module Spec with `ns`.
816fn prefix_spec(sub: &mut Spec, ns: &str) {
817    for w in &mut sub.widgets {
818        w.path = format!(".{ns}.{}", w.path.trim_start_matches('.'));
819        if let Some(s) = &mut w.source {
820            prefix_pipeline(&mut s.pipeline, ns);
821        }
822        if let Some(p) = &mut w.search {
823            prefix_pipeline(p, ns);
824        }
825    }
826    for b in &mut sub.binds {
827        prefix_action(&mut b.action, ns);
828    }
829    for e in &mut sub.expects {
830        prefix_action(&mut e.action, ns);
831    }
832    for t in &mut sub.timeouts {
833        prefix_action(&mut t.action, ns);
834    }
835    for (_, a) in &mut sub.mouse_binds {
836        prefix_action(a, ns);
837    }
838    for a in &mut sub.resize_binds {
839        prefix_action(a, ns);
840    }
841    if let Some(out) = &mut sub.out {
842        prefix_pipeline(out, ns);
843    }
844    // Session refs: namespace the binding name and the actor it runs, so `.ns.w`
845    // is distinct and its (also-prefixed) actor resolves after merge.
846    for r in &mut sub.actor_refs {
847        r.name = prefix_name(&r.name, ns);
848        r.actor = prefix_name(&r.actor, ns);
849    }
850}
851
852/// Merge a namespaced module Spec into `dst`.
853fn merge_spec(dst: &mut Spec, src: Spec, ns: &str) -> Result<(), String> {
854    dst.widgets.extend(src.widgets);
855    dst.binds.extend(src.binds);
856    dst.expects.extend(src.expects);
857    dst.timeouts.extend(src.timeouts);
858    dst.mouse_binds.extend(src.mouse_binds);
859    dst.resize_binds.extend(src.resize_binds);
860    dst.tests.extend(src.tests);
861    // A namespaced module's `via` ops already embed their resolved `Arc<ActorDef>`
862    // (bound during the fresh sub-build), so they work post-merge. Carry the defs
863    // under `ns.NAME` keys so they don't collide with the host's actors.
864    for (name, def) in src.actors {
865        dst.actors.insert(prefix_name(&name, ns), def);
866    }
867    // Session refs already namespaced by `prefix_spec`; carry them over.
868    dst.actor_refs.extend(src.actor_refs);
869    // A module's `theme` applies only when the host hasn't set one (host wins).
870    if dst.theme.is_none() {
871        dst.theme = src.theme;
872    }
873    if let Some(out) = src.out {
874        if dst.out.is_some() {
875            return Err(format!(
876                "import: `{ns}` defines `out`, but one is already set"
877            ));
878        }
879        dst.out = Some(out);
880    }
881    if let Some(sp) = src.spawn {
882        if stream_source_set(dst) {
883            return Err(format!(
884                "import: `{ns}` defines a spawn source, but one is already set"
885            ));
886        }
887        dst.spawn = Some(sp);
888        dst.spawn_pty = src.spawn_pty;
889    }
890    if let Some(f) = src.source_file {
891        if stream_source_set(dst) {
892            return Err(format!(
893                "import: `{ns}` defines a `<` file source, but one is already set"
894            ));
895        }
896        dst.source_file = Some(f);
897    }
898    if let Some(p) = src.poll {
899        if stream_source_set(dst) {
900            return Err(format!(
901                "import: `{ns}` defines a `!` poll source, but one is already set"
902            ));
903        }
904        dst.poll = Some(p);
905    }
906    Ok(())
907}
908
909/// Process `cmds` into `spec`. `import NAME` resolves and inlines a module
910/// (stdlib preset or user file); `depth` guards against import cycles.
911fn build_into(
912    spec: &mut Spec,
913    cmds: &[Command],
914    depth: usize,
915) -> Result<(), crate::err::SpecError> {
916    if depth > 16 {
917        return Err("import: module nesting too deep (cycle?)".into());
918    }
919    for c in cmds {
920        // Process one command; a returned error with no span yet is anchored to
921        // this command's verb (its char offset) so the LSP points at the line.
922        let res: Result<(), crate::err::SpecError> = (|| -> Result<(), crate::err::SpecError> {
923            if c.name == "import" {
924                let name = c
925                    .args
926                    .first()
927                    .and_then(Arg::as_str)
928                    .ok_or("import: missing module name")?;
929                // `import X as Y`: build the module into a fresh sub-Spec (so its
930                // intra-module by-path refs resolve), namespace every render-time
931                // name with `Y`, then merge — so `.Y.foo` and its controls resolve.
932                if c.args.get(1).and_then(Arg::as_str) == Some("as") {
933                    let alias = c
934                        .args
935                        .get(2)
936                        .and_then(Arg::as_str)
937                        .ok_or("import: `as` requires an alias (import X as Y)")?;
938                    if alias.is_empty() || alias.contains(['.', '/', ' ']) {
939                        return Err(format!("import: invalid namespace alias `{alias}`").into());
940                    }
941                    let src = resolve_module(name)?;
942                    let sub_cmds = crate::parser::parse(&src)?;
943                    let mut sub = Spec::default();
944                    build_into(&mut sub, &sub_cmds, depth + 1)?;
945                    prefix_spec(&mut sub, alias);
946                    merge_spec(spec, sub, alias)?;
947                } else {
948                    let src = resolve_module(name)?;
949                    let sub = crate::parser::parse(&src)?;
950                    build_into(spec, &sub, depth + 1)?;
951                }
952            } else if c.name == "actor" {
953                // `actor NAME(state) { on MSG(p) { … } }` — a message-handling
954                // behavior (SPEC §15). Stored by name; a `via NAME` pipeline op
955                // fans the stream across a pool of it.
956                let def = crate::actor::parse_actor(&c.args)?;
957                spec.actors.insert(def.name.clone(), Arc::new(def));
958            } else if c.name == "__rust_compile" {
959                // Desugared `rust { ... }` block (see `rust_ffi`): compile the
960                // base64 body to a cached cdylib and register its exports, so a
961                // later `name(args)` call in a where/map/calc expression resolves.
962                // Runs at build time, before any render-time expression eval.
963                let b64 = c
964                    .args
965                    .first()
966                    .and_then(Arg::as_str)
967                    .ok_or("__rust_compile: missing block body")?;
968                fusevm::ffi::compile_and_register(b64).map_err(crate::err::SpecError::from)?;
969            } else if let Some(kind) = WidgetKind::from(&c.name) {
970                let path = c
971                    .args
972                    .first()
973                    .and_then(Arg::as_str)
974                    .ok_or_else(|| format!("{}: missing widget path", c.name))?;
975                if !path.starts_with('.') {
976                    return Err(format!(
977                        "{}: widget path must start with '.', got `{path}`",
978                        c.name
979                    )
980                    .into());
981                }
982                spec.widgets.push(Widget {
983                    path: path.to_string(),
984                    kind,
985                    opts: parse_opts(&c.args[1..]),
986                    source: None,
987                    search: None,
988                    grid: None,
989                    span: (1, 1),
990                });
991            } else if c.name == "source" {
992                let path = c
993                    .args
994                    .first()
995                    .and_then(Arg::as_str)
996                    .ok_or("source: missing path")?;
997                let body = match c.args.get(1) {
998                    Some(Arg::Block(b)) => b,
999                    _ => return Err("source: expected `{ body }`".into()),
1000                };
1001                let pipeline = pipeline_from_body(body, &spec.actors)?;
1002                set_source(spec, path, Source { pipeline })?;
1003            } else if c.name == "search" {
1004                // `search .name { in; … }` — a select widget's fuzzy-match key
1005                // pipeline (fzf --nth). The row still shows/emits its `source`.
1006                let path = c
1007                    .args
1008                    .first()
1009                    .and_then(Arg::as_str)
1010                    .ok_or("search: missing path")?;
1011                let body = match c.args.get(1) {
1012                    Some(Arg::Block(b)) => b,
1013                    _ => return Err("search: expected `{ body }`".into()),
1014                };
1015                let pipeline = pipeline_from_body(body, &spec.actors)?;
1016                set_search(spec, path, pipeline)?;
1017            } else if c.name == "bind" {
1018                // `bind KEY ACTION` — KEY is a control key (`C-<letter>`, `<Enter>`…),
1019                // a mouse event (`<Click>`), or `<Resize>`; ACTION is a single verb or
1020                // a `{ … }` block.
1021                let keyspec = c
1022                    .args
1023                    .first()
1024                    .and_then(Arg::as_str)
1025                    .ok_or("bind: missing key (e.g. C-u, <Click>)")?;
1026                let action =
1027                    parse_bind_or_expect_action(&c.args[1..]).map_err(|e| format!("bind: {e}"))?;
1028                match keyspec {
1029                    "<Click>" | "<Button-1>" => {
1030                        spec.mouse_binds.push((MouseTrigger::Click, action))
1031                    }
1032                    "<Resize>" | "<Configure>" => spec.resize_binds.push(action),
1033                    _ => {
1034                        let key = parse_key(keyspec).ok_or_else(|| {
1035                        format!("bind: `{keyspec}` is not a bindable key (use C-<letter>, <Enter>/<Esc>/<Tab>/<Key-x>, <Click>, <Resize>)")
1036                    })?;
1037                        spec.binds.push(Bind { key, action });
1038                    }
1039                }
1040            } else if c.name == "expect" {
1041                match c.args.first() {
1042                    // Block form `expect { /re/ ACTION; /re2/ ACTION }` (Tcl Expect's
1043                    // multi-pattern block): each inner command is one clause — its
1044                    // NAME is the /regex/, its args are the ACTION. Emit one Expect
1045                    // per clause; all fire live per line (tui.rs loops every entry).
1046                    Some(Arg::Block(clauses)) => {
1047                        for clause in clauses {
1048                            let pattern =
1049                                compile_regex(&clause.name).map_err(|e| format!("expect: {e}"))?;
1050                            let action = parse_bind_or_expect_action(&clause.args)
1051                                .map_err(|e| format!("expect: {e}"))?;
1052                            spec.expects.push(Expect { pattern, action });
1053                        }
1054                    }
1055                    // Single-clause form `expect /regex/ ACTION` — ACTION as for `bind`.
1056                    _ => {
1057                        let pattern = regex_arg(c)?;
1058                        let action = parse_bind_or_expect_action(&c.args[1..])
1059                            .map_err(|e| format!("expect: {e}"))?;
1060                        spec.expects.push(Expect { pattern, action });
1061                    }
1062                }
1063            } else if c.name == "timeout" {
1064                // `timeout Ns ACTION` — fire ACTION when the stream goes idle for Ns.
1065                let dspec = c
1066                    .args
1067                    .first()
1068                    .and_then(Arg::as_str)
1069                    .ok_or("timeout: missing duration (e.g. 5s, 500ms)")?;
1070                let dur = parse_duration(dspec).ok_or_else(|| {
1071                    format!("timeout: `{dspec}` is not a duration (use Ns/Nms/Nm)")
1072                })?;
1073                let action = parse_bind_or_expect_action(&c.args[1..])
1074                    .map_err(|e| format!("timeout: {e}"))?;
1075                spec.timeouts.push(Timeout { dur, action });
1076            } else if c.name == "out" {
1077                let body = match c.args.first() {
1078                    Some(Arg::Block(b)) => b,
1079                    _ => return Err("out: expected `{ body }`".into()),
1080                };
1081                let pipeline = pipeline_from_body(body, &spec.actors)?;
1082                spec.out = Some(pipeline);
1083            } else if c.name == "test" {
1084                // `test "NAME" { given …; run { in; … }; want … }` — an
1085                // in-language unit test, run headlessly by `arb --test`.
1086                let name = c
1087                    .args
1088                    .first()
1089                    .and_then(Arg::as_str)
1090                    .ok_or("test: expected a name — `test \"NAME\" { … }`")?
1091                    .to_string();
1092                let body = match c.args.get(1) {
1093                    Some(Arg::Block(b)) => b,
1094                    _ => return Err("test: expected `{ given …; run { … }; want … }`".into()),
1095                };
1096                let tc = parse_test_case(name, body, &spec.actors)?;
1097                spec.tests.push(tc);
1098            } else if c.name == "spawn" && c.args.get(1).and_then(Arg::as_str) == Some("=") {
1099                // `spawn NAME = ACTOR(init)` — a session actor binding (§15),
1100                // distinct from the `spawn CMD` process source (disambiguated by
1101                // the `=` second token). `tell`/`ask` drive it.
1102                let decl = parse_actor_ref(&c.name, &c.args, &spec.actors)?;
1103                spec.actor_refs.push(decl);
1104            } else if c.name == "pool" {
1105                // `pool NAME = ACTOR * N` — a supervised session pool binding.
1106                let decl = parse_actor_ref(&c.name, &c.args, &spec.actors)?;
1107                spec.actor_refs.push(decl);
1108            } else if c.name == "supervise" {
1109                // `supervise NAME { on crash { restart | stop } }` — set a ref's
1110                // restart policy. Default is restart (respawn a dead worker); a
1111                // `stop` clause makes the pool fail-stop.
1112                apply_supervise(&c.args, &mut spec.actor_refs)?;
1113            } else if c.name == "spawn" {
1114                // `spawn CMD…` or `spawn { CMD }`: launch CMD via `sh -c` and use
1115                // its stdout as the stream (input source, in place of stdin). A
1116                // leading `-pty` runs CMD on a pseudo-terminal so it behaves as if
1117                // interactive and `send "…"` can drive its stdin (Expect).
1118                let args = c.args.as_slice();
1119                let (pty, args) = match args.first().and_then(Arg::as_str) {
1120                    Some("-pty") => (true, &args[1..]),
1121                    _ => (false, args),
1122                };
1123                let cmd = match args.first() {
1124                    Some(Arg::Block(b)) => block_to_shell(b),
1125                    _ => args
1126                        .iter()
1127                        .filter_map(Arg::as_str)
1128                        .collect::<Vec<_>>()
1129                        .join(" "),
1130                };
1131                if cmd.trim().is_empty() {
1132                    return Err("spawn: missing command".into());
1133                }
1134                if stream_source_set(spec) {
1135                    return Err("spawn: a stream source is already declared".into());
1136                }
1137                spec.spawn = Some(cmd);
1138                spec.spawn_pty = pty;
1139            } else if c.name == "<" {
1140                // `< FILE`: read FILE as the stream (input source, in place of stdin).
1141                // An unquoted absolute path (`/var/log/x`) is truncated by the lexer's
1142                // `/…/` regex branch — quote it (`< "/var/log/x"`).
1143                let file = c
1144                    .args
1145                    .first()
1146                    .and_then(Arg::as_str)
1147                    .filter(|f| !f.trim().is_empty())
1148                    .ok_or("`<`: missing file path")?;
1149                if stream_source_set(spec) {
1150                    return Err("`<`: a stream source is already declared".into());
1151                }
1152                spec.source_file = Some(file.to_string());
1153            } else if c.name == "!" {
1154                // `! CMD every Ns`: re-run CMD every interval. CMD may be bare words
1155                // or a `{ … }` block; the interval follows the `every` keyword.
1156                let evy = c
1157                    .args
1158                    .iter()
1159                    .position(|a| a.as_str() == Some("every"))
1160                    .ok_or("`!` source: expected `CMD every Ns`")?;
1161                let dspec = c
1162                    .args
1163                    .get(evy + 1)
1164                    .and_then(Arg::as_str)
1165                    .ok_or("`!` source: `every` needs a duration (e.g. 1s, 500ms)")?;
1166                let dur = parse_duration(dspec).ok_or_else(|| {
1167                    format!("`!` source: `{dspec}` is not a duration (use Ns/Nms/Nm)")
1168                })?;
1169                let cmd = match c.args.first() {
1170                    Some(Arg::Block(b)) => block_to_shell(b),
1171                    _ => c.args[..evy]
1172                        .iter()
1173                        .filter_map(Arg::as_str)
1174                        .collect::<Vec<_>>()
1175                        .join(" "),
1176                };
1177                if cmd.trim().is_empty() {
1178                    return Err("`!` source: missing command".into());
1179                }
1180                if stream_source_set(spec) {
1181                    return Err("`!`: a stream source is already declared".into());
1182                }
1183                spec.poll = Some((cmd, dur));
1184            } else if c.name == "rows" || c.name == "cols" {
1185                // `rows "1 2 1"` / `cols "20 * 2*"` — proportional grid track sizes.
1186                let spec_str = c
1187                    .args
1188                    .iter()
1189                    .filter_map(Arg::as_str)
1190                    .collect::<Vec<_>>()
1191                    .join(" ");
1192                let tracks = parse_tracks(&spec_str)?;
1193                if c.name == "rows" {
1194                    spec.row_tracks = Some(tracks);
1195                } else {
1196                    spec.col_tracks = Some(tracks);
1197                }
1198            } else if c.name == "gap" {
1199                // `gap N` — blank cells between grid rows/columns.
1200                let n = c
1201                    .args
1202                    .first()
1203                    .and_then(Arg::as_str)
1204                    .and_then(|s| s.parse::<u16>().ok())
1205                    .ok_or("gap: expected a cell count (`gap 1`)")?;
1206                spec.gap = n.min(64);
1207            } else if c.name == "theme" {
1208                // `theme NAME` — one of the 31 built-in palettes; or
1209                // `theme custom c1 c2 c3 c4 c5 c6` — a 6-index custom palette.
1210                let first =
1211                    c.args.first().and_then(Arg::as_str).ok_or(
1212                        "theme: expected a name (`theme neon-noir`) or `theme custom c1..c6`",
1213                    )?;
1214                if first == "off" || first == "none" {
1215                    // Opt out to the classic cyan scheme; block the default resolver.
1216                    spec.theme = None;
1217                    spec.theme_off = true;
1218                } else if first == "custom" {
1219                    let idx: Vec<u8> = c.args[1..]
1220                        .iter()
1221                        .filter_map(Arg::as_str)
1222                        .filter_map(|s| s.parse::<u8>().ok())
1223                        .collect();
1224                    if idx.len() != 6 {
1225                        return Err(
1226                            "theme custom: expected 6 color indices 0-255 (`theme custom c1 c2 c3 c4 c5 c6`)"
1227                                .into(),
1228                        );
1229                    }
1230                    spec.theme = Some(crate::theme::custom([
1231                        idx[0], idx[1], idx[2], idx[3], idx[4], idx[5],
1232                    ]));
1233                } else {
1234                    spec.theme = Some(crate::theme::by_name(first).ok_or_else(|| {
1235                        format!(
1236                            "theme: unknown theme `{first}` (see `arb --list-themes`; or `theme custom c1..c6`)"
1237                        )
1238                    })?);
1239                }
1240            } else if c.name == "layout" {
1241                // `layout horizontal|vertical` — the no-grid auto-tile direction.
1242                match c.args.first().and_then(Arg::as_str) {
1243                    Some("horizontal") | Some("h") => spec.flow = Flow::Horizontal,
1244                    Some("vertical") | Some("v") => spec.flow = Flow::Vertical,
1245                    other => {
1246                        return Err(format!(
1247                            "layout: expected `horizontal` or `vertical`, got `{}`",
1248                            other.unwrap_or("")
1249                        )
1250                        .into())
1251                    }
1252                }
1253            } else if c.name == "grid" {
1254                let path = c
1255                    .args
1256                    .first()
1257                    .and_then(Arg::as_str)
1258                    .ok_or("grid: missing path")?;
1259                let o = parse_opts(&c.args[1..]);
1260                // Bound every grid coordinate/span: `compute_rects` sums `row+rowspan`
1261                // (unguarded usize add -> overflow panic near usize::MAX) and builds a
1262                // per-cell layout constraint vector of that size (a huge span like
1263                // `-colspan 50000000` allocates millions of constraints and pegs the
1264                // cassowary solver -> hang). No real dashboard grid exceeds this.
1265                const MAX_GRID: usize = 256;
1266                let opt = |k: &str, d: usize| {
1267                    o.get(k)
1268                        .and_then(|s: &String| s.parse::<usize>().ok())
1269                        .unwrap_or(d)
1270                        .min(MAX_GRID)
1271                };
1272                // `-span` is a colspan shorthand; `-rowspan`/`-colspan` are explicit.
1273                let colspan = opt("colspan", opt("span", 1)).max(1);
1274                let rowspan = opt("rowspan", 1).max(1);
1275                set_grid(
1276                    spec,
1277                    path,
1278                    (opt("row", 0), opt("col", 0)),
1279                    (rowspan, colspan),
1280                )?;
1281            } else if c.name.starts_with('.') {
1282                if c.args.first().and_then(Arg::as_str) == Some("<-")
1283                    && c.args.get(1).and_then(Arg::as_str) == Some("in")
1284                {
1285                    // `.path <- in` bind shorthand (empty pipeline).
1286                    let path = c.name.clone();
1287                    set_source(spec, &path, Source { pipeline: vec![] })?;
1288                } else if c.args.first().and_then(Arg::as_str) == Some("configure") {
1289                    // `.path configure -max 200`: merge new opts into the target
1290                    // widget (build-time; later keys win). Runtime reconfigure via a
1291                    // bind/expect mutating live opts is a separate, larger feature.
1292                    let opts = parse_opts(&c.args[1..]);
1293                    configure_widget(spec, &c.name, opts)?;
1294                }
1295            }
1296            // Unknown verbs are ignored.
1297            Ok(())
1298        })();
1299        res.map_err(|e| e.or_span(c.pos, c.name.chars().count()))?;
1300    }
1301    Ok(())
1302}
1303
1304/// Resolve a module name to its source: a local `NAME.arb`, then
1305/// `~/.arb/lib/NAME.arb`, then a bundled stdlib preset.
1306fn resolve_module(name: &str) -> Result<String, String> {
1307    // A path-like or already-suffixed name (`import "./lib.arb"`, `import
1308    // "/abs/lib.arb"`) is read verbatim — don't double up the extension.
1309    if name.ends_with(".arb") || name.contains('/') {
1310        if let Ok(s) = std::fs::read_to_string(name) {
1311            return Ok(s);
1312        }
1313    }
1314    let local = format!("{name}.arb");
1315    if let Ok(s) = std::fs::read_to_string(&local) {
1316        return Ok(s);
1317    }
1318    if let Some(dir) = lib_dir() {
1319        if let Ok(s) = std::fs::read_to_string(dir.join(format!("{name}.arb"))) {
1320            return Ok(s);
1321        }
1322    }
1323    // Installed registry packages (`~/.arb/pkg`) — the SPEC §17 `pkg` tier.
1324    if let Some(dir) = crate::pkg::pkg_dir() {
1325        if let Some(s) = crate::pkg::read_pkg_module(&dir, name) {
1326            return Ok(s);
1327        }
1328    }
1329    bundled_module(name)
1330        .map(str::to_string)
1331        .ok_or_else(|| format!("import: module `{name}` not found"))
1332}
1333
1334/// Names of the bundled stdlib presets.
1335pub const STDLIB_NAMES: &[&str] = &[
1336    "nums",
1337    "logs",
1338    "http",
1339    "json",
1340    "table",
1341    "top",
1342    "docker",
1343    "k8s",
1344    "nginx",
1345    "git",
1346    "systemd",
1347    "redis",
1348    "postgres",
1349    "mysql",
1350    "mongodb",
1351    "kafka",
1352    "prometheus",
1353    "elasticsearch",
1354    "rabbitmq",
1355    "apache",
1356    "haproxy",
1357    "journalctl",
1358    "dmesg",
1359    "ps",
1360    "htop",
1361    "iostat",
1362    "vmstat",
1363    "ss",
1364    "dig",
1365    "curl",
1366    "gh",
1367    "terraform",
1368    "aws",
1369    "gcloud",
1370    "azure",
1371    "ansible",
1372    "consul",
1373    "vault",
1374    "etcd",
1375    "nomad",
1376    "envoy",
1377    "memcached",
1378    "varnish",
1379    "pgbouncer",
1380    "celery",
1381    "sidekiq",
1382    "gunicorn",
1383    "supervisor",
1384    "fail2ban",
1385    "iptables",
1386    "conntrack",
1387    "sar",
1388    "nats",
1389    "tomcat",
1390    "puma",
1391    "lighttpd",
1392    "helm",
1393    "podman",
1394    "containerd",
1395    "crictl",
1396    "istioctl",
1397    "linkerd",
1398    "cilium",
1399    "argocd",
1400    "fluxcd",
1401    "velero",
1402    "kustomize",
1403    "skopeo",
1404    "buildah",
1405    "stern",
1406    "kubectx",
1407    "jenkins",
1408    "gitlabrunner",
1409    "circleci",
1410    "drone",
1411    "buildkite",
1412    "concourse",
1413    "woodpecker",
1414    "spinnaker",
1415    "tekton",
1416    "teamcity",
1417    "packer",
1418    "vagrant",
1419    "pulumi",
1420    "chef",
1421    "puppet",
1422    "salt",
1423    "cloudformation",
1424    "cdk",
1425    "doctl",
1426    "hcloud",
1427    "fly",
1428    "heroku",
1429    "linode",
1430    "vultr",
1431    "scaleway",
1432    "cassandra",
1433    "scylla",
1434    "cockroachdb",
1435    "clickhouse",
1436    "influxdb",
1437    "neo4j",
1438    "couchdb",
1439    "dynamodb",
1440    "mariadb",
1441    "duckdb",
1442    "sqlite",
1443    "mssql",
1444    "timescaledb",
1445    "arangodb",
1446    "tidb",
1447    "victoriametrics",
1448    "questdb",
1449    "riak",
1450    "dgraph",
1451    "opensearch",
1452    "grafana",
1453    "loki",
1454    "tempo",
1455    "jaeger",
1456    "zipkin",
1457    "datadog",
1458    "newrelic",
1459    "sentry",
1460    "statsd",
1461    "telegraf",
1462    "collectd",
1463    "netdata",
1464    "zabbix",
1465    "nagios",
1466    "icinga",
1467    "pulsar",
1468    "activemq",
1469    "nsq",
1470    "beanstalkd",
1471    "caddy",
1472    "traefik",
1473    "uwsgi",
1474    "phpfpm",
1475    "tcpdump",
1476    "tshark",
1477    "nmap",
1478    "netstat",
1479    "iftop",
1480    "nethogs",
1481    "vnstat",
1482    "mtr",
1483    "zfs",
1484    "btrfs",
1485    "smartctl",
1486    "nvme",
1487    "rclone",
1488];
1489
1490fn bundled_module(name: &str) -> Option<&'static str> {
1491    Some(match name {
1492        "nums" => include_str!("../stdlib/nums.arb"),
1493        "logs" => include_str!("../stdlib/logs.arb"),
1494        "http" => include_str!("../stdlib/http.arb"),
1495        "json" => include_str!("../stdlib/json.arb"),
1496        "table" => include_str!("../stdlib/table.arb"),
1497        "top" => include_str!("../stdlib/top.arb"),
1498        "docker" => include_str!("../stdlib/docker.arb"),
1499        "k8s" => include_str!("../stdlib/k8s.arb"),
1500        "nginx" => include_str!("../stdlib/nginx.arb"),
1501        "git" => include_str!("../stdlib/git.arb"),
1502        "systemd" => include_str!("../stdlib/systemd.arb"),
1503        "redis" => include_str!("../stdlib/redis.arb"),
1504        "postgres" => include_str!("../stdlib/postgres.arb"),
1505        "mysql" => include_str!("../stdlib/mysql.arb"),
1506        "mongodb" => include_str!("../stdlib/mongodb.arb"),
1507        "kafka" => include_str!("../stdlib/kafka.arb"),
1508        "prometheus" => include_str!("../stdlib/prometheus.arb"),
1509        "elasticsearch" => include_str!("../stdlib/elasticsearch.arb"),
1510        "rabbitmq" => include_str!("../stdlib/rabbitmq.arb"),
1511        "apache" => include_str!("../stdlib/apache.arb"),
1512        "haproxy" => include_str!("../stdlib/haproxy.arb"),
1513        "journalctl" => include_str!("../stdlib/journalctl.arb"),
1514        "dmesg" => include_str!("../stdlib/dmesg.arb"),
1515        "ps" => include_str!("../stdlib/ps.arb"),
1516        "htop" => include_str!("../stdlib/htop.arb"),
1517        "iostat" => include_str!("../stdlib/iostat.arb"),
1518        "vmstat" => include_str!("../stdlib/vmstat.arb"),
1519        "ss" => include_str!("../stdlib/ss.arb"),
1520        "dig" => include_str!("../stdlib/dig.arb"),
1521        "curl" => include_str!("../stdlib/curl.arb"),
1522        "gh" => include_str!("../stdlib/gh.arb"),
1523        "terraform" => include_str!("../stdlib/terraform.arb"),
1524        "aws" => include_str!("../stdlib/aws.arb"),
1525        "gcloud" => include_str!("../stdlib/gcloud.arb"),
1526        "azure" => include_str!("../stdlib/azure.arb"),
1527        "ansible" => include_str!("../stdlib/ansible.arb"),
1528        "consul" => include_str!("../stdlib/consul.arb"),
1529        "vault" => include_str!("../stdlib/vault.arb"),
1530        "etcd" => include_str!("../stdlib/etcd.arb"),
1531        "nomad" => include_str!("../stdlib/nomad.arb"),
1532        "envoy" => include_str!("../stdlib/envoy.arb"),
1533        "memcached" => include_str!("../stdlib/memcached.arb"),
1534        "varnish" => include_str!("../stdlib/varnish.arb"),
1535        "pgbouncer" => include_str!("../stdlib/pgbouncer.arb"),
1536        "celery" => include_str!("../stdlib/celery.arb"),
1537        "sidekiq" => include_str!("../stdlib/sidekiq.arb"),
1538        "gunicorn" => include_str!("../stdlib/gunicorn.arb"),
1539        "supervisor" => include_str!("../stdlib/supervisor.arb"),
1540        "fail2ban" => include_str!("../stdlib/fail2ban.arb"),
1541        "iptables" => include_str!("../stdlib/iptables.arb"),
1542        "conntrack" => include_str!("../stdlib/conntrack.arb"),
1543        "sar" => include_str!("../stdlib/sar.arb"),
1544        "nats" => include_str!("../stdlib/nats.arb"),
1545        "tomcat" => include_str!("../stdlib/tomcat.arb"),
1546        "puma" => include_str!("../stdlib/puma.arb"),
1547        "lighttpd" => include_str!("../stdlib/lighttpd.arb"),
1548        "helm" => include_str!("../stdlib/helm.arb"),
1549        "podman" => include_str!("../stdlib/podman.arb"),
1550        "containerd" => include_str!("../stdlib/containerd.arb"),
1551        "crictl" => include_str!("../stdlib/crictl.arb"),
1552        "istioctl" => include_str!("../stdlib/istioctl.arb"),
1553        "linkerd" => include_str!("../stdlib/linkerd.arb"),
1554        "cilium" => include_str!("../stdlib/cilium.arb"),
1555        "argocd" => include_str!("../stdlib/argocd.arb"),
1556        "fluxcd" => include_str!("../stdlib/fluxcd.arb"),
1557        "velero" => include_str!("../stdlib/velero.arb"),
1558        "kustomize" => include_str!("../stdlib/kustomize.arb"),
1559        "skopeo" => include_str!("../stdlib/skopeo.arb"),
1560        "buildah" => include_str!("../stdlib/buildah.arb"),
1561        "stern" => include_str!("../stdlib/stern.arb"),
1562        "kubectx" => include_str!("../stdlib/kubectx.arb"),
1563        "jenkins" => include_str!("../stdlib/jenkins.arb"),
1564        "gitlabrunner" => include_str!("../stdlib/gitlabrunner.arb"),
1565        "circleci" => include_str!("../stdlib/circleci.arb"),
1566        "drone" => include_str!("../stdlib/drone.arb"),
1567        "buildkite" => include_str!("../stdlib/buildkite.arb"),
1568        "concourse" => include_str!("../stdlib/concourse.arb"),
1569        "woodpecker" => include_str!("../stdlib/woodpecker.arb"),
1570        "spinnaker" => include_str!("../stdlib/spinnaker.arb"),
1571        "tekton" => include_str!("../stdlib/tekton.arb"),
1572        "teamcity" => include_str!("../stdlib/teamcity.arb"),
1573        "packer" => include_str!("../stdlib/packer.arb"),
1574        "vagrant" => include_str!("../stdlib/vagrant.arb"),
1575        "pulumi" => include_str!("../stdlib/pulumi.arb"),
1576        "chef" => include_str!("../stdlib/chef.arb"),
1577        "puppet" => include_str!("../stdlib/puppet.arb"),
1578        "salt" => include_str!("../stdlib/salt.arb"),
1579        "cloudformation" => include_str!("../stdlib/cloudformation.arb"),
1580        "cdk" => include_str!("../stdlib/cdk.arb"),
1581        "doctl" => include_str!("../stdlib/doctl.arb"),
1582        "hcloud" => include_str!("../stdlib/hcloud.arb"),
1583        "fly" => include_str!("../stdlib/fly.arb"),
1584        "heroku" => include_str!("../stdlib/heroku.arb"),
1585        "linode" => include_str!("../stdlib/linode.arb"),
1586        "vultr" => include_str!("../stdlib/vultr.arb"),
1587        "scaleway" => include_str!("../stdlib/scaleway.arb"),
1588        "cassandra" => include_str!("../stdlib/cassandra.arb"),
1589        "scylla" => include_str!("../stdlib/scylla.arb"),
1590        "cockroachdb" => include_str!("../stdlib/cockroachdb.arb"),
1591        "clickhouse" => include_str!("../stdlib/clickhouse.arb"),
1592        "influxdb" => include_str!("../stdlib/influxdb.arb"),
1593        "neo4j" => include_str!("../stdlib/neo4j.arb"),
1594        "couchdb" => include_str!("../stdlib/couchdb.arb"),
1595        "dynamodb" => include_str!("../stdlib/dynamodb.arb"),
1596        "mariadb" => include_str!("../stdlib/mariadb.arb"),
1597        "duckdb" => include_str!("../stdlib/duckdb.arb"),
1598        "sqlite" => include_str!("../stdlib/sqlite.arb"),
1599        "mssql" => include_str!("../stdlib/mssql.arb"),
1600        "timescaledb" => include_str!("../stdlib/timescaledb.arb"),
1601        "arangodb" => include_str!("../stdlib/arangodb.arb"),
1602        "tidb" => include_str!("../stdlib/tidb.arb"),
1603        "victoriametrics" => include_str!("../stdlib/victoriametrics.arb"),
1604        "questdb" => include_str!("../stdlib/questdb.arb"),
1605        "riak" => include_str!("../stdlib/riak.arb"),
1606        "dgraph" => include_str!("../stdlib/dgraph.arb"),
1607        "opensearch" => include_str!("../stdlib/opensearch.arb"),
1608        "grafana" => include_str!("../stdlib/grafana.arb"),
1609        "loki" => include_str!("../stdlib/loki.arb"),
1610        "tempo" => include_str!("../stdlib/tempo.arb"),
1611        "jaeger" => include_str!("../stdlib/jaeger.arb"),
1612        "zipkin" => include_str!("../stdlib/zipkin.arb"),
1613        "datadog" => include_str!("../stdlib/datadog.arb"),
1614        "newrelic" => include_str!("../stdlib/newrelic.arb"),
1615        "sentry" => include_str!("../stdlib/sentry.arb"),
1616        "statsd" => include_str!("../stdlib/statsd.arb"),
1617        "telegraf" => include_str!("../stdlib/telegraf.arb"),
1618        "collectd" => include_str!("../stdlib/collectd.arb"),
1619        "netdata" => include_str!("../stdlib/netdata.arb"),
1620        "zabbix" => include_str!("../stdlib/zabbix.arb"),
1621        "nagios" => include_str!("../stdlib/nagios.arb"),
1622        "icinga" => include_str!("../stdlib/icinga.arb"),
1623        "pulsar" => include_str!("../stdlib/pulsar.arb"),
1624        "activemq" => include_str!("../stdlib/activemq.arb"),
1625        "nsq" => include_str!("../stdlib/nsq.arb"),
1626        "beanstalkd" => include_str!("../stdlib/beanstalkd.arb"),
1627        "caddy" => include_str!("../stdlib/caddy.arb"),
1628        "traefik" => include_str!("../stdlib/traefik.arb"),
1629        "uwsgi" => include_str!("../stdlib/uwsgi.arb"),
1630        "phpfpm" => include_str!("../stdlib/phpfpm.arb"),
1631        "tcpdump" => include_str!("../stdlib/tcpdump.arb"),
1632        "tshark" => include_str!("../stdlib/tshark.arb"),
1633        "nmap" => include_str!("../stdlib/nmap.arb"),
1634        "netstat" => include_str!("../stdlib/netstat.arb"),
1635        "iftop" => include_str!("../stdlib/iftop.arb"),
1636        "nethogs" => include_str!("../stdlib/nethogs.arb"),
1637        "vnstat" => include_str!("../stdlib/vnstat.arb"),
1638        "mtr" => include_str!("../stdlib/mtr.arb"),
1639        "zfs" => include_str!("../stdlib/zfs.arb"),
1640        "btrfs" => include_str!("../stdlib/btrfs.arb"),
1641        "smartctl" => include_str!("../stdlib/smartctl.arb"),
1642        "nvme" => include_str!("../stdlib/nvme.arb"),
1643        "rclone" => include_str!("../stdlib/rclone.arb"),
1644        _ => return None,
1645    })
1646}
1647
1648/// List available presets as `(name, description)` — bundled stdlib plus any
1649/// user modules in `~/.arb/lib`. The description is the preset's first `#` line.
1650pub fn list_presets() -> Vec<(String, String)> {
1651    let mut out: Vec<(String, String)> = STDLIB_NAMES
1652        .iter()
1653        .map(|n| {
1654            (
1655                n.to_string(),
1656                first_comment(bundled_module(n).unwrap_or("")),
1657            )
1658        })
1659        .collect();
1660    if let Some(dir) = lib_dir() {
1661        out.extend(list_user_presets(&dir));
1662    }
1663    out
1664}
1665
1666fn first_comment(src: &str) -> String {
1667    src.lines()
1668        .find_map(|l| l.trim().strip_prefix('#'))
1669        .map(|s| s.trim().to_string())
1670        .unwrap_or_default()
1671}
1672
1673/// Canonical accent color for a widget's `-color NAME` opt, as a `#rrggbb` hex —
1674/// the single source of truth shared by the TUI (parsed to an RGB color) and the
1675/// web dashboard (used directly in CSS/SVG). Unknown/absent names default to cyan.
1676/// Parse a scalar control bound (`-min`/`-max`/`-step`): a plain number, a
1677/// duration (`5s`/`500ms`/`2m`/`1h`) as seconds, or a size (`1kb`/`4mb`/`2gb`)
1678/// as bytes. Unparseable -> 0.
1679pub fn parse_scalar(s: &str) -> f64 {
1680    let s = s.trim();
1681    if let Some(d) = parse_duration(s) {
1682        return d.as_secs_f64();
1683    }
1684    let lower = s.to_ascii_lowercase();
1685    for (suf, mult) in [("kb", 1024.0), ("mb", 1048576.0), ("gb", 1073741824.0)] {
1686        if let Some(n) = lower.strip_suffix(suf) {
1687            if let Ok(v) = n.trim().parse::<f64>() {
1688                return v * mult;
1689            }
1690        }
1691    }
1692    s.parse::<f64>().unwrap_or(0.0)
1693}
1694
1695/// Whether `name` is one of the fixed semantic color names (green/red/…) — an
1696/// explicit, theme-independent override, distinct from a theme palette slot.
1697pub fn is_named_color(name: &str) -> bool {
1698    matches!(
1699        name.trim().to_ascii_lowercase().as_str(),
1700        "green"
1701            | "red"
1702            | "yellow"
1703            | "orange"
1704            | "magenta"
1705            | "pink"
1706            | "blue"
1707            | "white"
1708            | "gray"
1709            | "grey"
1710            | "cyan"
1711    )
1712}
1713
1714pub fn color_hex(name: Option<&str>) -> &'static str {
1715    match name.map(|s| s.trim().to_ascii_lowercase()).as_deref() {
1716        Some("green") => "#00e676",
1717        Some("red") => "#ff5252",
1718        Some("yellow") => "#ffd740",
1719        Some("orange") => "#ffab40",
1720        Some("magenta") | Some("pink") => "#e040fb",
1721        Some("blue") => "#40c4ff",
1722        Some("white") => "#e0e0e0",
1723        Some("gray") | Some("grey") => "#9e9e9e",
1724        _ => "#00e5ff", // cyan (default)
1725    }
1726}
1727
1728/// The user preset library directory: `$ARB_LIB` when set (used by tests and for
1729/// relocating the library), else `$HOME/.arb/lib`. `None` if neither is set.
1730pub fn lib_dir() -> Option<std::path::PathBuf> {
1731    if let Some(d) = std::env::var_os("ARB_LIB") {
1732        return Some(std::path::PathBuf::from(d));
1733    }
1734    std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".arb/lib"))
1735}
1736
1737/// Install a spec `src` into `dir` as `NAME.arb` — the shareable-package unit.
1738/// The spec is validated (parse + build) first; an invalid package is rejected
1739/// so the library only ever holds runnable dashboards. Returns the written path.
1740pub fn install_preset(
1741    dir: &std::path::Path,
1742    name: &str,
1743    src: &str,
1744) -> Result<std::path::PathBuf, String> {
1745    if name.is_empty() || name.contains(['/', '\\', '.']) {
1746        return Err(format!("install: invalid preset name `{name}`"));
1747    }
1748    let cmds = crate::parser::parse(src).map_err(|e| format!("install: invalid spec: {e}"))?;
1749    build(&cmds).map_err(|e| format!("install: invalid spec: {e}"))?;
1750    std::fs::create_dir_all(dir).map_err(|e| format!("install: {e}"))?;
1751    let path = dir.join(format!("{name}.arb"));
1752    std::fs::write(&path, src).map_err(|e| format!("install: {e}"))?;
1753    Ok(path)
1754}
1755
1756/// Remove `NAME.arb` from `dir`. Returns whether a preset was actually removed.
1757pub fn uninstall_preset(dir: &std::path::Path, name: &str) -> std::io::Result<bool> {
1758    let path = dir.join(format!("{name}.arb"));
1759    if path.exists() {
1760        std::fs::remove_file(&path)?;
1761        Ok(true)
1762    } else {
1763        Ok(false)
1764    }
1765}
1766
1767/// List installed user presets in `dir` as `(name, description)`, sorted by name.
1768/// The description is the preset's first `#` comment line.
1769pub fn list_user_presets(dir: &std::path::Path) -> Vec<(String, String)> {
1770    let mut out = Vec::new();
1771    if let Ok(entries) = std::fs::read_dir(dir) {
1772        for e in entries.flatten() {
1773            let path = e.path();
1774            if path.extension().and_then(|s| s.to_str()) == Some("arb") {
1775                if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
1776                    let src = std::fs::read_to_string(&path).unwrap_or_default();
1777                    out.push((stem.to_string(), first_comment(&src)));
1778                }
1779            }
1780        }
1781    }
1782    out.sort_by(|a, b| a.0.cmp(&b.0));
1783    out
1784}
1785
1786/// Collect `-flag value` pairs into an options map.
1787fn parse_opts(args: &[Arg]) -> BTreeMap<String, String> {
1788    let mut m = BTreeMap::new();
1789    let mut i = 0;
1790    while i < args.len() {
1791        if let Some(flag) = args[i].as_str().and_then(|w| w.strip_prefix('-')) {
1792            // A block value (`-tabs {a b}`) becomes a comma-joined word list:
1793            // each top-level command contributes its name plus its word args
1794            // (Tcl-flavored `{a b}` is one command `a b`), so `{a b}` -> "a,b".
1795            let val = match args.get(i + 1) {
1796                Some(Arg::Block(cmds)) => {
1797                    let mut words = Vec::new();
1798                    for c in cmds {
1799                        words.push(c.name.clone());
1800                        words.extend(c.args.iter().filter_map(|a| a.as_str().map(str::to_string)));
1801                    }
1802                    words.join(",")
1803                }
1804                Some(a) => a.as_str().unwrap_or("").to_string(),
1805                None => String::new(),
1806            };
1807            m.insert(flag.to_string(), val);
1808            i += 2;
1809        } else {
1810            i += 1;
1811        }
1812    }
1813    m
1814}
1815
1816/// Parse a `test "NAME" { … }` body into a [`TestCase`]. Clauses: `given LINES…`
1817/// (input, one line per arg), `run { in; … }` (the pipeline, required), and
1818/// `want LINES…` (expected output). Unknown clauses / a missing `run` error.
1819fn parse_test_case(
1820    name: String,
1821    body: &[Command],
1822    actors: &BTreeMap<String, Arc<ActorDef>>,
1823) -> Result<TestCase, String> {
1824    let str_args = |c: &Command| -> Vec<String> {
1825        c.args
1826            .iter()
1827            .filter_map(Arg::as_str)
1828            .map(String::from)
1829            .collect()
1830    };
1831    let mut given = Vec::new();
1832    let mut want = Vec::new();
1833    let mut ops = None;
1834    for c in body {
1835        match c.name.as_str() {
1836            "given" => given = str_args(c),
1837            "want" => want = str_args(c),
1838            "run" => {
1839                let b = match c.args.first() {
1840                    Some(Arg::Block(b)) => b,
1841                    _ => return Err(format!("test `{name}`: `run` expects `{{ in; … }}`")),
1842                };
1843                // Reuse the real body compiler, so a test can exercise native
1844                // verbs and the jq/xpath front-ends alike.
1845                ops = Some(pipeline_from_body(b, actors).map_err(|e| e.msg)?);
1846            }
1847            other => {
1848                return Err(format!(
1849                    "test `{name}`: unknown clause `{other}` (use given / run / want)"
1850                ))
1851            }
1852        }
1853    }
1854    let ops = ops.ok_or_else(|| format!("test `{name}`: missing `run {{ … }}`"))?;
1855    Ok(TestCase {
1856        name,
1857        given,
1858        ops,
1859        want,
1860    })
1861}
1862
1863/// Compile a `source { … }` body into a query pipeline. Must start with `in`.
1864fn pipeline_from_body(
1865    cmds: &[Command],
1866    actors: &BTreeMap<String, Arc<ActorDef>>,
1867) -> Result<Vec<QueryOp>, crate::err::SpecError> {
1868    let mut ops = Vec::new();
1869    let mut saw_in = false;
1870    for c in cmds {
1871        // Process one op; on error, anchor the diagnostic to THIS (nested) verb's
1872        // source position, not the outer `source`/`out` command (the IIFE lets the
1873        // arms' `return Err` unwind to the per-command span attach below).
1874        let step = (|| -> Result<(), crate::err::SpecError> {
1875            // jq front-end: a body command whose first token is a jq literal (starts
1876            // with `.`, or a `select(…)`/`map(…)` stage) is translated to arb ops.
1877            // Inside a `source` body a leading `.` is unambiguous — widget-path decls
1878            // never appear here. The whole command text (verb + args) is reconstructed
1879            // so the jq `|` pipe, which is not an arb separator, can be split by `jq`.
1880            if c.name.starts_with('.')
1881                || c.name.starts_with("select(")
1882                || c.name.starts_with("map(")
1883            {
1884                let mut parts = vec![c.name.clone()];
1885                parts.extend(c.args.iter().filter_map(Arg::as_str).map(str::to_string));
1886                let jq_ops = crate::jq::translate(&parts.join(" "))?;
1887                ops.extend(jq_ops);
1888                return Ok(());
1889            }
1890            // xpath front-end: a body command whose first token is an xpath literal
1891            // (`/…`, `//…`, or `@…`) translates to arb's Find/Attr/Text ops. Disjoint
1892            // from the jq test above (`.`/`select(`/`map(`) and from native verbs
1893            // (alnum), so the three coexist in one body unambiguously.
1894            if c.name.starts_with('/') || c.name.starts_with('@') {
1895                let mut parts = vec![c.name.clone()];
1896                parts.extend(c.args.iter().filter_map(Arg::as_str).map(str::to_string));
1897                let xp_ops = crate::xpath::translate(&parts.join(" "))?;
1898                ops.extend(xp_ops);
1899                return Ok(());
1900            }
1901            match c.name.as_str() {
1902                "in" | "in.json" | "in.html" | "in.xml" | "in.logfmt" => saw_in = true,
1903                "in.csv" => {
1904                    saw_in = true;
1905                    ops.push(QueryOp::Csv);
1906                }
1907                "in.tsv" => {
1908                    saw_in = true;
1909                    ops.push(QueryOp::Tsv);
1910                }
1911                "in.yaml" | "in.yml" => {
1912                    saw_in = true;
1913                    ops.push(QueryOp::Yaml);
1914                }
1915                "in.toml" => {
1916                    saw_in = true;
1917                    ops.push(QueryOp::Toml);
1918                }
1919                "sel" => {
1920                    let words: Vec<&str> = c.args.iter().filter_map(Arg::as_str).collect();
1921                    let mut css_parts = Vec::new();
1922                    let mut attr = None;
1923                    let mut i = 0;
1924                    while i < words.len() {
1925                        if words[i] == "-attr" {
1926                            attr = words.get(i + 1).map(|s| s.to_string());
1927                            i += 2;
1928                        } else {
1929                            css_parts.push(words[i]);
1930                            i += 1;
1931                        }
1932                    }
1933                    let css = css_parts.join(" ");
1934                    if css.trim().is_empty() {
1935                        return Err("sel: expected a CSS selector".into());
1936                    }
1937                    ops.push(QueryOp::Sel { css, attr });
1938                }
1939                "find" => {
1940                    let css = c
1941                        .args
1942                        .iter()
1943                        .filter_map(Arg::as_str)
1944                        .collect::<Vec<_>>()
1945                        .join(" ");
1946                    if css.trim().is_empty() {
1947                        return Err("find: expected a tag/selector".into());
1948                    }
1949                    ops.push(QueryOp::Find(css));
1950                }
1951                "attr" => {
1952                    let name = str_arg(c);
1953                    if name.is_empty() {
1954                        return Err("attr: expected an attribute name".into());
1955                    }
1956                    ops.push(QueryOp::Attr(name));
1957                }
1958                "text" => ops.push(QueryOp::Text),
1959                "match" | "grep" => ops.push(QueryOp::Match(regex_arg(c)?)),
1960                "reject" | "grepv" => ops.push(QueryOp::Reject(regex_arg(c)?)),
1961                "field" => ops.push(QueryOp::Field(field_sel(&c.args)?)),
1962                "fields" => {
1963                    let cols: Vec<usize> = c
1964                        .args
1965                        .iter()
1966                        .filter_map(Arg::as_str)
1967                        .filter_map(|s| s.parse::<usize>().ok())
1968                        .collect();
1969                    if cols.is_empty() {
1970                        return Err("fields: expected column numbers (e.g. fields 1 3)".into());
1971                    }
1972                    ops.push(QueryOp::Fields(cols));
1973                }
1974                "each" => ops.push(QueryOp::Each),
1975                "count" => ops.push(QueryOp::Count),
1976                "rate" => ops.push(QueryOp::Rate),
1977                "tally" => ops.push(QueryOp::Tally),
1978                "sum" => ops.push(QueryOp::Sum),
1979                "min" => ops.push(QueryOp::Min),
1980                "max" => ops.push(QueryOp::Max),
1981                "avg" => ops.push(QueryOp::Avg),
1982                "keys" => ops.push(QueryOp::Keys),
1983                "vals" => ops.push(QueryOp::Vals),
1984                "pick" => {
1985                    let keys: Vec<String> = c
1986                        .args
1987                        .iter()
1988                        .filter_map(Arg::as_str)
1989                        .map(str::to_string)
1990                        .collect();
1991                    if keys.is_empty() {
1992                        return Err("pick: expected one or more key names".into());
1993                    }
1994                    ops.push(QueryOp::Pick(keys));
1995                }
1996                "sort" => {
1997                    let flags: Vec<&str> = c.args.iter().filter_map(Arg::as_str).collect();
1998                    ops.push(QueryOp::Sort {
1999                        numeric: flags.contains(&"-n"),
2000                        reverse: flags.contains(&"-r"),
2001                    });
2002                }
2003                "uniq" => ops.push(QueryOp::Uniq),
2004                "rev" => ops.push(QueryOp::Rev),
2005                "first" => ops.push(QueryOp::First),
2006                "last" => ops.push(QueryOp::Last),
2007                "upper" => ops.push(QueryOp::Upper),
2008                "lower" => ops.push(QueryOp::Lower),
2009                "trim" => ops.push(QueryOp::Trim),
2010                "replace" => {
2011                    let re = regex_arg(c)?;
2012                    let to = c
2013                        .args
2014                        .get(1)
2015                        .and_then(Arg::as_str)
2016                        .unwrap_or("")
2017                        .to_string();
2018                    ops.push(QueryOp::Replace(re, to));
2019                }
2020                "join" => {
2021                    let sep = c
2022                        .args
2023                        .first()
2024                        .and_then(Arg::as_str)
2025                        .unwrap_or(" ")
2026                        .to_string();
2027                    ops.push(QueryOp::Join(sep));
2028                }
2029                "nth" => ops.push(QueryOp::Nth(count_arg(c, "nth")?)),
2030                "take" => ops.push(QueryOp::Take(count_arg(c, "take")?)),
2031                "drop" => ops.push(QueryOp::Drop(count_arg(c, "drop")?)),
2032                "calc" => {
2033                    let src = c
2034                        .args
2035                        .iter()
2036                        .filter_map(Arg::as_str)
2037                        .collect::<Vec<_>>()
2038                        .join(" ");
2039                    ops.push(QueryOp::Calc(crate::expr::parse(&src)?));
2040                }
2041                "where" => {
2042                    let src = c
2043                        .args
2044                        .iter()
2045                        .filter_map(Arg::as_str)
2046                        .collect::<Vec<_>>()
2047                        .join(" ");
2048                    ops.push(QueryOp::Where(crate::expr::parse(&src)?));
2049                }
2050                "map" => {
2051                    let src = c
2052                        .args
2053                        .iter()
2054                        .filter_map(Arg::as_str)
2055                        .collect::<Vec<_>>()
2056                        .join(" ");
2057                    ops.push(QueryOp::Map(crate::expr::parse(&src)?));
2058                }
2059                "via" => {
2060                    // `via NAME` / `via NAME * N` — fan the stream across a pool of
2061                    // actor NAME. Tokens join then split on `*`: left = actor name,
2062                    // right = optional worker count (0 = one per hardware thread).
2063                    let joined = c
2064                        .args
2065                        .iter()
2066                        .filter_map(Arg::as_str)
2067                        .collect::<Vec<_>>()
2068                        .join(" ");
2069                    let (name, workers) = match joined.split_once('*') {
2070                        Some((n, w)) => {
2071                            let count = w.trim().parse::<usize>().map_err(|_| {
2072                                format!("via: `* {}` is not a worker count", w.trim())
2073                            })?;
2074                            // Cap the pool so `via NAME * 9999999` can't spawn a
2075                            // runaway number of threads.
2076                            (n.trim().to_string(), count.min(1024))
2077                        }
2078                        None => (joined.trim().to_string(), 0),
2079                    };
2080                    if name.is_empty() {
2081                        return Err("via: expected an actor name (`via NAME [* N]`)".into());
2082                    }
2083                    let def = actors
2084                        .get(&name)
2085                        .ok_or_else(|| format!("via: no actor named `{name}` in scope (declare `actor {name}(state) {{ … }}` before this `via`)"))?
2086                        .clone();
2087                    ops.push(QueryOp::Via(def, workers));
2088                }
2089                "sort_by" => {
2090                    let field = str_arg(c);
2091                    if field.is_empty() {
2092                        return Err("sort_by: expected a field name".into());
2093                    }
2094                    ops.push(QueryOp::SortBy(field));
2095                }
2096                "unique_by" => {
2097                    let field = str_arg(c);
2098                    if field.is_empty() {
2099                        return Err("unique_by: expected a field name".into());
2100                    }
2101                    ops.push(QueryOp::UniqueBy(field));
2102                }
2103                "count_by" => {
2104                    let field = str_arg(c);
2105                    if field.is_empty() {
2106                        return Err("count_by: expected a field name".into());
2107                    }
2108                    ops.push(QueryOp::CountBy(field));
2109                }
2110                "group_by" => {
2111                    let field = str_arg(c);
2112                    if field.is_empty() {
2113                        return Err("group_by: expected a field name".into());
2114                    }
2115                    ops.push(QueryOp::GroupBy(field));
2116                }
2117                "min_by" => {
2118                    let field = str_arg(c);
2119                    if field.is_empty() {
2120                        return Err("min_by: expected a field name".into());
2121                    }
2122                    ops.push(QueryOp::MinBy(field));
2123                }
2124                "max_by" => {
2125                    let field = str_arg(c);
2126                    if field.is_empty() {
2127                        return Err("max_by: expected a field name".into());
2128                    }
2129                    ops.push(QueryOp::MaxBy(field));
2130                }
2131                "has" => {
2132                    let key = str_arg(c);
2133                    if key.is_empty() {
2134                        return Err("has: expected a key name".into());
2135                    }
2136                    ops.push(QueryOp::Has(key));
2137                }
2138                "entries" => {
2139                    if !c.args.is_empty() {
2140                        return Err("entries: takes no arguments".into());
2141                    }
2142                    ops.push(QueryOp::Entries);
2143                }
2144                "flatten" => ops.push(QueryOp::Flatten),
2145                "add" => ops.push(QueryOp::Add),
2146                "over" => {
2147                    let n = c
2148                        .args
2149                        .first()
2150                        .and_then(Arg::as_str)
2151                        .and_then(|s| s.parse::<f64>().ok())
2152                        .ok_or_else(|| "over: expected a numeric threshold".to_string())?;
2153                    ops.push(QueryOp::Over(n));
2154                }
2155                "under" => {
2156                    let n: f64 = str_arg(c)
2157                        .parse()
2158                        .map_err(|_| "under: expected a number".to_string())?;
2159                    ops.push(QueryOp::Under(n));
2160                }
2161                "between" => {
2162                    let lo = c
2163                        .args
2164                        .first()
2165                        .and_then(Arg::as_str)
2166                        .and_then(|s| s.parse::<f64>().ok())
2167                        .ok_or_else(|| "between: expected two numbers A B".to_string())?;
2168                    let hi = c
2169                        .args
2170                        .get(1)
2171                        .and_then(Arg::as_str)
2172                        .and_then(|s| s.parse::<f64>().ok())
2173                        .ok_or_else(|| "between: expected two numbers A B".to_string())?;
2174                    ops.push(QueryOp::Between(lo, hi));
2175                }
2176                "enumerate" => {
2177                    ops.push(QueryOp::Enumerate);
2178                }
2179                "words" => {
2180                    if !c.args.is_empty() {
2181                        return Err("words: takes no arguments".into());
2182                    }
2183                    ops.push(QueryOp::Words);
2184                }
2185                "dedup" => ops.push(QueryOp::Dedup),
2186                "tailn" => ops.push(QueryOp::Tailn(count_arg(c, "tailn")?)),
2187                "pad" => {
2188                    let n = count_arg(c, "pad")?;
2189                    ops.push(QueryOp::Pad(n));
2190                }
2191                "lpad" => ops.push(QueryOp::Lpad(count_arg(c, "lpad")?)),
2192                "grepf" => {
2193                    let field = c
2194                        .args
2195                        .first()
2196                        .and_then(Arg::as_str)
2197                        .ok_or_else(|| "grepf: expected FIELD and /re/".to_string())?
2198                        .to_string();
2199                    let raw = c
2200                        .args
2201                        .get(1)
2202                        .and_then(Arg::as_str)
2203                        .ok_or_else(|| "grepf: expected a pattern".to_string())?;
2204                    let pat = raw
2205                        .strip_prefix('/')
2206                        .and_then(|s| s.strip_suffix('/'))
2207                        .unwrap_or(raw);
2208                    let re =
2209                        regex::Regex::new(pat).map_err(|e| format!("grepf: bad regex: {e}"))?;
2210                    ops.push(QueryOp::Grepf(field, re));
2211                }
2212                "apply" => {
2213                    let name = str_arg(c);
2214                    let name = name.strip_prefix('.').unwrap_or(&name).to_string();
2215                    ops.push(QueryOp::Apply(name));
2216                }
2217                "basename" => ops.push(QueryOp::Basename),
2218                "dirname" => ops.push(QueryOp::Dirname),
2219                "commafy" => ops.push(QueryOp::Commafy),
2220                "bytes" => ops.push(QueryOp::Bytes),
2221                "duration" => ops.push(QueryOp::Duration),
2222                "flip" => {
2223                    ops.push(QueryOp::Flip);
2224                }
2225                "b64" => {
2226                    ops.push(QueryOp::B64);
2227                }
2228                "b64d" => {
2229                    ops.push(QueryOp::B64d);
2230                }
2231                "hex" => ops.push(QueryOp::Hex),
2232                "unhex" => {
2233                    ops.push(QueryOp::Unhex);
2234                }
2235                "urlenc" => {
2236                    ops.push(QueryOp::Urlenc);
2237                }
2238                "urldec" => {
2239                    ops.push(QueryOp::Urldec);
2240                }
2241                "extract" => {
2242                    ops.push(QueryOp::Extract(regex_arg(c)?));
2243                }
2244                "split" => {
2245                    let delim = str_arg(c);
2246                    if delim.is_empty() {
2247                        return Err("split: expected a non-empty delimiter".into());
2248                    }
2249                    ops.push(QueryOp::Split(delim));
2250                }
2251                "substr" => {
2252                    let args: Vec<usize> = c
2253                        .args
2254                        .iter()
2255                        .filter_map(Arg::as_str)
2256                        .filter_map(|s| s.parse::<usize>().ok())
2257                        .collect();
2258                    if args.len() != 2 {
2259                        return Err("substr: expected two non-negative integer args A B".into());
2260                    }
2261                    ops.push(QueryOp::Substr(args[0], args[1]));
2262                }
2263                "chars" => ops.push(QueryOp::Chars),
2264                "title" => {
2265                    ops.push(QueryOp::Title);
2266                }
2267                "repeat" => {
2268                    let n = count_arg(c, "repeat")?;
2269                    ops.push(QueryOp::Repeat(n));
2270                }
2271                "set" => {
2272                    let key = str_arg(c);
2273                    if key.is_empty() {
2274                        return Err("set: expected key and value".into());
2275                    }
2276                    let val = c
2277                        .args
2278                        .iter()
2279                        .filter_map(Arg::as_str)
2280                        .nth(1)
2281                        .unwrap_or("")
2282                        .to_string();
2283                    ops.push(QueryOp::Set(key, val));
2284                }
2285                "del" => {
2286                    let key = str_arg(c);
2287                    if key.is_empty() {
2288                        return Err("del: expected a key name".into());
2289                    }
2290                    ops.push(QueryOp::Del(key));
2291                }
2292                "rename" => {
2293                    let args: Vec<String> = c
2294                        .args
2295                        .iter()
2296                        .filter_map(Arg::as_str)
2297                        .map(str::to_string)
2298                        .collect();
2299                    if args.len() != 2 || args[0].is_empty() || args[1].is_empty() {
2300                        return Err("rename: expected OLD NEW key names".into());
2301                    }
2302                    ops.push(QueryOp::Rename(args[0].clone(), args[1].clone()));
2303                }
2304                "default" => {
2305                    let args: Vec<String> = c
2306                        .args
2307                        .iter()
2308                        .filter_map(Arg::as_str)
2309                        .map(str::to_string)
2310                        .collect();
2311                    if args.len() != 2 {
2312                        return Err("default: expected exactly two args: key value".into());
2313                    }
2314                    ops.push(QueryOp::Default(args[0].clone(), args[1].clone()));
2315                }
2316                "merge" => {
2317                    ops.push(QueryOp::Merge);
2318                }
2319                "floor" => {
2320                    ops.push(QueryOp::Floor);
2321                }
2322                "ceil" => {
2323                    ops.push(QueryOp::Ceil);
2324                }
2325                "clamp" => {
2326                    let mut it = c.args.iter().filter_map(Arg::as_str);
2327                    let lo = it.next().and_then(|s| s.parse::<f64>().ok());
2328                    let hi = it.next().and_then(|s| s.parse::<f64>().ok());
2329                    match (lo, hi) {
2330                        (Some(lo), Some(hi)) => ops.push(QueryOp::Clamp(lo, hi)),
2331                        _ => return Err("clamp: expected LO HI numeric args".into()),
2332                    }
2333                }
2334                "contains" => ops.push(QueryOp::Contains(str_arg(c))),
2335                "starts" => ops.push(QueryOp::Starts(str_arg(c))),
2336                "ends" => ops.push(QueryOp::Ends(str_arg(c))),
2337                "nonempty" => ops.push(QueryOp::Nonempty),
2338                "numeric" => ops.push(QueryOp::Numeric),
2339                "len" => ops.push(QueryOp::Len),
2340                // jq `length`: JSON-aware (array/object/string/number), vs `len`
2341                // which is the raw char count.
2342                "length" => ops.push(QueryOp::JsonLen),
2343                "wc" => ops.push(QueryOp::Wc),
2344                "abs" => ops.push(QueryOp::Abs),
2345                "round" => ops.push(QueryOp::Round),
2346                "delta" => ops.push(QueryOp::Delta),
2347                "cumsum" => ops.push(QueryOp::Cumsum),
2348                "sma" => ops.push(QueryOp::Sma(count_arg(c, "sma")?)),
2349                "ewma" => {
2350                    let a = str_arg(c).parse::<f64>().map_err(|_| {
2351                        "ewma: expected a smoothing factor 0–1 (e.g. 0.3)".to_string()
2352                    })?;
2353                    ops.push(QueryOp::Ewma(a));
2354                }
2355                "prepend" => ops.push(QueryOp::Prepend(str_arg(c))),
2356                "append" => ops.push(QueryOp::Append(str_arg(c))),
2357                "cut" => {
2358                    let delim = str_arg(c);
2359                    let n = c
2360                        .args
2361                        .get(1)
2362                        .and_then(Arg::as_str)
2363                        .and_then(|s| s.parse::<usize>().ok())
2364                        .unwrap_or(0);
2365                    ops.push(QueryOp::Cut(delim, n));
2366                }
2367                "median" => ops.push(QueryOp::Median),
2368                "percentile" => {
2369                    let p = str_arg(c)
2370                        .parse::<f64>()
2371                        .map_err(|_| "percentile: expected a number 0–100 (e.g. 99)".to_string())?;
2372                    ops.push(QueryOp::Percentile(p));
2373                }
2374                "p50" => ops.push(QueryOp::Percentile(50.0)),
2375                "p90" => ops.push(QueryOp::Percentile(90.0)),
2376                "p95" => ops.push(QueryOp::Percentile(95.0)),
2377                "p99" => ops.push(QueryOp::Percentile(99.0)),
2378                "stddev" => ops.push(QueryOp::Stddev),
2379                "range" => ops.push(QueryOp::Range),
2380                "product" => ops.push(QueryOp::Product),
2381                "distinct" => ops.push(QueryOp::Distinct),
2382                "sample" => ops.push(QueryOp::Sample(count_arg(c, "sample")?)),
2383                "bins" => ops.push(QueryOp::Bins(count_arg(c, "bins")?)),
2384                "index" => ops.push(QueryOp::Index(count_arg(c, "index")?)),
2385                "slice" => {
2386                    let a = c
2387                        .args
2388                        .first()
2389                        .and_then(Arg::as_str)
2390                        .and_then(|s| s.parse::<usize>().ok())
2391                        .unwrap_or(1);
2392                    let b = c
2393                        .args
2394                        .get(1)
2395                        .and_then(Arg::as_str)
2396                        .and_then(|s| s.parse::<usize>().ok())
2397                        .unwrap_or(usize::MAX);
2398                    ops.push(QueryOp::Slice(a, b));
2399                }
2400                other => return Err(format!("source: unknown verb `{other}`").into()),
2401            }
2402            Ok(())
2403        })();
2404        step.map_err(|e| e.or_span(c.pos, c.name.chars().count()))?;
2405    }
2406    if !saw_in {
2407        return Err("source: pipeline must start with `in`".into());
2408    }
2409    Ok(ops)
2410}
2411
2412/// Compile a `/pattern/` (or bare `pattern`) literal into a `Regex`. Shared by
2413/// the arg form (`match /re/`, single-clause `expect /re/ …`) and the
2414/// `expect { }` block-clause form, where the `/re/` arrives as the clause
2415/// command's *name*.
2416fn compile_regex(raw: &str) -> Result<Regex, String> {
2417    let pat = raw
2418        .strip_prefix('/')
2419        .and_then(|s| s.strip_suffix('/'))
2420        .unwrap_or(raw);
2421    Regex::new(pat).map_err(|e| format!("bad regex: {e}"))
2422}
2423
2424/// Reconstruct a shell string from a `{ … }` block body: each top-level command
2425/// contributes its verb + word args, commands joined by `; ` (`{ ps aux }` ->
2426/// "ps aux"; `{ tail -f a.log; grep err }` -> "tail -f a.log; grep err").
2427fn block_to_shell(cmds: &[Command]) -> String {
2428    cmds.iter()
2429        .map(|c| {
2430            let mut w = vec![c.name.clone()];
2431            w.extend(c.args.iter().filter_map(|a| a.as_str().map(str::to_string)));
2432            w.join(" ")
2433        })
2434        .collect::<Vec<_>>()
2435        .join("; ")
2436}
2437
2438/// Read a regex argument, stripping optional `/…/` delimiters. The error carries
2439/// this command's source span so a bad regex anchors to the offending verb (e.g.
2440/// `match` inside a `source { … }` body), not the enclosing directive.
2441fn regex_arg(c: &Command) -> Result<Regex, crate::err::SpecError> {
2442    let span =
2443        |msg: String| crate::err::SpecError::from(msg).or_span(c.pos, c.name.chars().count());
2444    let raw = c
2445        .args
2446        .first()
2447        .and_then(Arg::as_str)
2448        .ok_or_else(|| span(format!("{}: expected a pattern", c.name)))?;
2449    compile_regex(raw).map_err(|e| span(format!("{}: {e}", c.name)))
2450}
2451
2452/// Parse a required count argument for `take`/`drop`.
2453/// The first arg as a string (empty if absent) — for verbs taking a literal.
2454fn str_arg(c: &Command) -> String {
2455    c.args
2456        .first()
2457        .and_then(Arg::as_str)
2458        .unwrap_or("")
2459        .to_string()
2460}
2461
2462fn count_arg(c: &Command, verb: &str) -> Result<usize, String> {
2463    c.args
2464        .first()
2465        .and_then(Arg::as_str)
2466        .and_then(|s| s.parse::<usize>().ok())
2467        .ok_or_else(|| format!("{verb}: expected a count"))
2468}
2469
2470/// A single numeric arg selects a whitespace column; anything else is a JSON
2471/// key path (`field a b c` -> a.b.c).
2472fn field_sel(args: &[Arg]) -> Result<FieldSel, String> {
2473    let words: Vec<&str> = args.iter().filter_map(Arg::as_str).collect();
2474    if words.is_empty() {
2475        return Err("field: expected a column number or key path".into());
2476    }
2477    if words.len() == 1 {
2478        if let Ok(n) = words[0].parse::<usize>() {
2479            return Ok(FieldSel::Col(n));
2480        }
2481    }
2482    Ok(FieldSel::Key(words.iter().map(|s| s.to_string()).collect()))
2483}
2484
2485fn set_source(spec: &mut Spec, path: &str, src: Source) -> Result<(), String> {
2486    for w in &mut spec.widgets {
2487        if w.path == path {
2488            w.source = Some(src);
2489            return Ok(());
2490        }
2491    }
2492    Err(format!("source: no widget named `{path}`"))
2493}
2494
2495/// `.path configure -k v …`: merge `opts` into the named widget's options
2496/// (later keys win), so a spec can retune a widget after declaring it.
2497fn configure_widget(
2498    spec: &mut Spec,
2499    path: &str,
2500    opts: BTreeMap<String, String>,
2501) -> Result<(), String> {
2502    for w in &mut spec.widgets {
2503        if w.path == path {
2504            w.opts.extend(opts);
2505            return Ok(());
2506        }
2507    }
2508    Err(format!("configure: no widget named `{path}`"))
2509}
2510
2511fn set_search(spec: &mut Spec, path: &str, pipeline: Vec<QueryOp>) -> Result<(), String> {
2512    for w in &mut spec.widgets {
2513        if w.path == path {
2514            w.search = Some(pipeline);
2515            return Ok(());
2516        }
2517    }
2518    Err(format!("search: no widget named `{path}`"))
2519}
2520
2521fn set_grid(
2522    spec: &mut Spec,
2523    path: &str,
2524    cell: (usize, usize),
2525    span: (usize, usize),
2526) -> Result<(), String> {
2527    for w in &mut spec.widgets {
2528        if w.path == path {
2529            w.grid = Some(cell);
2530            w.span = span;
2531            return Ok(());
2532        }
2533    }
2534    Err(format!("grid: no widget named `{path}`"))
2535}