Skip to main content

oxdock_parser/
commands.rs

1//! Single-site command registry for all OxDock commands.
2//!
3//! `declare_commands!` is the sole source of truth. It generates:
4//! - StepKind enum : all command + structural AST variants
5//! - `pub fn lower_command(name, raw_args)` : name-dispatched lowering
6//! - `pub fn all_metadata()` : collects `CommandMeta` from all declarations
7//!   plus `all_structural_metadata()` (structural statements are documented
8//!   through the same pipeline so reference docs cannot drift).
9//!
10//! To add a command: add one block inside `declare_commands!`.
11//! To add a structural statement: extend the `structural [...]` list,
12//! `all_structural_metadata()`, and the `structural_metadata_covers_all_structural_kinds`
13//! tripwire below.
14
15use std::collections::HashSet;
16use std::fmt;
17
18use crate::ast::{
19    Arg, ArgPart, ArithOp, Command, CompareOp, Expr, GuardExpr, IoBinding, IoStream, MathOp,
20    ModuleTable, PipeTarget, Step, Value, WorkspaceTarget,
21};
22use crate::command::{
23    ArgSpec, ArgType, CommandMeta, Example, FlagSpec, FlagValueType, IoDirection, Stream,
24    split_assignment,
25};
26use crate::constants::{
27    KEYWORD_APPEND, KEYWORD_APPEND_LINE, KEYWORD_ARCHIVE, KEYWORD_ASSERT_CONTAINS,
28    KEYWORD_ASSERT_EQ, KEYWORD_ASSERT_NE, KEYWORD_ASYNC, KEYWORD_AWAIT, KEYWORD_BREAK,
29    KEYWORD_CANCEL, KEYWORD_CASE, KEYWORD_CONTINUE, KEYWORD_COPY, KEYWORD_COPY_GIT,
30    KEYWORD_DEFAULT, KEYWORD_ECHO, KEYWORD_ELSE, KEYWORD_ENV, KEYWORD_EXIT, KEYWORD_EXPAND,
31    KEYWORD_EXPORT, KEYWORD_FAIL, KEYWORD_FOR, KEYWORD_FUNC, KEYWORD_IF, KEYWORD_IMPORT,
32    KEYWORD_INHERIT_ENV, KEYWORD_INSTALL, KEYWORD_ISOLATED, KEYWORD_LET, KEYWORD_LIST_APPEND,
33    KEYWORD_LS, KEYWORD_MKDIR, KEYWORD_PROMPT, KEYWORD_READ, KEYWORD_READ_LINE, KEYWORD_REMOTE,
34    KEYWORD_REMOVE, KEYWORD_RETURN, KEYWORD_RUN, KEYWORD_SET_EXECUTABLE, KEYWORD_SLEEP,
35    KEYWORD_SWITCH, KEYWORD_SYMLINK, KEYWORD_TIMEOUT, KEYWORD_TYPE, KEYWORD_UNARCHIVE,
36    KEYWORD_WHILE, KEYWORD_WITH_IO, KEYWORD_WORKDIR, KEYWORD_WORKSPACE, KEYWORD_WRITE,
37};
38use crate::error::{ParseError, ParseResult, SpanContext};
39use indoc::indoc;
40
41// ── Helpers ────────────────────────────────────────────────────────────────
42
43// Value-parsing helpers (`strip_surrounding_quotes`,
44// `split_assignment`, `parse_duration`, `format_duration`) live in
45// `crate::command` beside the `ArgType` validators that call them.
46
47/// Reserved words that can never name a `REMOTE` target: the workspace
48/// roots plus the block keyword itself. Shared with CLI inventory
49/// validation so charset rules cannot drift between parser and host.
50pub const REMOTE_RESERVED_WORDS: &[&str] =
51    &["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM", KEYWORD_REMOTE];
52
53/// Validate a `REMOTE` target name: start alnum, then alnum, `_`, or
54/// `-`, max 64 chars. Safe in CLI flags, log lines, tarball names, and
55/// muxio stream labels without quoting.
56pub fn is_valid_remote_target(target: &str) -> bool {
57    if target.is_empty() || target.len() > 64 {
58        return false;
59    }
60    if REMOTE_RESERVED_WORDS.contains(&target) {
61        return false;
62    }
63    let mut chars = target.chars();
64    match chars.next() {
65        Some(first) if first.is_ascii_alphanumeric() => {}
66        _ => return false,
67    }
68    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
69}
70
71/// Join free-text tail arguments into one value. Single args pass through
72/// untouched (preserving `Arg::Expr`); all-`String` tails join exactly like the
73/// historical `join_args`; tails containing expressions become `Arg::Parts`
74/// with single-space separators so `$x` is never silently dropped.
75fn join_value(args: Vec<Arg>, cmd_name: &str) -> ParseResult<Arg> {
76    if args.is_empty() {
77        return Err(ParseError::validation(
78            cmd_name,
79            format!("{cmd_name} requires at least one argument"),
80            &SpanContext::line_only(0),
81        ));
82    }
83    if args.len() == 1 {
84        return Ok(args.into_iter().next().unwrap());
85    }
86    if args.iter().all(|a| matches!(a, Arg::String(..))) {
87        return Ok(Arg::String(
88            args.iter()
89                .map(|a| a.as_str())
90                .collect::<Vec<_>>()
91                .join(" "),
92            false,
93        ));
94    }
95    let mut parts = Vec::new();
96    for (index, arg) in args.into_iter().enumerate() {
97        if index > 0 {
98            parts.push(ArgPart::Text(" ".to_string(), false));
99        }
100        match arg {
101            Arg::String(text, quoted) => parts.push(ArgPart::Text(text, quoted)),
102            Arg::Expr(expr) => parts.push(ArgPart::Expr(expr)),
103            Arg::Parts(inner) => parts.extend(inner),
104        }
105    }
106    Ok(Arg::Parts(parts))
107}
108
109/// Canonical `lower_command` entry for direct callers holding one pre-joined
110/// `KEY=value` token. Script parsing never reaches this : the grammar splits
111/// assignments on raw spans first (see `lower_env_command` in parser.rs).
112pub fn lower_env_assignment(args: Vec<Arg>) -> ParseResult<StepKind> {
113    let arg = args.into_iter().next().ok_or_else(|| {
114        ParseError::validation(
115            KEYWORD_ENV,
116            "ENV requires KEY=value".to_string(),
117            &SpanContext::line_only(0),
118        )
119    })?;
120    let Some((key, value)) = split_assignment(arg.as_str()).map_err(|e| {
121        ParseError::validation(KEYWORD_ENV, e.to_string(), &SpanContext::line_only(0))
122    })?
123    else {
124        return Err(ParseError::validation(
125            KEYWORD_ENV,
126            "ENV requires KEY=value format".to_string(),
127            &SpanContext::line_only(0),
128        ));
129    };
130    Ok(StepKind::Env { key, value })
131}
132
133/// Collapse a grammar-classified assignment for commands that take no
134/// assignments (`RUN`, `COPY`, ...): canonical `key=<rendered value>` text.
135/// Runtime semantics survive intact : `{{ }}` templates stay textual for
136/// `expand_string`, and `RUN`'s own post-pass expands bare `$var`.
137pub(crate) fn canonical_assignment_arg(key: &str, value: &Arg) -> Arg {
138    Arg::String(format!("{key}={}", value.render()), false)
139}
140
141/// Render an [`AssertTarget`] for `Display`: stream markers print bare
142/// (`stdout` reparses to the marker); values print like other args.
143fn fmt_assert_target(target: &AssertTarget) -> String {
144    match target {
145        AssertTarget::Value(arg) => fmt_value(arg, quote_msg),
146        _ => target.render(),
147    }
148}
149
150/// Render one `Arg` for `Display`: expressions print raw (`$x` must never be
151/// quoted or reparsing would literalize them); mixed values print raw unless
152/// they hold instruction-boundary characters (`;`, `}`, linebreaks), which
153/// force quoting for reparseability.
154fn fmt_value(arg: &Arg, quote: fn(&str) -> String) -> String {
155    match arg {
156        Arg::Expr(_) => arg.render(),
157        Arg::String(text, _) => quote(text),
158        Arg::Parts(_) => {
159            let rendered = arg.render();
160            if rendered.contains(';')
161                || rendered.contains('}')
162                || rendered.contains('\n')
163                || rendered.contains('\r')
164            {
165                quote(&rendered)
166            } else {
167                rendered
168            }
169        }
170    }
171}
172
173fn quote_dsl_string(s: &str) -> String {
174    // Single quoting core for Display output: backslash and quote
175    // escapes only. The `quote_*`/`fmt_*` helpers below differ in *when*
176    // a value needs quoting, never in *how*. No brace or control
177    // handling: the parser passes literal contents verbatim, so Display
178    // round-trips without them (unlike `escape_dsl_string` in `literal`,
179    // which inverts runtime `expand_string` and must also
180    // escape `{{` triples and controls).
181    // Multi-line values render as `"""` blocks on their own lines at
182    // column zero, so lowering recovers the bytes exactly: the leading
183    // newline strips once, the empty closing baseline contributes no
184    // common prefix, and the trailing newline strips once. Quote-holding
185    // values stay double-quoted with `\"` escapes: blocks admit raw
186    // quotes for the string grammar, but no Rust token stream can carry
187    // them (the lexer ends the literal at every raw `"`), so block
188    // rendering would shred on the token pathway while escaping keeps
189    // both pathways agreeing. Blank-only and carriage-return values
190    // keep the legacy raw double-quoted spelling instead: block
191    // lowering would normalize them away.
192    if s.contains('\n') && !s.contains('"') && !s.contains('\r') && !s.trim().is_empty() {
193        let escaped = escape_block_text(s);
194        return format!("\"\"\"\n{escaped}\n\"\"\"");
195    }
196    format!("\"{}\"", escape_inline_text(s))
197}
198
199/// Escape text for double-quoted rendering so a render cycle adds no
200/// layer: recognized escapes pass through verbatim (the parser keeps
201/// them verbatim and both lexers accept them), while the delimiter and
202/// anything neither lexer takes raw gets escaped.
203fn escape_inline_text(s: &str) -> String {
204    let mut out = String::with_capacity(s.len() + 2);
205    let mut chars = s.chars().peekable();
206    while let Some(c) = chars.next() {
207        match c {
208            '"' => out.push_str("\\\""),
209            '\\' => {
210                // Recognized pairs emit atomically: reprocessing the
211                // trailing quote through the `"` arm above would grow
212                // the pair a second backslash.
213                if matches!(
214                    chars.peek(),
215                    Some('n' | 't' | 'r' | '\\' | '"' | '\'' | '0')
216                ) {
217                    out.push('\\');
218                    out.push(chars.next().unwrap_or('\\'));
219                } else {
220                    out.push_str("\\\\");
221                }
222            }
223            _ => out.push(c),
224        }
225    }
226    out
227}
228
229/// Escape block payloads: the delimiter triple always escapes first,
230/// and a backslash survives raw only where both lexers take it
231/// (recognized escapes, including the ones just introduced; a real
232/// newline or `{` after it would break Rust lexing, so those double
233/// like everything else unrecognized).
234fn escape_block_text(s: &str) -> String {
235    let preescaped = s.replace("\"\"\"", "\\\"\\\"\\\"");
236    let mut out = String::with_capacity(preescaped.len());
237    let mut chars = preescaped.chars().peekable();
238    while let Some(c) = chars.next() {
239        if c != '\\' {
240            out.push(c);
241            continue;
242        }
243        let keep = matches!(
244            chars.peek(),
245            Some('n' | 't' | 'r' | '\\' | '"' | '\'' | '0')
246        );
247        out.push('\\');
248        if !keep {
249            out.push('\\');
250        }
251    }
252    out
253}
254
255fn quote_arg(s: &str) -> String {
256    let is_safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
257        && !s.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '/' || c == '.')
258        && !crate::Command::is_statement_keyword(s);
259    if is_safe && !s.is_empty() {
260        s.to_string()
261    } else {
262        quote_dsl_string(s)
263    }
264}
265
266fn quote_msg(s: &str) -> String {
267    let safe = s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
268        && !s.starts_with(|c: char| c.is_ascii_digit())
269        && !crate::Command::is_statement_keyword(s);
270    if safe && !s.is_empty() {
271        s.to_string()
272    } else {
273        quote_dsl_string(s)
274    }
275}
276
277fn quote_run(s: &str) -> String {
278    if s.is_empty() || s.chars().any(|c| c == ';' || c == '\n') || s.contains("//") {
279        return quote_dsl_string(s);
280    }
281    s.split(' ')
282        .map(|w| {
283            if w.starts_with(|c: char| c.is_ascii_digit())
284                || w.starts_with(['/', '.', '-', ':', '='])
285            {
286                quote_dsl_string(w)
287            } else {
288                w.to_string()
289            }
290        })
291        .collect::<Vec<_>>()
292        .join(" ")
293}
294
295/// Render one exec-form (`RUN [...]`) argv element for `Display`:
296/// string literals print JSON-quoted; typed expressions (`$var`,
297/// `F()`, ints, bools, nested lists) print raw via `render` so
298/// reparsing yields the same typed element; mixed values print raw
299/// unless they hold instruction-boundary characters.
300fn fmt_exec_arg(arg: &Arg) -> String {
301    match arg {
302        Arg::String(text, _) => quote_dsl_string(text),
303        Arg::Expr(_) => arg.render(),
304        Arg::Parts(_) => {
305            let rendered = arg.render();
306            if rendered.contains(';')
307                || rendered.contains('}')
308                || rendered.contains('\n')
309                || rendered.contains('\r')
310            {
311                quote_dsl_string(&rendered)
312            } else {
313                rendered
314            }
315        }
316    }
317}
318
319/// Render an [`Arg`] for `Display`: the quoted flag drives quoting (not
320/// content sniffing : digit-leading values like `10s` or `0` must stay
321/// bare to reparse with the same flag).
322fn fmt_raw_arg(arg: &Arg) -> String {
323    match arg {
324        Arg::String(s, true) => quote_dsl_string(s),
325        _ => arg.render(),
326    }
327}
328
329fn fmt_io(b: &IoBinding) -> String {
330    let s = match b.stream {
331        IoStream::Stdin => "stdin".to_string(),
332        IoStream::Stdout => "stdout".to_string(),
333        IoStream::Stderr => "stderr".to_string(),
334        IoStream::Tty => "tty".to_string(),
335        IoStream::Rows(rows) => format!("rows={rows}"),
336        IoStream::Cols(cols) => format!("cols={cols}"),
337    };
338    match &b.pipe {
339        Some(PipeTarget::Var(v)) => format!("{}=${}", s, v),
340        None => s,
341    }
342}
343
344// ── declare_commands! ──────────────────────────────────────────────────────
345
346// Keywords parsed by PEG rules rather than plain-command lowering (`WITH_IO`,
347// `AWAIT`, ...). When a line starts with one of these but fails to parse as
348// such, lowering falls through here : report a committed syntax error instead
349// of an unknown command.
350pub(crate) fn is_known_command(name: &str) -> bool {
351    if name == KEYWORD_ELSE {
352        return true;
353    }
354    all_metadata().iter().any(|meta| meta.name == name)
355}
356
357pub(crate) fn invalid_syntax_error(name: &str, raw_args: &[Arg]) -> ParseError {
358    let received = raw_args
359        .iter()
360        .map(Arg::render)
361        .collect::<Vec<_>>()
362        .join(" ");
363    let got = if received.is_empty() {
364        "nothing".to_string()
365    } else {
366        format!("`{received}`")
367    };
368    let found = if received.is_empty() {
369        None
370    } else {
371        Some(received.clone())
372    };
373    let expected = all_metadata()
374        .iter()
375        .find(|meta| meta.name == name)
376        .map(|meta| vec![meta.syntax.to_string()])
377        .unwrap_or_default();
378    let ctx = SpanContext::line_only(0);
379    match structural_hint(name, &received) {
380        Some(hint) => ParseError::invalid_syntax(
381            name,
382            format!("invalid syntax for command {name}: {hint}"),
383            found,
384            expected,
385            Some(hint),
386            &ctx,
387        ),
388        None => ParseError::invalid_syntax(
389            name,
390            format!("invalid syntax for command {name}: got {got}."),
391            found,
392            expected,
393            None,
394            &ctx,
395        ),
396    }
397}
398
399fn unknown_command_error(name: &str, raw_args: &[Arg]) -> ParseError {
400    let received = raw_args
401        .iter()
402        .map(Arg::render)
403        .collect::<Vec<_>>()
404        .join(" ");
405    let hint = structural_hint(name, &received).or_else(|| case_hint(name));
406    let ctx = SpanContext::line_only(0);
407    match hint {
408        Some(hint) => ParseError::unknown_command(
409            name,
410            format!("unknown command: {name}\n{hint}"),
411            Some(hint),
412            &ctx,
413        ),
414        None => ParseError::unknown_command(name, format!("unknown command: {name}"), None, &ctx),
415    }
416}
417
418/// Single decision function for the lowering fallback: keyword led lines
419/// (structural statements, `ELSE`, every registered command) are committed
420/// syntax errors, never unknown commands. Only truly unknown names fall
421/// through to `unknown_command_error`. Callers enrich the result with the
422/// token span via `ParseError::with_span`.
423pub(crate) fn classify(name: &str, raw_args: &[Arg]) -> ParseError {
424    if is_known_command(name) {
425        invalid_syntax_error(name, raw_args)
426    } else {
427        unknown_command_error(name, raw_args)
428    }
429}
430
431fn structural_hint(name: &str, received: &str) -> Option<String> {
432    let got = if received.is_empty() {
433        "nothing".to_string()
434    } else {
435        format!("`{received}`")
436    };
437    match name {
438        name if name == KEYWORD_WITH_IO => Some(with_io_hint(&got, received)),
439        name if name == KEYWORD_AWAIT => Some(format!(
440            "AWAIT waits for a background task variable, e.g. `LET $t: HANDLE<VOID> = ASYNC ECHO hi` then `AWAIT $t`; got {got}."
441        )),
442        name if name == KEYWORD_CANCEL => Some(format!(
443            "CANCEL stops a background task variable, e.g. `CANCEL $t` (from `LET $t: HANDLE<VOID> = ASYNC ...`); got {got}."
444        )),
445        name if name == KEYWORD_ASYNC => Some(format!(
446            "ASYNC runs a command in the background, e.g. `ASYNC RUN ...`, `ASYNC {{ ... }}`, or `LET $t: HANDLE<T> = ASYNC ...`; got {got}."
447        )),
448        name if name == KEYWORD_FOR => Some(format!(
449            "FOR loops need `FOR $item: TYPE IN <expr> {{ ... }}` (or `FOR $key: STRING, $value: TYPE IN <expr> {{ ... }}`); got {got}."
450        )),
451        name if name == KEYWORD_IF => Some(format!(
452            "IF needs a condition and a block, e.g. `IF true {{ ECHO yes }}`; got {got}."
453        )),
454        name if name == KEYWORD_ELSE => Some(format!(
455            "ELSE must directly follow an `IF ... {{ ... }}` block, e.g. `IF true {{ ECHO yes }} ELSE {{ ECHO no }}`; got {got}."
456        )),
457        name if name == KEYWORD_SWITCH => Some(format!(
458            "SWITCH needs a value or bare condition list plus braced CASE arms, e.g. `SWITCH $cmd {{ CASE \"a\" {{ ECHO yes }} DEFAULT {{ ECHO no }} }}`; got {got}."
459        )),
460        name if name == KEYWORD_CASE => Some(format!(
461            "CASE only appears inside a SWITCH body, e.g. `SWITCH $cmd {{ CASE \"a\", \"b\" {{ ECHO yes }} }}`; got {got}."
462        )),
463        name if name == KEYWORD_DEFAULT => Some(format!(
464            "DEFAULT only appears inside a SWITCH body, e.g. `SWITCH $cmd {{ CASE \"a\" {{ ECHO yes }} DEFAULT {{ ECHO no }} }}`; got {got}."
465        )),
466        name if name == KEYWORD_LET => Some(format!(
467            "LET assigns a variable, e.g. `LET $name: STRING = <expr>`, `LET $t: HANDLE<T> = ASYNC ...`, `LET $out: STRING = <command>` (capture), `LET $out: STRING = AWAIT $t`, or `LET $var: TYPE = {{ ... }}` (inline block); got {got}."
468        )),
469        "SET" => Some(
470            "`SET` is not a keyword; mutate a declared variable with `$var = <expr>`, e.g. `$count = 2`.".to_string(),
471        ),
472        name if name == KEYWORD_TIMEOUT => Some(format!(
473            "TIMEOUT needs a duration and a command or block, e.g. `TIMEOUT 30s RUN ...`; got {got}."
474        )),
475        name if name == KEYWORD_FAIL => Some(format!(
476            "FAIL needs a message, a code, or a block, e.g. `FAIL \"boom\"`, `FAIL 2 \"boom\"`, or `FAIL \"boom\" {{ ECHO usage }}`; got {got}."
477        )),
478        name if name == KEYWORD_REMOTE => Some(format!(
479            "REMOTE needs a target and a braced block, e.g. `REMOTE prod [$version, env:DEPLOY_ENV] {{ ... }}`; got {got}."
480        )),
481        name if name == KEYWORD_FUNC => Some(format!(
482            "FUNC defines a function, e.g. `FUNC GREET($name: STRING): STRING {{ RETURN $name }}`; got {got}."
483        )),
484        name if name == KEYWORD_RETURN => Some(format!(
485            "RETURN ends the nearest function, ASYNC task, or inline LET block with a value, e.g. `RETURN $x`; got {got}."
486        )),
487        name if name == KEYWORD_WHILE => Some(format!(
488            "WHILE needs a Bool condition and a block, e.g. `WHILE !$done {{ ... }}`; got {got}."
489        )),
490        name if name == KEYWORD_BREAK => Some(
491            "`BREAK` exits the innermost enclosing FOR/WHILE loop or SWITCH; it must appear inside a loop or SWITCH.".to_string(),
492        ),
493        name if name == KEYWORD_CONTINUE => Some(
494            "`CONTINUE` skips to the next iteration of the innermost enclosing FOR/WHILE loop; it must appear inside a loop (a SWITCH never captures it).".to_string(),
495        ),
496        name if name == KEYWORD_INHERIT_ENV => Some(format!(
497            "INHERIT_ENV takes a key list, e.g. `INHERIT_ENV [HOME, PATH]`; got {got}."
498        )),
499        name if name == KEYWORD_IMPORT => Some(format!(
500            "IMPORT brings module functions into bare-call scope, e.g. `IMPORT [STD]` or `IMPORT [STD, MOCK]`; file imports take a quoted path with a mandatory alias, e.g. `IMPORT [\"./lib.oxdock\" AS LIB]`, and brackets mix both across lines, e.g. `IMPORT [STD, \"a.oxdock\" AS A]`; got {got}."
501        )),
502        name if name == KEYWORD_EXPORT => Some(
503            "EXPORT marks script FUNCs and qualified host functions as tools, e.g. `EXPORT FOO`, `EXPORT [FOO, STD::INT]`."
504                .to_string(),
505        ),
506        _ => None,
507    }
508}
509
510/// Diagnose a `WITH_IO` line that failed to parse: most often a malformed
511/// binding list (bindings are bare streams, `<stream>=$var`, bare `tty`,
512/// or `rows`/`cols` dimensions).
513fn with_io_hint(got: &str, received: &str) -> String {
514    const SYNTAX: &str =
515        "WITH_IO needs `WITH_IO [bindings] <command>` or `WITH_IO [bindings] { <commands> }`";
516    const BINDINGS: &str = "bindings are `stdin`, `stdout`, `stderr`, or `<stream>=$var` with a PIPE-typed variable (e.g. `[stdout=$p]`, `[stdin=$p]`); `tty` is a bare flag for RUN steps, with `rows = <int>` / `cols = <int>` geometry (e.g. `[tty, rows=40, cols=100]`)";
517    if let Some(after_open) = received.strip_prefix('[') {
518        match after_open.split_once(']') {
519            None => {
520                return format!("{SYNTAX}: missing closing `]` in the binding list; got {got}.");
521            }
522            Some((bindings, _)) => {
523                for part in bindings.split(',') {
524                    let part = part.trim();
525                    if part.is_empty() {
526                        continue;
527                    }
528                    let (stream, binding) = match part.split_once('=') {
529                        Some((stream, binding)) => (stream.trim(), Some(binding.trim())),
530                        None => (part, None),
531                    };
532                    if matches!(stream, "rows" | "cols") {
533                        let valid = binding.is_some_and(|value| {
534                            value
535                                .parse::<u64>()
536                                .is_ok_and(|dim| (1..=u64::from(u16::MAX)).contains(&dim))
537                        });
538                        if !valid {
539                            return format!(
540                                "{SYNTAX}: invalid geometry `{part}`; `rows`/`cols` need a positive integer 1-65535 (e.g. `rows=40`) and require `tty`; got {got}."
541                            );
542                        }
543                        continue;
544                    }
545                    if stream == "tty" {
546                        if binding.is_some() {
547                            return format!(
548                                "{SYNTAX}: invalid binding `{part}`; `tty` is a bare flag (geometry rides `rows`/`cols`, e.g. `[tty, rows=40]`); got {got}."
549                            );
550                        }
551                        continue;
552                    }
553                    if !matches!(stream, "stdin" | "stdout" | "stderr") {
554                        return format!(
555                            "{SYNTAX}: invalid stream `{stream}`; expected `stdin`, `stdout`, `stderr`, or `tty`; got {got}."
556                        );
557                    }
558                    let valid = match binding {
559                        None => true,
560                        Some(value) => value.strip_prefix('$').is_some_and(|var| {
561                            !var.trim().is_empty()
562                                && var.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
563                        }),
564                    };
565                    if !valid {
566                        return format!(
567                            "{SYNTAX}: invalid binding `{part}`; {BINDINGS}; got {got}."
568                        );
569                    }
570                }
571            }
572        }
573    }
574    format!("{SYNTAX}; got {got}. {BINDINGS}.")
575}
576
577/// `echo hi` is almost certainly `ECHO hi`: commands are uppercase.
578fn case_hint(name: &str) -> Option<String> {
579    let upper = name.to_ascii_uppercase();
580    if upper != name
581        && all_metadata()
582            .iter()
583            .any(|meta| meta.name == upper.as_str())
584    {
585        return Some(format!("did you mean `{upper}`? commands are uppercase."));
586    }
587    None
588}
589
590macro_rules! declare_commands {
591    (
592        structural [
593            $( $sname:ident $( { $( $sfname:ident : $sftype:ty ),* $(,)? } )? ),* $(,)?
594        ]
595
596        $(
597            $cmd_ident:ident => [
598                name: $name:expr,
599                variant: $vname:ident $( { $( $vfname:ident : $vftype:ty ),* $(,)? } )? $( ( $( $ttuple:ty ),* $(,)? ) )?,
600                syntax: $syntax:expr,
601                summary: $summary:expr,
602                description: $desc:expr,
603                args: $args:expr,
604                flags: $flags:expr,
605                default_output: $out:expr,
606                examples: $examples:expr,
607                lower: $lower:expr,
608            ]
609        ),* $(,)?
610    ) => {
611        #[derive(Debug, Clone, PartialEq)]
612        pub enum StepKind {
613            $( $vname $( { $( $vfname : $vftype ),* } )? $( ( $( $ttuple ),* ) )?, )*
614            $( $sname $( { $( $sfname : $sftype ),* } )?, )*
615        }
616
617        pub fn lower_command(name: &str, raw_args: Vec<Arg>) -> ParseResult<StepKind> {
618            match name {
619                $(
620                    s if s == $name => {
621                        let meta = CommandMeta {
622                            name: $name, syntax: $syntax, summary: $summary,
623                            description: $desc, args: $args, flags: $flags,
624                            default_output: $out, examples: $examples,
625                            in_index: true,
626                        };
627                        let (flags, positional) = crate::strip_flags(raw_args, &meta)?;
628                        crate::command::validate_positionals_against_meta(
629                            s,
630                            &meta.args,
631                            &positional,
632                        )?;
633                        let lower_fn: fn(Vec<(String, Arg)>, Vec<Arg>) -> ParseResult<StepKind> = $lower;
634                        lower_fn(flags, positional)
635                    }
636                )*
637                _ => {
638                    Err(classify(name, &raw_args))
639                }
640            }
641        }
642
643        pub fn all_metadata() -> Vec<CommandMeta> {
644            let mut out = vec![
645                $( CommandMeta {
646                    name: $name, syntax: $syntax, summary: $summary,
647                    description: $desc, args: $args, flags: $flags,
648                    default_output: $out, examples: $examples,
649                    in_index: true,
650                }, )*
651            ];
652            // Structural statements are registered separately (see
653            // all_structural_metadata) but documented through the same
654            // pipeline so oxdock-render never drifts from the parser.
655            out.extend(all_structural_metadata());
656            out
657        }
658    };
659}
660
661/// Generate both raw-string fragment walkers from one match:
662/// helper and closure names arrive as macro arguments (so every
663/// reference shares the invocation's syntax context), types are
664/// fixed per method, and the arm list rides as one trailing brace
665/// group (no repetition, so no follow-token ambiguity). A new
666/// string-carrying variant fails compilation at both expansion
667/// sites until it is added here, and the two walkers can never
668/// disagree about what counts as template text.
669macro_rules! define_raw_string_walkers {
670    ($f:ident, $wa:ident, $wo:ident, $wt:ident, { $($arms:tt)* }) => {
671        /// Visit every immediate raw string fragment (literal argument text
672        /// and mixed-value text fragments). Typed expressions are NOT
673        /// visited here. Boxed sub-kinds and bodies are NOT descended, same
674        /// as [`walk_exprs`](Self::walk_exprs): the caller recurses through
675        /// [`walk_child_kinds`](Self::walk_child_kinds) or the checker's own
676        /// body walk. Exhaustive for the same reason: a new string-carrying
677        /// variant must appear here or env-template checking misses it.
678        pub fn walk_raw_strings(&self, $f: &mut impl FnMut(&str)) {
679            // One `Arg`: literal text and mixed-text fragments; typed expressions are skipped.
680            fn $wa(arg: &Arg, $f: &mut impl FnMut(&str)) {
681                match arg {
682                    Arg::String(text, _) => $f(text),
683                    Arg::Expr(_) => {}
684                    Arg::Parts(parts) => {
685                        for part in parts {
686                            if let ArgPart::Text(text, _) = part {
687                                $f(text);
688                            }
689                        }
690                    }
691                }
692            }
693            // An optional `Arg`, when present.
694            fn $wo(arg: &Option<Arg>, $f: &mut impl FnMut(&str)) {
695                if let Some(arg) = arg {
696                    $wa(arg, $f);
697                }
698            }
699            // An assertion target holding a value.
700            fn $wt(target: &AssertTarget, $f: &mut impl FnMut(&str)) {
701                if let AssertTarget::Value(arg) = target {
702                    $wa(arg, $f);
703                }
704            }
705            match self {
706                $($arms)*
707            }
708        }
709        /// Mutable twin of [`walk_raw_strings`](Self::walk_raw_strings):
710        /// same fragments, same non-descending boundary. The parse-time
711        /// placeholder qualifier runs through this; the static env check
712        /// runs through the shared twin, so both agree fragment for fragment.
713        pub fn walk_raw_strings_mut(&mut self, $f: &mut impl FnMut(&mut String)) {
714            // One `Arg`: literal text and mixed-text fragments; typed expressions are skipped.
715            fn $wa(arg: &mut Arg, $f: &mut impl FnMut(&mut String)) {
716                match arg {
717                    Arg::String(text, _) => $f(text),
718                    Arg::Expr(_) => {}
719                    Arg::Parts(parts) => {
720                        for part in parts {
721                            if let ArgPart::Text(text, _) = part {
722                                $f(text);
723                            }
724                        }
725                    }
726                }
727            }
728            // An optional `Arg`, when present.
729            fn $wo(arg: &mut Option<Arg>, $f: &mut impl FnMut(&mut String)) {
730                if let Some(arg) = arg {
731                    $wa(arg, $f);
732                }
733            }
734            // An assertion target holding a value.
735            fn $wt(target: &mut AssertTarget, $f: &mut impl FnMut(&mut String)) {
736                if let AssertTarget::Value(arg) = target {
737                    $wa(arg, $f);
738                }
739            }
740            match self {
741                $($arms)*
742            }
743        }
744    };
745}
746
747// Generate both expression walkers from one match:
748/// helper and closure names arrive as macro arguments (so every
749/// reference shares the invocation's syntax context), types are
750/// fixed per method, and the arm list rides as one trailing brace
751/// group (no repetition, so no follow-token ambiguity). A new
752/// expression-carrying variant fails compilation at both expansion
753/// sites until it is added here, and the two walkers can never
754/// disagree about what counts as an immediate child expression.
755macro_rules! define_expr_walkers {
756    ($f:ident, $wa:ident, $wo:ident, $wt:ident, { $($arms:tt)* }) => {
757        /// Visit every immediate child expression (arguments, conditions,
758        /// durations, initializers). Boxed sub-kinds and bodies are NOT
759        /// descended: pair with [`walk_child_kinds`](Self::walk_child_kinds)
760        /// or use [`walk_step_exprs`](Self::walk_step_exprs) for the full
761        /// tree. Exhaustive: a new variant fails compilation here, so AST
762        /// passes built on this visitor can never silently miss a command.
763        pub fn walk_exprs(&self, $f: &mut impl FnMut(&Expr)) {
764            // One `Arg`: the typed expressions inside; literal text is skipped.
765            fn $wa(arg: &Arg, $f: &mut impl FnMut(&Expr)) {
766                match arg {
767                    Arg::Expr(expr) => $f(expr),
768                    Arg::Parts(parts) => {
769                        for part in parts {
770                            if let ArgPart::Expr(expr) = part {
771                                $f(expr);
772                            }
773                        }
774                    }
775                    Arg::String(..) => {}
776                }
777            }
778            // An optional `Arg`, when present.
779            fn $wo(arg: &Option<Arg>, $f: &mut impl FnMut(&Expr)) {
780                if let Some(arg) = arg {
781                    $wa(arg, $f);
782                }
783            }
784            // An assertion target holding a value.
785            fn $wt(target: &AssertTarget, $f: &mut impl FnMut(&Expr)) {
786                if let AssertTarget::Value(arg) = target {
787                    $wa(arg, $f);
788                }
789            }
790            match self {
791                $($arms)*
792            }
793        }
794        /// Mutable twin of [`walk_exprs`](Self::walk_exprs): visits every
795        /// immediate child expression mutably. Bodies are NOT descended,
796        /// matching the immutable boundary: the parse-time placeholder
797        /// qualifier recurses per statement with its own frames.
798        /// Exhaustive for the same reason: new expression carriers fail
799        /// compilation here.
800        pub fn walk_exprs_mut(&mut self, $f: &mut impl FnMut(&mut Expr)) {
801            // One `Arg`: the typed expressions inside; literal text is skipped.
802            fn $wa(arg: &mut Arg, $f: &mut impl FnMut(&mut Expr)) {
803                match arg {
804                    Arg::Expr(expr) => $f(expr),
805                    Arg::Parts(parts) => {
806                        for part in parts {
807                            if let ArgPart::Expr(expr) = part {
808                                $f(expr);
809                            }
810                        }
811                    }
812                    Arg::String(..) => {}
813                }
814            }
815            // An optional `Arg`, when present.
816            fn $wo(arg: &mut Option<Arg>, $f: &mut impl FnMut(&mut Expr)) {
817                if let Some(arg) = arg {
818                    $wa(arg, $f);
819                }
820            }
821            // An assertion target holding a value.
822            fn $wt(target: &mut AssertTarget, $f: &mut impl FnMut(&mut Expr)) {
823                if let AssertTarget::Value(arg) = target {
824                    $wa(arg, $f);
825                }
826            }
827            match self {
828                $($arms)*
829            }
830        }
831    };
832}
833
834impl StepKind {
835    define_expr_walkers!(f, walk_arg, walk_opt, walk_target, {
836            StepKind::Assign { expr, .. } | StepKind::Set { expr, .. } => f(expr),
837            StepKind::Return { expr, .. } => f(expr),
838            StepKind::Call { args, .. } => {
839                for arg in args {
840                    f(arg);
841                }
842            }
843            StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => {}
844            StepKind::For { in_expr, .. } => f(in_expr),
845            StepKind::If { cond, else_ifs, .. } => {
846                f(cond);
847                for (cond, _) in else_ifs {
848                    f(cond);
849                }
850            }
851            StepKind::Switch {
852                discriminant,
853                cases,
854                ..
855            } => {
856                if let Some(disc) = discriminant {
857                    f(disc);
858                }
859                for (exprs, _) in cases {
860                    for expr in exprs {
861                        f(expr);
862                    }
863                }
864            }
865            StepKind::While { cond, .. } => f(cond),
866            StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
867                walk_arg(duration, f);
868            }
869            StepKind::Fail { code, message, .. } => {
870                walk_opt(code, f);
871                walk_opt(message, f);
872            }
873            StepKind::Workdir(arg)
874            | StepKind::Echo(arg)
875            | StepKind::Run(arg)
876            | StepKind::Mkdir(arg)
877            | StepKind::Exit(arg) => walk_arg(arg, f),
878            StepKind::Env { value, .. } => walk_arg(value, f),
879            StepKind::Copy { from, to, .. }
880            | StepKind::Symlink { from, to, .. }
881            | StepKind::Archive {
882                src: from, dst: to, ..
883            }
884            | StepKind::Install { from, to } => {
885                walk_arg(from, f);
886                walk_arg(to, f);
887            }
888            StepKind::SetExecutable { path } => walk_arg(path, f),
889            StepKind::Unarchive {
890                src,
891                dst,
892                max_bytes,
893            } => {
894                walk_arg(src, f);
895                walk_arg(dst, f);
896                walk_opt(max_bytes, f);
897            }
898            StepKind::CopyGit { rev, from, to, .. } => {
899                walk_arg(rev, f);
900                walk_arg(from, f);
901                walk_arg(to, f);
902            }
903            StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
904            StepKind::Remove { path, .. } => walk_arg(path, f),
905            StepKind::Prompt {
906                message, default, ..
907            } => {
908                walk_arg(message, f);
909                walk_opt(default, f);
910            }
911            StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
912                walk_arg(path, f);
913                walk_opt(contents, f);
914            }
915            StepKind::AppendLine { path, contents } => {
916                walk_arg(path, f);
917                walk_arg(contents, f);
918            }
919            StepKind::Expand { path, overrides } => {
920                walk_opt(path, f);
921                for (_, value) in overrides {
922                    walk_arg(value, f);
923                }
924            }
925            StepKind::AssertEq {
926                actual, expected, ..
927            }
928            | StepKind::AssertNe {
929                actual, expected, ..
930            } => {
931                walk_target(actual, f);
932                walk_opt(expected, f);
933            }
934            StepKind::AssertContains { haystack, needle } => {
935                walk_target(haystack, f);
936                walk_arg(needle, f);
937            }
938            StepKind::ListAppend { item, .. } => walk_arg(item, f),
939            StepKind::RunExec { argv } => {
940                for arg in argv {
941                    walk_arg(arg, f);
942                }
943            }
944            StepKind::WithIo { .. }
945            | StepKind::WithIoBlock { .. }
946            | StepKind::TypeAlias { .. }
947            | StepKind::Workspace(_)
948            | StepKind::InheritEnv { .. }
949            | StepKind::Isolated { .. }
950            | StepKind::IsolatedInheritEnv { .. }
951            | StepKind::ReadLine { .. }
952            | StepKind::AssignCapture { .. }
953            | StepKind::AwaitCapture { .. }
954            | StepKind::AsyncBlock { .. }
955            | StepKind::AssignAsync { .. }
956            | StepKind::Await { .. }
957            | StepKind::Cancel { .. }
958            | StepKind::RemoteBlock { .. }
959            | StepKind::FuncDef { .. }
960            | StepKind::Break
961            | StepKind::Continue => {}
962    });
963
964    define_raw_string_walkers!(f, walk_arg, walk_opt, walk_target, {
965        StepKind::Assign { .. }
966                | StepKind::Set { .. }
967                | StepKind::Call { .. }
968                | StepKind::Return { .. }
969                | StepKind::For { .. }
970                | StepKind::If { .. }
971                | StepKind::Switch { .. }
972                | StepKind::While { .. } => {}
973                StepKind::Timeout { duration, .. } | StepKind::Sleep { duration } => {
974                    walk_arg(duration, f);
975                }
976                StepKind::Fail { code, message, .. } => {
977                    walk_opt(code, f);
978                    walk_opt(message, f);
979                }
980                StepKind::Workdir(arg)
981                | StepKind::Echo(arg)
982                | StepKind::Run(arg)
983                | StepKind::Mkdir(arg)
984                | StepKind::Exit(arg) => walk_arg(arg, f),
985                StepKind::Env { value, .. } => walk_arg(value, f),
986                StepKind::Copy { from, to, .. }
987                | StepKind::Symlink { from, to, .. }
988                | StepKind::Archive {
989                    src: from, dst: to, ..
990                }
991                | StepKind::Install { from, to } => {
992                    walk_arg(from, f);
993                    walk_arg(to, f);
994                }
995                StepKind::SetExecutable { path } => walk_arg(path, f),
996                StepKind::Unarchive {
997                    src,
998                    dst,
999                    max_bytes,
1000                } => {
1001                    walk_arg(src, f);
1002                    walk_arg(dst, f);
1003                    walk_opt(max_bytes, f);
1004                }
1005                StepKind::CopyGit { rev, from, to, .. } => {
1006                    walk_arg(rev, f);
1007                    walk_arg(from, f);
1008                    walk_arg(to, f);
1009                }
1010                StepKind::Ls(arg) | StepKind::Read(arg) => walk_opt(arg, f),
1011                StepKind::Remove { path, .. } => walk_arg(path, f),
1012                StepKind::Prompt {
1013                    message, default, ..
1014                } => {
1015                    walk_arg(message, f);
1016                    walk_opt(default, f);
1017                }
1018                StepKind::Write { path, contents } | StepKind::Append { path, contents } => {
1019                    walk_arg(path, f);
1020                    walk_opt(contents, f);
1021                }
1022                StepKind::AppendLine { path, contents } => {
1023                    walk_arg(path, f);
1024                    walk_arg(contents, f);
1025                }
1026                StepKind::Expand { path, overrides } => {
1027                    walk_opt(path, f);
1028                    for (_, value) in overrides {
1029                        walk_arg(value, f);
1030                    }
1031                }
1032                StepKind::AssertEq {
1033                    actual, expected, ..
1034                }
1035                | StepKind::AssertNe {
1036                    actual, expected, ..
1037                } => {
1038                    walk_target(actual, f);
1039                    walk_opt(expected, f);
1040                }
1041                StepKind::AssertContains { haystack, needle } => {
1042                    walk_target(haystack, f);
1043                    walk_arg(needle, f);
1044                }
1045                StepKind::ListAppend { item, .. } => walk_arg(item, f),
1046                StepKind::RunExec { argv } => {
1047                    for arg in argv {
1048                        walk_arg(arg, f);
1049                    }
1050                }
1051                StepKind::WithIo { .. }
1052                | StepKind::WithIoBlock { .. }
1053                | StepKind::TypeAlias { .. }
1054                | StepKind::Workspace(_)
1055                | StepKind::ImportFile { .. }
1056                | StepKind::ImportFuncs { .. }
1057                | StepKind::InheritEnv { .. }
1058                | StepKind::Isolated { .. }
1059                | StepKind::IsolatedInheritEnv { .. }
1060                | StepKind::ReadLine { .. }
1061                | StepKind::AssignCapture { .. }
1062                | StepKind::AwaitCapture { .. }
1063                | StepKind::AsyncBlock { .. }
1064                | StepKind::AssignAsync { .. }
1065                | StepKind::Await { .. }
1066                | StepKind::Cancel { .. }
1067                | StepKind::RemoteBlock { .. }
1068                | StepKind::FuncDef { .. }
1069                | StepKind::Break
1070                | StepKind::Continue => {}
1071    });
1072
1073    /// Visit every immediate child kind: boxed sub-commands and the kinds
1074    /// of every body step. Exhaustive like [`walk_exprs`](Self::walk_exprs):
1075    /// new block shapes fail compilation here.
1076    pub fn walk_child_kinds(&self, f: &mut impl FnMut(&StepKind)) {
1077        fn walk_body(body: &[Step], f: &mut impl FnMut(&StepKind)) {
1078            for step in body {
1079                f(&step.kind);
1080            }
1081        }
1082        match self {
1083            StepKind::WithIo { cmd, .. } => f(cmd),
1084            StepKind::AssignCapture { cmd, .. } => f(cmd),
1085            StepKind::For { body, .. }
1086            | StepKind::While { body, .. }
1087            | StepKind::FuncDef { body, .. }
1088            | StepKind::Timeout { body, .. }
1089            | StepKind::Fail { body, .. }
1090            | StepKind::Isolated { body }
1091            | StepKind::AssignAsync { body, .. }
1092            | StepKind::AsyncBlock { body }
1093            | StepKind::RemoteBlock { body, .. } => walk_body(body, f),
1094            StepKind::If {
1095                then_body,
1096                else_ifs,
1097                else_body,
1098                ..
1099            } => {
1100                walk_body(then_body, f);
1101                for (_, body) in else_ifs {
1102                    walk_body(body, f);
1103                }
1104                if let Some(body) = else_body {
1105                    walk_body(body, f);
1106                }
1107            }
1108            StepKind::Switch {
1109                cases,
1110                default_body,
1111                ..
1112            } => {
1113                for (_, body) in cases {
1114                    walk_body(body, f);
1115                }
1116                if let Some(body) = default_body {
1117                    walk_body(body, f);
1118                }
1119            }
1120            StepKind::InheritEnv { .. }
1121            | StepKind::IsolatedInheritEnv { .. }
1122            | StepKind::TypeAlias { .. }
1123            | StepKind::Workdir(_)
1124            | StepKind::Workspace(_)
1125            | StepKind::Env { .. }
1126            | StepKind::Echo(_)
1127            | StepKind::Run(_)
1128            | StepKind::RunExec { .. }
1129            | StepKind::Copy { .. }
1130            | StepKind::CopyGit { .. }
1131            | StepKind::Symlink { .. }
1132            | StepKind::Archive { .. }
1133            | StepKind::Unarchive { .. }
1134            | StepKind::Install { .. }
1135            | StepKind::SetExecutable { .. }
1136            | StepKind::Mkdir(_)
1137            | StepKind::Ls(_)
1138            | StepKind::Read(_)
1139            | StepKind::ReadLine { .. }
1140            | StepKind::Prompt { .. }
1141            | StepKind::Write { .. }
1142            | StepKind::Append { .. }
1143            | StepKind::AppendLine { .. }
1144            | StepKind::Remove { .. }
1145            | StepKind::Expand { .. }
1146            | StepKind::AssertEq { .. }
1147            | StepKind::AssertNe { .. }
1148            | StepKind::AssertContains { .. }
1149            | StepKind::Exit(_)
1150            | StepKind::WithIoBlock { .. }
1151            | StepKind::Assign { .. }
1152            | StepKind::Set { .. }
1153            | StepKind::AwaitCapture { .. }
1154            | StepKind::Await { .. }
1155            | StepKind::Cancel { .. }
1156            | StepKind::Sleep { .. }
1157            | StepKind::ListAppend { .. }
1158            | StepKind::Call { .. }
1159            | StepKind::ImportFile { .. }
1160            | StepKind::ImportFuncs { .. }
1161            | StepKind::Return { .. }
1162            | StepKind::Break
1163            | StepKind::Continue => {}
1164        }
1165    }
1166
1167    /// Visit every descendant expression in the full subtree: immediate
1168    /// expressions (deep via [`Expr::walk`](crate::ast::Expr::walk)) plus
1169    /// every nested body and boxed sub-command. The single traversal every
1170    /// AST inspection pass should use.
1171    pub fn walk_step_exprs(&self, f: &mut impl FnMut(&Expr)) {
1172        self.walk_exprs(&mut |expr| expr.walk(f));
1173        self.walk_child_kinds(&mut |kind| kind.walk_step_exprs(f));
1174    }
1175}
1176
1177/// First-argument target for `ASSERT_EQ` / `ASSERT_CONTAINS`.
1178///
1179/// Values (`Arg`) evaluate in memory and never touch disk. The `Stdout`
1180/// and `Stderr` markers observe stream buffers. Pipes are asserted through
1181/// plain variables: a `$var` holding a `PIPE` peeks its backend bytes at
1182/// runtime, so no pipe marker variant exists. Bare `stdout` / `stderr`
1183/// spellings lower to markers; quoted spellings stay literal string
1184/// values, so quoting remains interchangeable everywhere.
1185#[derive(Debug, Clone, PartialEq)]
1186pub enum AssertTarget {
1187    Value(Arg),
1188    Stdout,
1189    Stderr,
1190}
1191
1192impl AssertTarget {
1193    pub fn render(&self) -> String {
1194        match self {
1195            AssertTarget::Value(arg) => arg.render(),
1196            AssertTarget::Stdout => "stdout".to_string(),
1197            AssertTarget::Stderr => "stderr".to_string(),
1198        }
1199    }
1200}
1201
1202/// Lower the first positional of `ASSERT_EQ` / `ASSERT_CONTAINS`.
1203///
1204/// `Arg::Expr` (variables, key-paths, calls) is always a value : a `$var`
1205/// holding a `PIPE` peeks its backend bytes at runtime. Bare (unquoted)
1206/// `stdout` / `stderr` spellings become stream markers; every other
1207/// spelling, quoted or not, stays a literal value. In particular a `$var`
1208/// holding a path never reads disk, and quoted `"stdout"` names the
1209/// seven-character string, not the stream.
1210fn lower_assert_target(arg: Arg) -> ParseResult<AssertTarget> {
1211    match arg {
1212        Arg::Expr(_) => Ok(AssertTarget::Value(arg)),
1213        Arg::String(text, quoted) if !quoted => match text.as_str() {
1214            "stdout" => Ok(AssertTarget::Stdout),
1215            "stderr" => Ok(AssertTarget::Stderr),
1216            _ => Ok(AssertTarget::Value(lower_assert_operand(Arg::String(
1217                text, false,
1218            )))),
1219        },
1220        other => Ok(AssertTarget::Value(lower_assert_operand(other))),
1221    }
1222}
1223
1224/// Give bare (unquoted, template-free) assertion operands the same typing
1225/// they carry in expression positions, so `ASSERT_EQ $status 200` compares
1226/// `Int(200)` rather than the string `"200"`. Signed integers (`-5` in
1227/// first position), decimals (`3.5`), and `true`/`false` all convert;
1228/// everything else, including quoted strings, stays a string. Note a
1229/// grammar property, not a limitation of this helper: `$x -5` in argument
1230/// position parses as subtraction (`expr_add_sub`), so negative expected
1231/// values must be bound first (`LET $e: INT = 0 - 5`).
1232fn lower_assert_operand(arg: Arg) -> Arg {
1233    match arg {
1234        Arg::String(text, false) => {
1235            // Separators strip only when well-formed, so `1_000_000`
1236            // types as Int while `1__0` keeps its literal reading,
1237            // exactly like expression position. The original text
1238            // survives below for the string case.
1239            let clean = crate::command::strip_digit_separators(&text);
1240            if let Ok(i) = clean.parse::<i64>() {
1241                Arg::Expr(Expr::Literal(Value::int(i)))
1242            } else if clean.contains('.') && clean.parse::<f64>().is_ok() {
1243                Arg::Expr(Expr::Literal(Value::float(
1244                    clean.parse::<f64>().unwrap_or(f64::NAN),
1245                )))
1246            } else if text == "true" {
1247                Arg::Expr(Expr::Literal(Value::bool(true)))
1248            } else if text == "false" {
1249                Arg::Expr(Expr::Literal(Value::bool(false)))
1250            } else {
1251                Arg::String(text, false)
1252            }
1253        }
1254        other => other,
1255    }
1256}
1257
1258/// Shared positional lowering for `ASSERT_EQ`/`ASSERT_NE`: one actual plus
1259/// an optional expected, with `--hash` carrying the expectation in the
1260/// flag. Combining `--hash` with a positional expected is rejected so a
1261/// stray value cannot silently vanish. `verb` names the command for errors.
1262fn lower_equality_args(
1263    verb: &str,
1264    flags: Vec<(String, Arg)>,
1265    args: Vec<Arg>,
1266) -> ParseResult<(Option<String>, AssertTarget, Option<Arg>)> {
1267    let hash = flags
1268        .iter()
1269        .find(|(k, _)| k == "hash")
1270        .map(|(_, v)| v.as_str().to_string());
1271    let mut it = args.into_iter();
1272    let actual = lower_assert_target(it.next().ok_or_else(|| {
1273        ParseError::validation(
1274            verb,
1275            format!("{verb} requires a value"),
1276            &SpanContext::line_only(0),
1277        )
1278    })?)?;
1279    let remaining: Vec<Arg> = it.map(lower_assert_operand).collect::<Vec<Arg>>();
1280    let expected = if remaining.is_empty() {
1281        if hash.is_some() {
1282            None
1283        } else {
1284            return Err(ParseError::validation(
1285                verb,
1286                format!("{verb} requires an expected value"),
1287                &SpanContext::line_only(0),
1288            ));
1289        }
1290    } else {
1291        if hash.is_some() {
1292            return Err(ParseError::validation(
1293                verb,
1294                format!("{verb} --hash cannot be combined with an expected value"),
1295                &SpanContext::line_only(0),
1296            ));
1297        }
1298        Some(join_value(remaining, verb)?)
1299    };
1300    Ok((hash, actual, expected))
1301}
1302
1303declare_commands! {
1304    structural [
1305        WithIo { bindings: Vec<IoBinding>, cmd: Box<StepKind> },
1306        WithIoBlock { bindings: Vec<IoBinding> },
1307        TypeAlias { name: String, target: String },
1308        For { key_var: Option<String>, key_type: Option<String>, var: String, var_type: String, in_expr: Expr, body: Vec<Step> },
1309        If { cond: Box<Expr>, then_body: Vec<Step>, else_ifs: Vec<(Box<Expr>, Vec<Step>)>, else_body: Option<Vec<Step>> },
1310        Switch { discriminant: Option<Box<Expr>>, cases: Vec<(Vec<Expr>, Vec<Step>)>, default_body: Option<Vec<Step>> },
1311        Assign { var: String, decl_type: String, expr: Expr },
1312        Set { var: String, expr: Expr },
1313        AssignCapture { var: String, decl_type: String, cmd: Box<StepKind> },
1314        AwaitCapture { out_var: String, out_type: String, task_var: String },
1315        AsyncBlock { body: Vec<Step> },
1316        AssignAsync { var: String, decl_type: String, body: Vec<Step> },
1317        Await { var: String },
1318        Cancel { var: String },
1319        Timeout { duration: Arg, body: Vec<Step> },
1320        Fail { code: Option<Arg>, message: Option<Arg>, body: Vec<Step> },
1321        Isolated { body: Vec<Step> },
1322        IsolatedInheritEnv { keys: Vec<String> },
1323        RemoteBlock { target: String, vars: Vec<String>, env: Vec<String>, body: Vec<Step> },
1324        RunExec { argv: Vec<Arg> },
1325        FuncDef { name: String, params: Vec<(String, String, bool)>, return_type: String, is_async: bool, body: Vec<Step>, docs: Option<(String, String)> },
1326        Call { name: String, args: Vec<Expr> },
1327        Return { expr: Box<Expr>, is_bare: bool },
1328        ImportFile { path: String, alias: String },
1329        ImportFuncs {
1330            path: String,
1331            alias: Option<String>,
1332            func_names: Vec<String>,
1333            type_names: Vec<String>,
1334        },
1335        While { cond: Box<Expr>, body: Vec<Step> },
1336        Break,
1337        Continue,
1338    ]
1339
1340    Workdir => [
1341        name: KEYWORD_WORKDIR,
1342        variant: Workdir(Arg),
1343        syntax: "WORKDIR <path>",
1344        summary: "Change the working directory.",
1345        description: indoc! {r#"
1346            Sets the current working directory.
1347
1348            Relative paths resolve against the current directory; `/` resets to
1349            the workspace root. Paths cannot escape the workspace.
1350        "#},
1351        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Directory to change to", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1352        flags: &[],
1353        default_output: None,
1354        examples: &[ Example { name: "change working directory", fence_meta: None, code: indoc! {r#"
1355            # Later relative paths resolve under the new directory.
1356            WORKDIR project/src
1357            WRITE generated.txt generated-under-workdir
1358
1359            LET $body: STRING = READ generated.txt
1360            ASSERT_EQ $body "generated-under-workdir"
1361        "#} },             Example { name: "workdir in a scoped block", fence_meta: None, code: indoc! {r#"
1362            # The block reverts to the starting directory on exit.
1363            LET $outside: STRING = CWD
1364            MKDIR project
1365
1366            [bool:true] {
1367                WORKDIR project
1368                WRITE inner.txt inner
1369            }
1370
1371            LET $back: STRING = CWD
1372            ASSERT_EQ $back $outside
1373            LET $body: STRING = READ project/inner.txt
1374            ASSERT_EQ $body "inner"
1375        "#} } ],
1376        lower: |_flags, args| {
1377            let path = args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_WORKDIR, "WORKDIR requires a path".to_string(), &SpanContext::line_only(0)))?;
1378            Ok(StepKind::Workdir(path))
1379        },
1380    ],
1381
1382    Workspace => [
1383        name: KEYWORD_WORKSPACE,
1384        variant: Workspace(WorkspaceTarget),
1385        syntax: "WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]",
1386        summary: "Switch workspace roots.",
1387        description: indoc! {r#"
1388            Switches the workspace root. The selection reverts at scope
1389            exit like `WORKDIR`.
1390
1391            - `SNAPSHOT`: the materialized build snapshot (the default).
1392              One session-shared directory: every selection resolves to
1393              it, in any block.
1394            - `LOCAL`: the local workspace directory.
1395            - `CACHE`: a persistent per-project directory shared across
1396              runs, never evicted. It lives under the OS user cache
1397              (`OXDOCK_CACHE_DIR` pins an exact directory);
1398              `WORKSPACE CACHE --local` keeps it in
1399              `<project>/.cache/workspace` instead.
1400            - `SYSTEM`: full filesystem access. Scripts using it are not
1401              hermetic.
1402        "#},
1403        args: &[ ArgSpec { name: "target", arg_type: ArgType::OneOf(&["SNAPSHOT", "LOCAL", "CACHE", "SYSTEM"]), description: "Target root", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1404        flags: &[ FlagSpec { name: "local", long: "--local", value_type: FlagValueType::Flag, required: false, description: "Use the project-local cache directory instead of the OS user cache (CACHE only)" } ],
1405        default_output: None,
1406        examples: &[ Example { name: "switch roots", fence_meta: None, code: indoc! {r#"
1407            IMPORT [STD]
1408            WORKSPACE LOCAL
1409
1410            LET $t: STRING = PATH_TYPE(".")
1411            ASSERT_EQ $t "dir"
1412        "#} }, Example { name: "workspace cache in a scoped block", fence_meta: None, code: indoc! {r#"
1413            [bool:true] {
1414                WORKSPACE CACHE
1415                WRITE cached.txt cached-content
1416            }
1417
1418            COPY --from-workspace CACHE cached.txt restored.txt
1419            LET $body: STRING = READ restored.txt
1420            ASSERT_EQ $body "cached-content"
1421        "#} } ],
1422        lower: |flags, args| {
1423            let local = flags.iter().any(|(k, _)| k == "local");
1424            let target = args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_WORKSPACE, "WORKSPACE requires a target".to_string(), &SpanContext::line_only(0)))?;
1425            match target.as_str() {
1426                "SNAPSHOT" | "LOCAL" | "SYSTEM" if local => Err(ParseError::validation(KEYWORD_WORKSPACE, "WORKSPACE --local requires CACHE".to_string(), &SpanContext::line_only(0))),
1427                "SNAPSHOT" => Ok(StepKind::Workspace(WorkspaceTarget::Snapshot)),
1428                "LOCAL" => Ok(StepKind::Workspace(WorkspaceTarget::Local)),
1429                "CACHE" => Ok(StepKind::Workspace(WorkspaceTarget::Cache { local })),
1430                "SYSTEM" => Ok(StepKind::Workspace(WorkspaceTarget::System)),
1431                other => Err(ParseError::validation(KEYWORD_WORKSPACE, format!("unknown workspace target: {other}"), &SpanContext::line_only(0))),
1432            }
1433        },
1434    ],
1435
1436    Env => [
1437        name: KEYWORD_ENV,
1438        variant: Env { key: String, value: Arg },
1439        syntax: "ENV KEY=value",
1440        summary: "Set an environment variable.",
1441        description: indoc! {r#"
1442            Inserts or updates an env var.
1443
1444            The value uses the unified string-value rules shared by every command:
1445            `"..."` or `'...'` quotes keep exact bytes (spaces, tabs), a lone `$var`
1446            evaluates that variable, `{{ ... }}` placeholders interpolate, unquoted
1447            words join with single spaces, and the first `=` splits key from value
1448            (`KEY=a=b` stores `a=b`).
1449
1450            A `$var` inside larger text stays literal — write `{{ $var }}` to
1451            interpolate there.
1452        "#},
1453        args: &[ ArgSpec { name: "assignment", arg_type: ArgType::String, description: "KEY=value pair; the value resolves as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1454        flags: &[],
1455        default_output: None,
1456        examples: &[
1457            Example { name: "set env", fence_meta: None, code: indoc! {r#"
1458                ENV APP_MODE=production
1459                LET $mode: STRING = env:APP_MODE
1460                ASSERT_EQ $mode "production"
1461            "#} },
1462            Example { name: "quoted value with spaces", fence_meta: None, code: indoc! {r#"
1463                # Quotes keep the space: SET_FORTH stores `outer scope`.
1464                ENV SET_FORTH="outer scope"
1465                WRITE out.txt "{{ env:SET_FORTH }}"
1466
1467                LET $body: STRING = READ out.txt
1468                ASSERT_EQ $body "outer scope"
1469            "#} },
1470            Example { name: "variable value", fence_meta: None, code: indoc! {r#"
1471                # A lone $var evaluates, like ECHO $var.
1472                LET $who: STRING = "Alice"
1473                ENV GREETING=$who
1474                WRITE out.txt "{{ env:GREETING }}"
1475
1476                LET $body: STRING = READ out.txt
1477                ASSERT_EQ $body "Alice"
1478            "#} },
1479            Example { name: "all value forms agree", fence_meta: None, code: indoc! {r#"
1480                # A bare variable, a quoted literal, and a template all
1481                # store plain strings through the same value rules.
1482                LET $x: STRING = "Ada"
1483                ENV A=$x
1484                ENV B="hello world"
1485                ENV C="{{ $x }} concatenated"
1486                WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"
1487
1488                LET $body: STRING = READ check.txt
1489                ASSERT_EQ $body "Ada|hello world|Ada concatenated"
1490            "#} },
1491            Example { name: "scoped env reverts", fence_meta: None, code: indoc! {r#"
1492                # ENV inside a braced block reverts when the block exits
1493                ENV MODE=production
1494
1495                [bool:true] {
1496                    ENV MODE=staging
1497                    WRITE inner.txt "{{ env:MODE }}"
1498                }
1499
1500                WRITE outer.txt "{{ env:MODE }}"
1501
1502                LET $inner_body: STRING = READ inner.txt
1503                ASSERT_EQ $inner_body "staging"
1504
1505                LET $outer_body: STRING = READ outer.txt
1506                ASSERT_EQ $outer_body "production"
1507            "#} },
1508            Example { name: "shell reads env per platform", fence_meta: None, code: indoc! {r#"
1509                # A shell command reads its own environment, with
1510                # per-platform spelling: quoted "$VAR" passes the parser
1511                # through untouched on Unix ...
1512                ENV PROXY_PORT=23791
1513
1514                [family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"
1515
1516                # ... while cmd expands %VAR% on Windows.
1517                [family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%
1518
1519                ASSERT_CONTAINS $o "23791"
1520            "#} },
1521        ],
1522        lower: |_flags, args| lower_env_assignment(args),
1523    ],
1524
1525    InheritEnv => [
1526        name: KEYWORD_INHERIT_ENV,
1527        variant: InheritEnv { keys: Vec<String> },
1528        syntax: "INHERIT_ENV [<key>, ...]",
1529        summary: "Inherit env vars from host.",
1530        description: indoc! {r#"
1531            Declares which host environment variables to inherit into the script.
1532
1533            Must appear before any other commands. Several directives may
1534            appear so platform-specific names ride explicit guards
1535            (`[family:windows] INHERIT_ENV [USERPROFILE]`); each guarded
1536            line runs only when its guard passes.
1537
1538            Sandbox defaults need no declaration: loader bindings,
1539            terminal defaults, the host lookup path, and the user's
1540            profile locations seed automatically. See OxDock
1541            Environment Variable Contracts for the exact list, which grows with the
1542            engine.
1543
1544            Secrets and tool config stay opt-in here: a token or a
1545            `CARGO_HOME` override arrives only through this directive.
1546        "#},
1547        args: &[ ArgSpec { name: "keys", arg_type: ArgType::Rest(&ArgType::String), description: "Host variables to inherit", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1548        flags: &[],
1549        default_output: None,
1550        examples: &[ Example { name: "inherit env", fence_meta: None, code: indoc! {r#"
1551            [family:unix] INHERIT_ENV [HOME]
1552            LET $path: STRING = env:PATH
1553            [family:unix] ASSERT_CONTAINS $path ":"
1554            [family:windows] ASSERT_CONTAINS $path ";"
1555        "#} } ],
1556        lower: |_flags, args| {
1557            let keys = args.into_iter().map(|a| a.as_str().to_string()).collect();
1558            Ok(StepKind::InheritEnv { keys })
1559        },
1560    ],
1561
1562    Echo => [
1563        name: KEYWORD_ECHO,
1564        variant: Echo(Arg),
1565        syntax: "ECHO <message>",
1566        summary: "Print to stdout.",
1567        description: "Outputs message to stdout.",
1568        args: &[ ArgSpec { name: "message", arg_type: ArgType::Rest(&ArgType::String), description: "Text", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1569        flags: &[],
1570        default_output: Some(Stream::Stdout),
1571        examples: &[
1572            Example { name: "echo", fence_meta: None, code: indoc! {r#"
1573                ECHO build-complete
1574                ASSERT_CONTAINS stdout "build-complete"
1575            "#} },
1576            Example { name: "variables", fence_meta: None, code: indoc! {r#"
1577                # {{ }} interpolates inside text; a lone $var evaluates on its own.
1578                LET $x: STRING = "World"
1579                ECHO "braced:{{ $x }}"
1580                ECHO $x
1581                ASSERT_EQ stdout "braced:World\nWorld\n"
1582            "#} },
1583            Example { name: "interpolation", fence_meta: None, code: indoc! {r#"
1584                # `{{ env:KEY }}` reads the script environment; a bare name
1585                # resolves a DSL variable instead. Spelling rules:
1586                # `script_env:` is always case-sensitive; `env:` is
1587                # case-sensitive too, except on Windows where it matches
1588                # case-insensitively. Every read must be declared first:
1589                # KEY here comes from the ENV below.
1590                ENV USER=OxDock
1591                LET $WHO: STRING = "Ada"
1592                ECHO "Hello {{ env:USER }}! Hi {{ WHO }}! Again {{ script_env:USER }}!"
1593                ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada! Again OxDock!"
1594            "#} },
1595            Example { name: "undeclared env read fails", fence_meta: Some("expect_error:\"env:OXDOCK_DOC_NO_SUCH_KEY\""), code: indoc! {r#"
1596                # No declaration anywhere: the whole-closure static gate
1597                # rejects the read before the first step runs. (The
1598                # error names the variable: undeclared environment
1599                # variable `env:OXDOCK_DOC_NO_SUCH_KEY`.)
1600                ECHO "Hello {{ env:OXDOCK_DOC_NO_SUCH_KEY }}!"
1601            "#} },
1602        ],
1603        lower: |_flags, args| Ok(StepKind::Echo(join_value(args, KEYWORD_ECHO)?)),
1604    ],
1605
1606    Run => [
1607        name: KEYWORD_RUN,
1608        variant: Run(Arg),
1609        syntax: "RUN <command...> | RUN [\"exe\", \"arg\", ...]",
1610        summary: "Execute shell command or direct executable.",
1611        description: indoc! {r#"
1612            Shell form (`RUN <command...>`) runs the joined command string in the
1613            batch shell (`sh -c` / `cmd /C`). Never the operator's login
1614            shell: login shells re-pollute scrubbed children from system
1615            profiles and break script portability, so step execution is
1616            pinned to POSIX `sh` (interactive `oxdock --shell` still uses
1617            `$SHELL`).
1618
1619            Exec form (`RUN ["exe", "arg", ...]`) spawns the executable directly
1620            with no shell, so there is no shell expansion, globbing, redirection,
1621            or pipes; use it for portable commands.
1622
1623            Guards and wrappers (`ASYNC`, `TIMEOUT`, `WITH_IO`, `LET`) apply to
1624            both forms.
1625        "#},
1626        args: &[ ArgSpec { name: "command", arg_type: ArgType::Rest(&ArgType::String), description: "Command", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1627        flags: &[],
1628        default_output: None,
1629        examples: &[ Example { name: "run", fence_meta: None, code: indoc! {r#"
1630            # Spawned children resolve through the seeded host PATH:
1631            # closed child env is the default, not ambient inherit.
1632            RUN echo hello
1633
1634            # Captured runs prove the output, not just the exit status.
1635            LET $o: STRING = RUN echo hello
1636            ASSERT_CONTAINS $o "hello"
1637        "#}         }, Example { name: "run exec form", fence_meta: None, code: indoc! {r#"
1638            # No shell: `>` stays a literal argument, so no file is created.
1639            # Toolchain spawns bridge the host home explicitly: rustup
1640            # shims resolve toolchains through the host home.
1641            IMPORT [STD]
1642            [family:unix] INHERIT_ENV [HOME]
1643            [family:windows] INHERIT_ENV [USERPROFILE]
1644            RUN ["cargo", "--version", ">", "x.txt"]
1645            ASSERT_CONTAINS stdout "cargo"
1646
1647            LET $t: STRING = PATH_TYPE("x.txt")
1648            ASSERT_EQ $t "absent"
1649        "#} } ],
1650        lower: |_flags, args| match args.as_slice() {
1651            [Arg::Expr(Expr::List(elems))] if elems.is_empty() => {
1652                Err(ParseError::validation(KEYWORD_RUN, "RUN requires at least one argument".to_string(), &SpanContext::line_only(0)))
1653            }
1654            [Arg::Expr(Expr::List(elems))] => Ok(StepKind::RunExec {
1655                argv: elems.iter().cloned().map(Arg::Expr).collect(),
1656            }),
1657            _ => Ok(StepKind::Run(join_value(args, KEYWORD_RUN)?)),
1658        },
1659    ],
1660
1661    Copy => [
1662        name: KEYWORD_COPY,
1663        variant: Copy { from_workspace: Option<WorkspaceTarget>, from_host: bool, to_host: bool, from: Arg, to: Arg },
1664        syntax: "COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>",
1665        summary: "Copy file into workspace.",
1666        description: "Copies from host (the source is never moved or modified). Docker destination semantics: a file copied onto a directory (an existing one, or a trailing-slash spell like `out/`) is duplicated inside it under its own basename; a directory source duplicates its contents into the destination; any other destination path is created holding the copied bytes.",
1667        args: &[
1668            ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1669            ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1670        ],
1671        flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Copy from the given workspace root instead of the build context" }, FlagSpec { name: "from_host", long: "--from-host", value_type: FlagValueType::Flag, required: false, description: "Fetch from the host workspace into the guest (REMOTE bodies only)" }, FlagSpec { name: "to_host", long: "--to-host", value_type: FlagValueType::Flag, required: false, description: "Push from the guest workspace back to the host (REMOTE bodies only)" } ],
1672        default_output: None,
1673        examples: &[ Example { name: "copy", fence_meta: Some("roots:unified"), code: indoc! {r#"
1674            # Copy to a new name, then read back.
1675            WRITE src.txt content
1676            COPY src.txt dst.txt
1677
1678            LET $body: STRING = READ dst.txt
1679            ASSERT_EQ $body "content"
1680        "#} }, Example { name: "copy from workspace", fence_meta: None, code: indoc! {r#"
1681            # Same name, different contents per root: only LOCAL has ws-content.
1682            WRITE shared.txt from-snapshot
1683            WORKSPACE LOCAL
1684            WRITE shared.txt ws-content
1685
1686            WORKSPACE SNAPSHOT
1687            COPY --from-workspace LOCAL shared.txt ws-copy.txt
1688
1689            LET $body: STRING = READ ws-copy.txt
1690            ASSERT_EQ $body "ws-content"
1691        "#} } ],
1692        lower: |flags, args| {
1693            let from_workspace = flags
1694                .iter()
1695                .find(|(k, _)| k == "from_workspace")
1696                .map(|(_, v)| match v.as_str() {
1697                    "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1698                    "LOCAL" => Ok(WorkspaceTarget::Local),
1699                    "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1700                    "SYSTEM" => Ok(WorkspaceTarget::System),
1701                    other => Err(ParseError::validation(KEYWORD_COPY, format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1702                })
1703                .transpose()?;
1704            let mut it = args.into_iter();
1705            let from = it.next().ok_or_else(|| ParseError::validation(KEYWORD_COPY, "COPY requires a source".to_string(), &SpanContext::line_only(0)))?;
1706            let to = it.next().ok_or_else(|| ParseError::validation(KEYWORD_COPY, "COPY requires a destination".to_string(), &SpanContext::line_only(0)))?;
1707            let from_host = flags.iter().any(|(k, _)| k == "from_host");
1708            let to_host = flags.iter().any(|(k, _)| k == "to_host");
1709            if from_host && to_host {
1710                return Err(ParseError::validation(KEYWORD_COPY, "COPY --from-host and --to-host are mutually exclusive".to_string(), &SpanContext::line_only(0)));
1711            }
1712            Ok(StepKind::Copy { from_workspace, from_host, to_host, from, to })
1713        },
1714    ],
1715
1716    CopyGit => [
1717        name: KEYWORD_COPY_GIT,
1718        variant: CopyGit { rev: Arg, from: Arg, to: Arg, include_dirty: bool },
1719        syntax: "COPY_GIT [--include-dirty] <rev> <src> <dst>",
1720        summary: "Copy from git revision.",
1721        description: "Checkout and copy.",
1722        args: &[
1723            ArgSpec { name: "rev", arg_type: ArgType::String, description: "Rev", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1724            ArgSpec { name: "src", arg_type: ArgType::Path, description: "Src", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
1725            ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Dst", io: IoDirection::Write, index: 2, required: true, fallback_stream: None },
1726        ],
1727        flags: &[ FlagSpec { name: "dirty", long: "--include-dirty", value_type: FlagValueType::Flag, required: false, description: "Include dirty" } ],
1728        default_output: None,
1729        examples: &[ Example { name: "git copy missing source errors", fence_meta: Some("expect_error:\"COPY source missing\""), code: indoc! {r#"COPY_GIT HEAD src.txt dst.txt"#} } ],
1730        lower: |flags, args| {
1731            let include_dirty = flags.iter().any(|(k, _)| k == "dirty");
1732            let mut it = args.into_iter();
1733            let rev = it.next().ok_or_else(|| ParseError::validation(KEYWORD_COPY_GIT, "COPY_GIT requires a revision".to_string(), &SpanContext::line_only(0)))?;
1734            let from = it.next().ok_or_else(|| ParseError::validation(KEYWORD_COPY_GIT, "COPY_GIT requires a source".to_string(), &SpanContext::line_only(0)))?;
1735            let to = it.next().ok_or_else(|| ParseError::validation(KEYWORD_COPY_GIT, "COPY_GIT requires a destination".to_string(), &SpanContext::line_only(0)))?;
1736            Ok(StepKind::CopyGit { rev, from, to, include_dirty })
1737        },
1738    ],
1739
1740    Symlink => [
1741        name: KEYWORD_SYMLINK,
1742        variant: Symlink { from_workspace: Option<WorkspaceTarget>, from: Arg, to: Arg },
1743        syntax: "SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>",
1744        summary: "Create symlink.",
1745        description: "Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.",
1746        args: &[
1747            ArgSpec { name: "from", arg_type: ArgType::Path, description: "Target", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1748            ArgSpec { name: "to", arg_type: ArgType::Path, description: "Link", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1749        ],
1750        flags: &[ FlagSpec { name: "from_workspace", long: "--from-workspace", value_type: FlagValueType::String, required: false, description: "Symlink from the given workspace root instead of the build context" } ],
1751        default_output: None,
1752        examples: &[ Example { name: "symlink", fence_meta: Some("roots:unified"), code: indoc! {r#"
1753            # A symlink reads like its target.
1754            WRITE original.txt content
1755            SYMLINK original.txt link.txt
1756
1757            LET $body: STRING = READ link.txt
1758            ASSERT_EQ $body "content"
1759        "#} }, Example { name: "symlink from workspace", fence_meta: None, code: indoc! {r#"
1760            # Same name, different contents per root: only LOCAL has ws-content.
1761            WRITE shared.txt from-snapshot
1762            WORKSPACE LOCAL
1763            WRITE shared.txt ws-content
1764
1765            WORKSPACE SNAPSHOT
1766            SYMLINK --from-workspace LOCAL shared.txt ws-link.txt
1767
1768            LET $body: STRING = READ ws-link.txt
1769            ASSERT_EQ $body "ws-content"
1770        "#} } ],
1771        lower: |flags, args| {
1772            let from_workspace = flags
1773                .iter()
1774                .find(|(k, _)| k == "from_workspace")
1775                .map(|(_, v)| match v.as_str() {
1776                    "SNAPSHOT" => Ok(WorkspaceTarget::Snapshot),
1777                    "LOCAL" => Ok(WorkspaceTarget::Local),
1778                    "CACHE" => Ok(WorkspaceTarget::Cache { local: false }),
1779                    "SYSTEM" => Ok(WorkspaceTarget::System),
1780                    other => Err(ParseError::validation(KEYWORD_SYMLINK, format!("unknown workspace source: {other}"), &SpanContext::line_only(0))),
1781                })
1782                .transpose()?;
1783            let mut it = args.into_iter();
1784            let from = it.next().ok_or_else(|| ParseError::validation(KEYWORD_SYMLINK, "SYMLINK requires a source".to_string(), &SpanContext::line_only(0)))?;
1785            let to = it.next().ok_or_else(|| ParseError::validation(KEYWORD_SYMLINK, "SYMLINK requires a target".to_string(), &SpanContext::line_only(0)))?;
1786            Ok(StepKind::Symlink { from_workspace, from, to })
1787        },
1788    ],
1789
1790    Mkdir => [
1791        name: KEYWORD_MKDIR,
1792        variant: Mkdir(Arg),
1793        syntax: "MKDIR <path>",
1794        summary: "Create directory.",
1795        description: "Creates dir with parents.",
1796        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir path", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1797        flags: &[],
1798        default_output: None,
1799        examples: &[ Example { name: "mkdir", fence_meta: None, code: indoc! {r#"
1800            IMPORT [STD]
1801            MKDIR deeply/nested/tree
1802
1803            LET $t: STRING = PATH_TYPE("deeply/nested/tree")
1804            ASSERT_EQ $t "dir"
1805        "#} } ],
1806        lower: |_flags, args| Ok(StepKind::Mkdir(args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_MKDIR, "MKDIR requires a path".to_string(), &SpanContext::line_only(0)))?)),
1807    ],
1808
1809    Install => [
1810        name: KEYWORD_INSTALL,
1811        variant: Install { from: Arg, to: Arg },
1812        syntax: "INSTALL <source> <dest>",
1813        summary: "Atomically install a verified binary as executable.",
1814        description: "Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.",
1815        args: &[
1816            ArgSpec { name: "from", arg_type: ArgType::Path, description: "Source file", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1817            ArgSpec { name: "to", arg_type: ArgType::Path, description: "Dest file", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1818        ],
1819        flags: &[],
1820        default_output: None,
1821        examples: &[ Example { name: "install", fence_meta: Some("roots:unified"), code: indoc! {r#"
1822            # Place a verified binary with executable mode.
1823            IMPORT [STD]
1824            WRITE src.bin payload
1825            INSTALL src.bin dst-bin/tool
1826
1827            LET $t: STRING = PATH_TYPE("dst-bin/tool")
1828            ASSERT_EQ $t "file"
1829        "#} } ],
1830        lower: |_flags, args| {
1831            let mut it = args.into_iter();
1832            let from = it.next().ok_or_else(|| ParseError::validation(KEYWORD_INSTALL, "INSTALL requires a source".to_string(), &SpanContext::line_only(0)))?;
1833            let to = it.next().ok_or_else(|| ParseError::validation(KEYWORD_INSTALL, "INSTALL requires a destination".to_string(), &SpanContext::line_only(0)))?;
1834            Ok(StepKind::Install { from, to })
1835        },
1836    ],
1837
1838    SetExecutable => [
1839        name: KEYWORD_SET_EXECUTABLE,
1840        variant: SetExecutable { path: Arg },
1841        syntax: "SET_EXECUTABLE <path>",
1842        summary: "Mark a file executable.",
1843        description: "Sets the executable bit on an existing file without moving it. Owner rwx on Unix, bit no-op elsewhere, so the same script runs on every platform; a missing path fails everywhere. `INSTALL` stages, marks, and renames in one atomic step; this command only flips the bit where the file already lives.",
1844        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File to mark executable", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
1845        flags: &[],
1846        default_output: None,
1847        examples: &[ Example { name: "set-executable", fence_meta: Some("roots:unified"), code: indoc! {r#"
1848            # Mark a rendered script executable in place.
1849            IMPORT [STD]
1850            WRITE tool.sh "echo hi"
1851            SET_EXECUTABLE tool.sh
1852
1853            LET $t: STRING = PATH_TYPE("tool.sh")
1854            ASSERT_EQ $t "file"
1855        "#} } ],
1856        lower: |_flags, args| Ok(StepKind::SetExecutable { path: args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_SET_EXECUTABLE, "SET_EXECUTABLE requires a path".to_string(), &SpanContext::line_only(0)))? }),
1857    ],
1858
1859    Archive => [
1860        name: KEYWORD_ARCHIVE,
1861        variant: Archive { src: Arg, dst: Arg, raw: bool },
1862        syntax: "ARCHIVE [--raw] <src> <dst>",
1863        summary: "Pack a file or directory into a tarball.",
1864        description: indoc! {r#"
1865            Packs a file or directory into a tarball, gzip-compressed by
1866            default (`--raw` writes an uncompressed tar instead).
1867
1868            A lone file packs as a single top-level entry under its
1869            basename; a directory recurses, preserving empty dirs. Source
1870            modes ride in the headers on Unix, so system `tar` restores
1871            them elsewhere. Symlink sources refuse: archives cross trust
1872            boundaries, so links never resolve into member bytes. Hashing
1873            stays with `HASH_SHA256`, which reads the finished archive
1874            like any other file.
1875        "#},
1876        args: &[
1877            ArgSpec { name: "src", arg_type: ArgType::Path, description: "File or directory to pack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1878            ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Archive file to write", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1879        ],
1880        flags: &[ FlagSpec { name: "raw", long: "--raw", value_type: FlagValueType::Flag, required: false, description: "Write an uncompressed tar instead of gzip" } ],
1881        default_output: None,
1882        examples: &[ Example { name: "archive directory", fence_meta: None, code: indoc! {r#"
1883            # Stage a small tree to pack.
1884            WRITE bundle/app.txt bundled-payload
1885            WRITE bundle/nested/deep.txt deep-payload
1886
1887            # ARCHIVE packs it gzip-compressed by default.
1888            ARCHIVE bundle bundle.tar.gz
1889
1890            # UNARCHIVE restores the tree under the destination.
1891            UNARCHIVE bundle.tar.gz restored
1892
1893            # The payloads arrive byte-identical.
1894            LET $body: STRING = READ restored/app.txt
1895            ASSERT_EQ $body "bundled-payload"
1896
1897            LET $deep: STRING = READ restored/nested/deep.txt
1898            ASSERT_EQ $deep "deep-payload"
1899        "#} }, Example { name: "archive raw", fence_meta: None, code: indoc! {r#"
1900            # A lone file packs as a single top-level entry.
1901            WRITE tool.bin tool-payload
1902
1903            # Raw archives skip gzip and stay readable by any tar.
1904            ARCHIVE --raw tool.bin tool.tar
1905            UNARCHIVE tool.tar tool-out
1906
1907            # The entry lands under its basename.
1908            LET $body: STRING = READ tool-out/tool.bin
1909            ASSERT_EQ $body "tool-payload"
1910        "#} } ],
1911        lower: |flags, args| {
1912            let raw = flags.iter().any(|(k, _)| k == "raw");
1913            let mut it = args.into_iter();
1914            let src = it.next().ok_or_else(|| ParseError::validation(KEYWORD_ARCHIVE, "ARCHIVE requires a source".to_string(), &SpanContext::line_only(0)))?;
1915            let dst = it.next().ok_or_else(|| ParseError::validation(KEYWORD_ARCHIVE, "ARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1916            Ok(StepKind::Archive { src, dst, raw })
1917        },
1918    ],
1919
1920    Unarchive => [
1921        name: KEYWORD_UNARCHIVE,
1922        variant: Unarchive { src: Arg, dst: Arg, max_bytes: Option<Arg> },
1923        syntax: "UNARCHIVE <src> <dst> [--max-bytes <bytes>]",
1924        summary: "Unpack a tarball into a directory.",
1925        description: indoc! {r#"
1926            Unpacks a tarball under the destination directory, creating
1927            it first. Gzip and raw (`ARCHIVE --raw`) tarballs
1928            self-identify by magic bytes, so no flag is needed.
1929
1930            Member bytes meter against a 1 GiB default expansion cap
1931            across the whole archive: a decompression bomb trips it
1932            instead of filling the disk, and `--max-bytes` moves the
1933            ceiling either way (plain integer bytes). The tripped member
1934            stays truncated on disk while the step fails loudly.
1935
1936            Symlink and special members refuse naming the entry, and
1937            absolute or escaping paths fail closed before any byte
1938            lands: the member sanitizer plus the destination join check
1939            form two independent walls. Unix modes recorded in the
1940            headers restore on unpack; other platforms land default
1941            modes (confer executability with `INSTALL` there).
1942        "#},
1943        args: &[
1944            ArgSpec { name: "src", arg_type: ArgType::Path, description: "Archive file to unpack", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
1945            ArgSpec { name: "dst", arg_type: ArgType::Path, description: "Directory to unpack under", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
1946        ],
1947        flags: &[ FlagSpec { name: "max_bytes", long: "--max-bytes", value_type: FlagValueType::String, required: false, description: "Cap total unpacked member bytes: bare digits are bytes (`1_000_000` grouping allowed), suffixes B/KB/MB/GB/TB (decimal) and KIB/MIB/GIB/TIB (binary), any case, one optional space before the unit (defaults to 1 GiB)" } ],
1948        default_output: None,
1949        examples: &[ Example { name: "unarchive", fence_meta: None, code: indoc! {r#"
1950            # Pack a note, then restore it under a fresh destination.
1951            WRITE pack/note.txt packed-note
1952            ARCHIVE pack pack.tar.gz
1953            UNARCHIVE pack.tar.gz unpacked
1954
1955            LET $body: STRING = READ unpacked/note.txt
1956            ASSERT_EQ $body "packed-note"
1957        "#}         }, Example { name: "unarchive with a lower cap", fence_meta: None, code: indoc! {r#"
1958            # Small payloads clear even a tight ceiling.
1959            WRITE pack/note.txt packed-note
1960            ARCHIVE pack pack.tar.gz
1961            UNARCHIVE pack.tar.gz capped --max-bytes 100KB
1962
1963            LET $body: STRING = READ capped/note.txt
1964            ASSERT_EQ $body "packed-note"
1965        "#} } ],
1966        lower: |flags, args| {
1967            let mut it = args.into_iter();
1968            let src = it.next().ok_or_else(|| ParseError::validation(KEYWORD_UNARCHIVE, "UNARCHIVE requires an archive".to_string(), &SpanContext::line_only(0)))?;
1969            let dst = it.next().ok_or_else(|| ParseError::validation(KEYWORD_UNARCHIVE, "UNARCHIVE requires a destination".to_string(), &SpanContext::line_only(0)))?;
1970            let max_bytes = flags
1971                .into_iter()
1972                .find_map(|(k, v)| (k == "max_bytes").then_some(v));
1973            // Static literals fail fast at parse; templates and
1974            // variables defer to the runtime resolver, which enforces
1975            // the same shape on the resolved value.
1976            if let Some(Arg::String(text, _)) = max_bytes.as_ref()
1977                && !text.contains("{{")
1978                && let Err(e) = crate::command::parse_byte_count(text)
1979            {
1980                return Err(ParseError::validation(
1981                    "UNARCHIVE",
1982                    format!("UNARCHIVE --max-bytes {e:#}"),
1983                    &SpanContext::line_only(0),
1984                ));
1985            }
1986            Ok(StepKind::Unarchive { src, dst, max_bytes })
1987        },
1988    ],
1989
1990    Ls => [
1991        name: KEYWORD_LS,
1992        variant: Ls(Option<Arg>),
1993        syntax: "LS [<path>]",
1994        summary: "List directory.",
1995        description: "Lists entries.",
1996        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Dir", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
1997        flags: &[],
1998        default_output: Some(Stream::Stdout),
1999        examples: &[ Example { name: "ls", fence_meta: None, code: indoc! {r#"
2000            MKDIR inventory
2001            WRITE inventory/a.txt a
2002            LS inventory
2003            ASSERT_CONTAINS stdout "a.txt"
2004        "#} } ],
2005        lower: |_flags, args| Ok(StepKind::Ls(args.into_iter().next())),
2006    ],
2007
2008    Read => [
2009        name: KEYWORD_READ,
2010        variant: Read(Option<Arg>),
2011        syntax: "READ [<path>]",
2012        summary: "Read file to stdout.",
2013        description: "Outputs file contents.",
2014        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Read, index: 0, required: false, fallback_stream: None } ],
2015        flags: &[],
2016        default_output: Some(Stream::Stdout),
2017        examples: &[ Example { name: "read", fence_meta: None, code: indoc! {r#"
2018            WRITE note.txt "hello"
2019            READ note.txt
2020
2021            LET $body: STRING = READ note.txt
2022            ASSERT_EQ $body "hello"
2023        "#} } ],
2024        lower: |_flags, args| Ok(StepKind::Read(args.into_iter().next())),
2025    ],
2026
2027    ReadLine => [
2028        name: KEYWORD_READ_LINE,
2029        variant: ReadLine { var: String },
2030        syntax: "READ_LINE $var",
2031        summary: "Read one line from stdin into a variable.",
2032        description: indoc! {r#"
2033            Reads bytes until newline without waiting for EOF, leaving the pipe open.
2034
2035            Trailing newline is stripped (shell-read parity). On premature EOF
2036            assigns accumulated bytes and returns.
2037        "#},
2038        args: &[ ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the line binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2039        flags: &[],
2040        default_output: None,
2041        examples: &[ Example { name: "read line", fence_meta: None, code: indoc! {r#"
2042            # The trailing newline is stripped: the variable holds exactly `first`.
2043            LET $lines: PIPE
2044            WITH_IO [stdout=$lines] ECHO "first"
2045            WITH_IO [stdin=$lines] READ_LINE $reply
2046            ASSERT_EQ $reply "first"
2047        "#} } ],
2048        lower: |_flags, args| {
2049            let arg = args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_READ_LINE, "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))?;
2050            let var = match arg {
2051                Arg::Expr(Expr::Var(name)) => name,
2052                // Quoted "$var" keeps its sigil through the generic string
2053                // path; templates defer untouched exactly as before.
2054                Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
2055                other => return Err(ParseError::validation(KEYWORD_READ_LINE, format!("READ_LINE requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2056            };
2057            if var.is_empty() {
2058                return Err(ParseError::validation(KEYWORD_READ_LINE, "READ_LINE requires a variable".to_string(), &SpanContext::line_only(0)))
2059            }
2060            Ok(StepKind::ReadLine { var })
2061        },
2062    ],
2063
2064    Prompt => [
2065        name: KEYWORD_PROMPT,
2066        variant: Prompt { var: String, message: Arg, default: Option<Arg> },
2067        syntax: "PROMPT $var <message> [<default>]",
2068        summary: "Prompt on the terminal into a variable.",
2069        description: indoc! {r#"
2070            Prints `{message} [{default}]: ` (or `{message}: ` with no
2071            default) to stderr and reads one line from the terminal.
2072
2073            Empty input yields the default when one is given, else an
2074            empty string. EOF aborts loudly. Non-TTY stdin never reads:
2075            a default binds with a stderr note, while no default bails.
2076        "#},
2077        args: &[
2078            ArgSpec { name: "var", arg_type: ArgType::String, description: "Target variable (`$name`); the answer binds as STRING", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2079            ArgSpec { name: "message", arg_type: ArgType::String, description: "Prompt message", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
2080            ArgSpec { name: "default", arg_type: ArgType::String, description: "Default on empty input", io: IoDirection::Read, index: 2, required: false, fallback_stream: None },
2081        ],
2082        flags: &[],
2083        default_output: None,
2084        examples: &[ Example { name: "prompt needs a terminal", fence_meta: Some("expect_error:\"non-TTY\""), code: indoc! {r#"
2085            # A redirected stdin can never answer: without a default the
2086            # prompt fails instead of hanging or reading piped stdin.
2087            LET $p: PIPE
2088            WITH_IO [stdin=$p] PROMPT $dir "Install destination?"
2089        "#} } ],
2090        lower: |_flags, args| {
2091            let mut it = args.into_iter();
2092            let var_arg = it.next().ok_or_else(|| ParseError::validation(KEYWORD_PROMPT, "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))?;
2093            let var = match var_arg {
2094                Arg::Expr(Expr::Var(name)) => name,
2095                Arg::String(s, _) if s.starts_with('$') || s.contains("{{") => s.trim_start_matches('$').to_string(),
2096                other => return Err(ParseError::validation(KEYWORD_PROMPT, format!("PROMPT requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2097            };
2098            if var.is_empty() {
2099                return Err(ParseError::validation(KEYWORD_PROMPT, "PROMPT requires a variable".to_string(), &SpanContext::line_only(0)))
2100            }
2101            let message = it.next().ok_or_else(|| ParseError::validation(KEYWORD_PROMPT, "PROMPT requires a message".to_string(), &SpanContext::line_only(0)))?;
2102            let default = it.next();
2103            Ok(StepKind::Prompt { var, message, default })
2104        },
2105    ],
2106
2107    Write => [
2108        name: KEYWORD_WRITE,
2109        variant: Write { path: Arg, contents: Option<Arg> },
2110        syntax: "WRITE <path> [<contents>]",
2111        summary: "Write to file.",
2112        description: "Writes contents. Bytes land exactly as given: no line-ending translation happens on any platform (LF stays LF, even on Windows), so the same script produces identical files everywhere.",
2113        args: &[
2114            ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2115            ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
2116        ],
2117        flags: &[],
2118        default_output: None,
2119        examples: &[ Example { name: "write", fence_meta: None, code: indoc! {r#"
2120            WRITE output.txt hello-world
2121            LET $body: STRING = READ output.txt
2122            ASSERT_EQ $body "hello-world"
2123        "#} } ],
2124        lower: |_flags, args| {
2125            let mut it = args.into_iter();
2126            let path = it.next().ok_or_else(|| ParseError::validation(KEYWORD_WRITE, "WRITE requires a path".to_string(), &SpanContext::line_only(0)))?;
2127            let remaining: Vec<Arg> = it.collect();
2128            let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, KEYWORD_WRITE)?) };
2129            Ok(StepKind::Write { path, contents })
2130        },
2131    ],
2132
2133    Append => [
2134        name: KEYWORD_APPEND,
2135        variant: Append { path: Arg, contents: Option<Arg> },
2136        syntax: "APPEND <path> [<contents>]",
2137        summary: "Append to file.",
2138        description: "Appends contents with no separator and no line ending: bytes concatenate exactly, so `APPEND` never terminates the line (use `APPEND_LINE` for that). Bytes land exactly as given: no line-ending translation happens on any platform (LF stays LF, even on Windows), so the same script produces identical files everywhere.",
2139        args: &[
2140            ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2141            ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Content", io: IoDirection::Write, index: 1, required: false, fallback_stream: Some(Stream::Stdin) },
2142        ],
2143        flags: &[],
2144        default_output: None,
2145        examples: &[ Example { name: "append", fence_meta: None, code: indoc! {r#"
2146            WRITE log.txt line1
2147            APPEND log.txt line2
2148
2149            # No separator or newline is added: the bytes concatenate
2150            # exactly, so this asserts the unterminated form.
2151            LET $all: STRING = READ log.txt
2152            ASSERT_EQ $all "line1line2"
2153        "#} } ],
2154        lower: |_flags, args| {
2155            let mut it = args.into_iter();
2156            let path = it.next().ok_or_else(|| ParseError::validation(KEYWORD_APPEND, "APPEND requires a path".to_string(), &SpanContext::line_only(0)))?;
2157            let remaining: Vec<Arg> = it.collect();
2158            let contents = if remaining.is_empty() { None } else { Some(join_value(remaining, KEYWORD_APPEND)?) };
2159            Ok(StepKind::Append { path, contents })
2160        },
2161    ],
2162
2163    AppendLine => [
2164        name: KEYWORD_APPEND_LINE,
2165        variant: AppendLine { path: Arg, contents: Arg },
2166        syntax: "APPEND_LINE <path> <contents>",
2167        summary: "Append one line to a file.",
2168        description: "Appends contents plus exactly one trailing LF newline (`\\n`, never the platform newline), so callers never spell the terminator by hand and output bytes stay identical on every OS. Contents are required: unlike APPEND there is no stdin form, a line is a complete value, not a stream.",
2169        args: &[
2170            ArgSpec { name: "path", arg_type: ArgType::Path, description: "File", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2171            ArgSpec { name: "contents", arg_type: ArgType::Rest(&ArgType::String), description: "Line content (the newline is added)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2172        ],
2173        flags: &[],
2174        default_output: None,
2175        examples: &[ Example { name: "append-line", fence_meta: None, code: indoc! {r#"
2176            WRITE log.txt line1
2177            APPEND_LINE log.txt line2
2178            APPEND_LINE log.txt line3
2179
2180            # Each APPEND_LINE terminates its own write.
2181            LET $all: STRING = READ log.txt
2182            ASSERT_EQ $all "line1line2\nline3\n"
2183        "#} } ],
2184        lower: |_flags, args| {
2185            let mut it = args.into_iter();
2186            let path = it.next().ok_or_else(|| ParseError::validation(KEYWORD_APPEND_LINE, "APPEND_LINE requires a path".to_string(), &SpanContext::line_only(0)))?;
2187            let remaining: Vec<Arg> = it.collect();
2188            let contents = join_value(remaining, KEYWORD_APPEND_LINE)?;
2189            Ok(StepKind::AppendLine { path, contents })
2190        },
2191    ],
2192
2193    Remove => [
2194        name: KEYWORD_REMOVE,
2195        variant: Remove { path: Arg, recursive: bool },
2196        syntax: "REMOVE [--recursive] <path>",
2197        summary: "Remove a file, symlink, or directory.",
2198        description: "Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.",
2199        args: &[ ArgSpec { name: "path", arg_type: ArgType::Path, description: "Path to remove", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2200        flags: &[ FlagSpec { name: "recursive", long: "--recursive", value_type: FlagValueType::Flag, required: false, description: "Remove a directory tree" } ],
2201        default_output: None,
2202        examples: &[ Example { name: "remove", fence_meta: None, code: indoc! {r#"
2203            # WRITE then REMOVE leaves nothing behind.
2204            IMPORT [STD]
2205            WRITE scratch.txt content
2206
2207            # Assert original file is written
2208            LET $o: STRING = PATH_TYPE("scratch.txt")
2209            ASSERT_EQ $o "file"
2210
2211            REMOVE scratch.txt
2212
2213            # Assert file has been removed
2214            LET $t: STRING = PATH_TYPE("scratch.txt")
2215            ASSERT_EQ $t "absent"
2216        "#} } ],
2217        lower: |flags, args| {
2218            let recursive = flags.iter().any(|(k, _)| k == "recursive");
2219            let path = args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_REMOVE, "REMOVE requires a path".to_string(), &SpanContext::line_only(0)))?;
2220            Ok(StepKind::Remove { path, recursive })
2221        },
2222    ],
2223
2224    Expand => [
2225        name: KEYWORD_EXPAND,
2226        variant: Expand { path: Option<Arg>, overrides: Vec<(String, Arg)> },
2227        syntax: "EXPAND [<path>] [<KEY=val> ...]",
2228        summary: "Expand a template file (or stdin) to stdout.",
2229        description: indoc! {r#"
2230            A template is any text file — or piped stdin when no path is given —
2231            containing `{{ ... }}` placeholders. EXPAND replaces each placeholder
2232            and prints the result to stdout.
2233
2234            Placeholders: `{{ NAME }}` reads a `KEY=val` override passed on this
2235            command; `{{ env:NAME }}` reads an override, falling back to the
2236            environment; `{{ $var }}` reads a script variable (dotted paths allowed).
2237            A missing key is an error, never a silent empty.
2238
2239            Calls: `{{ MODULE::FUNC(args) }}` invokes a pure registry function
2240            with `$var.path` references and `STRING`, `INT`, `FLOAT`, and `BOOL`
2241            literals as arguments. A bare `{{ NAME(args) }}` resolves exactly
2242            like a statement-position call: `IMPORT [MODULE]` brings the names
2243            into scope, unimported names fail naming the fix, ambiguity fails
2244            closed. Arguments check against the registered
2245            signature, so wrong arity or mistyped values fail at the call;
2246            unknown names fail listing the known functions. Only pure
2247            functions resolve here: stateful, script-defined, and pipe-backed
2248            entries fail naming themselves, since placeholder evaluation
2249            carries no step context. The same calls resolve in ordinary
2250            strings, so both paths agree.
2251
2252            Substitution runs in a single pass. `EXPAND` is not recursive and does not
2253            expand nested placeholders: a value that itself contains `{{ ... }}` is
2254            inserted verbatim and never expanded again.
2255
2256            A bare `$var` argument is a template path; `KEY=val` arguments are
2257            overrides whose values follow the unified string-value rules (same as
2258            `ENV`: quotes keep exact bytes, a lone `$var` evaluates,
2259            `{{ ... }}` interpolates).
2260
2261            NOTE: `WRITE` interpolates `{{ ... }}` while writing, so escape it
2262            (`\{{ ... }}`) when writing a template file for a later `EXPAND`.
2263
2264            With no path, the template arrives on stdin through a pipe. When piping
2265            from a shell, single-quote the template (`echo '{{ $x }}'`): double
2266            quotes let the shell swallow `$x`, so oxdock receives an empty `{{ }}`
2267            placeholder and errors.
2268        "#},
2269        args: &[
2270            ArgSpec { name: "path", arg_type: ArgType::Path, description: "Template file to expand; omit to expand stdin", io: IoDirection::Read, index: 0, required: false, fallback_stream: None },
2271            ArgSpec { name: "overrides", arg_type: ArgType::Rest(&ArgType::String), description: "Template overrides shadowing that key (unified string values)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
2272        ],
2273        flags: &[],
2274        default_output: Some(Stream::Stdout),
2275        examples: &[
2276            Example { name: "expand", fence_meta: None, code: indoc! {r#"
2277                # Placeholders read overrides first, then the environment.
2278                ENV NAME="Alice"
2279                WRITE template.md "Hello {{ env:NAME }}!"
2280                EXPAND template.md
2281
2282                ASSERT_CONTAINS stdout "Hello Alice!"
2283            "#} },
2284            Example { name: "override with spaces", fence_meta: None, code: indoc! {r#"
2285                # WRITE would interpolate {{ }} right away, so escape it.
2286                # The file must literally contain {{ env:NAME }} for EXPAND.
2287                WRITE template.md "Hello \{{ env:NAME }}!"
2288                EXPAND template.md NAME="Alice Smith"
2289
2290                ASSERT_CONTAINS stdout "Hello Alice Smith!"
2291            "#} },
2292            Example { name: "variable override", fence_meta: None, code: indoc! {r#"
2293                # Same escaping: keep the placeholder literal until EXPAND.
2294                # A lone $who evaluates, like ECHO $who.
2295                LET $who: STRING = "Bob"
2296                WRITE template.md "Hi \{{ env:WHO }}!"
2297                EXPAND template.md WHO=$who
2298
2299                ASSERT_CONTAINS stdout "Hi Bob!"
2300            "#} },
2301            Example { name: "override forms agree", fence_meta: None, code: indoc! {r#"
2302                # A bare variable and a template-with-tail expand identically.
2303                LET $x: STRING = "Ada"
2304                WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
2305                EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"
2306
2307                ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"
2308            "#} },
2309            Example { name: "expand stdin", fence_meta: None, code: indoc! {r#"
2310                # No path: the template arrives on stdin through a pipe.
2311                LET $tpl: PIPE
2312                WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
2313                WITH_IO [stdin=$tpl] EXPAND NAME=Alice
2314
2315                ASSERT_CONTAINS stdout "Hello Alice!"
2316            "#} },
2317            Example { name: "override does not leak", fence_meta: None, code: indoc! {r#"
2318                # KEY=val overrides shadow env for that EXPAND only.
2319                # They never update the environment itself.
2320                ENV NAME="Alice"
2321                WRITE template.md "Hi \{{ env:NAME }}!"
2322
2323                EXPAND template.md NAME="Bob"
2324                ASSERT_CONTAINS stdout "Hi Bob!"
2325
2326                EXPAND template.md
2327                ASSERT_CONTAINS stdout "Hi Alice!"
2328            "#} },
2329            Example { name: "function call", fence_meta: None, code: indoc! {r#"
2330                # Pure registry functions run inside placeholders.
2331                # WRITE would interpolate {{ }} right away, so escape it.
2332                IMPORT [STD]
2333                WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"
2334
2335                EXPAND template.md
2336                ASSERT_CONTAINS stdout "Count: 2!"
2337            "#} },
2338            Example { name: "bare override", fence_meta: None, code: indoc! {r#"
2339                # A bare name reads a KEY=val override with no prefix.
2340                WRITE template.md "Hi \{{ NAME }}!"
2341
2342                EXPAND template.md NAME=Ada
2343                ASSERT_CONTAINS stdout "Hi Ada!"
2344            "#} },
2345            Example { name: "variable placeholder", fence_meta: None, code: indoc! {r#"
2346                # `{{ $var }}` placeholders read script variables, dotted
2347                # paths included. Escape at WRITE so EXPAND sees it.
2348                LET $u: MAP<name: STRING> = {name: "Bo"}
2349                WRITE template.md "Hi \{{ $u.name }}!"
2350
2351                EXPAND template.md
2352                ASSERT_CONTAINS stdout "Hi Bo!"
2353            "#} },
2354            Example { name: "missing key fails", fence_meta: Some("expect_error:\"missing required step override argument\""), code: indoc! {r#"
2355                # A missing key is an error, never a silent empty.
2356                WRITE template.md "Hi \{{ NAME }}!"
2357
2358                EXPAND template.md
2359            "#} },
2360        ],
2361        lower: |_flags, args| {
2362            let mut path = None;
2363            let mut overrides = Vec::new();
2364            for arg in args {
2365                let text = arg.as_str();
2366                if let Some((key, value)) = split_assignment(text).map_err(|e| ParseError::validation(KEYWORD_EXPAND, e.to_string(), &SpanContext::line_only(0)))? {
2367                    overrides.push((key, value));
2368                } else if path.is_none() { path = Some(arg); }
2369                else { return Err(ParseError::validation(KEYWORD_EXPAND, "EXPAND accepts at most one path".to_string(), &SpanContext::line_only(0))) }
2370            }
2371            Ok(StepKind::Expand { path, overrides })
2372        },
2373    ],
2374
2375    AssertEq => [
2376        name: KEYWORD_ASSERT_EQ,
2377        variant: AssertEq { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
2378        syntax: Command::AssertEq.syntax(),
2379        summary: "Assert strict equality.",
2380        description: indoc! {r#"
2381            Compares two evaluated values with typed equality (no coercion:
2382            `INT(42)` never equals `STRING("42")`), aborting the pipeline
2383            with a step-numbered error showing expected vs actual otherwise.
2384
2385            Both sides are values: `$var`, literals, templates, and calls
2386            evaluate in memory and never touch disk. Read files explicitly
2387            first (`LET $text: STRING = READ "out.txt"`, then
2388            `ASSERT_EQ $text ...`).
2389            Bare `stdout` / `stderr` observe stream buffers; a `$var`
2390            holding a `PIPE` observes its backend bytes. `--hash` compares
2391            the SHA-256 of a string, pipe, or captured-stdout actual
2392            instead of the raw bytes (`stderr` is unsupported).
2393        "#},
2394        args: &[
2395            ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
2396            ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Expected (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
2397        ],
2398        flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
2399        default_output: None,
2400        examples: &[ Example { name: "assert eq", fence_meta: None, code: indoc! {r#"
2401            LET $status: INT = 200
2402            ASSERT_EQ $status 200
2403        "#} },
2404        Example { name: "assert eq file", fence_meta: None, code: indoc! {r#"
2405            WRITE payload.bin stable-content
2406            LET $body: STRING = READ payload.bin
2407            ASSERT_EQ $body "stable-content"
2408        "#} },
2409        Example { name: "assert eq hash", fence_meta: None, code: indoc! {r#"
2410            # --hash compares the SHA-256 digest instead of raw bytes.
2411            WRITE payload.bin stable-content
2412            LET $body: STRING = READ payload.bin
2413            ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body
2414        "#} } ],
2415        lower: |flags, args| {
2416            let (hash, actual, expected) = lower_equality_args(Command::AssertEq.as_str(), flags, args)?;
2417            Ok(StepKind::AssertEq { hash, actual, expected })
2418        },
2419    ],
2420
2421    AssertNe => [
2422        name: KEYWORD_ASSERT_NE,
2423        variant: AssertNe { hash: Option<String>, actual: AssertTarget, expected: Option<Arg> },
2424        syntax: Command::AssertNe.syntax(),
2425        summary: "Assert strict inequality.",
2426        description: indoc! {r#"
2427            Compares two evaluated values with typed inequality (no coercion:
2428            `INT(42)` never equals `STRING("42")`), aborting the pipeline
2429            with a step-numbered error showing expected vs actual when they
2430            are equal; differing values pass silently.
2431
2432            Both sides are values: `$var`, literals, templates, and calls
2433            evaluate in memory and never touch disk. Read files explicitly
2434            first (`LET $text: STRING = READ "out.txt"`, then
2435            `ASSERT_NE $text ...`).
2436            Bare `stdout` / `stderr` observe stream buffers; a `$var`
2437            holding a `PIPE` observes its backend bytes. `--hash` compares
2438            the SHA-256 of a string, pipe, or captured-stdout actual
2439            instead of the raw bytes (`stderr` is unsupported); the digest
2440            must differ from the given hash.
2441        "#},
2442        args: &[
2443            ArgSpec { name: "actual", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
2444            ArgSpec { name: "expected", arg_type: ArgType::Rest(&ArgType::Any), description: "Value the actual must differ from (required unless --hash)", io: IoDirection::Read, index: 1, required: false, fallback_stream: None },
2445        ],
2446        flags: &[ FlagSpec { name: "hash", long: "--hash", value_type: FlagValueType::String, required: false, description: "SHA-256" } ],
2447        default_output: None,
2448        examples: &[ Example { name: "assert ne", fence_meta: None, code: indoc! {r#"
2449            LET $status: INT = 200
2450            ASSERT_NE $status 404
2451        "#} },
2452        Example { name: "assert ne file", fence_meta: None, code: indoc! {r#"
2453            WRITE payload.bin stable-content
2454            LET $body: STRING = READ payload.bin
2455            ASSERT_NE $body "other-content"
2456        "#} },
2457        Example { name: "assert ne hash", fence_meta: None, code: indoc! {r#"
2458            # --hash compares the SHA-256 digest instead of raw bytes.
2459            WRITE payload.bin stable-content
2460            LET $body: STRING = READ payload.bin
2461            ASSERT_NE --hash 0000000000000000000000000000000000000000000000000000000000000000 $body
2462        "#} } ],
2463        lower: |flags, args| {
2464            let (hash, actual, expected) = lower_equality_args(Command::AssertNe.as_str(), flags, args)?;
2465            Ok(StepKind::AssertNe { hash, actual, expected })
2466        },
2467    ],
2468
2469    AssertContains => [
2470        name: KEYWORD_ASSERT_CONTAINS,
2471        variant: AssertContains { haystack: AssertTarget, needle: Arg },
2472        syntax: Command::AssertContains.syntax(),
2473        summary: "Assert containment.",
2474        description: indoc! {r#"
2475            Checks containment and aborts the pipeline with a step-numbered
2476            error otherwise: substring for strings, element match for lists,
2477            key presence for maps, substring over stream and pipe buffers.
2478
2479            Like `ASSERT_EQ`, both sides are values read without implicit
2480            I/O; read files explicitly first
2481            (`LET $text: STRING = READ "cfg.txt"`).
2482            Bare `stdout` / `stderr` observe stream buffers; a `$var`
2483            holding a `PIPE` observes its backend bytes.
2484        "#},
2485        args: &[
2486            ArgSpec { name: "haystack", arg_type: ArgType::Any, description: "Value, stdout, stderr, or a $var holding a PIPE", io: IoDirection::Read, index: 0, required: true, fallback_stream: None },
2487            ArgSpec { name: "needle", arg_type: ArgType::Rest(&ArgType::Any), description: "Substring, element, or key", io: IoDirection::Read, index: 1, required: true, fallback_stream: None },
2488        ],
2489        flags: &[],
2490        default_output: None,
2491        examples: &[ Example { name: "assert contains", fence_meta: None, code: indoc! {r#"
2492            ECHO build-complete
2493            ASSERT_CONTAINS stdout "build-complete"
2494        "#} } ],
2495        lower: |flags, args| {
2496            let _ = flags;
2497            let mut it = args.into_iter();
2498            let haystack = lower_assert_target(it.next().ok_or_else(|| ParseError::validation(Command::AssertContains.as_str(), format!("{} requires a value", Command::AssertContains.as_str()), &SpanContext::line_only(0)))?)?;
2499            let remaining: Vec<Arg> = it
2500                .map(lower_assert_operand)
2501                .collect::<Vec<Arg>>();
2502            if remaining.is_empty() {
2503                return Err(ParseError::validation(Command::AssertContains.as_str(), format!("{} requires a needle", Command::AssertContains.as_str()), &SpanContext::line_only(0)))
2504            }
2505            let needle = join_value(remaining, Command::AssertContains.as_str())?;
2506            Ok(StepKind::AssertContains { haystack, needle })
2507        },
2508    ],
2509
2510    Exit => [
2511        name: KEYWORD_EXIT,
2512        variant: Exit(Arg),
2513        syntax: "EXIT <code>",
2514        summary: "Exit pipeline.",
2515        description: indoc! {r#"
2516            Stops the pipeline immediately with an `EXIT requested with code <code>`
2517            error; steps after it never run, at any nesting depth.
2518
2519            Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state,
2520            anonymous background tasks are killed synchronously, and files written
2521            before the EXIT persist.
2522
2523            The code reaches the OS: the CLI exits with `<code>` clamped to
2524            0..=255, and a guest EXIT relays through `REMOTE` the same way.
2525        "#},
2526        args: &[ ArgSpec { name: "code", arg_type: ArgType::Int, description: "Code", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2527        flags: &[],
2528        default_output: None,
2529        examples: &[ Example { name: "exit", fence_meta: Some("expect_error:\"EXIT requested with code 0\""), code: indoc! {r#"EXIT 0"#} } ],
2530        lower: |_flags, args| {
2531            // Static literals were already Int-checked by the central
2532            // validator; dynamics resolve (and validate) at runtime.
2533            let code = args.into_iter().next().ok_or_else(|| ParseError::validation(KEYWORD_EXIT, "EXIT requires a code".to_string(), &SpanContext::line_only(0)))?;
2534            Ok(StepKind::Exit(code))
2535        },
2536    ],
2537
2538    Sleep => [
2539        name: KEYWORD_SLEEP,
2540        variant: Sleep { duration: Arg },
2541        syntax: "SLEEP <duration>",
2542        summary: "Pause execution for a duration.",
2543        description: indoc! {r#"
2544            Parks the step for the duration (e.g. 500ms, 10s, 2m).
2545
2546            Cooperative: checks for cancellation so an enclosing TIMEOUT or task
2547            teardown interrupts the sleep. Cross-platform alternative to shell sleep
2548            for testing time boundaries.
2549        "#},
2550        args: &[ ArgSpec { name: "duration", arg_type: ArgType::Duration, description: "How long to sleep", io: IoDirection::Write, index: 0, required: true, fallback_stream: None } ],
2551        flags: &[],
2552        default_output: None,
2553        examples: &[
2554            Example { name: "sleep", fence_meta: None, code: indoc! {r#"SLEEP 100ms"#} },
2555            Example {
2556                name: "sleep variable duration",
2557                fence_meta: None,
2558                code: indoc! {r#"
2559                # Durations resolve at runtime, so variables work too:
2560                # quoted or bare, both bind the same string.
2561                LET $pause: STRING = "100ms"
2562                SLEEP $pause
2563
2564                LET $bare: STRING = 100ms
2565                SLEEP $bare
2566            "#},
2567            },
2568        ],
2569        lower: |_flags, args| {
2570            let mut it = args.into_iter();
2571            let raw = it
2572                .next()
2573                .ok_or_else(|| ParseError::validation(KEYWORD_SLEEP, "SLEEP requires a duration (e.g. SLEEP 500ms)".to_string(), &SpanContext::line_only(0)))?;
2574            if it.next().is_some() {
2575                return Err(ParseError::validation(KEYWORD_SLEEP, "SLEEP takes exactly one duration argument".to_string(), &SpanContext::line_only(0)))
2576            }
2577            // Static literals were Duration-checked by the central
2578            // validator; dynamics ($var, templates) resolve at runtime.
2579            Ok(StepKind::Sleep { duration: raw })
2580        },
2581    ],
2582
2583    ListAppend => [
2584        name: KEYWORD_LIST_APPEND,
2585        variant: ListAppend { list: String, item: Arg },
2586        syntax: "LIST_APPEND $list <item>",
2587        summary: "Append an item to a LIST variable in place.",
2588        description: indoc! {r#"
2589            Appends the item to the LIST variable in place.
2590
2591            When the binding holds the only reference the push runs in
2592            amortized constant time. Aliased buffers detach first, so
2593            other holders keep their contents.
2594        "#},
2595        args: &[
2596            ArgSpec { name: "list", arg_type: ArgType::List, description: "Target LIST variable (`$name`)", io: IoDirection::Write, index: 0, required: true, fallback_stream: None },
2597            ArgSpec { name: "item", arg_type: ArgType::Any, description: "Item to append (any value)", io: IoDirection::Write, index: 1, required: true, fallback_stream: None },
2598        ],
2599        flags: &[],
2600        default_output: None,
2601        examples: &[ Example { name: "list append", fence_meta: None, code: indoc! {r#"
2602            # Appends accumulate in order.
2603            LET $items: LIST<STRING> = []
2604            LIST_APPEND $items "first"
2605            LIST_APPEND $items "second"
2606
2607            LET $want: LIST<STRING> = ["first", "second"]
2608            ASSERT_EQ $items $want
2609        "#} } ],
2610        lower: |_flags, args| {
2611            let mut it = args.into_iter();
2612            let raw_list = it
2613                .next()
2614                .ok_or_else(|| ParseError::validation(KEYWORD_LIST_APPEND, "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
2615            let list = match raw_list {
2616                Arg::Expr(Expr::Var(name)) => name,
2617                Arg::String(s, _) => s.trim_start_matches('$').to_string(),
2618                other => return Err(ParseError::validation(KEYWORD_LIST_APPEND, format!("LIST_APPEND requires a $variable, found {:?}", other), &SpanContext::line_only(0))),
2619            };
2620            if list.is_empty() {
2621                return Err(ParseError::validation(KEYWORD_LIST_APPEND, "LIST_APPEND requires a LIST variable (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))
2622            }
2623            let item = it
2624                .next()
2625                .ok_or_else(|| ParseError::validation(KEYWORD_LIST_APPEND, "LIST_APPEND requires an item to append (e.g. LIST_APPEND $items $x)".to_string(), &SpanContext::line_only(0)))?;
2626            if it.next().is_some() {
2627                return Err(ParseError::validation(KEYWORD_LIST_APPEND, "LIST_APPEND takes exactly two arguments: LIST_APPEND $list <item>".to_string(), &SpanContext::line_only(0)))
2628            }
2629            Ok(StepKind::ListAppend { list, item })
2630        },
2631    ],
2632}
2633
2634// ── Structural metadata ──────────────────────────────────────────────────
2635// Single source of truth for structural-statement documentation (TIMEOUT,
2636// ASYNC, AWAIT, WITH_IO, IF, FOR, ...). These constructs are parsed by PEG
2637// rules rather than `declare_commands!`, so their reference docs live here
2638// instead of `crates/docs-gen/src/command_ref.rs` : adding a structural
2639// StepKind without registering it here fails `structural_metadata_covers_all_structural_kinds`
2640// below, and oxdock-render renders these entries dynamically (no hardcoded copy).
2641pub fn all_structural_metadata() -> Vec<CommandMeta> {
2642    vec![
2643        CommandMeta {
2644            in_index: true,
2645            name: KEYWORD_WITH_IO,
2646            syntax: "WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...",
2647            summary: "Reroute standard streams.",
2648            description: indoc! {r#"
2649                Reroutes the standard streams of the next command or, in block form,
2650                of every enclosed command.
2651
2652                Bindings map streams (`stdin`, `stdout`, `stderr`) to a PIPE-typed
2653                variable (`stdout=$p`, `stdin=$p`), resolved from the variable
2654                when the step runs. Both stdout and stderr pipes capture output
2655                the same way. Declare the handle first with `LET $p: PIPE`.
2656
2657                A `RUN` step can opt into a pseudo-terminal with the bare `tty`
2658                flag instead of a new command: `WITH_IO [tty] RUN [...]`
2659                spawns the child under a pty sized from the host terminal
2660                when it names none (24x80 fallback off-terminal;
2661                `rows = <int>` / `cols = <int>` override each side).
2662                Unnamed sides track the host window while the step runs
2663                (signal-driven on Unix, polled where no window signal
2664                exists); explicit sides stay pinned.
2665
2666                The master carries the child's interleaved stdout and stderr
2667                as one stream, so it routes exclusively to `stdout` (step
2668                capture or a `stdout = $p` pipe): `stderr` bindings alongside
2669                `tty` are rejected, and `tty` outside a `RUN` step is
2670                rejected. Pty-backed descriptors never promote to OS
2671                kernel pipes, even inside `ASYNC` single-`RUN` bodies.
2672
2673                `stdin = $p` feeds the master; bare `[tty]`
2674                with a real terminal stdin feeds host keys the same
2675                way (raw, transparent) and stays closed headless. Host
2676                interrupt keys reach the child instead of cancelling the
2677                step, so bind a step `TIMEOUT` for a guaranteed exit.
2678
2679                Expect pty translation in assertions:
2680                newlines arrive as carriage return plus newline, and prompts
2681                echo input. On Windows, lone line feeds in fed input expand
2682                to carriage-return line feeds for console submission, so
2683                portable scripts need no per-platform line endings.
2684
2685                An input pipe that EOFs contributes a
2686                terminal-echoed end-of-transmission marker on some
2687                platforms: prefer `ASSERT_CONTAINS` over byte-exact
2688                assertions on fed sessions.
2689
2690                Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a
2691                producer can finish before the consumer starts.
2692
2693                If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or
2694                not, the pipe is a zero copy OS kernel pipe instead: pair it with a
2695                consumer that runs while the producer is alive, since output past the
2696                64 KiB kernel buffer stalls until drained. That promotion never crosses
2697                a function boundary: pipes created, bound, or passed by variable inside FUNC
2698                bodies are always script pipes, even when the surrounding task would
2699                otherwise promote.
2700
2701                A second producer or consumer on a live handle is an explicit
2702                error. A handle bound as output can later feed another
2703                command's `stdin`, connecting commands without touching the
2704                terminal. Binding `stdout` and `stderr` to the same live
2705                handle fails deterministically. Merge streams in shell
2706                via `2>&1` instead.
2707
2708                Nested blocks stack defaults; inline bindings override inherited ones for
2709                their command only; closing a block restores previous wiring.
2710            "#},
2711            args: &[],
2712            flags: &[],
2713            default_output: None,
2714            examples: &[
2715                Example {
2716                    name: "with_io block",
2717                    fence_meta: None,
2718                    code: indoc! {r#"
2719                LET $log: PIPE
2720                WITH_IO [stdout=$log] {
2721                  ECHO first
2722                  ECHO second
2723                }
2724                WITH_IO [stdin=$log] WRITE captured.txt
2725
2726                # The piped bytes landed in the file.
2727                LET $body: STRING = READ captured.txt
2728                ASSERT_CONTAINS $body "first"
2729                ASSERT_CONTAINS $body "second"
2730            "#},
2731                },
2732                Example {
2733                    name: "variable pipe binding",
2734                    fence_meta: None,
2735                    code: indoc! {r#"
2736                # Declare the pipe first: `LET $p: PIPE` mints a fresh
2737                # backend without touching a stream. A plain string here
2738                # would be a TypeMismatch.
2739                LET $p: PIPE
2740                WITH_IO [stdout=$p] ECHO hello
2741                WITH_IO [stdin=$p] READ_LINE $line
2742                ASSERT_EQ $line "hello"
2743            "#},
2744                },
2745                Example {
2746                    name: "pty terminal binding",
2747                    fence_meta: None,
2748                    code: indoc! {r#"
2749                # A RUN step under bare `tty` sees a terminal: newlines
2750                # arrive translated, so assert with CONTAINS, never EQ.
2751                LET $p: PIPE
2752                WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
2753                WITH_IO [stdin=$p] READ_LINE $line
2754                ASSERT_CONTAINS $line "hello-tty"
2755            "#},
2756                },
2757            ],
2758        },
2759        CommandMeta {
2760            in_index: true,
2761            name: KEYWORD_FOR,
2762            syntax: "FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }",
2763            summary: "Iterate over a list or map.",
2764            description: indoc! {r#"
2765                The loop variable receives each element (lists) or value (maps); with
2766                two variables, the first receives the key.
2767
2768                Loop variables are declared with explicit types and scoped per iteration;
2769                they do not leak outward. The body may be a braced block
2770                or a single-line `{ ... }` command.
2771
2772                `GLOB("...")` patterns must be quoted (`*` is not a bare word, so
2773                `GLOB(*)` is a parse error); GLOB returns a root-relative sorted list,
2774                empty when nothing matches, and rejects `..` escapes.
2775            "#},
2776            args: &[],
2777            flags: &[],
2778            default_output: None,
2779            examples: &[
2780                Example {
2781                    name: "for loop",
2782                    fence_meta: None,
2783                    code: indoc! {r#"
2784                # Each element binds in turn; the loop body sees every one.
2785                LET $items: LIST<STRING> = ["a", "b"]
2786                FOR $item: STRING IN $items {
2787                  ECHO $item
2788                }
2789                ASSERT_CONTAINS stdout "a"
2790                ASSERT_CONTAINS stdout "b"
2791
2792                # Key and value bind together for maps.
2793                LET $map: MAP<x: INT> = {"x": 1}
2794                FOR $k: STRING, $v: INT IN $map {
2795                  ECHO "{{ $k }}={{ $v }}"
2796                }
2797                ASSERT_CONTAINS stdout "x=1"
2798            "#},
2799                },
2800                Example {
2801                    name: "expand every match",
2802                    fence_meta: None,
2803                    code: indoc! {r#"
2804                # Single-line body; $x is a template path, WHO an override.
2805                IMPORT [STD]
2806                WRITE a.txt "hi \{{ env:WHO }}!"
2807                FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
2808
2809                ASSERT_CONTAINS stdout "hi World!"
2810            "#},
2811                },
2812            ],
2813        },
2814        CommandMeta {
2815            in_index: true,
2816            name: KEYWORD_IF,
2817            syntax: "IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]",
2818            summary: "Conditional execution.",
2819            description: indoc! {r#"
2820                The condition is evaluated as a boolean expression.
2821
2822                Prefix `!` negates (`IF !false`); `&&` binds tighter than
2823                `||`, and both short-circuit, so `IF true || $missing`
2824                never evaluates the right side. Only Bool values are
2825                accepted as conditions.
2826            "#},
2827            args: &[],
2828            flags: &[],
2829            default_output: None,
2830            examples: &[
2831                Example {
2832                    name: "if else",
2833                    fence_meta: None,
2834                    code: indoc! {r#"
2835                IMPORT [STD]
2836
2837                # True branch runs; the false branch is skipped.
2838                IF true {
2839                  WRITE yes.txt taken
2840                } ELSE {
2841                  WRITE yes.txt skipped
2842                }
2843
2844                # ELSE IF selects the first true branch.
2845                IF false {
2846                  WRITE skipped.txt no
2847                } ELSE IF true {
2848                  WRITE fallback.txt taken
2849                }
2850
2851                # !false evaluates to true, so this branch runs.
2852                IF !false {
2853                  WRITE negated.txt taken
2854                }
2855
2856                LET $yes_body: STRING = READ yes.txt
2857                LET $fallback_body: STRING = READ fallback.txt
2858                LET $negated_body: STRING = READ negated.txt
2859                ASSERT_EQ $yes_body "taken"
2860                ASSERT_EQ $fallback_body "taken"
2861                ASSERT_EQ $negated_body "taken"
2862                LET $t: STRING = PATH_TYPE("skipped.txt")
2863                ASSERT_EQ $t "absent"
2864            "#},
2865                },
2866                Example {
2867                    name: "logical condition combination",
2868                    fence_meta: None,
2869                    code: indoc! {r#"
2870                IMPORT [STD]
2871                LET $role: STRING = "admin"
2872                LET $level: INT = 3
2873
2874                # || is true when either side holds; && needs both.
2875                IF $role == "owner" || $level >= 5 {
2876                    WRITE unexpected.txt no
2877                } ELSE {
2878                    WRITE fallback.txt or-false
2879                }
2880
2881                LET $fb: STRING = READ fallback.txt
2882                ASSERT_EQ $fb "or-false"
2883                LET $t1: STRING = PATH_TYPE("unexpected.txt")
2884                ASSERT_EQ $t1 "absent"
2885
2886                IF $role == "admin" || $level >= 5 {
2887                    WRITE chosen.txt or-true
2888                }
2889
2890                LET $ch: STRING = READ chosen.txt
2891                ASSERT_EQ $ch "or-true"
2892
2893                IF $role == "admin" && $level >= 5 {
2894                    WRITE unexpected-too.txt no
2895                } ELSE {
2896                    WRITE and.txt and-false
2897                }
2898
2899                LET $an: STRING = READ and.txt
2900                ASSERT_EQ $an "and-false"
2901                LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
2902                ASSERT_EQ $t2 "absent"
2903            "#},
2904                },
2905            ],
2906        },
2907        CommandMeta {
2908            in_index: true,
2909            name: KEYWORD_SWITCH,
2910            syntax: "SWITCH [<expr>] { CASE <expr>[, <expr> ...] { <commands> } ... [DEFAULT { <commands> }] }",
2911            summary: "Multi-way branch on a value or a condition list.",
2912            description: indoc! {r#"
2913                Compares one discriminant against each `CASE` value list in
2914                order with strict `==` (same rule as `IF` conditions:
2915                numerics compare across `INT` and `FLOAT`, every other
2916                cross-type pair is unequal). The first matching arm runs
2917                exclusively: later arms never run and there is no
2918                fallthrough, so group values with commas
2919                (`CASE "help", "h"`) instead of stacking bodies.
2920
2921                With no discriminant (`SWITCH { ... }`), each `CASE`
2922                carries its own boolean condition (a call counts: any
2923                expression evaluating to `BOOL`), and the first true arm
2924                runs. Conditions evaluate in order and stop at the first
2925                match, so later calls never run. A final `DEFAULT` arm
2926                runs when nothing matched; without one, no match is a
2927                no-op.
2928
2929                `BREAK` exits the `SWITCH` early (the remainder of the arm
2930                is skipped and an enclosing loop is unaffected); `CONTINUE`
2931                continues an enclosing loop; `RETURN` and `EXIT` propagate
2932                as usual.
2933            "#},
2934            args: &[],
2935            flags: &[],
2936            default_output: None,
2937            examples: &[
2938                Example {
2939                    name: "switch on a value",
2940                    fence_meta: None,
2941                    code: indoc! {r#"
2942                # The first arm whose value list contains the discriminant
2943                # runs; no later arm runs.
2944                LET $cmd: STRING = "help"
2945                SWITCH $cmd {
2946                  CASE "help", "h" {
2947                    WRITE chosen.txt help
2948                  }
2949                  CASE "summarize" {
2950                    WRITE chosen.txt summarize
2951                  }
2952                  DEFAULT {
2953                    WRITE chosen.txt fallback
2954                  }
2955                }
2956
2957                LET $body: STRING = READ chosen.txt
2958                ASSERT_EQ $body "help"
2959            "#},
2960                },
2961                Example {
2962                    name: "switch on conditions",
2963                    fence_meta: None,
2964                    code: indoc! {r#"
2965                # With no discriminant each CASE is its own condition;
2966                # calls work as conditions too.
2967                LET $n: INT = 2
2968                SWITCH {
2969                  CASE $n > 5 {
2970                    WRITE band.txt high
2971                  }
2972                  CASE $n > 1 {
2973                    WRITE band.txt mid
2974                  }
2975                  DEFAULT {
2976                    WRITE band.txt low
2977                  }
2978                }
2979
2980                LET $band: STRING = READ band.txt
2981                ASSERT_EQ $band "mid"
2982            "#},
2983                },
2984                Example {
2985                    name: "break and continue inside switch",
2986                    fence_meta: None,
2987                    code: indoc! {r#"
2988                # BREAK exits the SWITCH early: the trailing ECHO and
2989                # EXIT 1 never run, so reaching them would print a
2990                # marker and fail the script.
2991                # CONTINUE passes through to the enclosing loop.
2992                LET $items: LIST<STRING> = ["a", "skip", "b"]
2993                FOR $item: STRING IN $items {
2994                  SWITCH $item {
2995                    CASE "skip" {
2996                      CONTINUE
2997                    }
2998                    CASE "a" {
2999                      ECHO saw-a
3000                      BREAK
3001                      ECHO unreachable
3002                      EXIT 1
3003                    }
3004                    DEFAULT {
3005                      ECHO saw-other
3006                    }
3007                  }
3008                }
3009
3010                ASSERT_CONTAINS stdout "saw-a"
3011                ASSERT_CONTAINS stdout "saw-other"
3012            "#},
3013                },
3014                Example {
3015                    name: "switch arms with nested loops",
3016                    fence_meta: None,
3017                    code: indoc! {r#"
3018                # Loops nested in arms obey the innermost rule: inner
3019                # BREAK ends only the inner FOR, inner CONTINUE skips
3020                # only its iteration, and the arm keeps running past both.
3021                LET $hits: LIST<STRING> = []
3022                SWITCH "b" {
3023                  CASE "b" {
3024                    FOR $o: STRING IN ["x", "y"] {
3025                      FOR $i: INT IN [1, 2, 3] {
3026                        IF $i == 2 {
3027                          BREAK
3028                        }
3029                        LIST_APPEND $hits "b{{ $o }}{{ $i }}"
3030                      }
3031                    }
3032                    LIST_APPEND $hits "b-after"
3033                  }
3034                  DEFAULT {
3035                    LIST_APPEND $hits "b-wrong"
3036                  }
3037                }
3038
3039                SWITCH "c" {
3040                  CASE "c" {
3041                    FOR $o: STRING IN ["x", "y"] {
3042                      FOR $i: INT IN [1, 2, 3] {
3043                        IF $i == 2 {
3044                          CONTINUE
3045                        }
3046                        LIST_APPEND $hits "c{{ $o }}{{ $i }}"
3047                      }
3048                    }
3049                    LIST_APPEND $hits "c-after"
3050                  }
3051                  DEFAULT {
3052                    LIST_APPEND $hits "c-wrong"
3053                  }
3054                }
3055
3056                LET $want: LIST<STRING> = ["bx1", "by1", "b-after", "cx1", "cx3", "cy1", "cy3", "c-after"]
3057                ASSERT_EQ $hits $want
3058            "#},
3059                },
3060                Example {
3061                    name: "overlapping arms run first match only",
3062                    fence_meta: None,
3063                    code: indoc! {r#"
3064                # Overlapping arms never both run: the first match wins,
3065                # so order arms most specific first. There is no
3066                # fallthrough to the next CASE; CONTINUE would continue
3067                # an enclosing loop, not advance to the next arm.
3068                LET $n: INT = 10
3069                SWITCH {
3070                  CASE $n > 1 {
3071                    WRITE band.txt wide
3072                  }
3073                  CASE $n > 5 {
3074                    WRITE band.txt narrow
3075                  }
3076                  DEFAULT {
3077                    WRITE band.txt low
3078                  }
3079                }
3080
3081                LET $band: STRING = READ band.txt
3082                ASSERT_EQ $band "wide"
3083            "#},
3084                },
3085                Example {
3086                    name: "no fallthrough without break",
3087                    fence_meta: None,
3088                    code: indoc! {r#"
3089                # C falls through without break: this SWITCH does not.
3090                # One value matches two arms and neither uses BREAK,
3091                # yet only the first arm runs.
3092                LET $hits: LIST<STRING> = []
3093                SWITCH 1 {
3094                  CASE 1 {
3095                    LIST_APPEND $hits "first"
3096                  }
3097                  CASE 1 {
3098                    LIST_APPEND $hits "second"
3099                  }
3100                  DEFAULT {
3101                    LIST_APPEND $hits "default"
3102                  }
3103                }
3104
3105                LET $want: LIST<STRING> = ["first"]
3106                ASSERT_EQ $hits $want
3107            "#},
3108                },
3109                Example {
3110                    name: "continue never advances to the next arm",
3111                    fence_meta: None,
3112                    code: indoc! {r#"
3113                # 3 satisfies both CASE conditions, but only the first matching
3114                # arm runs. CONTINUE then jumps straight to the next loop
3115                # iteration: skipping both "small-unreached" in the arm and
3116                # "after" in the loop body (whereas BREAK would only exit the
3117                # SWITCH and still run "after").
3118                IMPORT [STD]
3119                LET $hits: LIST<STRING> = []
3120                FOR $n: INT IN [3] {
3121                  SWITCH {
3122                    CASE $n < 5 {
3123                      LIST_APPEND $hits "small"
3124                      CONTINUE
3125                      LIST_APPEND $hits "small-unreached"
3126                    }
3127                    CASE $n < 10 {
3128                      LIST_APPEND $hits "mid"
3129                    }
3130                  }
3131                  LIST_APPEND $hits "after"
3132                }
3133
3134                LET $want: LIST<STRING> = ["small"]
3135                ASSERT_EQ $hits $want
3136
3137                # Exactly one append ran: neither the rest of the arm
3138                # ("small-unreached"), the also-matching second arm
3139                # ("mid"), nor the trailing step ("after") executed.
3140                LET $count: INT = LEN($hits)
3141                ASSERT_EQ $count 1
3142            "#},
3143                },
3144                Example {
3145                    name: "strict equality, not C coercion",
3146                    fence_meta: None,
3147                    code: indoc! {r#"
3148                # No C-style coercion: STRING "1" never equals INT 1.
3149                # Numerics still compare across INT and FLOAT.
3150                LET $hits: LIST<STRING> = []
3151                SWITCH "1" {
3152                  CASE 1 {
3153                    LIST_APPEND $hits "coerced"
3154                  }
3155                  DEFAULT {
3156                    LIST_APPEND $hits "no-coercion"
3157                  }
3158                }
3159
3160                SWITCH 2 {
3161                  CASE 2.0 {
3162                    LIST_APPEND $hits "numeric-match"
3163                  }
3164                  DEFAULT {
3165                    LIST_APPEND $hits "numeric-miss"
3166                  }
3167                }
3168
3169                LET $want: LIST<STRING> = ["no-coercion", "numeric-match"]
3170                ASSERT_EQ $hits $want
3171            "#},
3172                },
3173                Example {
3174                    name: "later conditions never evaluate",
3175                    fence_meta: None,
3176                    code: indoc! {r#"
3177                # Each CASE without a discriminant is a call, and calls
3178                # stop at the first true arm. PROBE writes a marker, so
3179                # its absence proves it never ran.
3180                IMPORT [STD]
3181                FUNC PROBE($v: BOOL): BOOL {
3182                  WRITE probed.txt hit
3183                  RETURN $v
3184                }
3185                LET $n: INT = 2
3186                SWITCH {
3187                  CASE $n > 1 {
3188                    WRITE band.txt mid
3189                  }
3190                  CASE PROBE(true) {
3191                    WRITE band.txt probed
3192                  }
3193                  DEFAULT {
3194                    WRITE band.txt low
3195                  }
3196                }
3197
3198                LET $band: STRING = READ band.txt
3199                ASSERT_EQ $band "mid"
3200                LET $t: STRING = PATH_TYPE("probed.txt")
3201                ASSERT_EQ $t "absent"
3202            "#},
3203                },
3204                Example {
3205                    name: "no match without default is a no-op",
3206                    fence_meta: None,
3207                    code: indoc! {r#"
3208                # No arm matches and no DEFAULT: nothing runs and nothing
3209                # fails, so the write never happens.
3210                IMPORT [STD]
3211                SWITCH "zzz" {
3212                  CASE "a" {
3213                    WRITE picked.txt a
3214                  }
3215                  CASE "b" {
3216                    WRITE picked.txt b
3217                  }
3218                }
3219
3220                LET $t: STRING = PATH_TYPE("picked.txt")
3221                ASSERT_EQ $t "absent"
3222            "#},
3223                },
3224            ],
3225        },
3226        CommandMeta {
3227            in_index: true,
3228            name: KEYWORD_LET,
3229            syntax: "LET $var: TYPE = <expr> | LET $p: PIPE | LET $var: TYPE = ASYNC { <commands> } | LET $var: TYPE = <command> | LET $var: TYPE = AWAIT $task | LET $var: TYPE = { <commands> }",
3230            summary: "Bind script-local variables.",
3231            description: indoc! {r#"
3232                Declares a script-local variable with an explicit type (STRING, INT,
3233                FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
3234                in the same scope frame is a redeclaration error; mutate with
3235                `$var = <expr>`.
3236
3237                Variables are usable in templates (`{{ $var }}`), guards, and
3238                expressions. With `ASYNC`, spawns a background task and stores its
3239                handle (see ASYNC). The `$` sigil on the name is mandatory.
3240
3241                No hoisting: a variable exists only after its LET runs, in
3242                execution order. Reading `$var` before its LET (or after the
3243                block that declared it exits) fails with
3244                `undefined variable $var`. Scopes are a stack of frames and
3245                resolution walks innermost outward, so nothing pre-declares
3246                names. Function bodies read outer variables through the same
3247                walk, but their own LETs never leak out (see FUNC).
3248
3249                The right-hand side is always an expression — literals, lists, maps,
3250                arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
3251                parentheses), comparisons (`< <= > >=` binding tighter than
3252                `== !=`), logical `&&` (tighter) and `||` with short-circuit,
3253                `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
3254                `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
3255                `{{ ... }}` template; interpolation happens in string values,
3256                not here.
3257                The one exception is pipes: `LET $p: PIPE` with no `=`
3258                and no initializer mints a fresh anonymous backend,
3259                lazily materialized at first binding, so two declarations
3260                never share a channel.
3261
3262                Numbers are numeric literals: `42` binds `INT`, `3.14` binds
3263                `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
3264                so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
3265                Division by zero, overflow, and non-finite results are errors.
3266                Both numeric sides compare numerically (`1 == 1.0` is true);
3267                otherwise `==`/`!=` are strict (cross-type words are unequal,
3268                so `"true" == true` is false) and ordering on
3269                non-numerics is a Type Error. Constant subtrees fold at parse
3270                time and dynamic arithmetic compiles to flat RPN with
3271                identical semantics.
3272
3273                Float equality is exact with no epsilon. Floats store decimals
3274                in binary, so a value is exact only when its reduced fraction
3275                has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
3276                (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
3277                repeat forever in binary (like 1/3 in decimal) and truncate,
3278                so `0.1 + 0.2 == 0.3` is false (the sum is
3279                `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
3280                .125, .625, .875 are exact; .1, .2, .3 and similar are
3281                approximations. Bound approximations instead of comparing
3282                them: `IF $sum > 0.299999 && $sum < 0.300001`.
3283
3284                Comparisons do not chain: `a < b < c` is a parse error, not
3285                `(a < b) < c`. Chaining would compare a `BOOL` against a
3286                number (a runtime Type Error in C-style parsing) or evaluate
3287                the middle term twice (Python-style chaining), so the grammar
3288                accepts exactly one comparison operator per level. Write the
3289                conjunction explicitly: `$a < $b && $b < $c`. The same holds
3290                for equality (`$a == $b == $c` is rejected).
3291
3292                Captured command output is a string, so convert before math:
3293                `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
3294                whitespace; `FLOAT` accepts int strings and rejects
3295                non-finite).
3296
3297                Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
3298                as quoted.
3299
3300                When the right-hand side is a synchronous command
3301                (`LET $out: STRING = ECHO hi`), the command runs to completion and its
3302                exact stdout bytes are captured into the variable as a string (no newline
3303                stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
3304                an error). Combining capture with an explicit
3305                `WITH_IO [stdout=$var]` is a parse error.
3306
3307                Coming from Bash, the capture line looks familiar but behaves
3308                strictly:
3309
3310                | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
3311                | --- | --- | --- |
3312                | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
3313                | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
3314                | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
3315                | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
3316
3317                `LET $out: TYPE = AWAIT $var` binds the background task's
3318                explicit `RETURN` value instead (tasks stream their stdout
3319                live, so there is no output left to capture); a task that
3320                succeeded without `RETURN` yields `INT` 0, like a process
3321                exit status.
3322
3323                An inline block (`LET $var: TYPE = { <commands> }`) runs its
3324                steps in a fresh scope and binds the nearest `RETURN` value,
3325                like a zero-arg function body: fallthrough without `RETURN`
3326                binds `""`, and `BREAK`/`CONTINUE` escaping the block are
3327                errors. Think IIFE: the block executes immediately where it
3328                stands and its value is the result. The block reads outer
3329                variables but its own LETs never leak out. A `{k: v}` shape
3330                still parses as a map literal; anything else in braces is
3331                a block.
3332
3333                The split is deliberate: synchronous commands capture
3334                stdout because they run inline to completion on the same
3335                thread; background tasks never capture stdout because
3336                concurrent output has no well-defined value. Task results
3337                travel only through `RETURN` (or `INT` 0 for void tasks).
3338
3339                `LET $e: STRING = env:FOO` reads the script environment into a plain
3340                string.
3341            "#},
3342            args: &[],
3343            flags: &[],
3344            default_output: None,
3345            examples: &[
3346                Example {
3347                    name: "let",
3348                    fence_meta: None,
3349                    code: indoc! {r#"
3350                LET $name: STRING = "world"
3351                ECHO "hello, {{ $name }}"
3352                ASSERT_CONTAINS stdout "hello, world"
3353
3354                LET $items: LIST<STRING> = ["a", "b"]
3355                ASSERT_CONTAINS $items "a"
3356                ASSERT_CONTAINS $items "b"
3357
3358                LET $count: INT = 42
3359                ASSERT_EQ $count 42
3360            "#},
3361                },
3362                Example {
3363                    name: "bool coercion",
3364                    fence_meta: None,
3365                    code: indoc! {r#"
3366                # BOOL spellings coerce case-insensitively. Empty is
3367                # not a boolean: absent flags state a default through
3368                # BOOL_OR instead of converting here.
3369                LET $t: BOOL = "TRUE"
3370                ASSERT_EQ $t true
3371                LET $f: BOOL = "no"
3372                ASSERT_EQ $f false
3373            "#},
3374                },
3375                Example {
3376                    name: "bool coercion rejects empty",
3377                    fence_meta: Some("expect_error:\"expected BOOL\""),
3378                    code: indoc! {r#"
3379                # Empty never reads as false: an empty string fails
3380                # BOOL coercion instead of picking a polarity.
3381                ENV EMPTY_FLAG=""
3382                LET $e: BOOL = "{{ env:EMPTY_FLAG }}"
3383            "#},
3384                },
3385                Example {
3386                    name: "no hoisting",
3387                    fence_meta: Some("expect_error:\"undefined variable\""),
3388                    code: indoc! {r#"
3389                # Reading before the LET runs is an error, not an empty value.
3390                ECHO $too_early
3391                LET $too_early: STRING = "too late"
3392            "#},
3393                },
3394                Example {
3395                    name: "glob binding",
3396                    fence_meta: None,
3397                    code: indoc! {r#"
3398                # The RHS is an expression: GLOB(...) runs and binds a list.
3399                IMPORT [STD]
3400                WRITE a.txt "x"
3401                LET $files: LIST<STRING> = GLOB("*.txt")
3402                FOR $f: STRING IN $files { ECHO $f }
3403
3404                ASSERT_CONTAINS stdout "a.txt"
3405            "#},
3406                },
3407                Example {
3408                    name: "scoped variable reverts",
3409                    fence_meta: None,
3410                    code: indoc! {r#"
3411                # LET inside a braced block reverts when the block exits.
3412                LET $a: STRING = "outer"
3413
3414                [bool:true] {
3415                    LET $a: STRING = "inner"
3416                    WRITE inner.txt "{{ $a }}"
3417                }
3418
3419                WRITE outer.txt "{{ $a }}"
3420
3421                LET $in_body: STRING = READ inner.txt
3422                ASSERT_EQ $in_body "inner"
3423
3424                LET $out_body: STRING = READ outer.txt
3425                ASSERT_EQ $out_body "outer"
3426            "#},
3427                },
3428                Example {
3429                    name: "capture command output",
3430                    fence_meta: None,
3431                    code: indoc! {r#"
3432                # Capture keeps the trailing newline.
3433                LET $out: STRING = ECHO hi
3434                ASSERT_EQ $out "hi\n"
3435            "#},
3436                },
3437                Example {
3438                    name: "inline block",
3439                    fence_meta: None,
3440                    code: indoc! {r#"
3441                LET $who: STRING = "ada"
3442
3443                # An inline block binds its RETURN value like a function body.
3444                LET $res: STRING = {
3445                    LET $loud: STRING = "{{ $who }}!"
3446                    RETURN $loud
3447                }
3448                ASSERT_EQ $res "ada!"
3449
3450                # Any declared type works: the block value checks like any RHS.
3451                LET $n: INT = {
3452                    RETURN 40 + 2
3453                }
3454                ASSERT_EQ $n 42
3455            "#},
3456                },
3457                Example {
3458                    name: "arithmetic over captured output",
3459                    fence_meta: None,
3460                    code: indoc! {r#"
3461                # Captured output converts explicitly: INT() then arithmetic.
3462                IMPORT [STD]
3463                LET $size_str: STRING = ECHO 41
3464                LET $total: INT = INT($size_str) + 1
3465                ASSERT_EQ $total 42
3466
3467                # FLOAT() promotes instead of truncating.
3468                LET $ratio: FLOAT = 1 + 2.5
3469                ASSERT_EQ $ratio 3.5
3470
3471                # Int x Int stays INT: integer division truncates.
3472                LET $half: INT = 7 / 2
3473                ASSERT_EQ $half 3
3474            "#},
3475                },
3476                Example {
3477                    name: "float equality is exact",
3478                    fence_meta: None,
3479                    code: indoc! {r#"
3480                # Binary fractions compare cleanly; decimal fractions may not:
3481                # 0.1 + 0.2 is 0.30000000000000004, so == is false.
3482                IMPORT [STD]
3483                LET $exact: BOOL = 0.5 + 0.25 == 0.75
3484                LET $decimal: BOOL = 0.1 + 0.2 == 0.3
3485                IF $exact {
3486                    WRITE exact.txt yes
3487                }
3488                IF $decimal {
3489                    WRITE unexpected.txt no
3490                }
3491
3492                LET $ok: STRING = READ exact.txt
3493                ASSERT_EQ $ok "yes"
3494
3495                LET $t: STRING = PATH_TYPE("unexpected.txt")
3496                ASSERT_EQ $t "absent"
3497            "#},
3498                },
3499                Example {
3500                    name: "bound inexact decimals",
3501                    fence_meta: None,
3502                    code: indoc! {r#"
3503                # Never test inexact decimals for equality; bound them.
3504                LET $sum: FLOAT = 0.1 + 0.2
3505                IF $sum > 0.299999 && $sum < 0.300001 {
3506                    WRITE bounded.txt yes
3507                }
3508
3509                LET $ok: STRING = READ bounded.txt
3510                ASSERT_EQ $ok "yes"
3511            "#},
3512                },
3513                Example {
3514                    name: "inspect a variable",
3515                    fence_meta: None,
3516                    code: indoc! {r#"
3517                # INSPECT($var) snapshots a variable into a MAP: declared
3518                # type plus live details (pipe backend stats here), so
3519                # scripts can branch on engine state.
3520                IMPORT [STD]
3521                LET $p: PIPE
3522                WITH_IO [stdout=$p] ECHO hello
3523                LET $info: MAP<ANY> = INSPECT($p)
3524                IF $info.is_os_pipe {
3525                    WRITE unexpected.txt "should be a script pipe"
3526                }
3527
3528                ASSERT_EQ $info.type "PIPE"
3529                LET $t: STRING = PATH_TYPE("unexpected.txt")
3530                ASSERT_EQ $t "absent"
3531            "#},
3532                },
3533            ],
3534        },
3535        CommandMeta {
3536            // `MUTATION` is not an actual keyword, so don't index it as such.
3537            in_index: false,
3538            name: "MUTATION",
3539            syntax: "$var = <expr>",
3540            summary: "Mutate a declared variable.",
3541            description: indoc! {r#"
3542                Reassigns an existing variable, converting the new value to
3543                the type declared at LET time through the same narrow
3544                coercion pairs as declaration. Strings never parse to
3545                numbers implicitly: `$n = "42"` is a TypeMismatch for an
3546                INT, write `$n = INT("42")` instead.
3547                Expressions never convert: `"100" + 1` is a Type Error, use
3548                `INT()` / `FLOAT()` to cross that boundary explicitly.
3549
3550                The leading `$` distinguishes mutation from `KEY=value` command
3551                assignments. Assigning an undeclared variable or a mismatched type is
3552                an error.
3553
3554                Mutation writes through to the scope where the variable was
3555                declared, so it survives block exit: `LET $x` outside a block
3556                followed by `$x = ...` inside still reads back the new value
3557                afterwards, for every type. This is the counterpart to LET
3558                shadowing, where `LET $x` *inside* the block declares a
3559                separate inner variable that reverts on exit.
3560
3561                Reassignment rebinds the variable to a new value: values
3562                captured earlier keep the old word (see the rebinding
3563                example below).
3564            "#},
3565            args: &[],
3566            flags: &[],
3567            default_output: None,
3568            examples: &[
3569                Example {
3570                    name: "mutate",
3571                    fence_meta: None,
3572                    code: indoc! {r#"
3573                # Mutation writes through: the binding holds the new value.
3574                LET $count: INT = 1
3575                $count = 2
3576                ASSERT_EQ $count 2
3577            "#},
3578                },
3579                Example {
3580                    name: "rebind keeps earlier captures",
3581                    fence_meta: None,
3582                    code: indoc! {r#"
3583                # Reassignment rebinds: a map built from `$s` still
3584                # reads the original string after `$s` moves on.
3585                LET $s: STRING = "test"
3586                LET $m: MAP<ANY> = {a: $s}
3587                $s = "changed"
3588                ASSERT_EQ $m.a "test"
3589
3590                # Appending to one list binding never touches its clones.
3591                LET $a: LIST<STRING> = ["1"]
3592                LET $b: LIST<STRING> = $a
3593                LIST_APPEND $a "2"
3594                LET $want: LIST<STRING> = ["1"]
3595                ASSERT_EQ $b $want
3596            "#},
3597                },
3598                Example {
3599                    name: "convert before math",
3600                    fence_meta: None,
3601                    code: indoc! {r#"
3602                # Captured output is a string: `"100" + 1` is a Type Error.
3603                # Convert explicitly, then mutate with arithmetic.
3604                IMPORT [STD]
3605                LET $raw: STRING = ECHO 100
3606                LET $n: INT = INT($raw)
3607                $n = $n + 1
3608
3609                # The declared slot stays strict: strings parse only
3610                # through the explicit converter, never on assignment.
3611                $n = INT("42")
3612                ASSERT_EQ $n 42
3613
3614                # Same crossing for decimals via FLOAT().
3615                LET $frac_str: STRING = ECHO 2.5
3616                LET $f: FLOAT = FLOAT($frac_str) + 0.25
3617                ASSERT_EQ $f 2.75
3618            "#},
3619                },
3620            ],
3621        },
3622        CommandMeta {
3623            in_index: true,
3624            name: KEYWORD_ASYNC,
3625            syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE<T> = ASYNC { <commands> }",
3626            summary: "Run steps in a background thread.",
3627            description: indoc! {r#"
3628                Runs a command or block of commands in a background thread with
3629                subshell isolation.
3630
3631                Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
3632                task handle for `AWAIT`. Task output streams live to the parent
3633                stdout; a task publishes a value with an explicit `RETURN`,
3634                which `LET $out: TYPE = AWAIT $task` binds.
3635
3636                `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
3637                then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
3638                the main thread before the worker spawns. Placing `WITH_IO` directly
3639                inside `ASYNC` is rejected at parse time.
3640            "#},
3641            args: &[],
3642            flags: &[],
3643            default_output: None,
3644            examples: &[
3645                Example {
3646                    name: "async",
3647                    fence_meta: None,
3648                    code: indoc! {r#"
3649                # Inline and block forms both run in the background; AWAIT joins them.
3650                ASYNC ECHO "warming-up"
3651                LET $a: HANDLE<VOID> = ASYNC ECHO "first"
3652                LET $b: HANDLE<VOID> = ASYNC {
3653                    ECHO "second"
3654                }
3655                AWAIT $a
3656                AWAIT $b
3657                ASSERT_CONTAINS stdout "first"
3658                ASSERT_CONTAINS stdout "second"
3659                "#},
3660                },
3661                Example {
3662                    name: "async task handle",
3663                    fence_meta: None,
3664                    code: indoc! {r#"
3665                    LET $task: HANDLE<VOID> = ASYNC {
3666                        ECHO "built"
3667                    }
3668                    AWAIT $task
3669                    ASSERT_CONTAINS stdout "built"
3670                "#},
3671                },
3672            ],
3673        },
3674        CommandMeta {
3675            in_index: true,
3676            name: KEYWORD_AWAIT,
3677            syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
3678            summary: "Join a background task.",
3679            description: indoc! {r#"
3680                Blocks until the named task completes. Propagates errors if the task failed.
3681
3682                Task output streams live during the run; joining binds nothing by
3683                itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
3684                `RETURN` value instead, or `INT` 0 when the task succeeded
3685                without one (add `RETURN <expr>` to the task body to yield
3686                a value).
3687            "#},
3688            args: &[],
3689            flags: &[],
3690            default_output: None,
3691            examples: &[
3692                Example {
3693                    name: "await",
3694                    fence_meta: None,
3695                    code: indoc! {r#"
3696                LET $task: HANDLE<VOID> = ASYNC ECHO "done"
3697                AWAIT $task
3698                ASSERT_CONTAINS stdout "done"
3699            "#},
3700                },
3701                Example {
3702                    name: "await capture",
3703                    fence_meta: None,
3704                    code: indoc! {r#"
3705                LET $task: HANDLE<STRING> = ASYNC {
3706                    ECHO "logged"
3707                    RETURN "returned"
3708                }
3709
3710                # AWAIT binds the RETURN value, not the streamed output.
3711                LET $out: STRING = AWAIT $task
3712                ASSERT_EQ $out "returned"
3713            "#},
3714                },
3715            ],
3716        },
3717        CommandMeta {
3718            in_index: true,
3719            name: KEYWORD_CANCEL,
3720            syntax: "CANCEL $var",
3721            summary: "Synchronously cancel a background task.",
3722            description: indoc! {r#"
3723                Kills the named background task spawned via `LET $var: HANDLE<T> = ASYNC ...`.
3724
3725                Blocking: returns only after the task thread has been joined and its OS
3726                process reaped, so no residual filesystem or stream mutation follows. A
3727                later AWAIT $var reports cancellation. Only named tasks can be cancelled.
3728            "#},
3729            args: &[],
3730            flags: &[],
3731            default_output: None,
3732            examples: &[
3733                Example {
3734                    name: "cancel",
3735                    fence_meta: None,
3736                    code: indoc! {r#"
3737                LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
3738                CANCEL $task
3739            "#},
3740                },
3741                Example {
3742                    name: "await after cancel reports cancellation",
3743                    fence_meta: Some("expect_error:\"was cancelled\""),
3744                    code: indoc! {r#"
3745                # A cancelled task stays cancelled: joining it reports.
3746                LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
3747                CANCEL $task
3748                AWAIT $task
3749            "#},
3750                },
3751            ],
3752        },
3753        CommandMeta {
3754            in_index: true,
3755            name: KEYWORD_TIMEOUT,
3756            syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
3757            summary: "Enforce an execution deadline.",
3758            description: indoc! {r#"
3759                Aborts the wrapped step or block with a deadline error if it exceeds the
3760                duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
3761
3762                A blocking foreground process is killed.
3763
3764                ASYNC nests in either order with order-dependent deadline
3765                semantics: `LET $task: HANDLE<VOID> = ASYNC TIMEOUT 30s RUN "build"` enforces
3766                the deadline inside the background thread (a later `AWAIT $task`
3767                surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
3768                preempts a hung task from the awaiting side.
3769            "#},
3770            args: &[],
3771            flags: &[],
3772            default_output: None,
3773            examples: &[
3774                Example {
3775                    name: "timeout",
3776                    fence_meta: None,
3777                    code: indoc! {r#"
3778                    TIMEOUT 30s WRITE heartbeat.txt alive
3779                    LET $beat: STRING = READ heartbeat.txt
3780                    ASSERT_EQ $beat "alive"
3781                "#},
3782                },
3783                Example {
3784                    name: "timeout block",
3785                    fence_meta: None,
3786                    code: indoc! {r#"
3787                    TIMEOUT 30s {
3788                        WRITE a.txt one
3789                        WRITE b.txt two
3790                    }
3791                    LET $a: STRING = READ a.txt
3792                    LET $b: STRING = READ b.txt
3793                    ASSERT_EQ $a "one"
3794                    ASSERT_EQ $b "two"
3795                "#},
3796                },
3797                Example {
3798                    name: "deadline aborts the step",
3799                    fence_meta: Some("expect_error:\"TIMEOUT after\""),
3800                    code: indoc! {r#"
3801                    # 50ms expires long before the sleep does: the step dies
3802                    # with a deadline error instead of running out the clock.
3803                    TIMEOUT 50ms SLEEP 30s
3804                "#},
3805                },
3806                Example {
3807                    name: "timeout variable duration",
3808                    fence_meta: None,
3809                    code: indoc! {r#"
3810                    # Durations resolve at runtime, so variables work too.
3811                    LET $budget: DURATION = "30s"
3812                    TIMEOUT $budget WRITE heartbeat.txt alive
3813
3814                    LET $beat: STRING = READ heartbeat.txt
3815                    ASSERT_EQ $beat "alive"
3816                "#},
3817                },
3818                Example {
3819                    name: "timeout await",
3820                    fence_meta: None,
3821                    code: indoc! {r#"
3822                    # AWAIT form bounds a task join instead of a step.
3823                    LET $quick: HANDLE<VOID> = ASYNC {
3824                        ECHO hi
3825                    }
3826                    TIMEOUT 30s AWAIT $quick
3827                "#},
3828                },
3829            ],
3830        },
3831        CommandMeta {
3832            in_index: true,
3833            name: KEYWORD_FAIL,
3834            syntax: "FAIL [<code>] [<message>] [{ <commands> }]",
3835            summary: "Print a failure message and exit.",
3836            description: indoc! {r#"
3837                Prints the message to stderr (the `ECHO` plus `EXIT` idiom as
3838                one step, rerouted to the error stream), runs the optional
3839                block first, then exits through the `EXIT` path with
3840                `EXIT requested with code <code>`.
3841
3842                With no code the exit code is 1; with a code it clamps to
3843                0..=255 like `EXIT`. The block runs first in a child scope
3844                that reads caller locals, with its stdout rerouted to
3845                stderr, so usage text, cleanup, and callee output all land
3846                on the error stream while stdout stays empty: the only
3847                form a `FUNC` cannot express, since functions take values,
3848                never blocks. At least one of message or block is required.
3849
3850                A lone bare int is a silent code (`FAIL 2` exits 2 with no
3851                output); quoting decides, so `FAIL "2"` prints `2` and
3852                exits 1.
3853            "#},
3854            args: &[],
3855            flags: &[],
3856            default_output: Some(Stream::Stderr),
3857            examples: &[
3858                Example {
3859                    name: "fail",
3860                    fence_meta: Some("expect_error:\"EXIT requested with code 1\""),
3861                    code: indoc! {r#"
3862                    # The message prints to stderr, never stdout, so a
3863                    # failure cannot pollute captured output. No code
3864                    # means exit 1.
3865                    FAIL "cargo not found in image"
3866                    "#},
3867                },
3868                Example {
3869                    name: "fail code",
3870                    fence_meta: Some("expect_error:\"EXIT requested with code 2\""),
3871                    code: indoc! {r#"
3872                    # An explicit code exits with that code (clamped to
3873                    # 0..=255 like EXIT); the message still prints to
3874                    # stderr.
3875                    FAIL 2 "cargo not found in image"
3876                    "#},
3877                },
3878                Example {
3879                    name: "fail block",
3880                    fence_meta: Some("expect_error:\"EXIT requested with code 1\""),
3881                    code: indoc! {r#"
3882                    # The block runs first with its stdout rerouted to
3883                    # stderr: usage text and cleanup land on the error
3884                    # stream beside the message, and stdout stays empty.
3885                    # Callee output reroutes too: a FUNC called here
3886                    # inherits the swapped handle.
3887                    FAIL "unknown command" {
3888                        ECHO usage-text
3889                    }
3890                    "#},
3891                },
3892            ],
3893        },
3894        CommandMeta {
3895            in_index: true,
3896            name: KEYWORD_ISOLATED,
3897            syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
3898            summary: "Run steps with the seeded script environment.",
3899            description: indoc! {r#"
3900                Resets the script environment for the block to the session
3901                seed: spawned children see the sandbox defaults plus names
3902                the block re-adds through its leading `INHERIT_ENV`.
3903
3904                The allowlist resolves against the outer scope, never the
3905                host. Absent names stay absent silently, matching top-level
3906                `INHERIT_ENV`.
3907
3908                Script variables, pipes, and files flow through untouched;
3909                only `env:` is reset. Files share the session workspace:
3910                blocks selecting the same `WORKSPACE` target resolve to the
3911                same directory with no per-block overlay, so one block's
3912                writes are visible to another.
3913
3914                Blocks nest (each level re-seeds from the same seed, so
3915                nesting only narrows through the allowlists) and combine
3916                with `ASYNC` and `FUNC`. Scope exit restores the prior
3917                environment.
3918            "#},
3919            args: &[],
3920            flags: &[],
3921            default_output: None,
3922            examples: &[
3923                Example {
3924                    name: "isolated scope",
3925                    fence_meta: None,
3926                    code: indoc! {r#"
3927                    # The block sees a clean env; plain steps still run and
3928                    # outer bindings survive untouched.
3929                    ENV MODE=outer
3930                    ISOLATED {
3931                        ENV MODE=inner
3932                        WRITE inner.txt "{{ env:MODE }}"
3933                    }
3934                    LET $back: STRING = "{{ env:MODE }}"
3935                    ASSERT_EQ $back "outer"
3936                    LET $body: STRING = READ inner.txt
3937                    ASSERT_EQ $body "inner"
3938                "#},
3939                },
3940                Example {
3941                    name: "reseeded child env",
3942                    fence_meta: None,
3943                    code: indoc! {r#"
3944                    # The block resets to the session seed: plain steps and
3945                    # spawns run with zero prelude. PATH needs no
3946                    # declaration: contract seed rows are always admitted.
3947                    WRITE top-path.txt "{{ env:PATH }}"
3948                    ISOLATED {
3949                        WRITE inner-path.txt "{{ env:PATH }}"
3950                        RUN "echo seed-ok"
3951                    }
3952                    LET $top: STRING = READ top-path.txt
3953                    LET $inner: STRING = READ inner-path.txt
3954                    ASSERT_EQ $inner $top
3955                    ASSERT_CONTAINS stdout "seed-ok"
3956                "#},
3957                },
3958                Example {
3959                    name: "outer customs stay out",
3960                    fence_meta: Some("expect_error:\"env:OUTER_CUSTOM\""),
3961                    code: indoc! {r#"
3962                    # Outer customs never enter the block: without an
3963                    # allowlist entry the static gate rejects the read
3964                    # before the first step runs.
3965                    ENV OUTER_CUSTOM=outer-val
3966                    ISOLATED {
3967                        WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
3968                    }
3969                "#},
3970                },
3971                Example {
3972                    name: "absent names stay absent",
3973                    fence_meta: None,
3974                    code: indoc! {r#"
3975                    # Listing a name the outer scope lacks is not an error:
3976                    # the block simply runs without it.
3977                    ISOLATED {
3978                        INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
3979                        ECHO still-runs
3980                    }
3981                    ASSERT_CONTAINS stdout "still-runs"
3982                "#},
3983                },
3984                Example {
3985                    name: "nesting narrows",
3986                    fence_meta: None,
3987                    code: indoc! {r#"
3988                    # Each level snapshots the already-scrubbed parent, so
3989                    # an inner block cannot recover what the outer dropped.
3990                    ENV KEEP=yes
3991                    ISOLATED {
3992                        INHERIT_ENV [KEEP]
3993                        ISOLATED {
3994                            ENV KEEP=inner
3995                            WRITE deep.txt "{{ env:KEEP }}"
3996                        }
3997                        LET $mid: STRING = "{{ env:KEEP }}"
3998                        ASSERT_EQ $mid "yes"
3999                    }
4000                    LET $deep: STRING = READ deep.txt
4001                    ASSERT_EQ $deep "inner"
4002                "#},
4003                },
4004            ],
4005        },
4006        CommandMeta {
4007            in_index: true,
4008            name: KEYWORD_REMOTE,
4009            syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
4010            summary: "Run a sealed block on a remote target.",
4011            description: indoc! {r#"
4012                Runs the braced block on the named remote target, which the
4013                host binds at startup (`--remote`). The block is sealed:
4014                only header-listed `$var` and `env:NAME` entries cross, the
4015                guest starts empty, and results return through declared
4016                transfers or `WITH_IO` pipes.
4017
4018                The target is a static literal, never a variable. Unknown
4019                targets fail before execution starts.
4020
4021                Bodies check twice: the host static pass validates the
4022                body before anything ships, and the guest re-validates on
4023                arrival through the same entry point, so a body type error
4024                fails locally, never mid-run on the remote.
4025
4026                A failing guest fails the host step: EXIT in the body
4027                exits the guest, and the host relays the code to its own
4028                process exit status (see EXIT).
4029            "#},
4030            args: &[],
4031            flags: &[],
4032            default_output: None,
4033            examples: &[
4034                Example {
4035                    name: "sealed header values cross, outer scope does not",
4036                    fence_meta: Some("mock_remote:prod"),
4037                    code: indoc! {r#"
4038                    # Only header-listed names arrive: `$version` is visible
4039                    # on the guest, `$secret` was never sent.
4040                    LET $version: STRING = "1.2.3"
4041                    LET $secret: STRING = "host-only"
4042                    REMOTE prod [$version] {
4043                        WRITE version.txt "{{ $version }}"
4044                        COPY --to-host ./version.txt back.txt
4045                    }
4046
4047                    # The pushed file proves the guest saw the injected value.
4048                    LET $back: STRING = READ back.txt
4049                    ASSERT_EQ $back "1.2.3"
4050                "#},
4051                },
4052                Example {
4053                    name: "background tasks stream through shared pipes",
4054                    fence_meta: Some("mock_remote:prod"),
4055                    code: indoc! {r#"
4056                    # Two background REMOTEs share one capture pipe while a
4057                    # WITH_IO block holds the write end open.
4058                    IMPORT [STD]
4059                    LET $cap: PIPE
4060                    WITH_IO [stdout=$cap] {
4061                        LET $a: HANDLE<VOID> = ASYNC REMOTE prod {
4062                            ECHO "from-a"
4063                        }
4064                        LET $b: HANDLE<VOID> = ASYNC REMOTE prod {
4065                            ECHO "from-b"
4066                        }
4067                        AWAIT $a
4068                        AWAIT $b
4069                    }
4070
4071                    # EOF ends the drain: no sentinel line, no baked-in count.
4072                    LET $n: INT = 0
4073                    WHILE !EOF($cap) {
4074                        WITH_IO [stdin=$cap] READ_LINE $line
4075                        $n = $n + 1
4076                    }
4077                    ASSERT_EQ $n 2
4078                "#},
4079                },
4080                Example {
4081                    name: "declared files cross both directions",
4082                    fence_meta: Some("mock_remote:prod roots:unified"),
4083                    code: indoc! {r#"
4084                    # Fetches ride in, pushes ride back. Anything undeclared
4085                    # never leaves its side.
4086                    WRITE send.txt "payload"
4087                    REMOTE prod {
4088                        COPY --from-host ./send.txt got.txt
4089                        LET $v: STRING = READ got.txt
4090                        ASSERT_EQ $v "payload"
4091                        WRITE back.txt "returned"
4092                        COPY --to-host ./back.txt back.txt
4093                    }
4094
4095                    # The push landed on the host; guest staging is gone.
4096                    LET $b: STRING = READ back.txt
4097                    ASSERT_EQ $b "returned"
4098                "#},
4099                },
4100                Example {
4101                    name: "guest workspace selection stays on the guest",
4102                    fence_meta: Some("mock_remote:prod"),
4103                    code: indoc! {r#"
4104                    # WORKSPACE switches inside the block resolve against the
4105                    # guest staging dir, which serves as both the SNAPSHOT
4106                    # root and the LOCAL build context. The host selection
4107                    # restores when the block exits.
4108                    REMOTE prod {
4109                        WORKSPACE SNAPSHOT
4110                        WRITE out.txt "from-snapshot"
4111                        COPY --to-host ./out.txt snap.txt
4112                    }
4113
4114                    LET $s: STRING = READ snap.txt
4115                    ASSERT_EQ $s "from-snapshot"
4116                "#},
4117                },
4118                Example {
4119                    name: "guest cache persists across execs",
4120                    fence_meta: Some("mock_remote:prod"),
4121                    code: indoc! {r#"
4122                    # WORKSPACE CACHE addresses guest-local persistent
4123                    # storage: the second block reads what the first wrote,
4124                    # while the guest staging starts empty every time.
4125                    REMOTE prod {
4126                        WORKSPACE CACHE
4127                        WRITE marker.txt "run-marker"
4128                    }
4129                    REMOTE prod {
4130                        WORKSPACE CACHE
4131                        LET $m: STRING = READ marker.txt
4132                        ASSERT_EQ $m "run-marker"
4133                    }
4134                "#},
4135                },
4136                Example {
4137                    name: "pushes outside staging fail closed",
4138                    fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
4139                    code: indoc! {r#"
4140                    # WORKSPACE SYSTEM exposes the whole guest machine, but
4141                    # transfers stay staging scoped: a push source outside
4142                    # staging fails loudly instead of crossing.
4143                    REMOTE prod {
4144                        WORKSPACE SYSTEM
4145                        COPY --to-host /no/such/file.txt got.txt
4146                    }
4147                "#},
4148                },
4149                Example {
4150                    name: "guest exit fails the step, host survives",
4151                    fence_meta: Some(
4152                        "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
4153                    ),
4154                    code: indoc! {r#"
4155                    # EXIT in the body exits the guest with code 3. The
4156                    # host is unaffected: it keeps executing after the
4157                    # guest is already dead, and the failure surfaces as
4158                    # a host step error carrying the same code. The CLI
4159                    # then exits with it, so the guest code reaches the OS.
4160                    LET $t: HANDLE<VOID> = ASYNC REMOTE prod {
4161                        EXIT 3
4162                    }
4163                    WRITE host-alive.txt "still here"
4164                    AWAIT $t
4165                "#},
4166                },
4167                Example {
4168                    name: "remote block without a runner",
4169                    fence_meta: Some("expect_error:\"has no registered session\""),
4170                    code: indoc! {r#"
4171                    # Without a bound session, the block bails instead of
4172                    # executing anywhere unexpected.
4173                    REMOTE prod {
4174                        ECHO "do something on remote"
4175                    }
4176                "#},
4177                },
4178            ],
4179        },
4180        CommandMeta {
4181            in_index: true,
4182            name: KEYWORD_FUNC,
4183            syntax: "FUNC NAME([$param: TYPE, ...]): RET { <commands> } | ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }",
4184            summary: "Define a user function.",
4185            description: indoc! {r#"
4186                Defines a user function with UPPERCASE name and explicitly typed
4187                parameters. `FUNC` runs synchronously; `ASYNC FUNC` is the same
4188                with a structural guarantee: the declaration must be
4189                `HANDLE<T>`, so every `RETURN` hands out a task handle.
4190
4191                Params bind by position, converting each argument to its
4192                declared parameter type before the body runs.
4193                A trailing `$name?: TYPE` marks an optional param: callers
4194                may omit trailing optionals, which fill with zero values
4195                (`false`, `""`, `0`, `0.0`, `[]`, `{}`) before the body
4196                binds. A required param after an optional one fails at
4197                definition, and an optional param with no zero value
4198                (records with required fields, unions, handles, custom
4199                types) fails at definition naming the fix: drop the `?`
4200                or pass the argument explicitly.
4201                Bodies run in a fresh variable scope; LETs inside do not leak. A nested
4202                FUNC definition is scoped to its block and reverts on exit. Names share
4203                one namespace with native and host-registered functions, which a FUNC
4204                may never shadow.
4205
4206                Functions resolve like variables: a name is visible from its
4207                definition line, so recursion works but mutual recursion does
4208                not (the second name does not exist while the first body
4209                lowers). Calls name their module (`STD::GLOB(...)`) unless
4210                imported; see IMPORT.
4211
4212                Invoke any function with one syntax: `NAME(...)` as a statement
4213                (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
4214                the RETURN value (fallthrough without RETURN is a static error unless RET is VOID).
4215
4216                `ASYNC FUNC` does not spawn on call. The body runs
4217                synchronously on the caller thread up to its inner `ASYNC`
4218                step, which spawns the background task and yields its handle
4219                immediately; the function then hands that handle out with
4220                `RETURN $t`. The caller joins it separately with `AWAIT`.
4221            "#},
4222            args: &[],
4223            flags: &[],
4224            default_output: None,
4225            examples: &[
4226                Example {
4227                    name: "func def call",
4228                    fence_meta: None,
4229                    code: indoc! {r#"
4230                FUNC GREET($name: STRING): STRING {
4231                  RETURN $name
4232                }
4233
4234                LET $res: STRING = GREET("ada")
4235                ASSERT_EQ $res "ada"
4236
4237                # Statement form: parens stay, the value drops.
4238                GREET("bex")
4239            "#},
4240                },
4241                Example {
4242                    name: "bind then interpolate",
4243                    fence_meta: None,
4244                    code: indoc! {r#"
4245                # Script FUNCs run as steps, never inside {{ }}.
4246                FUNC GREET($name: STRING): STRING {
4247                  RETURN $name
4248                }
4249
4250                # Call as a step to capture the RETURN.
4251                LET $res: STRING = GREET("ada")
4252
4253                # {{ }} reads the bound var.
4254                LET $msg: STRING = "says {{ $res }}"
4255
4256                ASSERT_EQ $msg "says ada"
4257            "#},
4258                },
4259                Example {
4260                    name: "script funcs never resolve in placeholders",
4261                    fence_meta: Some(
4262                        "expect_error:\"placeholder function 'SCRIPT::GREET' is a script function\"",
4263                    ),
4264                    code: indoc! {r#"
4265                # Placeholders carry no step context: pure registry only.
4266                FUNC GREET($name: STRING): STRING {
4267                  RETURN $name
4268                }
4269
4270                # Bind the argument as a step var to keep quoting flat.
4271                LET $who: STRING = "ada"
4272
4273                # This fails naming the pure-only boundary.
4274                ECHO "{{ SCRIPT::GREET($who) }}"
4275            "#},
4276                },
4277                Example {
4278                    name: "optional params fill zero values",
4279                    fence_meta: None,
4280                    code: indoc! {r#"
4281                IMPORT [STD]
4282                # Trailing `?` params may be omitted; they fill with
4283                # zero values (false, empty map) before the body binds,
4284                # so plain IF works on an omitted BOOL.
4285                FUNC ENSURE($check?: BOOL, $opts?: MAP<mode?: STRING>): STRING {
4286                    IF $check {
4287                        RETURN "checked"
4288                    }
4289                    IF HAS_KEY($opts, "mode") {
4290                        RETURN "opts"
4291                    }
4292                    RETURN "plain"
4293                }
4294                LET $a: STRING = ENSURE()
4295                ASSERT_EQ $a "plain"
4296                LET $b: STRING = ENSURE(true)
4297                ASSERT_EQ $b "checked"
4298                LET $opts: MAP<mode?: STRING> = PARSE_JSON("{\"mode\": \"fast\"}")
4299                LET $c: STRING = ENSURE(false, $opts)
4300                ASSERT_EQ $c "opts"
4301            "#},
4302                },
4303                Example {
4304                    name: "optional params must trail",
4305                    fence_meta: Some("expect_error:\"optional ? params must be trailing\""),
4306                    code: indoc! {r#"
4307                # A required param after an optional one fails at definition.
4308                FUNC BAD($a?: STRING, $b: STRING): STRING {
4309                    RETURN $b
4310                }
4311            "#},
4312                },
4313                Example {
4314                    name: "async func is a handle guarantee",
4315                    fence_meta: None,
4316                    code: indoc! {r#"
4317                # Side by side: identical bodies, identical handling. The
4318                # ASYNC marker only guarantees the HANDLE declaration.
4319                ASYNC FUNC FETCH(): HANDLE<STRING> {
4320                  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
4321                  RETURN $t
4322                }
4323                FUNC MAKE(): HANDLE<STRING> {
4324                  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
4325                  RETURN $t
4326                }
4327
4328                # Both run synchronously to RETURN; the inner ASYNC spawns.
4329                LET $a: HANDLE<STRING> = FETCH()
4330                LET $b: HANDLE<STRING> = MAKE()
4331                LET $x: STRING = AWAIT $a
4332                LET $y: STRING = AWAIT $b
4333                ASSERT_EQ $x "hi"
4334                ASSERT_EQ $y "hi"
4335            "#},
4336                },
4337                Example {
4338                    name: "call with pipes",
4339                    fence_meta: None,
4340                    code: indoc! {r#"
4341                # A pipe handle travels into a function as a typed argument
4342                # and is usable as a binding target in both directions.
4343                # `LET $p: PIPE` mints the handle; `$p` passes it on.
4344                FUNC DRAIN($q: PIPE): STRING {
4345                  WITH_IO [stdin=$q] READ_LINE $line
4346                  RETURN $line
4347                }
4348
4349                LET $p: PIPE
4350                WITH_IO [stdout=$p] ECHO "payload"
4351
4352                LET $got: STRING = DRAIN($p)
4353                ASSERT_EQ $got "payload"
4354            "#},
4355                },
4356            ],
4357        },
4358        CommandMeta {
4359            in_index: true,
4360            name: KEYWORD_RETURN,
4361            syntax: "RETURN [<expr>]",
4362            summary: "Return a value from a function, task, or inline block.",
4363            description: indoc! {r#"
4364                Ends the nearest enclosing boundary with a value: a function
4365                call, an `ASYNC` task (bound by `LET $out: STRING = AWAIT $t`), or an
4366                inline `LET` block. Bare `RETURN` with no expression yields
4367                `""`.
4368
4369                Falling off the end without RETURN yields "". RETURN with no
4370                enclosing boundary (including at top level) is an error; use
4371                EXIT or ECHO there.
4372            "#},
4373            args: &[],
4374            flags: &[],
4375            default_output: None,
4376            examples: &[Example {
4377                name: "return",
4378                fence_meta: None,
4379                code: indoc! {r#"
4380                FUNC PICK($flag: BOOL): STRING {
4381                  IF $flag {
4382                    RETURN "yes"
4383                  }
4384                  RETURN "no"
4385                }
4386
4387                LET $res: STRING = PICK(true)
4388                ASSERT_EQ $res "yes"
4389
4390                # Fallthrough without RETURN yields its own value.
4391                LET $no: STRING = PICK(false)
4392                ASSERT_EQ $no "no"
4393            "#},
4394            }],
4395        },
4396        CommandMeta {
4397            in_index: true,
4398            name: KEYWORD_WHILE,
4399            syntax: "WHILE <bool-expr> { <commands> }",
4400            summary: "Loop while a condition holds.",
4401            description: indoc! {r#"
4402                Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
4403                non-Bool is a type error).
4404
4405                Each iteration runs in a fresh scope; mutate outer state with $var = ...
4406                so the next check observes it. BREAK exits the loop; CONTINUE skips to
4407                the next check.
4408            "#},
4409            args: &[],
4410            flags: &[],
4411            default_output: None,
4412            examples: &[Example {
4413                name: "while loop",
4414                fence_meta: None,
4415                code: indoc! {r#"
4416                # The condition re-evaluates every iteration: three passes, then stop.
4417                LET $n: INT = 0
4418                WHILE $n < 3 {
4419                  WRITE tick.txt "{{ $n }}"
4420                  $n = $n + 1
4421                }
4422
4423                ASSERT_EQ $n 3
4424                LET $tick: STRING = READ tick.txt
4425                ASSERT_EQ $tick "2"
4426            "#},
4427            }],
4428        },
4429        CommandMeta {
4430            in_index: true,
4431            name: KEYWORD_BREAK,
4432            syntax: KEYWORD_BREAK,
4433            summary: "Exit the innermost loop.",
4434            description: indoc! {r#"
4435                Exits the innermost enclosing FOR or WHILE loop.
4436
4437                BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
4438            "#},
4439            args: &[],
4440            flags: &[],
4441            default_output: None,
4442            examples: &[
4443                Example {
4444                    name: "break",
4445                    fence_meta: None,
4446                    code: indoc! {r#"
4447                # BREAK leaves after the first pass: only "a" is written.
4448                FOR $x: STRING IN ["a", "b"] {
4449                  WRITE picked.txt "{{ $x }}"
4450                  BREAK
4451                }
4452
4453                LET $body: STRING = READ picked.txt
4454                ASSERT_EQ $body "a"
4455            "#},
4456                },
4457                Example {
4458                    name: "break nested",
4459                    fence_meta: None,
4460                    code: indoc! {r#"
4461                # Inner BREAK exits only the inner loop: the outer runs
4462                # both passes, and each inner stops before 2.
4463                LET $hits: LIST<STRING> = []
4464                FOR $o: STRING IN ["x", "y"] {
4465                  FOR $i: INT IN [1, 2, 3] {
4466                    IF $i == 2 {
4467                      BREAK
4468                    }
4469                    LIST_APPEND $hits "{{ $o }}{{ $i }}"
4470                  }
4471                }
4472
4473                LET $want: LIST<STRING> = ["x1", "y1"]
4474                ASSERT_EQ $hits $want
4475            "#},
4476                },
4477            ],
4478        },
4479        CommandMeta {
4480            in_index: true,
4481            name: KEYWORD_CONTINUE,
4482            syntax: KEYWORD_CONTINUE,
4483            summary: "Skip to the next loop iteration.",
4484            description: indoc! {r#"
4485                Skips the rest of the innermost enclosing FOR or WHILE body and starts
4486                the next iteration.
4487
4488                CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
4489            "#},
4490            args: &[],
4491            flags: &[],
4492            default_output: None,
4493            examples: &[
4494                Example {
4495                    name: "continue",
4496                    fence_meta: None,
4497                    code: indoc! {r#"
4498                # CONTINUE skips the write on "a": only "b" lands.
4499                FOR $x: STRING IN ["a", "b"] {
4500                  IF $x == "a" {
4501                    CONTINUE
4502                  }
4503                  WRITE picked.txt "{{ $x }}"
4504                }
4505
4506                LET $body: STRING = READ picked.txt
4507                ASSERT_EQ $body "b"
4508            "#},
4509                },
4510                Example {
4511                    name: "continue nested",
4512                    fence_meta: None,
4513                    code: indoc! {r#"
4514                # Inner CONTINUE skips only the inner 2: the outer runs
4515                # both passes, and each inner still reaches 3.
4516                LET $hits: LIST<STRING> = []
4517                FOR $o: STRING IN ["x", "y"] {
4518                  FOR $i: INT IN [1, 2, 3] {
4519                    IF $i == 2 {
4520                      CONTINUE
4521                    }
4522                    LIST_APPEND $hits "{{ $o }}{{ $i }}"
4523                  }
4524                }
4525
4526                LET $want: LIST<STRING> = ["x1", "x3", "y1", "y3"]
4527                ASSERT_EQ $hits $want
4528            "#},
4529                },
4530            ],
4531        },
4532        CommandMeta {
4533            in_index: true,
4534            name: KEYWORD_IMPORT,
4535            syntax: "IMPORT [<module>, ...] | IMPORT <module> | IMPORT [\"<path>\" AS <ALIAS>] | IMPORT [<module | \"<path>\" AS <ALIAS> | [F, ... FROM (\"<path>\" | <module>) (AS <ALIAS>)?]>, ...]",
4536            summary: "Bring module functions into bare-call scope; import script files and types.",
4537            description: indoc! {r#"
4538                Bare calls:
4539                - Every call names its module (`STD::GLOB(...)`)
4540                  unless the module is imported. `IMPORT [STD]` lets
4541                  the rest of the scope call `GLOB(...)` bare.
4542                - Calls resolve at parse time: `SCRIPT` definitions
4543                  first, then imported modules. Unknown modules,
4544                  unknown functions, and unimported bare calls are
4545                  parse errors, never runtime surprises.
4546
4547                Scope:
4548                - `IMPORT` is a lowering directive, not a step. It
4549                  applies from its line to the enclosing block exit,
4550                  then reverts like `LET` scoping, with no runtime
4551                  footprint. Guards do not apply to it.
4552                - Two imported modules exporting one name is an
4553                  ambiguity error: qualify the call instead.
4554
4555                File imports:
4556                - Form: `IMPORT ["./lib.oxdock" AS LIB]` (any file
4557                  extension). The alias is mandatory and becomes the
4558                  namespace (`LIB::FOO`), with no filename inference.
4559                - Only `EXPORT`ed top-level `FUNC`s cross the
4560                  boundary. Unexported means private; variables are
4561                  never exportable.
4562                - Types cross qualified: a whole-file import exposes
4563                  every exported alias as `ALIAS::NAME` only
4564                  (`LET $p: LIB::PERSON` after
4565                  `IMPORT ["./lib.oxfile" AS LIB]`), mirroring func
4566                  views. Nothing bare leaks from an aliased import,
4567                  so same-named types in different files coexist;
4568                  harvests below stay the explicit way to request a
4569                  bare name.
4570                - Each file initializes once; every alias shares the
4571                  module's top-level bindings.
4572                - The file must exist when the run starts. Generated
4573                  imports are rejected before the first step.
4574
4575                Mixed brackets:
4576                - Brackets mix both kinds across lines if needed
4577                  (`IMPORT [STD, "a.oxdock" AS A]`). Each module entry
4578                  registers in order; each file entry runs in order.
4579                - Without an alias a file entry is a parse error.
4580                - Value positions (`LET`, `ASYNC`,
4581                  `WITH_IO`/`TIMEOUT` inners) take exactly one file
4582                  entry and no modules.
4583
4584                Selective harvests:
4585                - Form: `IMPORT [FOO FROM "x.oxdock"]`,
4586                  optionally `AS ALIAS`. Only the named top-level
4587                  functions register, bare or namespaced under the
4588                  alias. Harvested names must be `EXPORT`ed.
4589                - Single name needs no inner brackets
4590                  (`IMPORT [FOO FROM "x.oxdock"]`); several names from
4591                  one file combine in one bracket with explicit kinds
4592                  (`IMPORT [TYPE A, TYPE B FROM "x.oxdock"]`, file or
4593                  host alike: `IMPORT [FUNC FOO, FUNC BAR FROM
4594                  "x.oxdock"]`). Bare names always read as modules, so
4595                  a bare multi-name fails naming the explicit-kind
4596                  fix. Prefer one import per file over grouping
4597                  harvests.
4598                - Types and functions combine in one entry
4599                  (`IMPORT [TYPE PERSON, FUNC FOO FROM "x.oxdock"]`).
4600                  Harvested types must be `EXPORT TYPE`d. Unaliased
4601                  harvests persist bare globally (collision-checked),
4602                  so `FUNC` signatures keep working; aliased harvests
4603                  persist qualified-only, like whole-file imports.
4604                - The file body never executes, so harvesting is
4605                  side-effect free. The file's own nested imports
4606                  still load. Harvests produce no value and never
4607                  appear in value positions.
4608
4609                Host library types:
4610                - Form: `IMPORT [TYPE PIPE FROM STD]`. The import
4611                  validates the type resolves globally and records no
4612                  file. Host types stay global with or without the
4613                  harvest; the explicit form only documents the
4614                  dependency and fails fast on typos.
4615                - Bare `FROM` names a library; quoted `FROM`
4616                  names a file path. Quoted `FROM "STD"` still parses
4617                  for backcompat, but bare is preferred.
4618
4619                Paths:
4620                - Workspace-side, against the importing file's
4621                  directory (entry parent at top level; off-workspace
4622                  entries resolve like stdin against the root).
4623                - Relative operation paths resolve against the ambient
4624                  cwd in every file, module or entry alike. `WORKSPACE`
4625                  and `WORKDIR` mean the same everywhere.
4626                - Missing files fail before the first step runs.
4627                  Write-then-import in one script is rejected; check
4628                  libraries into the tree, or combine them at runtime
4629                  and run a child interpreter (see the child run
4630                  examples below).
4631
4632                Module rules (every file import is a module):
4633                - Context: never inherits the caller's namespace. Env
4634                  resets to the seed plus the module init's own
4635                  contributions (declared `INHERIT_ENV` names re-read
4636                  from the host on every call). Workspace selection
4637                  and cwd flow through untouched, so module code
4638                  observes the same workspace its importer does.
4639                - Determinism: behavior is a pure function of the
4640                  script. The same file with the same ambient cwd and
4641                  selection behaves identically no matter who imports
4642                  it.
4643                - State: one init per file, shared by every alias.
4644                  Top-level `LET` bindings drain into a single store
4645                  visible to all of the module's functions.
4646                - Workspace: `WORKSPACE` and `WORKDIR` mean the same
4647                  in module scope as in entry code, selecting the
4648                  shared workspace and moving the shared cwd.
4649                - Exports: only `EXPORT`ed top-level `FUNC`s and
4650                  `EXPORT TYPE` aliases cross. Variables never cross.
4651                - Imports: whole-file or harvest, only exported
4652                  functions and types cross. Stateful harvests are
4653                  rejected (import the file to share its module).
4654                  Nested imports load automatically.
4655                - Cycles: circular imports and depth over 32 fail
4656                  before the first step runs.
4657
4658                Exports and tools:
4659                - `EXPORT` marks top-level `FUNC`s as externally
4660                  callable (`EXPORT FOO`, `EXPORT [FOO, BAR]`) and as
4661                  the file importable interface. Re-exports promote
4662                  an import (`IMPORT ["x.oxdock" AS A]` then `EXPORT
4663                  A::FOO`).
4664                - `EXPORT TYPE` marks aliases the same way
4665                  (`EXPORT TYPE PERSON`, `EXPORT TYPE [A, B]`, mixed
4666                  `EXPORT [TYPE A, FUNC B]`). Only exported aliases
4667                  cross, so `FUNC` signatures survive imports.
4668                - Serving resolves re-exports through the registry;
4669                  unexported names fail tool setup instead of serving
4670                  a dead tool. The MCP server skips `TYPE` exports
4671                  when building tools while still resolving imported
4672                  types for signatures. Single-file scope otherwise;
4673                  see the MCP host for consumption.
4674            "#},
4675            args: &[],
4676            flags: &[],
4677            default_output: None,
4678            examples: &[
4679                Example {
4680                    name: "import",
4681                    fence_meta: None,
4682                    code: indoc! {r#"
4683                # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
4684                WRITE a.txt "hi \{{ env:WHO }}!"
4685                IMPORT [STD]
4686                FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
4687                ASSERT_CONTAINS stdout "hi World!"
4688            "#},
4689                },
4690                Example {
4691                    name: "import missing file fails upfront",
4692                    fence_meta: Some("expect_error:\"must exist when the run starts\""),
4693                    code: indoc! {r#"
4694                # Generated imports are rejected: a file that does not
4695                # exist when the run starts cannot be analyzed, so the
4696                # import fails before the first step runs.
4697                WORKSPACE LOCAL
4698                WRITE lib.oxdock 'FUNC F($x: STRING): STRING { RETURN $x } EXPORT F'
4699                IMPORT ["lib.oxdock" AS LIB]
4700            "#},
4701                },
4702                Example {
4703                    name: "import missing alias fails",
4704                    fence_meta: Some("expect_error:\"mandatory alias\""),
4705                    code: indoc! {r#"
4706                # A file entry without AS is a parse error.
4707                IMPORT ["./lib.oxdock"]
4708            "#},
4709                },
4710                Example {
4711                    name: "module cannot export a variable",
4712                    fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
4713                    code: indoc! {r#"
4714                # Only top-level FUNCs are exportable, never variables.
4715                LET $FOO: STRING = "x"
4716                EXPORT FOO
4717            "#},
4718                },
4719                Example {
4720                    name: "import re-export unknown alias fails",
4721                    fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
4722                    code: indoc! {r#"
4723                # Re-exports name a visible import alias.
4724                IMPORT ["x.oxdock" AS A]
4725                EXPORT NOSUCH::FOO
4726            "#},
4727                },
4728                Example {
4729                    name: "export type aliases",
4730                    fence_meta: None,
4731                    code: indoc! {r#"
4732                # TYPE aliases declare shapes once; EXPORT TYPE shares
4733                # them so importing files can use the same spelling.
4734                TYPE PERSON = MAP<name: STRING>
4735
4736                FUNC GREET($p: PERSON): STRING {
4737                    RETURN "hi {{ $p.name }}"
4738                }
4739                EXPORT GREET
4740                EXPORT TYPE PERSON
4741
4742                LET $p: PERSON = {name: "Ada"}
4743                LET $greeting: STRING = GREET($p)
4744                ASSERT_EQ $greeting "hi Ada"
4745            "#},
4746                },
4747                Example {
4748                    name: "import type from library",
4749                    fence_meta: None,
4750                    code: indoc! {r#"
4751                # One bracket mixes entry kinds: STD brings functions bare,
4752                # each harvest names a type. Types resolve globally with
4753                # or without the harvests; the explicit form only documents
4754                # the dependency, so this grouping is example only. Bare
4755                # FROM names a library; quoted FROM names a file path.
4756                IMPORT [STD, [TYPE PIPE FROM STD], [TYPE DURATION FROM STD]]
4757
4758                LET $p: PIPE
4759                WITH_IO [stdout=$p] ECHO hello
4760                WITH_IO [stdin=$p] READ_LINE $line
4761                ASSERT_EQ $line "hello"
4762
4763                LET $d: DURATION = "5s"
4764                LET $files: LIST<STRING> = GLOB("*.oxdock")
4765            "#},
4766                },
4767                Example {
4768                    name: "run rendered modules in a child",
4769                    fence_meta: Some("roots:unified"),
4770                    code: indoc! {r#"
4771                # Dynamic assembly with files: the parent writes a
4772                # library and an entry script, then runs the entry in a
4773                # fresh interpreter. Child-side {{ }} stays escaped so
4774                # the parent does not interpolate it while writing. The
4775                # child runs by path so entry-relative IMPORT resolves.
4776                # Unified roots: the child inherits one workspace, so
4777                # parent and child see the same files.
4778                IMPORT [STD]
4779                WRITE lib.oxfile """
4780                    FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
4781                    EXPORT GREET
4782                    """
4783                WRITE main.oxfile """
4784                    IMPORT ["lib.oxfile" AS LIB]
4785                    LET $g: STRING = LIB::GREET("Ada")
4786                    ECHO "says \{{ $g }}"
4787                    """
4788                LET $exe: STRING = INTERPRETER()
4789                LET $out: STRING = RUN [$exe, "main.oxfile"]
4790                ASSERT_CONTAINS $out "says hi Ada"
4791            "#},
4792                },
4793                Example {
4794                    name: "dynamic module assembly",
4795                    fence_meta: Some("roots:unified"),
4796                    code: indoc! {r#"
4797                # A function that assembles a module: MAKE_GREETER bakes
4798                # its argument into a generated file with a bare {{ }},
4799                # then a child run imports the result. Bare {{ }} injects
4800                # parent values at write time; escaped \{{ }} survives for
4801                # the child to interpolate. Bind imported calls with LET:
4802                # {{ }} placeholders resolve pure functions only.
4803                IMPORT [STD]
4804
4805                # The renderer: parent values land in the module source.
4806                FUNC MAKE_GREETER($who: STRING): STRING {
4807                    WRITE greeter.oxfile """
4808                        FUNC GREET(): STRING { RETURN "hi {{ $who }}" }
4809                        EXPORT GREET
4810                        """
4811                    RETURN "greeter.oxfile"
4812                }
4813
4814                # The entry: imports the rendered module by its path.
4815                WRITE main.oxfile """
4816                    IMPORT ["greeter.oxfile" AS G]
4817                    LET $g: STRING = G::GREET()
4818                    ECHO "says \{{ $g }}"
4819                    """
4820
4821                # Assemble, then run the entry in a fresh interpreter.
4822                LET $made: STRING = MAKE_GREETER("Ada")
4823                ASSERT_EQ $made "greeter.oxfile"
4824                LET $exe: STRING = INTERPRETER()
4825                LET $out: STRING = RUN [$exe, "main.oxfile"]
4826                ASSERT_CONTAINS $out "says hi Ada"
4827            "#},
4828                },
4829                Example {
4830                    name: "export unknown type fails",
4831                    fence_meta: Some("expect_error:\"does not match any top-level TYPE\""),
4832                    code: indoc! {r#"
4833                # Only declared TYPE aliases are exportable.
4834                TYPE PERSON = MAP<name: STRING>
4835                EXPORT TYPE ANIMAL
4836            "#},
4837                },
4838                Example {
4839                    name: "undeclared type fails",
4840                    fence_meta: Some("expect_error:\"unknown type\""),
4841                    code: indoc! {r#"
4842                # TYPE names must be declared before use.
4843                LET $p: PERSON = {name: "Ada"}
4844            "#},
4845                },
4846            ],
4847        },
4848    ]
4849}
4850
4851// ── Display ────────────────────────────────────────────────────────────────
4852
4853impl fmt::Display for StepKind {
4854    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4855        match self {
4856            StepKind::InheritEnv { keys } => {
4857                write!(f, "{} [{}]", KEYWORD_INHERIT_ENV, keys.join(", "))
4858            }
4859            StepKind::Workdir(a) => write!(f, "{} {}", KEYWORD_WORKDIR, fmt_value(a, quote_arg)),
4860            StepKind::Workspace(t) => write!(f, "{} {}", KEYWORD_WORKSPACE, t),
4861            StepKind::Env { key, value } => {
4862                write!(f, "{} {}={}", KEYWORD_ENV, key, fmt_value(value, quote_arg))
4863            }
4864            StepKind::Run(c) => write!(f, "{} {}", KEYWORD_RUN, fmt_value(c, quote_run)),
4865            StepKind::RunExec { argv } => {
4866                let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
4867                write!(f, "{} [{}]", KEYWORD_RUN, parts.join(", "))
4868            }
4869            StepKind::Echo(m) => write!(f, "{} {}", KEYWORD_ECHO, fmt_value(m, quote_msg)),
4870            StepKind::Copy {
4871                from_workspace,
4872                from_host,
4873                to_host,
4874                from,
4875                to,
4876            } => {
4877                let mut head = String::from(KEYWORD_COPY);
4878                if let Some(target) = from_workspace {
4879                    head.push_str(&format!(" --from-workspace {target}"));
4880                }
4881                if *from_host {
4882                    head.push_str(" --from-host");
4883                }
4884                if *to_host {
4885                    head.push_str(" --to-host");
4886                }
4887                write!(
4888                    f,
4889                    "{head} {} {}",
4890                    fmt_value(from, quote_arg),
4891                    fmt_value(to, quote_arg)
4892                )
4893            }
4894            StepKind::Symlink {
4895                from_workspace,
4896                from,
4897                to,
4898            } => {
4899                if let Some(target) = from_workspace {
4900                    write!(
4901                        f,
4902                        "{} --from-workspace {} {} {}",
4903                        KEYWORD_SYMLINK,
4904                        target,
4905                        fmt_value(from, quote_arg),
4906                        fmt_value(to, quote_arg)
4907                    )
4908                } else {
4909                    write!(
4910                        f,
4911                        "{} {} {}",
4912                        KEYWORD_SYMLINK,
4913                        fmt_value(from, quote_arg),
4914                        fmt_value(to, quote_arg)
4915                    )
4916                }
4917            }
4918            StepKind::Mkdir(a) => write!(f, "{} {}", KEYWORD_MKDIR, fmt_value(a, quote_arg)),
4919            StepKind::Install { from, to } => write!(
4920                f,
4921                "{} {} {}",
4922                KEYWORD_INSTALL,
4923                fmt_value(from, quote_arg),
4924                fmt_value(to, quote_arg)
4925            ),
4926            StepKind::SetExecutable { path } => {
4927                write!(
4928                    f,
4929                    "{} {}",
4930                    KEYWORD_SET_EXECUTABLE,
4931                    fmt_value(path, quote_arg)
4932                )
4933            }
4934            StepKind::Archive { src, dst, raw } => {
4935                if *raw {
4936                    write!(
4937                        f,
4938                        "{} --raw {} {}",
4939                        KEYWORD_ARCHIVE,
4940                        fmt_value(src, quote_arg),
4941                        fmt_value(dst, quote_arg)
4942                    )
4943                } else {
4944                    write!(
4945                        f,
4946                        "{} {} {}",
4947                        KEYWORD_ARCHIVE,
4948                        fmt_value(src, quote_arg),
4949                        fmt_value(dst, quote_arg)
4950                    )
4951                }
4952            }
4953            StepKind::Unarchive {
4954                src,
4955                dst,
4956                max_bytes,
4957            } => {
4958                write!(f, "{KEYWORD_UNARCHIVE}")?;
4959                if let Some(n) = max_bytes {
4960                    write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
4961                }
4962                write!(
4963                    f,
4964                    " {} {}",
4965                    fmt_value(src, quote_arg),
4966                    fmt_value(dst, quote_arg)
4967                )
4968            }
4969            StepKind::Ls(a) => {
4970                write!(f, "{KEYWORD_LS}")?;
4971                if let Some(x) = a {
4972                    write!(f, " {}", fmt_value(x, quote_arg))?;
4973                }
4974                Ok(())
4975            }
4976            StepKind::Read(a) => {
4977                write!(f, "{KEYWORD_READ}")?;
4978                if let Some(x) = a {
4979                    write!(f, " {}", fmt_value(x, quote_arg))?;
4980                }
4981                Ok(())
4982            }
4983            StepKind::ReadLine { var } => write!(f, "{} ${}", KEYWORD_READ_LINE, var),
4984            StepKind::Prompt {
4985                var,
4986                message,
4987                default,
4988            } => {
4989                write!(
4990                    f,
4991                    "{} ${} {}",
4992                    KEYWORD_PROMPT,
4993                    var,
4994                    fmt_value(message, quote_arg)
4995                )?;
4996                if let Some(d) = default {
4997                    write!(f, " {}", fmt_value(d, quote_arg))?;
4998                }
4999                Ok(())
5000            }
5001            StepKind::Write { path, contents } => {
5002                write!(f, "{} {}", KEYWORD_WRITE, fmt_value(path, quote_arg))?;
5003                if let Some(b) = contents {
5004                    write!(f, " {}", fmt_value(b, quote_msg))?;
5005                }
5006                Ok(())
5007            }
5008            StepKind::Append { path, contents } => {
5009                write!(f, "{} {}", KEYWORD_APPEND, fmt_value(path, quote_arg))?;
5010                if let Some(b) = contents {
5011                    write!(f, " {}", fmt_value(b, quote_msg))?;
5012                }
5013                Ok(())
5014            }
5015            StepKind::AppendLine { path, contents } => {
5016                write!(
5017                    f,
5018                    "{} {} {}",
5019                    KEYWORD_APPEND_LINE,
5020                    fmt_value(path, quote_arg),
5021                    fmt_value(contents, quote_msg)
5022                )
5023            }
5024            StepKind::Remove { path, recursive } => {
5025                if *recursive {
5026                    write!(
5027                        f,
5028                        "{} --recursive {}",
5029                        KEYWORD_REMOVE,
5030                        fmt_value(path, quote_arg)
5031                    )
5032                } else {
5033                    write!(f, "{} {}", KEYWORD_REMOVE, fmt_value(path, quote_arg))
5034                }
5035            }
5036            StepKind::Expand { path, overrides } => {
5037                write!(f, "{KEYWORD_EXPAND}")?;
5038                if let Some(p) = path {
5039                    write!(f, " {}", fmt_value(p, quote_arg))?;
5040                }
5041                for (k, v) in overrides {
5042                    write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
5043                }
5044                Ok(())
5045            }
5046            StepKind::AssertEq {
5047                hash,
5048                actual,
5049                expected,
5050            }
5051            | StepKind::AssertNe {
5052                hash,
5053                actual,
5054                expected,
5055            } => {
5056                let verb = match self {
5057                    StepKind::AssertEq { .. } => KEYWORD_ASSERT_EQ,
5058                    _ => KEYWORD_ASSERT_NE,
5059                };
5060                if let Some(d) = hash {
5061                    write!(f, "{verb} --hash {d} {}", fmt_assert_target(actual))?;
5062                } else {
5063                    write!(
5064                        f,
5065                        "{verb} {} {}",
5066                        fmt_assert_target(actual),
5067                        fmt_value(
5068                            expected
5069                                .as_ref()
5070                                .expect("Display of ASSERT without --hash needs expected"),
5071                            quote_msg
5072                        )
5073                    )?;
5074                }
5075                Ok(())
5076            }
5077            StepKind::AssertContains { haystack, needle } => write!(
5078                f,
5079                "{} {} {}",
5080                KEYWORD_ASSERT_CONTAINS,
5081                fmt_assert_target(haystack),
5082                fmt_value(needle, quote_msg)
5083            ),
5084            StepKind::WithIo { bindings, cmd } => {
5085                let p: Vec<String> = bindings.iter().map(fmt_io).collect();
5086                write!(f, "{} [{}] {}", KEYWORD_WITH_IO, p.join(", "), cmd)
5087            }
5088            StepKind::WithIoBlock { bindings } => {
5089                let p: Vec<String> = bindings.iter().map(fmt_io).collect();
5090                write!(f, "{} [{}] {{...}}", KEYWORD_WITH_IO, p.join(", "))
5091            }
5092            StepKind::CopyGit {
5093                rev,
5094                from,
5095                to,
5096                include_dirty,
5097            } => {
5098                if *include_dirty {
5099                    write!(
5100                        f,
5101                        "{} --include-dirty {} {} {}",
5102                        KEYWORD_COPY_GIT,
5103                        fmt_value(rev, quote_arg),
5104                        fmt_value(from, quote_arg),
5105                        fmt_value(to, quote_arg)
5106                    )
5107                } else {
5108                    write!(
5109                        f,
5110                        "{} {} {} {}",
5111                        KEYWORD_COPY_GIT,
5112                        fmt_value(rev, quote_arg),
5113                        fmt_value(from, quote_arg),
5114                        fmt_value(to, quote_arg)
5115                    )
5116                }
5117            }
5118            StepKind::Exit(code) => write!(f, "{} {}", KEYWORD_EXIT, fmt_raw_arg(code)),
5119            StepKind::Fail {
5120                code,
5121                message,
5122                body,
5123            } => {
5124                write!(f, "{}", KEYWORD_FAIL)?;
5125                if let Some(c) = code {
5126                    write!(f, " {}", fmt_raw_arg(c))?;
5127                }
5128                if let Some(m) = message {
5129                    // Quoting decides (`FAIL 2` is a silent code,
5130                    // `FAIL "2"` prints): a bare int-like message with
5131                    // no code alongside would reparse as the code, so
5132                    // pin quotes to keep the round-trip from inverting
5133                    // a message into a silent code.
5134                    let rendered = match m {
5135                        Arg::String(s, _)
5136                            if code.is_none()
5137                                && crate::command::strip_digit_separators(s)
5138                                    .parse::<i64>()
5139                                    .is_ok() =>
5140                        {
5141                            quote_dsl_string(s)
5142                        }
5143                        _ => fmt_value(m, quote_msg),
5144                    };
5145                    write!(f, " {rendered}")?;
5146                }
5147                if body.is_empty() {
5148                    // Only `FAIL {}` reaches here with neither code nor
5149                    // message (bare `FAIL` is a parse error): render the
5150                    // braces back so the empty block round-trips instead
5151                    // of collapsing into unparseable `FAIL`.
5152                    if code.is_none() && message.is_none() {
5153                        return write!(f, " {{}}");
5154                    }
5155                    return Ok(());
5156                }
5157                write!(f, " {{")?;
5158                for s in body {
5159                    write!(f, "\n    {}", s)?;
5160                }
5161                write!(f, "\n}}")
5162            }
5163            StepKind::Sleep { duration } => {
5164                write!(f, "{} {}", KEYWORD_SLEEP, fmt_raw_arg(duration))
5165            }
5166            StepKind::ListAppend { list, item } => {
5167                write!(f, "{} ${} {}", KEYWORD_LIST_APPEND, list, fmt_raw_arg(item))
5168            }
5169            StepKind::For {
5170                key_var,
5171                key_type,
5172                var,
5173                var_type,
5174                in_expr,
5175                body,
5176            } => {
5177                match key_var {
5178                    Some(k) => {
5179                        let kt = key_type.as_deref().unwrap_or("STRING");
5180                        write!(
5181                            f,
5182                            "{} ${}: {}, ${}: {} IN {} {{",
5183                            KEYWORD_FOR, k, kt, var, var_type, in_expr
5184                        )?
5185                    }
5186                    None => write!(
5187                        f,
5188                        "{} ${}: {} IN {} {{",
5189                        KEYWORD_FOR, var, var_type, in_expr
5190                    )?,
5191                }
5192                for s in body {
5193                    write!(f, "\n    {}", s)?;
5194                }
5195                write!(f, "\n}}")
5196            }
5197            StepKind::If {
5198                cond,
5199                then_body,
5200                else_ifs,
5201                else_body,
5202            } => {
5203                write!(f, "{} {} {{", KEYWORD_IF, cond)?;
5204                for s in then_body {
5205                    write!(f, "\n    {}", s)?;
5206                }
5207                write!(f, " }}")?;
5208                for (c, b) in else_ifs {
5209                    write!(f, " {} {} {} {{", KEYWORD_ELSE, KEYWORD_IF, c)?;
5210                    for s in b {
5211                        write!(f, "\n    {}", s)?;
5212                    }
5213                    write!(f, " }}")?;
5214                }
5215                if let Some(b) = else_body {
5216                    write!(f, " {} {{", KEYWORD_ELSE)?;
5217                    for s in b {
5218                        write!(f, "\n    {}", s)?;
5219                    }
5220                    write!(f, " }}")?;
5221                }
5222                Ok(())
5223            }
5224            StepKind::Switch {
5225                discriminant,
5226                cases,
5227                default_body,
5228            } => {
5229                match discriminant {
5230                    Some(disc) => write!(f, "{} {} {{", KEYWORD_SWITCH, disc)?,
5231                    None => write!(f, "{} {{", KEYWORD_SWITCH)?,
5232                }
5233                for (exprs, body) in cases {
5234                    write!(f, " {} ", KEYWORD_CASE)?;
5235                    for (i, expr) in exprs.iter().enumerate() {
5236                        if i > 0 {
5237                            write!(f, ", ")?;
5238                        }
5239                        write!(f, "{}", expr)?;
5240                    }
5241                    write!(f, " {{")?;
5242                    for s in body {
5243                        write!(f, "\n    {}", s)?;
5244                    }
5245                    write!(f, " }}")?;
5246                }
5247                if let Some(b) = default_body {
5248                    write!(f, " {} {{", KEYWORD_DEFAULT)?;
5249                    for s in b {
5250                        write!(f, "\n    {}", s)?;
5251                    }
5252                    write!(f, " }}")?;
5253                }
5254                write!(f, " }}")
5255            }
5256            StepKind::Assign {
5257                var,
5258                decl_type,
5259                expr,
5260            } => {
5261                // Bare pipe declarations round-trip without an initializer.
5262                if matches!(expr, Expr::FreshPipe) {
5263                    write!(f, "{} ${}: {}", KEYWORD_LET, var, decl_type)
5264                } else {
5265                    write!(f, "{} ${}: {} = {}", KEYWORD_LET, var, decl_type, expr)
5266                }
5267            }
5268            StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
5269            StepKind::AssignCapture {
5270                var,
5271                decl_type,
5272                cmd,
5273            } => {
5274                write!(f, "{} ${}: {} = {}", KEYWORD_LET, var, decl_type, cmd)
5275            }
5276            StepKind::AsyncBlock { body } => {
5277                write!(f, "{} {{", KEYWORD_ASYNC)?;
5278                for s in body {
5279                    write!(f, "\n    {}", s)?;
5280                }
5281                write!(f, "\n}}")
5282            }
5283            StepKind::AssignAsync {
5284                var,
5285                decl_type,
5286                body,
5287            } => {
5288                write!(
5289                    f,
5290                    "{} ${}: {} = {} {{",
5291                    KEYWORD_LET, var, decl_type, KEYWORD_ASYNC
5292                )?;
5293                for s in body {
5294                    write!(f, "\n    {}", s)?;
5295                }
5296                write!(f, "\n}}")
5297            }
5298            StepKind::Await { var } => write!(f, "{} ${}", KEYWORD_AWAIT, var),
5299            StepKind::AwaitCapture {
5300                out_var,
5301                out_type,
5302                task_var,
5303            } => {
5304                write!(
5305                    f,
5306                    "{} ${}: {} = {} ${}",
5307                    KEYWORD_LET, out_var, out_type, KEYWORD_AWAIT, task_var
5308                )
5309            }
5310            StepKind::Cancel { var } => write!(f, "{} ${}", KEYWORD_CANCEL, var),
5311            StepKind::Timeout { duration, body } => {
5312                let budget = fmt_raw_arg(duration);
5313                // Single-command form cannot carry an inner guard (the
5314                // grammar has no guard slot there), so guarded singles
5315                // take block form rather than silently dropping it.
5316                if body.len() == 1 && body[0].guard.is_none() {
5317                    write!(f, "{} {} {}", KEYWORD_TIMEOUT, budget, body[0].kind)
5318                } else {
5319                    write!(f, "{} {} {{", KEYWORD_TIMEOUT, budget)?;
5320                    for s in body {
5321                        write!(f, "\n    {}", s)?;
5322                    }
5323                    write!(f, "\n}}")
5324                }
5325            }
5326            StepKind::Isolated { body } => {
5327                if body.len() == 1 && body[0].guard.is_none() {
5328                    write!(f, "{} {}", KEYWORD_ISOLATED, body[0].kind)
5329                } else {
5330                    write!(f, "{} {{", KEYWORD_ISOLATED)?;
5331                    for s in body {
5332                        write!(f, "\n    {}", s)?;
5333                    }
5334                    write!(f, "\n}}")
5335                }
5336            }
5337            StepKind::IsolatedInheritEnv { keys } => {
5338                // Deliberately the prelude spelling: the node only ever
5339                // renders nested inside ISOLATED Display, where readers
5340                // see the enclosing block for what it is.
5341                write!(f, "{} [{}]", KEYWORD_INHERIT_ENV, keys.join(", "))
5342            }
5343            StepKind::RemoteBlock {
5344                target,
5345                vars,
5346                env,
5347                body,
5348            } => {
5349                let mut entries: Vec<String> = vars.iter().map(|v| format!("${v}")).collect();
5350                entries.extend(env.iter().map(|e| format!("env:{e}")));
5351                if entries.is_empty() {
5352                    write!(f, "{} {target} {{", KEYWORD_REMOTE)?;
5353                } else {
5354                    write!(f, "{} {target} [{}] {{", KEYWORD_REMOTE, entries.join(", "))?;
5355                }
5356                for s in body {
5357                    write!(f, "\n    {}", s)?;
5358                }
5359                write!(f, "\n}}")
5360            }
5361            StepKind::FuncDef {
5362                name,
5363                params,
5364                return_type,
5365                is_async,
5366                body,
5367                docs,
5368            } => {
5369                // Doc blocks render back as `#` lines so Display
5370                // reparses to identical docs (first line is the
5371                // summary, the rest follow verbatim).
5372                if let Some((_, full)) = docs {
5373                    for doc_line in full.split('\n') {
5374                        writeln!(f, "# {doc_line}")?;
5375                    }
5376                }
5377                let ps: Vec<String> = params
5378                    .iter()
5379                    .map(|(p, t, optional)| {
5380                        format!("${}{}: {}", p, if *optional { "?" } else { "" }, t)
5381                    })
5382                    .collect();
5383                if *is_async {
5384                    write!(
5385                        f,
5386                        "{} {} {}({}): {} {{",
5387                        KEYWORD_ASYNC,
5388                        KEYWORD_FUNC,
5389                        name,
5390                        ps.join(", "),
5391                        return_type
5392                    )?;
5393                } else {
5394                    write!(
5395                        f,
5396                        "{} {}({}): {} {{",
5397                        KEYWORD_FUNC,
5398                        name,
5399                        ps.join(", "),
5400                        return_type
5401                    )?;
5402                }
5403                for s in body {
5404                    write!(f, "\n    {}", s)?;
5405                }
5406                write!(f, "\n}}")
5407            }
5408            StepKind::Call { name, args } => {
5409                let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
5410                write!(f, "{}({})", name, ps.join(", "))
5411            }
5412            StepKind::ImportFile { path, alias } => {
5413                write!(f, "{} [\"{}\" AS {}]", KEYWORD_IMPORT, path, alias)
5414            }
5415            StepKind::ImportFuncs {
5416                path,
5417                alias,
5418                func_names,
5419                type_names,
5420            } => {
5421                let mut parts: Vec<String> = Vec::new();
5422                for t in type_names {
5423                    parts.push(format!("{KEYWORD_TYPE} {t}"));
5424                }
5425                for n in func_names {
5426                    parts.push(n.clone());
5427                }
5428                match alias {
5429                    Some(alias) => write!(
5430                        f,
5431                        "{} [[{} FROM \"{}\" AS {}]]",
5432                        KEYWORD_IMPORT,
5433                        parts.join(", "),
5434                        path,
5435                        alias
5436                    ),
5437                    None => write!(
5438                        f,
5439                        "{} [[{} FROM \"{}\"]]",
5440                        KEYWORD_IMPORT,
5441                        parts.join(", "),
5442                        path
5443                    ),
5444                }
5445            }
5446            StepKind::Return { expr, is_bare } => {
5447                if *is_bare {
5448                    write!(f, "{KEYWORD_RETURN}")
5449                } else {
5450                    write!(f, "{} {}", KEYWORD_RETURN, expr)
5451                }
5452            }
5453            StepKind::TypeAlias { name, target } => {
5454                write!(f, "{} {} = {}", KEYWORD_TYPE, name, target)
5455            }
5456            StepKind::While { cond, body } => {
5457                write!(f, "{} {} {{", KEYWORD_WHILE, cond)?;
5458                for s in body {
5459                    write!(f, "\n    {}", s)?;
5460                }
5461                write!(f, "\n}}")
5462            }
5463            StepKind::Break => write!(f, "{KEYWORD_BREAK}"),
5464            StepKind::Continue => write!(f, "{KEYWORD_CONTINUE}"),
5465        }
5466    }
5467}
5468
5469/// One lowered instruction token: a positional argument, or a pre-split
5470/// `KEY=value` assignment from the unified grammar rule. Assignments reach
5471/// ENV/EXPAND lowerings intact; every other command sees them collapsed to
5472/// canonical `key=value` text (see `lower_instruction_pair`).
5473pub(crate) enum InsToken {
5474    Pos(Arg),
5475    Assign(String, Arg),
5476}
5477
5478pub(crate) fn lower_env_tokens(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
5479    if tokens.is_empty() {
5480        return Err(ParseError::validation(
5481            KEYWORD_ENV,
5482            "ENV requires KEY=value".to_string(),
5483            ctx,
5484        ));
5485    }
5486    match tokens.as_slice() {
5487        [InsToken::Assign(key, value)] => {
5488            // Same KEY=value check the ENV lower applies on the
5489            // `lower_command` path, over the joined assignment form.
5490            if crate::command::split_assignment(&format!("{key}={}", value.render()))
5491                .map_err(|e| ParseError::validation(KEYWORD_ENV, e.to_string(), ctx))?
5492                .is_none()
5493            {
5494                return Err(ParseError::validation(
5495                    KEYWORD_ENV,
5496                    "ENV requires KEY=value format".to_string(),
5497                    ctx,
5498                ));
5499            }
5500            Ok(StepKind::Env {
5501                key: key.clone(),
5502                value: value.clone(),
5503            })
5504        }
5505        [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
5506            .map_err(|e| ParseError::validation(KEYWORD_ENV, e.to_string(), ctx))?
5507        {
5508            Some((key, value)) => Ok(StepKind::Env { key, value }),
5509            None => Err(ParseError::validation(
5510                KEYWORD_ENV,
5511                "ENV requires KEY=value format".to_string(),
5512                ctx,
5513            )),
5514        },
5515        _ => Err(ParseError::validation(
5516            KEYWORD_ENV,
5517            "ENV requires KEY=value format".to_string(),
5518            ctx,
5519        )),
5520    }
5521}
5522
5523/// Parser-direct `EXPAND` lowering: positional tokens are the optional path,
5524/// assignments are overrides. Split quoted values can never masquerade as
5525/// extra paths : tokenize time already proved they are one value.
5526pub(crate) fn lower_expand_tokens(
5527    ctx: &SpanContext,
5528    tokens: Vec<InsToken>,
5529) -> ParseResult<StepKind> {
5530    let mut path = None;
5531    let mut overrides = Vec::new();
5532    for token in tokens {
5533        match token {
5534            InsToken::Assign(key, value) => {
5535                if key.is_empty() {
5536                    return Err(ParseError::validation(
5537                        KEYWORD_EXPAND,
5538                        "EXPAND requires KEY=value format for overrides".to_string(),
5539                        ctx,
5540                    ));
5541                }
5542                overrides.push((key, value));
5543            }
5544            InsToken::Pos(arg) => match &arg {
5545                Arg::String(text, quoted) if !quoted && text.contains('=') => {
5546                    let Some((key, value)) = crate::command::split_assignment(text)
5547                        .map_err(|e| ParseError::validation(KEYWORD_EXPAND, e.to_string(), ctx))?
5548                    else {
5549                        return Err(ParseError::validation(
5550                            KEYWORD_EXPAND,
5551                            "EXPAND requires KEY=value format for overrides".to_string(),
5552                            ctx,
5553                        ));
5554                    };
5555                    overrides.push((key, value));
5556                }
5557                _ => {
5558                    if path.is_none() {
5559                        // Path-typed positional, checked like every other
5560                        // `lower_command` path arg (literals always pass;
5561                        // resolution stays runtime).
5562                        ArgType::Path.check_arg(&arg).map_err(|e| {
5563                            ParseError::validation(KEYWORD_EXPAND, e.to_string(), ctx)
5564                        })?;
5565                        path = Some(arg);
5566                    } else {
5567                        return Err(ParseError::validation(
5568                            KEYWORD_EXPAND,
5569                            "EXPAND accepts at most one path".to_string(),
5570                            ctx,
5571                        ));
5572                    }
5573                }
5574            },
5575        }
5576    }
5577    Ok(StepKind::Expand { path, overrides })
5578}
5579
5580/// Wrapper-shared validators, promoted verbatim from the retired pest
5581/// backend, so every parse entry point enforces identical bodies.
5582/// Pure outcome logic over [`StepKind`]: contexts only feed error spans.
5583#[derive(Default)]
5584pub(crate) struct IoBindingSet {
5585    stdin: Option<IoBinding>,
5586    stdout: Option<IoBinding>,
5587    stderr: Option<IoBinding>,
5588    tty: Option<IoBinding>,
5589    rows: Option<IoBinding>,
5590    cols: Option<IoBinding>,
5591}
5592
5593impl IoBindingSet {
5594    pub(crate) fn insert(&mut self, binding: IoBinding) {
5595        match binding.stream {
5596            IoStream::Stdin => self.stdin = Some(binding),
5597            IoStream::Stdout => self.stdout = Some(binding),
5598            IoStream::Stderr => self.stderr = Some(binding),
5599            IoStream::Tty => self.tty = Some(binding),
5600            IoStream::Rows(_) => self.rows = Some(binding),
5601            IoStream::Cols(_) => self.cols = Some(binding),
5602        }
5603    }
5604
5605    pub(crate) fn into_vec(self) -> Vec<IoBinding> {
5606        let mut out = Vec::new();
5607        if let Some(binding) = self.stdin {
5608            out.push(binding);
5609        }
5610        if let Some(binding) = self.stdout {
5611            out.push(binding);
5612        }
5613        if let Some(binding) = self.stderr {
5614            out.push(binding);
5615        }
5616        if let Some(binding) = self.tty {
5617            out.push(binding);
5618        }
5619        if let Some(binding) = self.rows {
5620            out.push(binding);
5621        }
5622        if let Some(binding) = self.cols {
5623            out.push(binding);
5624        }
5625        out
5626    }
5627}
5628
5629pub(crate) fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
5630    let mut set = IoBindingSet::default();
5631    for binding in defaults {
5632        set.insert(binding.clone());
5633    }
5634    for binding in overrides {
5635        set.insert(binding.clone());
5636    }
5637    set.into_vec()
5638}
5639
5640pub(crate) fn and_guard_exprs(
5641    left: Option<GuardExpr>,
5642    right: Option<GuardExpr>,
5643) -> Option<GuardExpr> {
5644    match (left, right) {
5645        (None, None) => None,
5646        (Some(expr), None) | (None, Some(expr)) => Some(expr),
5647        (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
5648    }
5649}
5650
5651pub(crate) fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
5652    bindings
5653        .iter()
5654        .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
5655}
5656
5657/// Reject async machinery inside a capture body: background tasks are
5658/// captured via `LET $o: STRING = AWAIT $t`, never inline.
5659pub(crate) fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
5660    let bad = match kind {
5661        StepKind::AsyncBlock { .. }
5662        | StepKind::AssignAsync { .. }
5663        | StepKind::Await { .. }
5664        | StepKind::AwaitCapture { .. }
5665        | StepKind::Cancel { .. } => true,
5666        _ => {
5667            let mut bad = false;
5668            kind.walk_child_kinds(&mut |child| {
5669                bad = bad || reject_async_in_capture(ctx, child).is_err();
5670            });
5671            bad
5672        }
5673    };
5674    if bad {
5675        return Err(ParseError::structural("let", "LET capture cannot run ASYNC/AWAIT/CANCEL inline; use LET $t: HANDLE<T> = ASYNC ... then LET $o: STRING = AWAIT $t".to_string(), ctx));
5676    }
5677    Ok(())
5678}
5679
5680/// Reject `WITH_IO [stdout=$var]` anywhere inside a capture body: the
5681/// capture sink owns stdout.
5682pub(crate) fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
5683    if let StepKind::WithIo { bindings, .. } = kind
5684        && has_stdout_pipe(bindings)
5685    {
5686        return Err(ParseError::structural(
5687            "let",
5688            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
5689                .to_string(),
5690            ctx,
5691        ));
5692    }
5693    let mut result = Ok(());
5694    kind.walk_child_kinds(&mut |child| {
5695        if result.is_ok() {
5696            result = reject_pipe_stdout_in_capture(ctx, child);
5697        }
5698    });
5699    result
5700}
5701
5702/// Rewrite prelude-shaped `INHERIT_ENV` nodes anywhere inside an `ISOLATED`
5703/// body into `IsolatedInheritEnv`: the nested allowlist reads the isolated
5704/// snapshot, never the host.
5705pub(crate) fn rewrite_isolated_inherit(body: &mut [Step]) {
5706    for step in body {
5707        rewrite_isolated_inherit_kind(&mut step.kind);
5708    }
5709}
5710
5711/// Single-kind half of [`rewrite_isolated_inherit`]: rewrite the node
5712/// itself, then recurse through whatever it contains (`WITH_IO` wraps and
5713/// captures hold one kind; loop/if bodies hold steps).
5714pub(crate) fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
5715    if let StepKind::InheritEnv { keys } = kind {
5716        *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
5717    }
5718    match kind {
5719        StepKind::For { body, .. }
5720        | StepKind::While { body, .. }
5721        | StepKind::Timeout { body, .. }
5722        | StepKind::Fail { body, .. }
5723        | StepKind::Isolated { body }
5724        | StepKind::AssignAsync { body, .. }
5725        | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
5726        StepKind::If {
5727            then_body,
5728            else_ifs,
5729            else_body,
5730            ..
5731        } => {
5732            rewrite_isolated_inherit(then_body);
5733            for (_, branch) in else_ifs {
5734                rewrite_isolated_inherit(branch);
5735            }
5736            if let Some(else_body) = else_body {
5737                rewrite_isolated_inherit(else_body);
5738            }
5739        }
5740        StepKind::Switch {
5741            cases,
5742            default_body,
5743            ..
5744        } => {
5745            for (_, branch) in cases {
5746                rewrite_isolated_inherit(branch);
5747            }
5748            if let Some(default_body) = default_body {
5749                rewrite_isolated_inherit(default_body);
5750            }
5751        }
5752        StepKind::WithIo { cmd, .. } | StepKind::AssignCapture { cmd, .. } => {
5753            rewrite_isolated_inherit_kind(cmd);
5754        }
5755        _ => {}
5756    }
5757}
5758
5759pub(crate) fn contains_inherit_env(kind: &StepKind) -> bool {
5760    if matches!(kind, StepKind::InheritEnv { .. }) {
5761        return true;
5762    }
5763    let mut found = false;
5764    kind.walk_child_kinds(&mut |child| {
5765        found = found || contains_inherit_env(child);
5766    });
5767    found
5768}
5769
5770/// Reject an `INHERIT_ENV` nested anywhere inside another command: the
5771/// prelude directive only reads at statement level (and, rewritten,
5772/// inside `ISOLATED` bodies, which never reach here).
5773pub(crate) fn reject_nested_inherit_env(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
5774    if contains_inherit_env(kind) {
5775        return Err(ParseError::structural(
5776            "inherit_env",
5777            "INHERIT_ENV cannot be nested inside other commands".to_string(),
5778            ctx,
5779        ));
5780    }
5781    Ok(())
5782}
5783
5784pub(crate) fn check_tty_wrapping(
5785    bindings: &[IoBinding],
5786    cmd: Option<&StepKind>,
5787    span: &SpanContext,
5788) -> ParseResult<()> {
5789    let has_tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
5790    let has_geometry = bindings
5791        .iter()
5792        .any(|b| matches!(b.stream, IoStream::Rows(_) | IoStream::Cols(_)));
5793    if has_geometry && !has_tty {
5794        return Err(ParseError::structural(
5795            "with_io",
5796            "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size".to_string(),
5797            span,
5798        ));
5799    }
5800    if !has_tty {
5801        return Ok(());
5802    }
5803    if bindings
5804        .iter()
5805        .any(|b| matches!(b.stream, IoStream::Stderr))
5806    {
5807        return Err(ParseError::structural(
5808            "with_io",
5809            "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex".to_string(),
5810            span,
5811        ));
5812    }
5813    match cmd {
5814        Some(StepKind::Run(_) | StepKind::RunExec { .. }) | None => Ok(()),
5815        Some(_) => Err(ParseError::structural(
5816            "with_io",
5817            "WITH_IO [tty] only wraps a RUN step: the pty master is one interleaved child stream, so terminal-unaware commands cannot run under it".to_string(),
5818            span,
5819        )),
5820    }
5821}
5822
5823/// Reject `WITH_IO` steps directly inside an `ASYNC` body: pipe wiring
5824/// belongs outside the task (`WITH_IO [...] ASYNC ...`), never inside.
5825pub(crate) fn reject_with_io_in_async(ctx: &SpanContext, body: &[Step]) -> ParseResult<()> {
5826    for step in body {
5827        if matches!(&step.kind, StepKind::WithIo { .. }) {
5828            return Err(ParseError::structural("async", "WITH_IO cannot be placed inside ASYNC. Place WITH_IO outside ASYNC instead (e.g. WITH_IO [...] ASYNC RUN ...)".to_string(), ctx));
5829        }
5830    }
5831    Ok(())
5832}
5833
5834/// Validate `EXPORT` names at end of parse. Forward references are
5835/// allowed (EXPORT may precede its FUNCs), so this runs against the
5836/// completed top-level scope. Bare names must match a top-level
5837/// `FUNC`; qualified `MOD::NAME` names must match a known module
5838/// member (opaque modules skip the member check; the runtime registry
5839/// resolves them or fails serving). Duplicates are rejected at the
5840/// EXPORT site. Promoted verbatim (the pest finish pass delegates).
5841pub(crate) fn validate_exports(
5842    ctx: &SpanContext,
5843    func_exports: &[String],
5844    type_exports: &[String],
5845    top: &HashSet<String>,
5846    top_types: &HashSet<String>,
5847    modules: &ModuleTable,
5848    top_imports: &[String],
5849) -> ParseResult<()> {
5850    for name in func_exports {
5851        let valid = match name.split_once(crate::constants::MODULE_SEPARATOR) {
5852            None => top.contains(name),
5853            Some((module, base)) if module == crate::constants::SCRIPT_MODULE_NAME => {
5854                top.contains(base)
5855            }
5856            Some((module, _base)) => match modules.modules.get(module) {
5857                None => {
5858                    // File-import aliases (#115) never enter the module
5859                    // table: a re-export names an imported function for
5860                    // the entry's own tool surface. The alias must be a
5861                    // visible import; whether the file actually exports
5862                    // the name is checked where the import loads (closure
5863                    // validation, then serving), since parse performs no
5864                    // IO. Anything else is an unknown module.
5865                    top_imports.iter().any(|m| m == module)
5866                }
5867                Some(None) => true,
5868                Some(Some(funcs)) => funcs.func_names.contains(_base),
5869            },
5870        };
5871        if !valid {
5872            return Err(ParseError::validation(
5873                crate::constants::KEYWORD_EXPORT,
5874                format!("EXPORT `{name}` does not match any top-level FUNC or known module member"),
5875                ctx,
5876            ));
5877        }
5878    }
5879    for name in type_exports {
5880        // Local TYPE aliases export bare; qualified `ALIAS::TYPE`
5881        // re-exports defer existence to import loading (same as func
5882        // re-exports), requiring only a visible import alias here.
5883        // Bare re-exports of imported types (whole-file types land
5884        // bare) defer when the file has imports, so `EXPORT PERSON`
5885        // after `IMPORT ["lib" AS LIB]` can promote the imported type.
5886        let valid = match name.split_once(crate::constants::MODULE_SEPARATOR) {
5887            None => top_types.contains(name) || !top_imports.is_empty(),
5888            Some((module, _base)) => {
5889                if module == crate::constants::SCRIPT_MODULE_NAME {
5890                    top_types.contains(_base)
5891                } else {
5892                    match modules.modules.get(module) {
5893                        None => top_imports.iter().any(|m| m == module),
5894                        // Host modules: types live in the global type
5895                        // directory, not the func table. Parse cannot
5896                        // know host type membership (descriptors register
5897                        // at runtime), so a known module passes here and
5898                        // import loading validates the member.
5899                        Some(_) => true,
5900                    }
5901                }
5902            }
5903        };
5904        if !valid {
5905            return Err(ParseError::validation(
5906                crate::constants::KEYWORD_EXPORT,
5907                format!("EXPORT TYPE `{name}` does not match any top-level TYPE"),
5908                ctx,
5909            ));
5910        }
5911    }
5912    Ok(())
5913}
5914
5915/// REMOTE whole-script validators and body-symbol collectors,
5916/// promoted verbatim from the pest backend (which delegates) so both
5917/// parse pathways enforce identical blocks.
5918/// Reject `COPY --from-host` / `--to-host` outside `REMOTE` bodies.
5919/// Transfer declarations only mean something where a session hoists them;
5920/// anywhere else they would silently behave as local copies.
5921pub(crate) fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
5922    fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
5923        if let StepKind::Copy {
5924            from_host, to_host, ..
5925        } = kind
5926            && (*from_host || *to_host)
5927            && !in_remote
5928        {
5929            return Err(ParseError::structural(
5930                "copy",
5931                "COPY --from-host and --to-host are only valid inside a REMOTE block".to_string(),
5932                ctx,
5933            ));
5934        }
5935        let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
5936        let mut result = Ok(());
5937        kind.walk_child_kinds(&mut |child| {
5938            if result.is_ok() {
5939                result = visit_kind(child, child_remote, ctx);
5940            }
5941        });
5942        result
5943    }
5944    for step in steps {
5945        visit_kind(&step.kind, false, ctx)?;
5946    }
5947    Ok(())
5948}
5949
5950/// True when any step in the slice (transitively, through nested bodies)
5951/// is a `REMOTE` block. `REMOTE` blocks never nest: the inner block would
5952/// have no session, no inventory, and no defined sync boundary.
5953pub(crate) fn contains_remote_block(steps: &[Step]) -> bool {
5954    steps.iter().any(|step| contains_remote_kind(&step.kind))
5955}
5956
5957pub(crate) fn contains_remote_kind(kind: &StepKind) -> bool {
5958    if matches!(kind, StepKind::RemoteBlock { .. }) {
5959        return true;
5960    }
5961    let mut found = false;
5962    kind.walk_child_kinds(&mut |child| {
5963        found = found || contains_remote_kind(child);
5964    });
5965    found
5966}
5967
5968/// Collect transitively defined `FUNC` names and invoked call names from a
5969/// `REMOTE` body. Statement calls, expression calls (including compiled
5970/// math ops and inline blocks), and calls nested in any sub-body are all
5971/// covered through the uniform [`StepKind`] walkers. Only user-defined
5972/// `SCRIPT` symbols matter downstream: qualified module calls pass through.
5973pub(crate) fn collect_remote_body_symbols(
5974    steps: &[Step],
5975    defs: &mut HashSet<String>,
5976    calls: &mut Vec<String>,
5977) {
5978    for step in steps {
5979        collect_remote_kind_symbols(&step.kind, defs, calls);
5980    }
5981}
5982
5983pub(crate) fn collect_remote_kind_symbols(
5984    kind: &StepKind,
5985    defs: &mut HashSet<String>,
5986    calls: &mut Vec<String>,
5987) {
5988    if let StepKind::FuncDef { name, .. } = kind {
5989        defs.insert(name.clone());
5990    }
5991    if let StepKind::Call { name, .. } = kind {
5992        calls.push(name.clone());
5993    }
5994    kind.walk_step_exprs(&mut |expr| match expr {
5995        Expr::Call { name, .. } => calls.push(name.clone()),
5996        Expr::CompiledMath(ops) => {
5997            for op in ops {
5998                if let MathOp::Call { name, .. } = op {
5999                    calls.push(name.clone());
6000                }
6001            }
6002        }
6003        Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
6004        _ => {}
6005    });
6006}
6007
6008/// Expression lowering core, promoted verbatim from the retired pest
6009/// backend: folding constructors, RPN compilation, boundary rejection,
6010/// and numeric classification. The parser calls
6011/// these directly, so folding and overflow behavior are single-sourced.
6012/// Reject a staged `UnsignedIntBoundary` in any position where unary `-`
6013/// cannot consume it (every compound constructor calls this on children).
6014/// Expression lowering core (promoted verbatim from the retired pest
6015/// backend): operates on `Expr`, never on token pairs.
6016pub(crate) fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
6017    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6018        return Err(ParseError::structural(
6019            "expr",
6020            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
6021            ctx,
6022        ));
6023    }
6024    Ok(())
6025}
6026
6027/// Apply unary `-`: fold literals, consume the `i64::MIN` boundary, else
6028/// compile to RPN `Neg` (or AST `0 - x` fallback for non-math operands).
6029/// Shared with the v2 backend.
6030pub(crate) fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
6031    match expr {
6032        Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
6033            (Some(n), _) => match n.checked_neg() {
6034                Some(neg) => Ok(Expr::Literal(Value::int(neg))),
6035                None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
6036            },
6037            (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
6038            (None, None) => {
6039                let other = Expr::Literal(v);
6040                if let Some(mut ops) = expr_to_rpn(&other) {
6041                    ops.push(MathOp::Neg);
6042                    Ok(Expr::CompiledMath(ops))
6043                } else {
6044                    // Non-math operand (list/map/logical): `0 - x` evaluates via
6045                    // the shared arithmetic helper to a runtime Type Error.
6046                    Ok(Expr::Arithmetic {
6047                        op: ArithOp::Sub,
6048                        left: Box::new(Expr::Literal(Value::int(0))),
6049                        right: Box::new(other),
6050                    })
6051                }
6052            }
6053        },
6054        Expr::UnsignedIntBoundary(n) => {
6055            if n == i64::MAX as u64 + 1 {
6056                Ok(Expr::Literal(Value::int(i64::MIN)))
6057            } else {
6058                Err(ParseError::structural(
6059                    "expr",
6060                    format!("integer overflow: {} exceeds i64::MAX", n),
6061                    ctx,
6062                ))
6063            }
6064        }
6065        other => {
6066            if let Some(mut ops) = expr_to_rpn(&other) {
6067                ops.push(MathOp::Neg);
6068                Ok(Expr::CompiledMath(ops))
6069            } else {
6070                // Non-math operand (list/map/logical): `0 - x` evaluates via
6071                // the shared arithmetic helper to a runtime Type Error.
6072                Ok(Expr::Arithmetic {
6073                    op: ArithOp::Sub,
6074                    left: Box::new(Expr::Literal(Value::int(0))),
6075                    right: Box::new(other),
6076                })
6077            }
6078        }
6079    }
6080}
6081
6082/// Try parse-time constant folding for binary arithmetic/comparison.
6083/// Returns `Some(literal)` on success, `None` when not both literals or
6084/// when the op would error at runtime (div-zero/overflow/non-finite:
6085/// leave for the RPN evaluator so the error surfaces at runtime).
6086fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
6087    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
6088        return None;
6089    };
6090    fold_arith_values(op, lv, rv).map(Expr::Literal)
6091}
6092
6093fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
6094    match (left.as_i64(), right.as_i64()) {
6095        (Some(a), Some(b)) => {
6096            let v = match op {
6097                ArithOp::Add => a.checked_add(b)?,
6098                ArithOp::Sub => a.checked_sub(b)?,
6099                ArithOp::Mul => a.checked_mul(b)?,
6100                ArithOp::Div => a.checked_div(b)?,
6101            };
6102            Some(Value::int(v))
6103        }
6104        _ => {
6105            let (af, bf) = (as_f64(left)?, as_f64(right)?);
6106            fold_float(op, af, bf)
6107        }
6108    }
6109}
6110
6111fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
6112    if !a.is_finite() || !b.is_finite() {
6113        return None;
6114    }
6115    let v = match op {
6116        ArithOp::Add => a + b,
6117        ArithOp::Sub => a - b,
6118        ArithOp::Mul => a * b,
6119        ArithOp::Div => {
6120            if b == 0.0 {
6121                return None;
6122            }
6123            a / b
6124        }
6125    };
6126    if v.is_finite() {
6127        Some(Value::float(v))
6128    } else {
6129        None
6130    }
6131}
6132
6133fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
6134    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
6135        return None;
6136    };
6137    match (lv.as_i64(), rv.as_i64()) {
6138        (Some(a), Some(b)) => {
6139            let r = match op {
6140                CompareOp::Eq => a == b,
6141                CompareOp::Ne => a != b,
6142                CompareOp::Lt => a < b,
6143                CompareOp::Le => a <= b,
6144                CompareOp::Gt => a > b,
6145                CompareOp::Ge => a >= b,
6146            };
6147            Some(Expr::Literal(Value::bool(r)))
6148        }
6149        _ => {
6150            if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
6151                return match op {
6152                    CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
6153                    CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
6154                    _ => None,
6155                };
6156            }
6157            let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
6158            let r = match op {
6159                CompareOp::Eq => af == bf,
6160                CompareOp::Ne => af != bf,
6161                CompareOp::Lt => af < bf,
6162                CompareOp::Le => af <= bf,
6163                CompareOp::Gt => af > bf,
6164                CompareOp::Ge => af >= bf,
6165            };
6166            Some(Expr::Literal(Value::bool(r)))
6167        }
6168    }
6169}
6170
6171fn as_f64(v: &Value) -> Option<f64> {
6172    if let Some(n) = v.as_i64() {
6173        return Some(n as f64);
6174    }
6175    match v.as_f64() {
6176        Some(f) if f.is_finite() => Some(f),
6177        _ => None,
6178    }
6179}
6180
6181/// Shared with the v2 backend: fold, compile to RPN, or keep the AST node.
6182pub(crate) fn make_arith(
6183    ctx: &SpanContext,
6184    op: ArithOp,
6185    left: Expr,
6186    right: Expr,
6187) -> ParseResult<Expr> {
6188    reject_boundary(ctx, &left)?;
6189    reject_boundary(ctx, &right)?;
6190    if let Some(folded) = try_fold_arith(op, &left, &right) {
6191        return Ok(folded);
6192    }
6193    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
6194        lops.append(&mut rops);
6195        lops.push(match op {
6196            ArithOp::Add => MathOp::Add,
6197            ArithOp::Sub => MathOp::Sub,
6198            ArithOp::Mul => MathOp::Mul,
6199            ArithOp::Div => MathOp::Div,
6200        });
6201        return Ok(Expr::CompiledMath(lops));
6202    }
6203    Ok(Expr::Arithmetic {
6204        op,
6205        left: Box::new(left),
6206        right: Box::new(right),
6207    })
6208}
6209
6210/// Shared with the v2 backend: fold, compile to RPN, or keep the AST node.
6211pub(crate) fn make_compare(
6212    ctx: &SpanContext,
6213    op: CompareOp,
6214    left: Expr,
6215    right: Expr,
6216) -> ParseResult<Expr> {
6217    reject_boundary(ctx, &left)?;
6218    reject_boundary(ctx, &right)?;
6219    if let Some(folded) = try_fold_compare(op, &left, &right) {
6220        return Ok(folded);
6221    }
6222    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
6223        lops.append(&mut rops);
6224        lops.push(match op {
6225            CompareOp::Eq => MathOp::Eq,
6226            CompareOp::Ne => MathOp::Ne,
6227            CompareOp::Lt => MathOp::Lt,
6228            CompareOp::Le => MathOp::Le,
6229            CompareOp::Gt => MathOp::Gt,
6230            CompareOp::Ge => MathOp::Ge,
6231        });
6232        return Ok(Expr::CompiledMath(lops));
6233    }
6234    Ok(Expr::Compare {
6235        op,
6236        left: Box::new(left),
6237        right: Box::new(right),
6238    })
6239}
6240
6241/// Convert an operand subtree to flat RPN. Returns `None` for shapes with
6242/// no RPN encoding (`Not`/`Logical`/`List`/`Map`/`FreshPipe`/stray boundary): callers
6243/// fall back to AST nodes evaluated recursively.
6244/// Shared with the v2 backend.
6245///
6246pub(crate) fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
6247    match expr {
6248        Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
6249        Expr::Var(name) => Some(vec![MathOp::LoadVar(name.clone())]),
6250        Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
6251        Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
6252            base: base.clone(),
6253            keys: keys.clone(),
6254        }]),
6255        Expr::Call { name, args } => {
6256            let mut ops = Vec::new();
6257            for arg in args {
6258                ops.extend(expr_to_rpn(arg)?);
6259            }
6260            ops.push(MathOp::Call {
6261                name: name.clone(),
6262                arity: args.len(),
6263            });
6264            Some(ops)
6265        }
6266        Expr::Inspect(var) => Some(vec![MathOp::Inspect(var.clone())]),
6267        Expr::Arithmetic { op, left, right } => {
6268            let mut ops = expr_to_rpn(left)?;
6269            ops.extend(expr_to_rpn(right)?);
6270            ops.push(match op {
6271                ArithOp::Add => MathOp::Add,
6272                ArithOp::Sub => MathOp::Sub,
6273                ArithOp::Mul => MathOp::Mul,
6274                ArithOp::Div => MathOp::Div,
6275            });
6276            Some(ops)
6277        }
6278        Expr::Compare { op, left, right } => {
6279            let mut ops = expr_to_rpn(left)?;
6280            ops.extend(expr_to_rpn(right)?);
6281            ops.push(match op {
6282                CompareOp::Eq => MathOp::Eq,
6283                CompareOp::Ne => MathOp::Ne,
6284                CompareOp::Lt => MathOp::Lt,
6285                CompareOp::Le => MathOp::Le,
6286                CompareOp::Gt => MathOp::Gt,
6287                CompareOp::Ge => MathOp::Ge,
6288            });
6289            Some(ops)
6290        }
6291        Expr::CompiledMath(ops) => Some(ops.clone()),
6292        Expr::FreshPipe => None,
6293        Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
6294        Expr::UnsignedIntBoundary(_) => None,
6295    }
6296}
6297
6298/// Pure numeric classification (the token backend gates
6299/// `_`-separator shape before calling: the classifier strips them, so
6300/// `1__0` must never reach it as numeric). Returns the literal,
6301/// `UnsignedIntBoundary` staging, or the exact pest error text.
6302pub(crate) fn classify_numeric_text(text: &str) -> Result<Expr, String> {
6303    let clean = text.replace('_', "");
6304    if clean.contains('.') {
6305        let parsed: f64 = clean
6306            .parse()
6307            .map_err(|_| format!("invalid float literal {text:?}"))?;
6308        if !parsed.is_finite() {
6309            return Err(format!("invalid float literal {text:?}"));
6310        }
6311        return Ok(Expr::Literal(Value::float(parsed)));
6312    }
6313    let digits: u64 = clean
6314        .parse()
6315        .map_err(|_| format!("integer overflow: {text:?} exceeds i64::MAX"))?;
6316    if digits <= i64::MAX as u64 {
6317        Ok(Expr::Literal(Value::int(digits as i64)))
6318    } else if digits == i64::MAX as u64 + 1 {
6319        Ok(Expr::UnsignedIntBoundary(digits))
6320    } else {
6321        Err(format!("integer overflow: {text:?} exceeds i64::MAX"))
6322    }
6323}
6324
6325#[cfg(test)]
6326mod tests {
6327    use super::*;
6328    use crate::command::{
6329        format_byte_count, format_duration, parse_byte_count, parse_duration,
6330        strip_digit_separators,
6331    };
6332    use crate::parser::parse_script;
6333
6334    fn parse_err(script: &str) -> String {
6335        parse_script(script, lower_command)
6336            .expect_err("script must fail to parse")
6337            .to_string()
6338    }
6339
6340    #[test]
6341    fn malformed_with_io_binding_names_the_bad_binding() {
6342        let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
6343        assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
6344        assert!(!err.contains("unknown command"), "{err}");
6345        assert!(err.contains("stdout=discard"), "{err}");
6346        assert!(err.contains("[stdout=$p]"), "{err}");
6347    }
6348
6349    #[test]
6350    fn connect_is_unknown_command() {
6351        // `CONNECT` left core for the NET plugin: the builtin name no
6352        // longer resolves. Use `NET_CONNECT` with explicit pipes.
6353        let err = parse_err("CONNECT 127.0.0.1:8080\n");
6354        assert!(err.contains("unknown command"), "{err}");
6355        assert!(err.contains("CONNECT"), "{err}");
6356    }
6357
6358    #[test]
6359    fn listen_is_unknown_command() {
6360        // `LISTEN` left core for the NET plugin: the builtin name no
6361        // longer resolves. Use `NET_LISTEN` for a listener handle.
6362        let err = parse_err("LISTEN 127.0.0.1:8080\n");
6363        assert!(err.contains("unknown command"), "{err}");
6364        assert!(err.contains("LISTEN"), "{err}");
6365    }
6366
6367    #[test]
6368    fn await_without_task_variable_points_at_syntax() {
6369        let err = parse_err("AWAIT ECHO \"test\"\n");
6370        assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
6371        assert!(!err.contains("unknown command"), "{err}");
6372        assert!(err.contains("AWAIT $t"), "{err}");
6373        assert!(err.contains("ECHO"), "{err}");
6374    }
6375
6376    #[test]
6377    fn bare_let_without_type_points_at_typed_syntax() {
6378        let err = parse_err("LET $x = 1\n");
6379        assert!(err.contains("LET requires explicit types"), "{err}");
6380        assert!(err.contains("LET $var: TYPE = <expr>"), "{err}");
6381    }
6382
6383    #[test]
6384    fn workspace_accepts_all_four_targets_uppercase_only() {
6385        // WORKSPACE targets are uppercase-only, like every other DSL
6386        // keyword argument: lowercase spellings are rejected.
6387        for (spelling, target) in [
6388            ("SNAPSHOT", WorkspaceTarget::Snapshot),
6389            ("LOCAL", WorkspaceTarget::Local),
6390            ("CACHE", WorkspaceTarget::Cache { local: false }),
6391            ("SYSTEM", WorkspaceTarget::System),
6392        ] {
6393            let steps =
6394                parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
6395            assert_eq!(steps.len(), 1);
6396            assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
6397            assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
6398        }
6399        for spelling in ["snapshot", "local", "cache", "system"] {
6400            let err = parse_err(&format!("WORKSPACE {spelling}\n"));
6401            assert!(
6402                err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
6403                "{spelling}: {err}"
6404            );
6405        }
6406        let err = parse_err("WORKSPACE REMOTE\n");
6407        assert!(
6408            err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
6409            "{err}"
6410        );
6411
6412        // `--local` selects the project-tree cache and round-trips
6413        // through Display; anywhere else it is rejected.
6414        let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
6415        assert_eq!(
6416            steps[0].kind,
6417            StepKind::Workspace(WorkspaceTarget::Cache { local: true })
6418        );
6419        assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
6420        for bad in [
6421            "WORKSPACE SNAPSHOT --local\n",
6422            "WORKSPACE LOCAL --local\n",
6423            "WORKSPACE SYSTEM --local\n",
6424        ] {
6425            let err = parse_err(bad);
6426            assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
6427        }
6428    }
6429
6430    #[test]
6431    fn archive_unarchive_parse_and_round_trip() {
6432        let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
6433        match &steps[0].kind {
6434            StepKind::Archive { src, dst, raw } => {
6435                assert_eq!(src.as_str(), "bundle");
6436                assert_eq!(dst.as_str(), "bundle.tar.gz");
6437                assert!(!raw);
6438            }
6439            other => panic!("expected Archive, got {other:?}"),
6440        }
6441        assert_eq!(
6442            steps[0].kind.to_string(),
6443            "ARCHIVE bundle \"bundle.tar.gz\""
6444        );
6445
6446        let steps =
6447            parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
6448        assert!(
6449            matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
6450            "unexpected lowering: {:?}",
6451            steps[0].kind
6452        );
6453        assert_eq!(
6454            steps[0].kind.to_string(),
6455            "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
6456        );
6457
6458        let steps =
6459            parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
6460        match &steps[0].kind {
6461            StepKind::Unarchive {
6462                src,
6463                dst,
6464                max_bytes,
6465            } => {
6466                assert_eq!(src.as_str(), "pack.tar.gz");
6467                assert_eq!(dst.as_str(), "unpacked");
6468                assert_eq!(max_bytes, &None);
6469            }
6470            other => panic!("expected Unarchive, got {other:?}"),
6471        }
6472        assert_eq!(
6473            steps[0].kind.to_string(),
6474            "UNARCHIVE \"pack.tar.gz\" unpacked"
6475        );
6476
6477        let steps = parse_script(
6478            "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
6479            lower_command,
6480        )
6481        .expect("parses");
6482        match &steps[0].kind {
6483            StepKind::Unarchive {
6484                src,
6485                dst,
6486                max_bytes,
6487            } => {
6488                assert_eq!(src.as_str(), "pack.tar.gz");
6489                assert_eq!(dst.as_str(), "unpacked");
6490                assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
6491            }
6492            other => panic!("expected Unarchive, got {other:?}"),
6493        }
6494        assert_eq!(
6495            steps[0].kind.to_string(),
6496            "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
6497        );
6498
6499        for script in [
6500            "ARCHIVE bundle bundle.tar.gz\n",
6501            "ARCHIVE --raw tool.bin tool.tar\n",
6502            "UNARCHIVE pack.tar.gz unpacked\n",
6503            "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
6504        ] {
6505            let first = parse_script(script, lower_command).expect("parses");
6506            let rendered = first[0].kind.to_string() + "\n";
6507            let second = parse_script(&rendered, lower_command).expect("reparses");
6508            // Quoting is parse provenance (Display normalizes it), so the
6509            // fixpoint is on rendering, not on full equality.
6510            assert_eq!(
6511                second[0].kind.to_string(),
6512                first[0].kind.to_string(),
6513                "Display must fixpoint for {script:?}"
6514            );
6515        }
6516
6517        for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
6518            let err = parse_err(bad);
6519            assert!(
6520                err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
6521                "{bad}: {err}"
6522            );
6523        }
6524    }
6525
6526    #[test]
6527    fn copy_from_workspace_selects_source_root() {
6528        for (spelling, target) in [
6529            ("SNAPSHOT", WorkspaceTarget::Snapshot),
6530            ("LOCAL", WorkspaceTarget::Local),
6531            ("CACHE", WorkspaceTarget::Cache { local: false }),
6532            ("SYSTEM", WorkspaceTarget::System),
6533        ] {
6534            let steps = parse_script(
6535                &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
6536                lower_command,
6537            )
6538            .expect("parses");
6539            assert!(
6540                matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
6541                "unexpected lowering for {spelling}: {:?}",
6542                steps[0].kind
6543            );
6544        }
6545        // The `=` form carries the value inline on one token: `--`
6546        // tokens never match `assignment`, so `strip_flags` splits it.
6547        for script in [
6548            "COPY --from-workspace=CACHE a.txt b.txt\n",
6549            "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
6550        ] {
6551            let steps = parse_script(script, lower_command).expect("parses");
6552            assert!(
6553                matches!(
6554                    &steps[0].kind,
6555                    StepKind::Copy {
6556                        from_workspace: Some(WorkspaceTarget::Cache { local: false }),
6557                        ..
6558                    }
6559                ),
6560                "unexpected lowering for {script:?}: {:?}",
6561                steps[0].kind
6562            );
6563        }
6564        // An absent flag means the build-context default.
6565        let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
6566        assert!(
6567            matches!(
6568                &steps[0].kind,
6569                StepKind::Copy {
6570                    from_workspace: None,
6571                    ..
6572                }
6573            ),
6574            "unexpected lowering: {:?}",
6575            steps[0].kind
6576        );
6577        // Unknown and lowercase values are rejected uppercase-only.
6578        for bad in ["REMOTE", "local"] {
6579            let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
6580            assert!(err.contains("unknown workspace source"), "{bad}: {err}");
6581        }
6582    }
6583
6584    #[test]
6585    fn symlink_from_workspace_selects_source_root() {
6586        for (spelling, target) in [
6587            ("SNAPSHOT", WorkspaceTarget::Snapshot),
6588            ("LOCAL", WorkspaceTarget::Local),
6589            ("CACHE", WorkspaceTarget::Cache { local: false }),
6590            ("SYSTEM", WorkspaceTarget::System),
6591        ] {
6592            let steps = parse_script(
6593                &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
6594                lower_command,
6595            )
6596            .expect("parses");
6597            assert!(
6598                matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
6599                "unexpected lowering for {spelling}: {:?}",
6600                steps[0].kind
6601            );
6602            let roundtrip = steps[0].kind.to_string();
6603            assert!(
6604                roundtrip.contains("--from-workspace"),
6605                "display should round-trip the flag: {roundtrip}"
6606            );
6607        }
6608        let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
6609        assert!(
6610            matches!(
6611                &steps[0].kind,
6612                StepKind::Symlink {
6613                    from_workspace: None,
6614                    ..
6615                }
6616            ),
6617            "unexpected lowering: {:?}",
6618            steps[0].kind
6619        );
6620        for bad in ["REMOTE", "local"] {
6621            let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
6622            assert!(err.contains("unknown workspace source"), "{bad}: {err}");
6623        }
6624        // The `=` form carries the value inline, like COPY.
6625        let steps = parse_script(
6626            "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
6627            lower_command,
6628        )
6629        .expect("parses");
6630        assert!(
6631            matches!(
6632                &steps[0].kind,
6633                StepKind::Symlink {
6634                    from_workspace: Some(WorkspaceTarget::Local),
6635                    ..
6636                }
6637            ),
6638            "unexpected lowering: {:?}",
6639            steps[0].kind
6640        );
6641    }
6642
6643    #[test]
6644    fn dash_dash_equals_tokens_bypass_assignment() {
6645        // `--` tokens never match `assignment`: flags keep their `=`
6646        // form as one argument, while other commands see the same text.
6647        let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
6648        let StepKind::Env { key, value } = &steps[0].kind else {
6649            panic!("expected Env, got {:?}", steps[0].kind);
6650        };
6651        assert_eq!(key, "--foo");
6652        assert_eq!(value.as_str(), "bar");
6653
6654        let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
6655        let StepKind::Run(cmd) = &steps[0].kind else {
6656            panic!("expected Run, got {:?}", steps[0].kind);
6657        };
6658        assert!(
6659            cmd.as_str().contains("--foo=bar"),
6660            "unexpected RUN lowering: {cmd:?}"
6661        );
6662
6663        let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
6664        let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
6665            .expect("parses");
6666        let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
6667            panic!("expected AssertEq, got {:?}", steps[0].kind);
6668        };
6669        assert_eq!(hash.as_deref(), Some(digest));
6670
6671        // EXPAND still treats `--k=v` positionals as overrides.
6672        let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
6673        let StepKind::Expand { path, overrides } = &steps[0].kind else {
6674            panic!("expected Expand, got {:?}", steps[0].kind);
6675        };
6676        assert!(path.is_none());
6677        assert_eq!(overrides.len(), 1);
6678        assert_eq!(overrides[0].0.as_str(), "--k");
6679    }
6680
6681    #[test]
6682    fn assert_ne_lowers_and_round_trips() {
6683        let steps = parse_script("ASSERT_NE $status 404\n", lower_command).expect("parses");
6684        let StepKind::AssertNe {
6685            hash,
6686            actual,
6687            expected,
6688        } = &steps[0].kind
6689        else {
6690            panic!("expected AssertNe, got {:?}", steps[0].kind);
6691        };
6692        assert!(hash.is_none());
6693        assert!(
6694            matches!(actual, AssertTarget::Value(_)),
6695            "unexpected actual: {actual:?}"
6696        );
6697        assert!(
6698            matches!(expected, Some(Arg::Expr(_))),
6699            "numeric expected lowers to an expression: {expected:?}"
6700        );
6701        let roundtrip = steps[0].kind.to_string();
6702        assert!(
6703            roundtrip.contains(Command::AssertNe.as_str()) && roundtrip.contains("404"),
6704            "display should round-trip the command: {roundtrip}"
6705        );
6706
6707        let err = parse_script("ASSERT_NE $status\n", lower_command).expect_err("needs expected");
6708        assert!(
6709            err.to_string().contains("requires an expected value"),
6710            "unexpected error: {err}"
6711        );
6712
6713        let err = parse_script("ASSERT_NE --hash abc123 $status \"junk\"\n", lower_command)
6714            .expect_err("hash plus expected must fail");
6715        assert!(
6716            err.to_string().contains("cannot be combined"),
6717            "unexpected error: {err}"
6718        );
6719
6720        // Parity: the shared lowering rejects the combination for EQ too.
6721        let err = parse_script("ASSERT_EQ --hash abc123 $status \"junk\"\n", lower_command)
6722            .expect_err("hash plus expected must fail");
6723        assert!(
6724            err.to_string().contains("cannot be combined"),
6725            "unexpected error: {err}"
6726        );
6727    }
6728
6729    #[test]
6730    fn space_before_paren_is_not_a_call() {
6731        // The call head and `(` must be contiguous: `ECHO (1 + 2)` is an
6732        // instruction, never a function invocation.
6733        let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
6734        assert_eq!(steps.len(), 1);
6735        assert!(
6736            !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
6737            "space before paren must not route to a call: {:?}",
6738            steps[0].kind
6739        );
6740    }
6741
6742    #[test]
6743    fn unknown_type_tag_parses_as_custom() {
6744        // Open type tags: declarations carry plain names and resolve
6745        // against the descriptor table at runtime, so host types need no
6746        // grammar change (see the custom_types core tests).
6747        let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
6748        let StepKind::Assign { decl_type, .. } = &steps[0].kind else {
6749            panic!("expected Assign, got {:?}", steps[0].kind);
6750        };
6751        assert_eq!(decl_type, "FOO");
6752    }
6753
6754    #[test]
6755    fn bare_for_without_types_is_rejected() {
6756        let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
6757        assert!(err.contains("FOR requires explicit types"), "{err}");
6758    }
6759
6760    #[test]
6761    fn mutate_statement_parses_without_keyword() {
6762        let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
6763        assert!(matches!(steps[0].kind, StepKind::Set { .. }));
6764    }
6765
6766    #[test]
6767    fn set_keyword_is_rejected_with_mutation_hint() {
6768        let err = parse_err("SET $y = 2\n");
6769        assert!(err.contains("not a keyword"), "{err}");
6770        assert!(err.contains("$var = <expr>"), "{err}");
6771    }
6772
6773    #[test]
6774    fn structural_fallthrough_commits_per_keyword() {
6775        for (script, cmd) in [
6776            ("CANCEL foo\n", "CANCEL"),
6777            ("TIMEOUT foo\n", "TIMEOUT"),
6778            ("FOR foo\n", "FOR"),
6779            ("IF foo\n", "IF"),
6780            ("LET foo\n", "LET"),
6781            // NOTE: INHERIT_ENV is dual-registered as a leaf command
6782            // (`INHERIT_ENV <key>...`), so `INHERIT_ENV foo` lowers
6783            // successfully instead of erroring : excluded here.
6784            ("ASYNC\n", "ASYNC"),
6785            ("ELSE foo\n", "ELSE"),
6786        ] {
6787            let err = parse_err(script);
6788            assert!(
6789                err.contains(&format!("invalid syntax for command {cmd}")),
6790                "{cmd}: {err}"
6791            );
6792            assert!(!err.contains("unknown command"), "{cmd}: {err}");
6793        }
6794    }
6795
6796    #[test]
6797    fn syntax_strings_open_with_their_keyword() {
6798        // `Command::syntax` is a `const fn` returning `&'static str`,
6799        // so it cannot `format!` the keyword constants in. This lock
6800        // is the divergence guard instead: renaming a keyword fails
6801        // here until its syntax string follows.
6802        for cmd in crate::COMMANDS {
6803            let keyword = cmd.as_str();
6804            let syntax = cmd.syntax();
6805            assert!(
6806                syntax.starts_with(keyword),
6807                "syntax for {keyword} diverges from its keyword: {syntax:?}"
6808            );
6809        }
6810        for meta in all_metadata() {
6811            // Pseudo-entry: documents `$var = <expr>`, which opens
6812            // with a variable, never its non-keyword name.
6813            if meta.name == "MUTATION" {
6814                continue;
6815            }
6816            assert!(
6817                meta.syntax.starts_with(meta.name),
6818                "syntax for {} diverges from its keyword: {:?}",
6819                meta.name,
6820                meta.syntax
6821            );
6822        }
6823    }
6824
6825    #[test]
6826    fn leaf_arity_errors_carry_invalid_syntax_prefix() {
6827        let err = parse_err("SLEEP 1s 2s\n");
6828        assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
6829        assert!(!err.contains("unknown command"), "{err}");
6830    }
6831
6832    #[test]
6833    fn list_append_lowers_variable_and_item() {
6834        let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
6835        let StepKind::ListAppend { list, item } = &steps[0].kind else {
6836            panic!("expected ListAppend, got {:?}", steps[0].kind);
6837        };
6838        assert_eq!(list, "items");
6839        assert!(matches!(item, Arg::String(s, _) if s == "hi"));
6840        assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
6841    }
6842
6843    #[test]
6844    fn list_append_accepts_call_shaped_item() {
6845        // A bare full-region call in arg position stays typed
6846        // (evaluated at runtime) instead of appending the source
6847        // text: same owner as assignment values and RUN-exec items.
6848        let steps = parse_script(
6849            "FUNC MAKE(): STRING { RETURN \"made\" }\nLIST_APPEND $items MAKE()\n",
6850            lower_command,
6851        )
6852        .expect("parses");
6853        let StepKind::ListAppend { list, item } = &steps[1].kind else {
6854            panic!("expected ListAppend, got {:?}", steps[1].kind);
6855        };
6856        assert_eq!(list, "items");
6857        assert!(
6858            matches!(item, Arg::Expr(Expr::Call { name, .. }) if name == "SCRIPT::MAKE"),
6859            "{item:?}"
6860        );
6861    }
6862
6863    #[test]
6864    fn list_append_rejects_unknown_call_shaped_item() {
6865        // Unknown callees fail loud (unknown-function, with span),
6866        // never silently append. Well-formed-statement errors win:
6867        // see `func_def_malformed_params_name_the_shape`.
6868        let err = parse_err("LIST_APPEND $items NOPE()\n");
6869        assert!(err.contains("unknown function `NOPE`"), "{err}");
6870    }
6871
6872    #[test]
6873    fn list_append_rejects_wrong_arity() {
6874        for script in [
6875            "LIST_APPEND\n",
6876            "LIST_APPEND $items\n",
6877            "LIST_APPEND $items \"a\" \"b\"\n",
6878        ] {
6879            let err = parse_err(script);
6880            assert!(
6881                err.contains("invalid syntax for command LIST_APPEND"),
6882                "{script}: {err}"
6883            );
6884            assert!(!err.contains("unknown command"), "{script}: {err}");
6885        }
6886    }
6887
6888    #[test]
6889    fn list_append_rejects_non_variable_target() {
6890        let err = parse_err("LIST_APPEND items \"a\"\n");
6891        assert!(
6892            err.contains("invalid syntax for command LIST_APPEND"),
6893            "{err}"
6894        );
6895        assert!(!err.contains("unknown command"), "{err}");
6896    }
6897
6898    #[test]
6899    fn read_line_rejects_bare_word_target() {
6900        // The `$var` shape lives in the lower function now that the
6901        // central vocabulary holds value types only: a missing sigil
6902        // fails lowering with the command-specific error.
6903        let err = parse_err("READ_LINE reply\n");
6904        assert!(err.contains("READ_LINE requires a $variable"), "{err}");
6905        assert!(!err.contains("unknown command"), "{err}");
6906    }
6907
6908    #[test]
6909    fn genuinely_unknown_command_keeps_bare_message() {
6910        let err = parse_err("FROBNICATE hi\n");
6911        assert!(err.contains("unknown command: FROBNICATE"), "{err}");
6912        assert!(!err.contains("did you mean"), "{err}");
6913    }
6914
6915    #[test]
6916    fn lowercase_command_suggests_uppercase() {
6917        // Lowercase never reaches lowering through `parse_script` (the
6918        // grammar rejects it with its own uppercase hint), so exercise the
6919        // public `lower_command` dispatcher directly.
6920        let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
6921            .expect_err("must fail")
6922            .to_string();
6923        assert!(err.contains("unknown command: echo"), "{err}");
6924        assert!(err.contains("did you mean `ECHO`"), "{err}");
6925    }
6926
6927    #[test]
6928    fn func_def_requires_typed_uppercase_name() {
6929        let steps = parse_script(
6930            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\n",
6931            lower_command,
6932        )
6933        .expect("func def parses");
6934        let StepKind::FuncDef {
6935            name,
6936            params,
6937            return_type,
6938            is_async,
6939            body,
6940            docs,
6941        } = &steps[0].kind
6942        else {
6943            panic!("expected FuncDef, got {:?}", steps[0].kind);
6944        };
6945        assert_eq!(name, "GREET");
6946        assert_eq!(
6947            params,
6948            &vec![("name".to_string(), "STRING".to_string(), false)],
6949            "{params:?}"
6950        );
6951        assert_eq!(return_type, "STRING", "{return_type:?}");
6952        assert!(!is_async, "plain FUNC is not async");
6953        assert!(matches!(body[0].kind, StepKind::Return { .. }));
6954        assert!(docs.is_none(), "undocumented FUNC carries no docs");
6955    }
6956
6957    #[test]
6958    fn lowercase_func_name_is_rejected() {
6959        let err = parse_err("FUNC greet($x: STRING) {\n  RETURN $x\n}\n");
6960        assert!(err.contains("FUNC"), "{err}");
6961    }
6962
6963    #[test]
6964    fn func_def_optional_params_parse_with_flag() {
6965        let steps = parse_script(
6966            "FUNC F($a: STRING, $b?: INT): STRING {\n  RETURN $a\n}\n",
6967            lower_command,
6968        )
6969        .expect("optional params parse");
6970        let StepKind::FuncDef { params, .. } = &steps[0].kind else {
6971            panic!("expected FuncDef, got {:?}", steps[0].kind);
6972        };
6973        assert_eq!(
6974            params,
6975            &vec![
6976                ("a".to_string(), "STRING".to_string(), false),
6977                ("b".to_string(), "INT".to_string(), true),
6978            ],
6979            "{params:?}"
6980        );
6981        assert_eq!(
6982            steps[0].kind.to_string(),
6983            "FUNC F($a: STRING, $b?: INT): STRING {\n    RETURN $a\n}",
6984            "display marks the optional"
6985        );
6986    }
6987
6988    #[test]
6989    fn func_def_optional_params_must_trail() {
6990        let err = parse_err("FUNC F($a?: INT, $b: STRING): STRING {\n  RETURN $b\n}\n");
6991        assert!(err.contains("optional ? params must be trailing"), "{err}");
6992        assert!(err.contains("`$b`"), "{err}");
6993    }
6994
6995    #[test]
6996    fn func_def_param_type_must_be_uppercase() {
6997        let err = parse_err("FUNC F($q: string): STRING {\n  RETURN $q\n}\n");
6998        assert!(err.contains("needs an uppercase type"), "{err}");
6999        assert!(err.contains("`string`"), "{err}");
7000    }
7001
7002    #[test]
7003    fn func_def_malformed_params_name_the_shape() {
7004        for (script, expected) in [
7005            (
7006                "FUNC F($x?): STRING {\n  RETURN \"hi\"\n}\n",
7007                "needs `: TYPE` after the name",
7008            ),
7009            (
7010                "FUNC F(bar): STRING {\n  RETURN \"hi\"\n}\n",
7011                "must be `$name: TYPE` separated by commas",
7012            ),
7013            (
7014                "FUNC F($x: STRING,): STRING {\n  RETURN $x\n}\n",
7015                "must not end with a trailing comma",
7016            ),
7017        ] {
7018            let err = parse_err(script);
7019            assert!(err.contains(expected), "{script}: {err}");
7020        }
7021        // `FUNC FOO() ECHO hi` still misses to generic: the
7022        // header-only invalid syntax echoes just the header.
7023        let err = parse_err("FUNC FOO() ECHO hi\n");
7024        assert!(err.contains("invalid syntax for command FUNC"), "{err}");
7025        assert!(err.contains("got `FOO() ECHO hi`"), "{err}");
7026    }
7027
7028    #[test]
7029    fn call_and_while_lower_correctly() {
7030        let steps = parse_script(
7031            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\nGREET(\"ada\")\n",
7032            lower_command,
7033        )
7034        .expect("call parses");
7035        assert!(
7036            matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
7037            "{:?}",
7038            steps[1].kind
7039        );
7040        let steps = parse_script(
7041            "FUNC GREET($a: STRING, $b: STRING): STRING {\n  RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
7042            lower_command,
7043        )
7044        .expect("spaced call parses");
7045        assert!(
7046            matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
7047            "{:?}",
7048            steps[1].kind
7049        );
7050        let steps = parse_script(
7051            indoc! {r#"
7052                WHILE !$done {
7053                  BREAK
7054                }
7055            "#},
7056            lower_command,
7057        )
7058        .expect("while parses");
7059        let StepKind::While { body, .. } = &steps[0].kind else {
7060            panic!("expected While, got {:?}", steps[0].kind);
7061        };
7062        assert!(matches!(body[0].kind, StepKind::Break));
7063    }
7064
7065    #[test]
7066    fn let_capture_call_and_async_call_lower() {
7067        // A bare `NAME(...)` on the LET RHS stays an expression assignment;
7068        // only ASYNC/TIMEOUT/command captures produce AssignCapture.
7069        let steps = parse_script(
7070            indoc! {r#"
7071                FUNC GREET($name: STRING): STRING {
7072                  RETURN $name
7073                }
7074                LET $r: STRING = GREET("ada")
7075            "#},
7076            lower_command,
7077        )
7078        .expect("capture call parses");
7079        let StepKind::Assign { var, expr, .. } = &steps[1].kind else {
7080            panic!("expected Assign, got {:?}", steps[1].kind);
7081        };
7082        assert_eq!(var, "r");
7083        assert!(
7084            matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
7085            "{expr:?}"
7086        );
7087        let steps = parse_script(
7088            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\nLET $t: HANDLE<STRING> = ASYNC GREET(\"a\")\n",
7089            lower_command,
7090        )
7091        .expect("async call parses");
7092        assert!(
7093            matches!(&steps[1].kind, StepKind::AssignAsync { .. }),
7094            "{:?}",
7095            steps[1].kind
7096        );
7097    }
7098
7099    #[test]
7100    fn multiline_call_args_span_lines() {
7101        // Regression: long invocations (e.g. 4-arg SSH_SERVE with an
7102        // options map) may put one argument per line. Bracket interiors
7103        // tolerate linebreaks while statement structure stays single-line.
7104        let steps = parse_script(
7105            "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP): STRING {\n  RETURN $b\n}\nLET $m: MAP = SERVE(\n  \"127.0.0.1:2241\",\n  \"test\",\n  \"test123\", {\n    key_path: \"test_key\"\n  }\n)\n",
7106            lower_command,
7107        )
7108        .expect("multiline call parses");
7109        let StepKind::Assign { expr, .. } = &steps[1].kind else {
7110            panic!("expected Assign, got {:?}", steps[1].kind);
7111        };
7112        let Expr::Call { name, args } = expr else {
7113            panic!("expected Call expr, got {expr:?}");
7114        };
7115        assert_eq!(name, "SCRIPT::SERVE");
7116        assert_eq!(args.len(), 4);
7117        assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
7118        // Display stays single-line; reparsing the same text is identical.
7119        let rendered = steps[1].to_string();
7120        assert!(!rendered.contains('\n'), "{rendered}");
7121        let script = "FUNC SERVE($b: STRING, $u: STRING, $p: STRING, $o: MAP): STRING {\n  RETURN $b\n}\nLET $m: MAP = SERVE(\n  \"127.0.0.1:2241\",\n  \"test\",\n  \"test123\", {\n    key_path: \"test_key\"\n  }\n)\n";
7122        let again = parse_script(script, lower_command).expect("reparse ok");
7123        assert_eq!(again, steps);
7124    }
7125
7126    #[test]
7127    fn multiline_bare_call_and_list_span_lines() {
7128        let steps = parse_script(
7129            indoc! {r#"
7130                FUNC GREET($a: STRING): STRING {
7131                  RETURN $a
7132                }
7133                GREET(
7134                  "ada"
7135                )
7136            "#},
7137            lower_command,
7138        )
7139        .expect("multiline bare call parses");
7140        let StepKind::Call { name, args } = &steps[1].kind else {
7141            panic!("expected Call, got {:?}", steps[1].kind);
7142        };
7143        assert_eq!(name, "SCRIPT::GREET");
7144        assert_eq!(args.len(), 1);
7145        let steps = parse_script(
7146            indoc! {r#"
7147                LET $l: LIST = [
7148                  "a",
7149                  "b"
7150                ]
7151            "#},
7152            lower_command,
7153        )
7154        .expect("multiline list parses");
7155        let StepKind::Assign { expr, .. } = &steps[0].kind else {
7156            panic!("expected Assign, got {:?}", steps[0].kind);
7157        };
7158        assert!(
7159            matches!(expr, Expr::List(items) if items.len() == 2),
7160            "{expr:?}"
7161        );
7162    }
7163
7164    #[test]
7165    fn parse_duration_units() {
7166        use std::time::Duration;
7167        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
7168        assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
7169        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
7170        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
7171        assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
7172        // One optional space separates number from unit, like bytes.
7173        assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
7174        assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
7175    }
7176
7177    #[test]
7178    fn parse_duration_rejects_garbage() {
7179        assert!(parse_duration("").is_err());
7180        assert!(parse_duration("banana").is_err());
7181        assert!(parse_duration("10x").is_err());
7182        assert!(parse_duration("0s").is_err());
7183        assert!(parse_duration("0").is_err());
7184        assert!(parse_duration("-5s").is_err());
7185        // Three parts or a split digit run stay rejected.
7186        assert!(parse_duration("30 s s").is_err());
7187        assert!(parse_duration("3 0s").is_err());
7188    }
7189
7190    #[test]
7191    fn parse_byte_count_units() {
7192        assert_eq!(parse_byte_count("500").unwrap(), 500);
7193        assert_eq!(parse_byte_count("500B").unwrap(), 500);
7194        assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
7195        assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
7196        assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
7197        assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
7198        assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
7199        assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
7200        assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
7201        assert_eq!(
7202            parse_byte_count("1TIB").unwrap(),
7203            1_024 * 1_024 * 1_024 * 1_024
7204        );
7205        // Case-insensitive: `1gb`, `1GB`, and `1Gb` agree.
7206        assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
7207        assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
7208        assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
7209        assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
7210        // Rust-literal grouping: separators ride between digits only.
7211        assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
7212        assert_eq!(
7213            parse_byte_count("1_000_000_000_000").unwrap(),
7214            1_000_000_000_000
7215        );
7216        assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
7217        assert_eq!(
7218            parse_byte_count("1_0GiB").unwrap(),
7219            10 * 1_024 * 1_024 * 1_024
7220        );
7221        // One optional space separates number from unit, never digits.
7222        assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
7223        assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
7224        assert_eq!(parse_byte_count("  2MB  ").unwrap(), 2_000_000);
7225        // A leading `+` rides spaced or glued; `-` stays rejected.
7226        assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
7227        assert!(parse_byte_count("-1 GB").is_err());
7228    }
7229
7230    #[test]
7231    fn parse_byte_count_rejects_garbage() {
7232        for bad in [
7233            "",
7234            "banana",
7235            "10x",
7236            "1G",
7237            "1K",
7238            "1.5GB",
7239            "-5",
7240            "-5GB",
7241            "0",
7242            "0GB",
7243            "_100",
7244            "100_",
7245            "1__000",
7246            "_",
7247            "1_GB",
7248            // A space splits tokens, never digit runs or units.
7249            "1 G B",
7250            "1 2",
7251            "1 0",
7252            // Absurd magnitudes fail loudly instead of wrapping.
7253            "1000000000000000000000000",
7254            "1000000000TB",
7255        ] {
7256            assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
7257        }
7258    }
7259
7260    #[test]
7261    fn format_byte_count_round_trips() {
7262        for text in [
7263            "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
7264        ] {
7265            let parsed = parse_byte_count(text).unwrap();
7266            let rendered = format_byte_count(parsed);
7267            assert_eq!(
7268                parse_byte_count(&rendered).unwrap(),
7269                parsed,
7270                "round-trip failed for {text}"
7271            );
7272        }
7273        assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
7274        assert_eq!(format_byte_count(1_000_000_000), "1GB");
7275    }
7276
7277    #[test]
7278    fn strip_digit_separators_passes_signs_through() {
7279        // Signs belong to signed domains: the strip keeps them so
7280        // `-1_000` reads as -1000 wherever ints coerce, while unsigned
7281        // callers (byte counts) still reject at parse time.
7282        assert_eq!(strip_digit_separators("-1_000"), "-1000");
7283        assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
7284        assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
7285        assert_eq!(strip_digit_separators("1_000"), "1000");
7286        for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
7287            assert_eq!(strip_digit_separators(untouched), untouched);
7288        }
7289        // Unsigned byte counts reject `-` at parse time but take `+`
7290        // like every other Rust-parsed number in the DSL.
7291        assert!(parse_byte_count("-1_000").is_err());
7292        assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
7293    }
7294
7295    #[test]
7296    fn format_byte_count_is_lossless() {
7297        // The canonical form parses back to the exact input value:
7298        // formatting never loses information, only spelling.
7299        // Zero is unrepresentable by design (like durations): the
7300        // parser rejects it, so it cannot round-trip.
7301        for n in [
7302            1,
7303            500,
7304            999,
7305            1_000,
7306            1_024,
7307            1_500,
7308            1_000_000,
7309            1_048_576,
7310            1_000_000_000,
7311            1_073_741_824,
7312            1_000_000_000_000,
7313            1_099_511_627_776,
7314            u64::MAX,
7315        ] {
7316            assert_eq!(
7317                parse_byte_count(&format_byte_count(n)).unwrap(),
7318                n,
7319                "lossless round-trip failed for {n}"
7320            );
7321        }
7322    }
7323
7324    #[test]
7325    fn format_duration_round_trips() {
7326        for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
7327            let parsed = parse_duration(text).unwrap();
7328            let rendered = format_duration(&parsed);
7329            assert_eq!(
7330                parse_duration(&rendered).unwrap(),
7331                parsed,
7332                "round-trip failed for {text}"
7333            );
7334        }
7335        assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
7336        assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
7337    }
7338
7339    #[test]
7340    fn structural_metadata_covers_all_structural_kinds() {
7341        use crate::ast::Value;
7342
7343        // Tripwire: adding a structural StepKind variant without registering
7344        // documentation fails to compile here (non-exhaustive match). Leaf
7345        // commands map to None; they are covered by declare_commands!.
7346        fn metadata_name(kind: &StepKind) -> Option<&'static str> {
7347            match kind {
7348                StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some("WITH_IO"),
7349                StepKind::For { .. } => Some("FOR"),
7350                StepKind::If { .. } => Some("IF"),
7351                StepKind::Switch { .. } => Some("SWITCH"),
7352                StepKind::Assign { .. } => Some("LET"),
7353                StepKind::Set { .. } => Some("MUTATION"),
7354                StepKind::AssignCapture { .. } => Some("LET"),
7355                StepKind::AwaitCapture { .. } => Some("AWAIT"),
7356                StepKind::AsyncBlock { .. } | StepKind::AssignAsync { .. } => Some("ASYNC"),
7357                StepKind::Await { .. } => Some("AWAIT"),
7358                StepKind::Cancel { .. } => Some("CANCEL"),
7359                StepKind::Timeout { .. } => Some("TIMEOUT"),
7360                StepKind::Fail { .. } => Some("FAIL"),
7361                StepKind::Isolated { .. } => Some("ISOLATED"),
7362                StepKind::IsolatedInheritEnv { .. } => Some("ISOLATED"),
7363                StepKind::RemoteBlock { .. } => Some("REMOTE"),
7364                StepKind::FuncDef { .. } => Some("FUNC"),
7365                // Bare `NAME(...)` calls share the `FUNC` reference page;
7366                // there is no call keyword to document on its own.
7367                StepKind::Call { .. } => None,
7368                // Both import forms are documented on the `IMPORT` page.
7369                StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => Some("IMPORT"),
7370                StepKind::Return { .. } => Some("RETURN"),
7371                StepKind::While { .. } => Some("WHILE"),
7372                StepKind::Break => Some("BREAK"),
7373                StepKind::Continue => Some("CONTINUE"),
7374                // Aliases are declared by `TYPE` but documented with the
7375                // type-word prose on the `LET` page (define-once,
7376                // use-everywhere); no dedicated reference page.
7377                StepKind::TypeAlias { .. } => Some("LET"),
7378                StepKind::RunExec { .. } => None,
7379                StepKind::Workdir(_)
7380                | StepKind::Workspace(_)
7381                | StepKind::Env { .. }
7382                | StepKind::InheritEnv { .. }
7383                | StepKind::Run(_)
7384                | StepKind::Echo(_)
7385                | StepKind::Copy { .. }
7386                | StepKind::Symlink { .. }
7387                | StepKind::Mkdir(_)
7388                | StepKind::Archive { .. }
7389                | StepKind::Unarchive { .. }
7390                | StepKind::Install { .. }
7391                | StepKind::SetExecutable { .. }
7392                | StepKind::Ls(_)
7393                | StepKind::Read(_)
7394                | StepKind::ReadLine { .. }
7395                | StepKind::Prompt { .. }
7396                | StepKind::Write { .. }
7397                | StepKind::Append { .. }
7398                | StepKind::AppendLine { .. }
7399                | StepKind::Remove { .. }
7400                | StepKind::Expand { .. }
7401                | StepKind::AssertEq { .. }
7402                | StepKind::AssertContains { .. }
7403                | StepKind::AssertNe { .. }
7404                | StepKind::CopyGit { .. }
7405                | StepKind::Exit(_)
7406                | StepKind::Sleep { .. }
7407                | StepKind::ListAppend { .. } => None,
7408            }
7409        }
7410
7411        // Exercise the matcher once per structural variant so the arms cannot
7412        // rot (a new variant breaks compilation above first).
7413        let dummies: Vec<StepKind> = vec![
7414            StepKind::WithIo {
7415                bindings: Vec::new(),
7416                cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
7417                    "x".to_string(),
7418                    false,
7419                ))),
7420            },
7421            StepKind::For {
7422                key_var: None,
7423                key_type: None,
7424                var: "i".to_string(),
7425                var_type: "STRING".to_string(),
7426                in_expr: Expr::Literal(Value::bool(true)),
7427                body: Vec::new(),
7428            },
7429            StepKind::If {
7430                cond: Box::new(Expr::Literal(Value::bool(true))),
7431                then_body: Vec::new(),
7432                else_ifs: Vec::new(),
7433                else_body: None,
7434            },
7435            StepKind::Switch {
7436                discriminant: None,
7437                cases: Vec::new(),
7438                default_body: None,
7439            },
7440            StepKind::Assign {
7441                var: "v".to_string(),
7442                decl_type: "BOOL".to_string(),
7443                expr: Expr::Literal(Value::bool(true)),
7444            },
7445            StepKind::Set {
7446                var: "v".to_string(),
7447                expr: Expr::Literal(Value::bool(true)),
7448            },
7449            StepKind::AssignCapture {
7450                var: "v".to_string(),
7451                decl_type: "STRING".to_string(),
7452                cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
7453                    "x".to_string(),
7454                    false,
7455                ))),
7456            },
7457            StepKind::AwaitCapture {
7458                out_var: "o".to_string(),
7459                out_type: "STRING".to_string(),
7460                task_var: "t".to_string(),
7461            },
7462            StepKind::AsyncBlock { body: Vec::new() },
7463            StepKind::AssignAsync {
7464                var: "t".to_string(),
7465                decl_type: "HANDLE".to_string(),
7466                body: Vec::new(),
7467            },
7468            StepKind::Await {
7469                var: "t".to_string(),
7470            },
7471            StepKind::Cancel {
7472                var: "t".to_string(),
7473            },
7474            StepKind::Timeout {
7475                duration: Arg::String("1s".to_string(), false),
7476                body: Vec::new(),
7477            },
7478            StepKind::Fail {
7479                code: None,
7480                message: None,
7481                body: Vec::new(),
7482            },
7483            StepKind::Isolated { body: Vec::new() },
7484            StepKind::IsolatedInheritEnv { keys: Vec::new() },
7485            StepKind::RemoteBlock {
7486                target: "prod".to_string(),
7487                vars: Vec::new(),
7488                env: Vec::new(),
7489                body: Vec::new(),
7490            },
7491            StepKind::FuncDef {
7492                name: "F".to_string(),
7493                params: Vec::new(),
7494                return_type: "STRING".to_string(),
7495                is_async: false,
7496                body: Vec::new(),
7497                docs: None,
7498            },
7499            StepKind::Call {
7500                name: "F".to_string(),
7501                args: Vec::new(),
7502            },
7503            StepKind::Return {
7504                expr: Box::new(Expr::Literal(Value::bool(true))),
7505                is_bare: false,
7506            },
7507            StepKind::While {
7508                cond: Box::new(Expr::Literal(Value::bool(true))),
7509                body: Vec::new(),
7510            },
7511            StepKind::Break,
7512            StepKind::Continue,
7513            StepKind::TypeAlias {
7514                name: "PERSON".to_string(),
7515                target: "MAP<name: STRING>".to_string(),
7516            },
7517        ];
7518        let registry = all_structural_metadata();
7519        for kind in &dummies {
7520            // Bare calls share the FUNC reference page and map to None.
7521            let Some(name) = metadata_name(kind) else {
7522                continue;
7523            };
7524            assert!(
7525                registry.iter().any(|meta| meta.name == name),
7526                "no structural metadata entry for {}",
7527                name
7528            );
7529        }
7530    }
7531}