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