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 ECHO and
3056                # EXIT 1 never run, so reaching them would print a
3057                # marker and fail the script.
3058                # CONTINUE passes through to the enclosing loop.
3059                LET $items: LIST<STRING> = ["a", "skip", "b"]
3060                FOR $item: STRING IN $items {
3061                  SWITCH $item {
3062                    CASE "skip" {
3063                      CONTINUE
3064                    }
3065                    CASE "a" {
3066                      ECHO saw-a
3067                      BREAK
3068                      ECHO unreachable
3069                      EXIT 1
3070                    }
3071                    DEFAULT {
3072                      ECHO saw-other
3073                    }
3074                  }
3075                }
3076
3077                ASSERT_CONTAINS stdout "saw-a"
3078                ASSERT_CONTAINS stdout "saw-other"
3079            "#},
3080                },
3081                Example {
3082                    name: "switch arms with nested loops",
3083                    fence_meta: None,
3084                    code: indoc! {r#"
3085                # Loops nested in arms obey the innermost rule: inner
3086                # BREAK ends only the inner FOR, inner CONTINUE skips
3087                # only its iteration, and the arm keeps running past both.
3088                LET $hits: LIST<STRING> = []
3089                SWITCH "b" {
3090                  CASE "b" {
3091                    FOR $o: STRING IN ["x", "y"] {
3092                      FOR $i: INT IN [1, 2, 3] {
3093                        IF $i == 2 {
3094                          BREAK
3095                        }
3096                        LIST_APPEND $hits "b{{ $o }}{{ $i }}"
3097                      }
3098                    }
3099                    LIST_APPEND $hits "b-after"
3100                  }
3101                  DEFAULT {
3102                    LIST_APPEND $hits "b-wrong"
3103                  }
3104                }
3105
3106                SWITCH "c" {
3107                  CASE "c" {
3108                    FOR $o: STRING IN ["x", "y"] {
3109                      FOR $i: INT IN [1, 2, 3] {
3110                        IF $i == 2 {
3111                          CONTINUE
3112                        }
3113                        LIST_APPEND $hits "c{{ $o }}{{ $i }}"
3114                      }
3115                    }
3116                    LIST_APPEND $hits "c-after"
3117                  }
3118                  DEFAULT {
3119                    LIST_APPEND $hits "c-wrong"
3120                  }
3121                }
3122
3123                LET $want: LIST<STRING> = ["bx1", "by1", "b-after", "cx1", "cx3", "cy1", "cy3", "c-after"]
3124                ASSERT_EQ $hits $want
3125            "#},
3126                },
3127                Example {
3128                    name: "overlapping arms run first match only",
3129                    fence_meta: None,
3130                    code: indoc! {r#"
3131                # Overlapping arms never both run: the first match wins,
3132                # so order arms most specific first. There is no
3133                # fallthrough to the next CASE; CONTINUE would continue
3134                # an enclosing loop, not advance to the next arm.
3135                LET $n: INT = 10
3136                SWITCH {
3137                  CASE $n > 1 {
3138                    WRITE band.txt wide
3139                  }
3140                  CASE $n > 5 {
3141                    WRITE band.txt narrow
3142                  }
3143                  DEFAULT {
3144                    WRITE band.txt low
3145                  }
3146                }
3147
3148                LET $band: STRING = READ band.txt
3149                ASSERT_EQ $band "wide"
3150            "#},
3151                },
3152                Example {
3153                    name: "no fallthrough without break",
3154                    fence_meta: None,
3155                    code: indoc! {r#"
3156                # C falls through without break: this SWITCH does not.
3157                # One value matches two arms and neither uses BREAK,
3158                # yet only the first arm runs.
3159                LET $hits: LIST<STRING> = []
3160                SWITCH 1 {
3161                  CASE 1 {
3162                    LIST_APPEND $hits "first"
3163                  }
3164                  CASE 1 {
3165                    LIST_APPEND $hits "second"
3166                  }
3167                  DEFAULT {
3168                    LIST_APPEND $hits "default"
3169                  }
3170                }
3171
3172                LET $want: LIST<STRING> = ["first"]
3173                ASSERT_EQ $hits $want
3174            "#},
3175                },
3176                Example {
3177                    name: "continue never advances to the next arm",
3178                    fence_meta: None,
3179                    code: indoc! {r#"
3180                # 3 satisfies both CASE conditions, but only the first matching
3181                # arm runs. CONTINUE then jumps straight to the next loop
3182                # iteration: skipping both "small-unreached" in the arm and
3183                # "after" in the loop body (whereas BREAK would only exit the
3184                # SWITCH and still run "after").
3185                IMPORT [STD]
3186                LET $hits: LIST<STRING> = []
3187                FOR $n: INT IN [3] {
3188                  SWITCH {
3189                    CASE $n < 5 {
3190                      LIST_APPEND $hits "small"
3191                      CONTINUE
3192                      LIST_APPEND $hits "small-unreached"
3193                    }
3194                    CASE $n < 10 {
3195                      LIST_APPEND $hits "mid"
3196                    }
3197                  }
3198                  LIST_APPEND $hits "after"
3199                }
3200
3201                LET $want: LIST<STRING> = ["small"]
3202                ASSERT_EQ $hits $want
3203
3204                # Exactly one append ran: neither the rest of the arm
3205                # ("small-unreached"), the also-matching second arm
3206                # ("mid"), nor the trailing step ("after") executed.
3207                LET $count: INT = LEN($hits)
3208                ASSERT_EQ $count 1
3209            "#},
3210                },
3211                Example {
3212                    name: "strict equality, not C coercion",
3213                    fence_meta: None,
3214                    code: indoc! {r#"
3215                # No C-style coercion: STRING "1" never equals INT 1.
3216                # Numerics still compare across INT and FLOAT.
3217                LET $hits: LIST<STRING> = []
3218                SWITCH "1" {
3219                  CASE 1 {
3220                    LIST_APPEND $hits "coerced"
3221                  }
3222                  DEFAULT {
3223                    LIST_APPEND $hits "no-coercion"
3224                  }
3225                }
3226
3227                SWITCH 2 {
3228                  CASE 2.0 {
3229                    LIST_APPEND $hits "numeric-match"
3230                  }
3231                  DEFAULT {
3232                    LIST_APPEND $hits "numeric-miss"
3233                  }
3234                }
3235
3236                LET $want: LIST<STRING> = ["no-coercion", "numeric-match"]
3237                ASSERT_EQ $hits $want
3238            "#},
3239                },
3240                Example {
3241                    name: "later conditions never evaluate",
3242                    fence_meta: None,
3243                    code: indoc! {r#"
3244                # Each CASE without a discriminant is a call, and calls
3245                # stop at the first true arm. PROBE writes a marker, so
3246                # its absence proves it never ran.
3247                IMPORT [STD]
3248                FUNC PROBE($v: BOOL): BOOL {
3249                  WRITE probed.txt hit
3250                  RETURN $v
3251                }
3252                LET $n: INT = 2
3253                SWITCH {
3254                  CASE $n > 1 {
3255                    WRITE band.txt mid
3256                  }
3257                  CASE PROBE(true) {
3258                    WRITE band.txt probed
3259                  }
3260                  DEFAULT {
3261                    WRITE band.txt low
3262                  }
3263                }
3264
3265                LET $band: STRING = READ band.txt
3266                ASSERT_EQ $band "mid"
3267                LET $t: STRING = PATH_TYPE("probed.txt")
3268                ASSERT_EQ $t "absent"
3269            "#},
3270                },
3271                Example {
3272                    name: "no match without default is a no-op",
3273                    fence_meta: None,
3274                    code: indoc! {r#"
3275                # No arm matches and no DEFAULT: nothing runs and nothing
3276                # fails, so the write never happens.
3277                IMPORT [STD]
3278                SWITCH "zzz" {
3279                  CASE "a" {
3280                    WRITE picked.txt a
3281                  }
3282                  CASE "b" {
3283                    WRITE picked.txt b
3284                  }
3285                }
3286
3287                LET $t: STRING = PATH_TYPE("picked.txt")
3288                ASSERT_EQ $t "absent"
3289            "#},
3290                },
3291            ],
3292        },
3293        CommandMeta {
3294            in_index: true,
3295            name: KEYWORD_LET,
3296            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> }",
3297            summary: "Bind script-local variables.",
3298            description: indoc! {r#"
3299                Declares a script-local variable with an explicit type (STRING, INT,
3300                FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET
3301                in the same scope frame is a redeclaration error; mutate with
3302                `$var = <expr>`.
3303
3304                Variables are usable in templates (`{{ $var }}`), guards, and
3305                expressions. With `ASYNC`, spawns a background task and stores its
3306                handle (see ASYNC). The `$` sigil on the name is mandatory.
3307
3308                No hoisting: a variable exists only after its LET runs, in
3309                execution order. Reading `$var` before its LET (or after the
3310                block that declared it exits) fails with
3311                `undefined variable $var`. Scopes are a stack of frames and
3312                resolution walks innermost outward, so nothing pre-declares
3313                names. Function bodies read outer variables through the same
3314                walk, but their own LETs never leak out (see FUNC).
3315
3316                The right-hand side is always an expression — literals, lists, maps,
3317                arithmetic (`+ - * /` with `*`/`/` binding tighter, unary `-`,
3318                parentheses), comparisons (`< <= > >=` binding tighter than
3319                `== !=`), logical `&&` (tighter) and `||` with short-circuit,
3320                `!` negation, `env:KEY` reads, `INSPECT($var)` snapshots,
3321                `GLOB("*.md")`, `INT(x)` / `FLOAT(x)` conversions — never a
3322                `{{ ... }}` template; interpolation happens in string values,
3323                not here.
3324                The one exception is pipes: `LET $p: PIPE` with no `=`
3325                and no initializer mints a fresh anonymous backend,
3326                lazily materialized at first binding, so two declarations
3327                never share a channel.
3328
3329                Numbers are numeric literals: `42` binds `INT`, `3.14` binds
3330                `FLOAT`. `Int x Int` stays `INT` (checked, integer division,
3331                so `7 / 2` is `3`); any `Float` operand promotes to `FLOAT`.
3332                Division by zero, overflow, and non-finite results are errors.
3333                Both numeric sides compare numerically (`1 == 1.0` is true);
3334                otherwise `==`/`!=` are strict (cross-type words are unequal,
3335                so `"true" == true` is false) and ordering on
3336                non-numerics is a Type Error. Constant subtrees fold at parse
3337                time and dynamic arithmetic compiles to flat RPN with
3338                identical semantics.
3339
3340                Float equality is exact with no epsilon. Floats store decimals
3341                in binary, so a value is exact only when its reduced fraction
3342                has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75
3343                (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10)
3344                repeat forever in binary (like 1/3 in decimal) and truncate,
3345                so `0.1 + 0.2 == 0.3` is false (the sum is
3346                `0.30000000000000004`). Rule of thumb: endings .5, .25, .75,
3347                .125, .625, .875 are exact; .1, .2, .3 and similar are
3348                approximations. Bound approximations instead of comparing
3349                them: `IF $sum > 0.299999 && $sum < 0.300001`.
3350
3351                Comparisons do not chain: `a < b < c` is a parse error, not
3352                `(a < b) < c`. Chaining would compare a `BOOL` against a
3353                number (a runtime Type Error in C-style parsing) or evaluate
3354                the middle term twice (Python-style chaining), so the grammar
3355                accepts exactly one comparison operator per level. Write the
3356                conjunction explicitly: `$a < $b && $b < $c`. The same holds
3357                for equality (`$a == $b == $c` is rejected).
3358
3359                Captured command output is a string, so convert before math:
3360                `LET $total: INT = $total + INT($size_str)` (`INT` trims ASCII
3361                whitespace; `FLOAT` accepts int strings and rejects
3362                non-finite).
3363
3364                Bare words need no quotes: `LET $d: STRING = 30s` binds the same string
3365                as quoted.
3366
3367                When the right-hand side is a synchronous command
3368                (`LET $out: STRING = ECHO hi`), the command runs to completion and its
3369                exact stdout bytes are captured into the variable as a string (no newline
3370                stripping; commands with no stdout capture as `""`; non-UTF8 stdout is
3371                an error). Combining capture with an explicit
3372                `WITH_IO [stdout=$var]` is a parse error.
3373
3374                Coming from Bash, the capture line looks familiar but behaves
3375                strictly:
3376
3377                | | Bash `output=$(...)` | OxDock `LET $out: STRING = ...` |
3378                | --- | --- | --- |
3379                | Trailing newlines | Stripped (all of them) | Preserved byte-exact |
3380                | Variable type | Always an untyped string | Declared: STRING, INT, FLOAT, ... |
3381                | Math on output | Implicit: `$((var + 1))` | Explicit: `INT($out) + 1` |
3382                | Failing command | Continues with empty output unless `set -e` | Step fails immediately, binds nothing |
3383
3384                `LET $out: TYPE = AWAIT $var` binds the background task's
3385                explicit `RETURN` value instead (tasks stream their stdout
3386                live, so there is no output left to capture); a task that
3387                succeeded without `RETURN` yields `INT` 0, like a process
3388                exit status.
3389
3390                An inline block (`LET $var: TYPE = { <commands> }`) runs its
3391                steps in a fresh scope and binds the nearest `RETURN` value,
3392                like a zero-arg function body: fallthrough without `RETURN`
3393                binds `""`, and `BREAK`/`CONTINUE` escaping the block are
3394                errors. Think IIFE: the block executes immediately where it
3395                stands and its value is the result. The block reads outer
3396                variables but its own LETs never leak out. A `{k: v}` shape
3397                still parses as a map literal; anything else in braces is
3398                a block.
3399
3400                The split is deliberate: synchronous commands capture
3401                stdout because they run inline to completion on the same
3402                thread; background tasks never capture stdout because
3403                concurrent output has no well-defined value. Task results
3404                travel only through `RETURN` (or `INT` 0 for void tasks).
3405
3406                `LET $e: STRING = env:FOO` reads the script environment into a plain
3407                string.
3408            "#},
3409            args: &[],
3410            flags: &[],
3411            default_output: None,
3412            examples: &[
3413                Example {
3414                    name: "let",
3415                    fence_meta: None,
3416                    code: indoc! {r#"
3417                LET $name: STRING = "world"
3418                ECHO "hello, {{ $name }}"
3419                ASSERT_CONTAINS stdout "hello, world"
3420
3421                LET $items: LIST<STRING> = ["a", "b"]
3422                ASSERT_CONTAINS $items "a"
3423                ASSERT_CONTAINS $items "b"
3424
3425                LET $count: INT = 42
3426                ASSERT_EQ $count 42
3427            "#},
3428                },
3429                Example {
3430                    name: "bool coercion",
3431                    fence_meta: None,
3432                    code: indoc! {r#"
3433                # BOOL spellings coerce case-insensitively. Empty is
3434                # not a boolean: absent flags state a default through
3435                # BOOL_OR instead of converting here.
3436                LET $t: BOOL = "TRUE"
3437                ASSERT_EQ $t true
3438                LET $f: BOOL = "no"
3439                ASSERT_EQ $f false
3440            "#},
3441                },
3442                Example {
3443                    name: "bool coercion rejects empty",
3444                    fence_meta: Some("expect_error:\"expected BOOL\""),
3445                    code: indoc! {r#"
3446                # Empty never reads as false: an empty string fails
3447                # BOOL coercion instead of picking a polarity.
3448                ENV EMPTY_FLAG=""
3449                LET $e: BOOL = "{{ env:EMPTY_FLAG }}"
3450            "#},
3451                },
3452                Example {
3453                    name: "no hoisting",
3454                    fence_meta: Some("expect_error:\"undefined variable\""),
3455                    code: indoc! {r#"
3456                # Reading before the LET runs is an error, not an empty value.
3457                ECHO $too_early
3458                LET $too_early: STRING = "too late"
3459            "#},
3460                },
3461                Example {
3462                    name: "glob binding",
3463                    fence_meta: None,
3464                    code: indoc! {r#"
3465                # The RHS is an expression: GLOB(...) runs and binds a list.
3466                IMPORT [STD]
3467                WRITE a.txt "x"
3468                LET $files: LIST<STRING> = GLOB("*.txt")
3469                FOR $f: STRING IN $files { ECHO $f }
3470
3471                ASSERT_CONTAINS stdout "a.txt"
3472            "#},
3473                },
3474                Example {
3475                    name: "scoped variable reverts",
3476                    fence_meta: None,
3477                    code: indoc! {r#"
3478                # LET inside a braced block reverts when the block exits.
3479                LET $a: STRING = "outer"
3480
3481                [bool:true] {
3482                    LET $a: STRING = "inner"
3483                    WRITE inner.txt "{{ $a }}"
3484                }
3485
3486                WRITE outer.txt "{{ $a }}"
3487
3488                LET $in_body: STRING = READ inner.txt
3489                ASSERT_EQ $in_body "inner"
3490
3491                LET $out_body: STRING = READ outer.txt
3492                ASSERT_EQ $out_body "outer"
3493            "#},
3494                },
3495                Example {
3496                    name: "capture command output",
3497                    fence_meta: None,
3498                    code: indoc! {r#"
3499                # Capture keeps the trailing newline.
3500                LET $out: STRING = ECHO hi
3501                ASSERT_EQ $out "hi\n"
3502            "#},
3503                },
3504                Example {
3505                    name: "inline block",
3506                    fence_meta: None,
3507                    code: indoc! {r#"
3508                LET $who: STRING = "ada"
3509
3510                # An inline block binds its RETURN value like a function body.
3511                LET $res: STRING = {
3512                    LET $loud: STRING = "{{ $who }}!"
3513                    RETURN $loud
3514                }
3515                ASSERT_EQ $res "ada!"
3516
3517                # Any declared type works: the block value checks like any RHS.
3518                LET $n: INT = {
3519                    RETURN 40 + 2
3520                }
3521                ASSERT_EQ $n 42
3522            "#},
3523                },
3524                Example {
3525                    name: "arithmetic over captured output",
3526                    fence_meta: None,
3527                    code: indoc! {r#"
3528                # Captured output converts explicitly: INT() then arithmetic.
3529                IMPORT [STD]
3530                LET $size_str: STRING = ECHO 41
3531                LET $total: INT = INT($size_str) + 1
3532                ASSERT_EQ $total 42
3533
3534                # FLOAT() promotes instead of truncating.
3535                LET $ratio: FLOAT = 1 + 2.5
3536                ASSERT_EQ $ratio 3.5
3537
3538                # Int x Int stays INT: integer division truncates.
3539                LET $half: INT = 7 / 2
3540                ASSERT_EQ $half 3
3541            "#},
3542                },
3543                Example {
3544                    name: "float equality is exact",
3545                    fence_meta: None,
3546                    code: indoc! {r#"
3547                # Binary fractions compare cleanly; decimal fractions may not:
3548                # 0.1 + 0.2 is 0.30000000000000004, so == is false.
3549                IMPORT [STD]
3550                LET $exact: BOOL = 0.5 + 0.25 == 0.75
3551                LET $decimal: BOOL = 0.1 + 0.2 == 0.3
3552                IF $exact {
3553                    WRITE exact.txt yes
3554                }
3555                IF $decimal {
3556                    WRITE unexpected.txt no
3557                }
3558
3559                LET $ok: STRING = READ exact.txt
3560                ASSERT_EQ $ok "yes"
3561
3562                LET $t: STRING = PATH_TYPE("unexpected.txt")
3563                ASSERT_EQ $t "absent"
3564            "#},
3565                },
3566                Example {
3567                    name: "bound inexact decimals",
3568                    fence_meta: None,
3569                    code: indoc! {r#"
3570                # Never test inexact decimals for equality; bound them.
3571                LET $sum: FLOAT = 0.1 + 0.2
3572                IF $sum > 0.299999 && $sum < 0.300001 {
3573                    WRITE bounded.txt yes
3574                }
3575
3576                LET $ok: STRING = READ bounded.txt
3577                ASSERT_EQ $ok "yes"
3578            "#},
3579                },
3580                Example {
3581                    name: "inspect a variable",
3582                    fence_meta: None,
3583                    code: indoc! {r#"
3584                # INSPECT($var) snapshots a variable into a MAP: declared
3585                # type plus live details (pipe backend stats here), so
3586                # scripts can branch on engine state.
3587                IMPORT [STD]
3588                LET $p: PIPE
3589                WITH_IO [stdout=$p] ECHO hello
3590                LET $info: MAP<ANY> = INSPECT($p)
3591                IF $info.is_os_pipe {
3592                    WRITE unexpected.txt "should be a script pipe"
3593                }
3594
3595                ASSERT_EQ $info.type "PIPE"
3596                LET $t: STRING = PATH_TYPE("unexpected.txt")
3597                ASSERT_EQ $t "absent"
3598            "#},
3599                },
3600            ],
3601        },
3602        CommandMeta {
3603            in_index: true,
3604            name: KEYWORD_CONST,
3605            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> }",
3606            summary: "Bind deeply immutable script-local values.",
3607            description: indoc! {r#"
3608                Declares a script-local constant with an explicit type. The
3609                right-hand side accepts every `LET` form (expression,
3610                capture, `ASYNC`, `AWAIT`, inline block, bare `PIPE`).
3611
3612                Immutability is deep and total: reassignment (`$var = ...`),
3613                `LIST_APPEND`, and `MAP_SET`/`MERGE_MAPS`
3614                on a `CONST` value all fail. Nested containers freeze with
3615                the binding, so reaching a list or map through a `CONST`
3616                never exposes a mutable handle. Reads use `$NAME`,
3617                exactly like `LET` reads.
3618
3619                `CONST` and `LET` share one namespace: declaring either
3620                twice in the same scope frame is a redeclaration error.
3621                A `CONST` name cannot collide with a reserved word or
3622                another binding. `FUNC` names live in a separate namespace
3623                and may share the spelling; only `EXPORT`s share one
3624                registry, so at most one of a same-named `FUNC`/`CONST`
3625                pair may be exported. Shadowing an outer binding in
3626                an inner block stays legal and the inner declaration
3627                reverts on block exit.
3628
3629                A file's top-level `CONST`s read inside that file's
3630                own `FUNC` bodies: immutable file state is visible by
3631                scope, while mutable state crosses only as explicit
3632                arguments. Visibility is declaration-ordered: a call
3633                landing before the `CONST` executes fails instead of
3634                reading uninitialized memory. `$ALIAS::NAME` reads work
3635                in bodies exactly like at top level. Writes stay
3636                forbidden everywhere: a body mutating a file `CONST`
3637                fails with the same message as a top-level write.
3638
3639                `CONST` is the only variable binding an `EXPORT` can name
3640                (`EXPORT CONST $NAME`, `EXPORT [CONST $A, $B]`): `LET`
3641                bindings never cross the module boundary. Importers read
3642                the value as `$ALIAS::NAME` (see IMPORT).
3643            "#},
3644            args: &[],
3645            flags: &[],
3646            default_output: None,
3647            examples: &[
3648                Example {
3649                    name: "const",
3650                    fence_meta: None,
3651                    code: indoc! {r#"
3652                # CONST reads through `$`, like LET.
3653                CONST $NAME: STRING = "world"
3654                ECHO "hello, {{ $NAME }}"
3655                ASSERT_CONTAINS stdout "hello, world"
3656
3657                # Containers freeze with the binding.
3658                CONST $ITEMS: LIST<STRING> = ["a", "b"]
3659                ASSERT_CONTAINS {{ $ITEMS }} "a"
3660
3661                # File CONSTs read inside the file's own FUNCs.
3662                CONST $GREETING: STRING = "hi"
3663                FUNC SHOUT(): STRING {
3664                    RETURN $GREETING
3665                }
3666                LET $s: STRING = SHOUT()
3667                ASSERT_EQ $s "hi"
3668            "#},
3669                },
3670                Example {
3671                    name: "const alias reads across modules",
3672                    fence_meta: Some("roots:unified"),
3673                    code: indoc! {r#"
3674                # Exported CONSTs cross only as alias reads, never bare.
3675                IMPORT [STD]
3676                WRITE lib.oxfile """
3677                    CONST $VERSION: STRING = "1.2.3"
3678                    CONST $BUILD: INT = 4
3679                    EXPORT CONST $VERSION
3680                    EXPORT [CONST $BUILD]
3681                    """
3682
3683                # The entry reads the exports at top level, in math, and in templates.
3684                WRITE main.oxfile """
3685                    IMPORT ["lib.oxfile" AS LIB]
3686                    LET $v: STRING = $LIB::VERSION
3687                    ASSERT_EQ $v "1.2.3"
3688                    LET $e: INT = $LIB::BUILD * 2
3689                    ASSERT_EQ $e 8
3690                    LET $w: STRING = "v\{{ $LIB::VERSION }}"
3691                    ASSERT_EQ $w "v1.2.3"
3692                    ECHO "export-ok \{{ $LIB::VERSION }}"
3693                    """
3694
3695                # A child run proves the import from a fresh interpreter.
3696                LET $exe: STRING = INTERPRETER()
3697                LET $out: STRING = RUN [$exe, "main.oxfile"]
3698                ASSERT_CONTAINS $out "export-ok 1.2.3"
3699            "#},
3700                },
3701                Example {
3702                    name: "const alias reads inside func bodies",
3703                    fence_meta: Some("roots:unified"),
3704                    code: indoc! {r#"
3705                # Alias reads work inside importer FUNC bodies exactly like at top level.
3706                IMPORT [STD]
3707                WRITE lib.oxfile """
3708                    CONST $VERSION: STRING = "1.2.3"
3709                    EXPORT CONST $VERSION
3710                    """
3711
3712                # The importer FUNCs return alias reads from expressions and templates.
3713                WRITE main.oxfile """
3714                    IMPORT ["lib.oxfile" AS LIB]
3715                    FUNC SHOW(): STRING {
3716                        RETURN $LIB::VERSION
3717                    }
3718                    FUNC LABELED(): STRING {
3719                        RETURN "v\{{ $LIB::VERSION }}"
3720                    }
3721                    LET $s: STRING = SHOW()
3722                    ASSERT_EQ $s "1.2.3"
3723                    LET $t: STRING = LABELED()
3724                    ASSERT_EQ $t "v1.2.3"
3725                    ECHO "body-ok \{{ $LIB::VERSION }}"
3726                    """
3727
3728                # A child run proves body reads from a fresh interpreter.
3729                LET $exe: STRING = INTERPRETER()
3730                LET $out: STRING = RUN [$exe, "main.oxfile"]
3731                ASSERT_CONTAINS $out "body-ok 1.2.3"
3732            "#},
3733                },
3734                Example {
3735                    name: "const rejects mutation",
3736                    fence_meta: Some("expect_error:\"cannot mutate CONST\""),
3737                    code: indoc! {r#"
3738                # SET on a CONST fails instead of rebinding.
3739                CONST $N: INT = 1
3740                $N = 2
3741            "#},
3742                },
3743                Example {
3744                    name: "const rejects append",
3745                    fence_meta: Some("expect_error:\"cannot mutate CONST\""),
3746                    code: indoc! {r#"
3747                # LIST_APPEND on a CONST fails instead of pushing.
3748                CONST $ITEMS: LIST<STRING> = ["a"]
3749                LIST_APPEND $ITEMS "b"
3750            "#},
3751                },
3752                Example {
3753                    name: "const freeze detaches from its source",
3754                    fence_meta: None,
3755                    code: indoc! {r#"
3756                # Freezing detaches: the LET source stays mutable.
3757                LET $inner: LIST<STRING> = ["a"]
3758                CONST $C: LIST<ANY> = [$inner]
3759                LIST_APPEND $inner "b"
3760                ASSERT_CONTAINS $inner "b"
3761
3762                # Equality ignores CONST-ness: the frozen copy equals an unfrozen twin.
3763                LET $twin: LIST<ANY> = [["a"]]
3764                ASSERT_EQ $C $twin
3765            "#},
3766                },
3767                Example {
3768                    name: "const nested freeze",
3769                    fence_meta: Some("expect_error:\"cannot mutate CONST\""),
3770                    code: indoc! {r#"
3771                # Nested containers freeze with the binding.
3772                CONST $C: LIST<ANY> = [["a"]]
3773                LET $nested: LIST<STRING> = $C.0
3774                LIST_APPEND $nested "b"
3775            "#},
3776                },
3777                Example {
3778                    name: "const alias shares frozenness",
3779                    fence_meta: Some("expect_error:\"cannot mutate CONST\""),
3780                    code: indoc! {r#"
3781                # Aliases share frozenness: copying a CONST never thaws it.
3782                CONST $C: LIST<STRING> = ["a"]
3783                LET $alias: LIST<STRING> = $C
3784                LIST_APPEND $alias "b"
3785            "#},
3786                },
3787                Example {
3788                    name: "const map set fails",
3789                    fence_meta: Some("expect_error:\"cannot mutate CONST\""),
3790                    code: indoc! {r#"
3791                # MAP_SET on a CONST fails instead of deriving.
3792                IMPORT [STD]
3793                CONST $M: MAP<ANY> = {a: 1}
3794                LET $z: MAP<ANY> = MAP_SET($M, "x", 1)
3795            "#},
3796                },
3797                Example {
3798                    name: "const merge maps fails",
3799                    fence_meta: Some("expect_error:\"cannot mutate CONST\""),
3800                    code: indoc! {r#"
3801                # MERGE_MAPS over a CONST fails instead of merging.
3802                IMPORT [STD]
3803                CONST $M: MAP<ANY> = {a: 1}
3804                LET $n: MAP<ANY> = MERGE_MAPS([$M], "overwrite")
3805            "#},
3806                },
3807            ],
3808        },
3809        CommandMeta {
3810            // `MUTATION` is not an actual keyword, so don't index it as such.
3811            in_index: false,
3812            name: "MUTATION",
3813            syntax: "$var = <expr>",
3814            summary: "Mutate a declared variable.",
3815            description: indoc! {r#"
3816                Reassigns an existing variable, converting the new value to
3817                the type declared at LET time through the same narrow
3818                coercion pairs as declaration. Strings never parse to
3819                numbers implicitly: `$n = "42"` is a TypeMismatch for an
3820                INT, write `$n = INT("42")` instead.
3821                Expressions never convert: `"100" + 1` is a Type Error, use
3822                `INT()` / `FLOAT()` to cross that boundary explicitly.
3823
3824                The leading `$` distinguishes mutation from `KEY=value` command
3825                assignments. Assigning an undeclared variable or a mismatched type is
3826                an error.
3827
3828                Mutation writes through to the scope where the variable was
3829                declared, so it survives block exit: `LET $x` outside a block
3830                followed by `$x = ...` inside still reads back the new value
3831                afterwards, for every type. This is the counterpart to LET
3832                shadowing, where `LET $x` *inside* the block declares a
3833                separate inner variable that reverts on exit.
3834
3835                Reassignment rebinds the variable to a new value: values
3836                captured earlier keep the old word (see the rebinding
3837                example below).
3838            "#},
3839            args: &[],
3840            flags: &[],
3841            default_output: None,
3842            examples: &[
3843                Example {
3844                    name: "mutate",
3845                    fence_meta: None,
3846                    code: indoc! {r#"
3847                # Mutation writes through: the binding holds the new value.
3848                LET $count: INT = 1
3849                $count = 2
3850                ASSERT_EQ $count 2
3851            "#},
3852                },
3853                Example {
3854                    name: "rebind keeps earlier captures",
3855                    fence_meta: None,
3856                    code: indoc! {r#"
3857                # Reassignment rebinds: a map built from `$s` still
3858                # reads the original string after `$s` moves on.
3859                LET $s: STRING = "test"
3860                LET $m: MAP<ANY> = {a: $s}
3861                $s = "changed"
3862                ASSERT_EQ $m.a "test"
3863
3864                # Appending to one list binding never touches its clones.
3865                LET $a: LIST<STRING> = ["1"]
3866                LET $b: LIST<STRING> = $a
3867                LIST_APPEND $a "2"
3868                LET $want: LIST<STRING> = ["1"]
3869                ASSERT_EQ $b $want
3870            "#},
3871                },
3872                Example {
3873                    name: "convert before math",
3874                    fence_meta: None,
3875                    code: indoc! {r#"
3876                # Captured output is a string: `"100" + 1` is a Type Error.
3877                # Convert explicitly, then mutate with arithmetic.
3878                IMPORT [STD]
3879                LET $raw: STRING = ECHO 100
3880                LET $n: INT = INT($raw)
3881                $n = $n + 1
3882
3883                # The declared slot stays strict: strings parse only
3884                # through the explicit converter, never on assignment.
3885                $n = INT("42")
3886                ASSERT_EQ $n 42
3887
3888                # Same crossing for decimals via FLOAT().
3889                LET $frac_str: STRING = ECHO 2.5
3890                LET $f: FLOAT = FLOAT($frac_str) + 0.25
3891                ASSERT_EQ $f 2.75
3892            "#},
3893                },
3894                Example {
3895                    name: "reject keypath target",
3896                    fence_meta: Some("expect_error:\"cannot assign to $M.a\""),
3897                    code: indoc! {r#"
3898                # Rebind the whole variable to update one entry.
3899                IMPORT [STD]
3900                LET $M: MAP<ANY> = {a: 1}
3901                $M = MAP_SET($M, "a", 2)
3902                ASSERT_EQ $M.a 2
3903
3904                # Key paths read in expressions but are never mutation targets.
3905                $M.a = 3
3906            "#},
3907                },
3908            ],
3909        },
3910        CommandMeta {
3911            in_index: true,
3912            name: KEYWORD_ASYNC,
3913            syntax: "ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE<T> = ASYNC { <commands> }",
3914            summary: "Run steps in a background thread.",
3915            description: indoc! {r#"
3916                Runs a command or block of commands in a background thread with
3917                subshell isolation.
3918
3919                Mutations (ENV, WORKDIR) stay within the block. With `LET`, stores a
3920                task handle for `AWAIT`. Task output streams live to the parent
3921                stdout; a task publishes a value with an explicit `RETURN`,
3922                which `LET $out: TYPE = AWAIT $task` binds.
3923
3924                `WITH_IO` must wrap `ASYNC` from the outside (`LET $p: PIPE` first,
3925                then `WITH_IO [stdout=$p] ASYNC ...`) so pipe endpoints allocate on
3926                the main thread before the worker spawns. Placing `WITH_IO` directly
3927                inside `ASYNC` is rejected at parse time.
3928            "#},
3929            args: &[],
3930            flags: &[],
3931            default_output: None,
3932            examples: &[
3933                Example {
3934                    name: "async",
3935                    fence_meta: None,
3936                    code: indoc! {r#"
3937                # Inline and block forms both run in the background; AWAIT joins them.
3938                ASYNC ECHO "warming-up"
3939                LET $a: HANDLE<VOID> = ASYNC ECHO "first"
3940                LET $b: HANDLE<VOID> = ASYNC {
3941                    ECHO "second"
3942                }
3943                AWAIT $a
3944                AWAIT $b
3945                ASSERT_CONTAINS stdout "first"
3946                ASSERT_CONTAINS stdout "second"
3947                "#},
3948                },
3949                Example {
3950                    name: "async task handle",
3951                    fence_meta: None,
3952                    code: indoc! {r#"
3953                    LET $task: HANDLE<VOID> = ASYNC {
3954                        ECHO "built"
3955                    }
3956                    AWAIT $task
3957                    ASSERT_CONTAINS stdout "built"
3958                "#},
3959                },
3960            ],
3961        },
3962        CommandMeta {
3963            in_index: true,
3964            name: KEYWORD_AWAIT,
3965            syntax: "AWAIT $var | LET $out: STRING = AWAIT $var",
3966            summary: "Join a background task.",
3967            description: indoc! {r#"
3968                Blocks until the named task completes. Propagates errors if the task failed.
3969
3970                Task output streams live during the run; joining binds nothing by
3971                itself. `LET $out: TYPE = AWAIT $var` binds the task's explicit
3972                `RETURN` value instead, or `INT` 0 when the task succeeded
3973                without one (add `RETURN <expr>` to the task body to yield
3974                a value).
3975            "#},
3976            args: &[],
3977            flags: &[],
3978            default_output: None,
3979            examples: &[
3980                Example {
3981                    name: "await",
3982                    fence_meta: None,
3983                    code: indoc! {r#"
3984                LET $task: HANDLE<VOID> = ASYNC ECHO "done"
3985                AWAIT $task
3986                ASSERT_CONTAINS stdout "done"
3987            "#},
3988                },
3989                Example {
3990                    name: "await capture",
3991                    fence_meta: None,
3992                    code: indoc! {r#"
3993                LET $task: HANDLE<STRING> = ASYNC {
3994                    ECHO "logged"
3995                    RETURN "returned"
3996                }
3997
3998                # AWAIT binds the RETURN value, not the streamed output.
3999                LET $out: STRING = AWAIT $task
4000                ASSERT_EQ $out "returned"
4001            "#},
4002                },
4003            ],
4004        },
4005        CommandMeta {
4006            in_index: true,
4007            name: KEYWORD_CANCEL,
4008            syntax: "CANCEL $var",
4009            summary: "Synchronously cancel a background task.",
4010            description: indoc! {r#"
4011                Kills the named background task spawned via `LET $var: HANDLE<T> = ASYNC ...`.
4012
4013                Blocking: returns only after the task thread has been joined and its OS
4014                process reaped, so no residual filesystem or stream mutation follows. A
4015                later AWAIT $var reports cancellation. Only named tasks can be cancelled.
4016            "#},
4017            args: &[],
4018            flags: &[],
4019            default_output: None,
4020            examples: &[
4021                Example {
4022                    name: "cancel",
4023                    fence_meta: None,
4024                    code: indoc! {r#"
4025                LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
4026                CANCEL $task
4027            "#},
4028                },
4029                Example {
4030                    name: "await after cancel reports cancellation",
4031                    fence_meta: Some("expect_error:\"was cancelled\""),
4032                    code: indoc! {r#"
4033                # A cancelled task stays cancelled: joining it reports.
4034                LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
4035                CANCEL $task
4036                AWAIT $task
4037            "#},
4038                },
4039            ],
4040        },
4041        CommandMeta {
4042            in_index: true,
4043            name: KEYWORD_TIMEOUT,
4044            syntax: "TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var",
4045            summary: "Enforce an execution deadline.",
4046            description: indoc! {r#"
4047                Aborts the wrapped step or block with a deadline error if it exceeds the
4048                duration (e.g. 500ms, 10s, 2m; a bare number means seconds).
4049
4050                A blocking foreground process is killed.
4051
4052                ASYNC nests in either order with order-dependent deadline
4053                semantics: `LET $task: HANDLE<VOID> = ASYNC TIMEOUT 30s RUN "build"` enforces
4054                the deadline inside the background thread (a later `AWAIT $task`
4055                surfaces the `TIMEOUT` error), while `TIMEOUT 30s AWAIT $task`
4056                preempts a hung task from the awaiting side.
4057            "#},
4058            args: &[],
4059            flags: &[],
4060            default_output: None,
4061            examples: &[
4062                Example {
4063                    name: "timeout",
4064                    fence_meta: None,
4065                    code: indoc! {r#"
4066                    TIMEOUT 30s WRITE heartbeat.txt alive
4067                    LET $beat: STRING = READ heartbeat.txt
4068                    ASSERT_EQ $beat "alive"
4069                "#},
4070                },
4071                Example {
4072                    name: "timeout block",
4073                    fence_meta: None,
4074                    code: indoc! {r#"
4075                    TIMEOUT 30s {
4076                        WRITE a.txt one
4077                        WRITE b.txt two
4078                    }
4079                    LET $a: STRING = READ a.txt
4080                    LET $b: STRING = READ b.txt
4081                    ASSERT_EQ $a "one"
4082                    ASSERT_EQ $b "two"
4083                "#},
4084                },
4085                Example {
4086                    name: "deadline aborts the step",
4087                    fence_meta: Some("expect_error:\"TIMEOUT after\""),
4088                    code: indoc! {r#"
4089                    # 50ms expires long before the sleep does: the step dies
4090                    # with a deadline error instead of running out the clock.
4091                    TIMEOUT 50ms SLEEP 30s
4092                "#},
4093                },
4094                Example {
4095                    name: "timeout variable duration",
4096                    fence_meta: None,
4097                    code: indoc! {r#"
4098                    # Durations resolve at runtime, so variables work too.
4099                    LET $budget: DURATION = "30s"
4100                    TIMEOUT $budget WRITE heartbeat.txt alive
4101
4102                    LET $beat: STRING = READ heartbeat.txt
4103                    ASSERT_EQ $beat "alive"
4104                "#},
4105                },
4106                Example {
4107                    name: "timeout await",
4108                    fence_meta: None,
4109                    code: indoc! {r#"
4110                    # AWAIT form bounds a task join instead of a step.
4111                    LET $quick: HANDLE<VOID> = ASYNC {
4112                        ECHO hi
4113                    }
4114                    TIMEOUT 30s AWAIT $quick
4115                "#},
4116                },
4117            ],
4118        },
4119        CommandMeta {
4120            in_index: true,
4121            name: KEYWORD_FAIL,
4122            syntax: "FAIL [<code>] [<message>] [{ <commands> }]",
4123            summary: "Print a failure message and exit.",
4124            description: indoc! {r#"
4125                Prints the message to stderr (the `ECHO` plus `EXIT` idiom as
4126                one step, rerouted to the error stream), runs the optional
4127                block first, then exits through the `EXIT` path with
4128                `EXIT requested with code <code>`.
4129
4130                With no code the exit code is 1; with a code it clamps to
4131                0..=255 like `EXIT`. The block runs first in a child scope
4132                that reads caller locals, with its stdout rerouted to
4133                stderr, so usage text, cleanup, and callee output all land
4134                on the error stream while stdout stays empty: the only
4135                form a `FUNC` cannot express, since functions take values,
4136                never blocks. At least one of message or block is required.
4137
4138                A lone bare int is a silent code (`FAIL 2` exits 2 with no
4139                output); quoting decides, so `FAIL "2"` prints `2` and
4140                exits 1.
4141            "#},
4142            args: &[],
4143            flags: &[],
4144            default_output: Some(Stream::Stderr),
4145            examples: &[
4146                Example {
4147                    name: "fail",
4148                    fence_meta: Some("expect_error:\"EXIT requested with code 1\""),
4149                    code: indoc! {r#"
4150                    # The message prints to stderr, never stdout, so a
4151                    # failure cannot pollute captured output. No code
4152                    # means exit 1.
4153                    FAIL "cargo not found in image"
4154                    "#},
4155                },
4156                Example {
4157                    name: "fail code",
4158                    fence_meta: Some("expect_error:\"EXIT requested with code 2\""),
4159                    code: indoc! {r#"
4160                    # An explicit code exits with that code (clamped to
4161                    # 0..=255 like EXIT); the message still prints to
4162                    # stderr.
4163                    FAIL 2 "cargo not found in image"
4164                    "#},
4165                },
4166                Example {
4167                    name: "fail block",
4168                    fence_meta: Some("expect_error:\"EXIT requested with code 1\""),
4169                    code: indoc! {r#"
4170                    # The block runs first with its stdout rerouted to
4171                    # stderr: usage text and cleanup land on the error
4172                    # stream beside the message, and stdout stays empty.
4173                    # Callee output reroutes too: a FUNC called here
4174                    # inherits the swapped handle.
4175                    FAIL "unknown command" {
4176                        ECHO usage-text
4177                    }
4178                    "#},
4179                },
4180            ],
4181        },
4182        CommandMeta {
4183            in_index: true,
4184            name: KEYWORD_ISOLATED,
4185            syntax: "ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>",
4186            summary: "Run steps with the seeded script environment.",
4187            description: indoc! {r#"
4188                Resets the script environment for the block to the session
4189                seed: spawned children see the sandbox defaults plus names
4190                the block re-adds through its leading `INHERIT_ENV`.
4191
4192                The allowlist resolves against the outer scope, never the
4193                host. Absent names stay absent silently, matching top-level
4194                `INHERIT_ENV`.
4195
4196                Script variables, pipes, and files flow through untouched;
4197                only `env:` is reset. Files share the session workspace:
4198                blocks selecting the same `WORKSPACE` target resolve to the
4199                same directory with no per-block overlay, so one block's
4200                writes are visible to another.
4201
4202                Blocks nest (each level re-seeds from the same seed, so
4203                nesting only narrows through the allowlists) and combine
4204                with `ASYNC` and `FUNC`. Scope exit restores the prior
4205                environment.
4206            "#},
4207            args: &[],
4208            flags: &[],
4209            default_output: None,
4210            examples: &[
4211                Example {
4212                    name: "isolated scope",
4213                    fence_meta: None,
4214                    code: indoc! {r#"
4215                    # The block sees a clean env; plain steps still run and
4216                    # outer bindings survive untouched.
4217                    ENV MODE=outer
4218                    ISOLATED {
4219                        ENV MODE=inner
4220                        WRITE inner.txt "{{ env:MODE }}"
4221                    }
4222                    LET $back: STRING = "{{ env:MODE }}"
4223                    ASSERT_EQ $back "outer"
4224                    LET $body: STRING = READ inner.txt
4225                    ASSERT_EQ $body "inner"
4226                "#},
4227                },
4228                Example {
4229                    name: "reseeded child env",
4230                    fence_meta: None,
4231                    code: indoc! {r#"
4232                    # The block resets to the session seed: plain steps and
4233                    # spawns run with zero prelude. PATH needs no
4234                    # declaration: contract seed rows are always admitted.
4235                    WRITE top-path.txt "{{ env:PATH }}"
4236                    ISOLATED {
4237                        WRITE inner-path.txt "{{ env:PATH }}"
4238                        RUN "echo seed-ok"
4239                    }
4240                    LET $top: STRING = READ top-path.txt
4241                    LET $inner: STRING = READ inner-path.txt
4242                    ASSERT_EQ $inner $top
4243                    ASSERT_CONTAINS stdout "seed-ok"
4244                "#},
4245                },
4246                Example {
4247                    name: "outer customs stay out",
4248                    fence_meta: Some("expect_error:\"env:OUTER_CUSTOM\""),
4249                    code: indoc! {r#"
4250                    # Outer customs never enter the block: without an
4251                    # allowlist entry the static gate rejects the read
4252                    # before the first step runs.
4253                    ENV OUTER_CUSTOM=outer-val
4254                    ISOLATED {
4255                        WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
4256                    }
4257                "#},
4258                },
4259                Example {
4260                    name: "absent names stay absent",
4261                    fence_meta: None,
4262                    code: indoc! {r#"
4263                    # Listing a name the outer scope lacks is not an error:
4264                    # the block simply runs without it.
4265                    ISOLATED {
4266                        INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
4267                        ECHO still-runs
4268                    }
4269                    ASSERT_CONTAINS stdout "still-runs"
4270                "#},
4271                },
4272                Example {
4273                    name: "nesting narrows",
4274                    fence_meta: None,
4275                    code: indoc! {r#"
4276                    # Each level snapshots the already-scrubbed parent, so
4277                    # an inner block cannot recover what the outer dropped.
4278                    ENV KEEP=yes
4279                    ISOLATED {
4280                        INHERIT_ENV [KEEP]
4281                        ISOLATED {
4282                            ENV KEEP=inner
4283                            WRITE deep.txt "{{ env:KEEP }}"
4284                        }
4285                        LET $mid: STRING = "{{ env:KEEP }}"
4286                        ASSERT_EQ $mid "yes"
4287                    }
4288                    LET $deep: STRING = READ deep.txt
4289                    ASSERT_EQ $deep "inner"
4290                "#},
4291                },
4292            ],
4293        },
4294        CommandMeta {
4295            in_index: true,
4296            name: KEYWORD_REMOTE,
4297            syntax: "REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }",
4298            summary: "Run a sealed block on a remote target.",
4299            description: indoc! {r#"
4300                Runs the braced block on the named remote target, which the
4301                host binds at startup (`--remote`). The block is sealed:
4302                only header-listed `$var` and `env:NAME` entries cross, the
4303                guest starts empty, and results return through declared
4304                transfers or `WITH_IO` pipes.
4305
4306                The target is a static literal, never a variable. Unknown
4307                targets fail before execution starts.
4308
4309                Bodies check twice: the host static pass validates the
4310                body before anything ships, and the guest re-validates on
4311                arrival through the same entry point, so a body type error
4312                fails locally, never mid-run on the remote.
4313
4314                A failing guest fails the host step: EXIT in the body
4315                exits the guest, and the host relays the code to its own
4316                process exit status (see EXIT).
4317            "#},
4318            args: &[],
4319            flags: &[],
4320            default_output: None,
4321            examples: &[
4322                Example {
4323                    name: "sealed header values cross, outer scope does not",
4324                    fence_meta: Some("mock_remote:prod"),
4325                    code: indoc! {r#"
4326                    # Only header-listed names arrive: `$version` is visible
4327                    # on the guest, `$secret` was never sent.
4328                    LET $version: STRING = "1.2.3"
4329                    LET $secret: STRING = "host-only"
4330                    REMOTE prod [$version] {
4331                        WRITE version.txt "{{ $version }}"
4332                        COPY --to-host ./version.txt back.txt
4333                    }
4334
4335                    # The pushed file proves the guest saw the injected value.
4336                    LET $back: STRING = READ back.txt
4337                    ASSERT_EQ $back "1.2.3"
4338                "#},
4339                },
4340                Example {
4341                    name: "background tasks stream through shared pipes",
4342                    fence_meta: Some("mock_remote:prod"),
4343                    code: indoc! {r#"
4344                    # Two background REMOTEs share one capture pipe while a
4345                    # WITH_IO block holds the write end open.
4346                    IMPORT [STD]
4347                    LET $cap: PIPE
4348                    WITH_IO [stdout=$cap] {
4349                        LET $a: HANDLE<VOID> = ASYNC REMOTE prod {
4350                            ECHO "from-a"
4351                        }
4352                        LET $b: HANDLE<VOID> = ASYNC REMOTE prod {
4353                            ECHO "from-b"
4354                        }
4355                        AWAIT $a
4356                        AWAIT $b
4357                    }
4358
4359                    # EOF ends the drain: no sentinel line, no baked-in count.
4360                    LET $n: INT = 0
4361                    WHILE !EOF($cap) {
4362                        WITH_IO [stdin=$cap] READ_LINE $line
4363                        $n = $n + 1
4364                    }
4365                    ASSERT_EQ $n 2
4366                "#},
4367                },
4368                Example {
4369                    name: "declared files cross both directions",
4370                    fence_meta: Some("mock_remote:prod roots:unified"),
4371                    code: indoc! {r#"
4372                    # Fetches ride in, pushes ride back. Anything undeclared
4373                    # never leaves its side.
4374                    WRITE send.txt "payload"
4375                    REMOTE prod {
4376                        COPY --from-host ./send.txt got.txt
4377                        LET $v: STRING = READ got.txt
4378                        ASSERT_EQ $v "payload"
4379                        WRITE back.txt "returned"
4380                        COPY --to-host ./back.txt back.txt
4381                    }
4382
4383                    # The push landed on the host; guest staging is gone.
4384                    LET $b: STRING = READ back.txt
4385                    ASSERT_EQ $b "returned"
4386                "#},
4387                },
4388                Example {
4389                    name: "guest workspace selection stays on the guest",
4390                    fence_meta: Some("mock_remote:prod"),
4391                    code: indoc! {r#"
4392                    # WORKSPACE switches inside the block resolve against the
4393                    # guest staging dir, which serves as both the SNAPSHOT
4394                    # root and the LOCAL build context. The host selection
4395                    # restores when the block exits.
4396                    REMOTE prod {
4397                        WORKSPACE SNAPSHOT
4398                        WRITE out.txt "from-snapshot"
4399                        COPY --to-host ./out.txt snap.txt
4400                    }
4401
4402                    LET $s: STRING = READ snap.txt
4403                    ASSERT_EQ $s "from-snapshot"
4404                "#},
4405                },
4406                Example {
4407                    name: "guest cache persists across execs",
4408                    fence_meta: Some("mock_remote:prod"),
4409                    code: indoc! {r#"
4410                    # WORKSPACE CACHE addresses guest-local persistent
4411                    # storage: the second block reads what the first wrote,
4412                    # while the guest staging starts empty every time.
4413                    REMOTE prod {
4414                        WORKSPACE CACHE
4415                        WRITE marker.txt "run-marker"
4416                    }
4417                    REMOTE prod {
4418                        WORKSPACE CACHE
4419                        LET $m: STRING = READ marker.txt
4420                        ASSERT_EQ $m "run-marker"
4421                    }
4422                "#},
4423                },
4424                Example {
4425                    name: "pushes outside staging fail closed",
4426                    fence_meta: Some("mock_remote:prod expect_error:\"escapes staging\""),
4427                    code: indoc! {r#"
4428                    # WORKSPACE SYSTEM exposes the whole guest machine, but
4429                    # transfers stay staging scoped: a push source outside
4430                    # staging fails loudly instead of crossing.
4431                    REMOTE prod {
4432                        WORKSPACE SYSTEM
4433                        COPY --to-host /no/such/file.txt got.txt
4434                    }
4435                "#},
4436                },
4437                Example {
4438                    name: "guest exit fails the step, host survives",
4439                    fence_meta: Some(
4440                        "mock_remote:prod expect_error:\"REMOTE 'prod' exited with code 3\"",
4441                    ),
4442                    code: indoc! {r#"
4443                    # EXIT in the body exits the guest with code 3. The
4444                    # host is unaffected: it keeps executing after the
4445                    # guest is already dead, and the failure surfaces as
4446                    # a host step error carrying the same code. The CLI
4447                    # then exits with it, so the guest code reaches the OS.
4448                    LET $t: HANDLE<VOID> = ASYNC REMOTE prod {
4449                        EXIT 3
4450                    }
4451                    WRITE host-alive.txt "still here"
4452                    AWAIT $t
4453                "#},
4454                },
4455                Example {
4456                    name: "remote block without a runner",
4457                    fence_meta: Some("expect_error:\"has no registered session\""),
4458                    code: indoc! {r#"
4459                    # Without a bound session, the block bails instead of
4460                    # executing anywhere unexpected.
4461                    REMOTE prod {
4462                        ECHO "do something on remote"
4463                    }
4464                "#},
4465                },
4466            ],
4467        },
4468        CommandMeta {
4469            in_index: true,
4470            name: KEYWORD_FUNC,
4471            syntax: "FUNC NAME([$param: TYPE, ...]): RET { <commands> } | ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }",
4472            summary: "Define a user function.",
4473            description: indoc! {r#"
4474                Defines a user function with UPPERCASE name and explicitly typed
4475                parameters. `FUNC` runs synchronously; `ASYNC FUNC` is the same
4476                with a structural guarantee: the declaration must be
4477                `HANDLE<T>`, so every `RETURN` hands out a task handle.
4478
4479                Params bind by position, converting each argument to its
4480                declared parameter type before the body runs.
4481                A trailing `$name?: TYPE` marks an optional param: callers
4482                may omit trailing optionals, which fill with zero values
4483                (`false`, `""`, `0`, `0.0`, `[]`, `{}`) before the body
4484                binds. A required param after an optional one fails at
4485                definition, and an optional param with no zero value
4486                (records with required fields, unions, handles, custom
4487                types) fails at definition naming the fix: drop the `?`
4488                or pass the argument explicitly.
4489                Bodies run isolated: a fresh variable scope plus the
4490                callee definition-site jail (workspace, cwd, and env
4491                reset; only explicit arguments cross, #322). Module
4492                bodies restore the workspace selection and cwd their
4493                own top-level left behind, so a lib declaring
4494                WORKSPACE at the top serves its FUNCs from there no
4495                matter which workspace the caller sits in; entry
4496                bodies restore the workspace selection and cwd sealed
4497                at their definition site (defaulting to the snapshot
4498                jail when none was set before definition). A FUNC-level
4499                WORKSPACE or WORKDIR statement overrides the file
4500                default for that call, and the caller context returns
4501                on every exit path. Conditional top-level configuration
4502                uses guards (`[env:FLAG] WORKSPACE LOCAL`): `IF` bodies
4503                unwind on exit and never become the jail; see IMPORT.
4504                LETs inside do not leak. A nested
4505                FUNC definition is scoped to its block and reverts on exit. Names share
4506                one namespace with native and host-registered functions, which a FUNC
4507                may never shadow.
4508
4509                Functions resolve like variables: a name is visible from its
4510                definition line, so recursion works but mutual recursion does
4511                not (the second name does not exist while the first body
4512                lowers). Calls name their module (`STD::GLOB(...)`) unless
4513                imported; see IMPORT.
4514
4515                Invoke any function with one syntax: `NAME(...)` as a statement
4516                (discarding the value) or `LET $var: TYPE = NAME(...)` to capture
4517                the RETURN value (fallthrough without RETURN is a static error unless RET is VOID).
4518
4519                `ASYNC FUNC` does not spawn on call. The body runs
4520                synchronously on the caller thread up to its inner `ASYNC`
4521                step, which spawns the background task and yields its handle
4522                immediately; the function then hands that handle out with
4523                `RETURN $t`. The caller joins it separately with `AWAIT`.
4524            "#},
4525            args: &[],
4526            flags: &[],
4527            default_output: None,
4528            examples: &[
4529                Example {
4530                    name: "func def call",
4531                    fence_meta: None,
4532                    code: indoc! {r#"
4533                FUNC GREET($name: STRING): STRING {
4534                  RETURN $name
4535                }
4536
4537                LET $res: STRING = GREET("ada")
4538                ASSERT_EQ $res "ada"
4539
4540                # Statement form: parens stay, the value drops.
4541                GREET("bex")
4542            "#},
4543                },
4544                Example {
4545                    name: "bind then interpolate",
4546                    fence_meta: None,
4547                    code: indoc! {r#"
4548                # Script FUNCs run as steps, never inside {{ }}.
4549                FUNC GREET($name: STRING): STRING {
4550                  RETURN $name
4551                }
4552
4553                # Call as a step to capture the RETURN.
4554                LET $res: STRING = GREET("ada")
4555
4556                # {{ }} reads the bound var.
4557                LET $msg: STRING = "says {{ $res }}"
4558
4559                ASSERT_EQ $msg "says ada"
4560            "#},
4561                },
4562                Example {
4563                    name: "script funcs never resolve in placeholders",
4564                    fence_meta: Some(
4565                        "expect_error:\"placeholder function 'SCRIPT::GREET' is a script function\"",
4566                    ),
4567                    code: indoc! {r#"
4568                # Placeholders carry no step context: pure registry only.
4569                FUNC GREET($name: STRING): STRING {
4570                  RETURN $name
4571                }
4572
4573                # Bind the argument as a step var to keep quoting flat.
4574                LET $who: STRING = "ada"
4575
4576                # This fails naming the pure-only boundary.
4577                ECHO "{{ SCRIPT::GREET($who) }}"
4578            "#},
4579                },
4580                Example {
4581                    name: "optional params fill zero values",
4582                    fence_meta: None,
4583                    code: indoc! {r#"
4584                IMPORT [STD]
4585                # Trailing `?` params may be omitted; they fill with
4586                # zero values (false, empty map) before the body binds,
4587                # so plain IF works on an omitted BOOL.
4588                FUNC ENSURE($check?: BOOL, $opts?: MAP<mode?: STRING>): STRING {
4589                    IF $check {
4590                        RETURN "checked"
4591                    }
4592                    IF HAS_KEY($opts, "mode") {
4593                        RETURN "opts"
4594                    }
4595                    RETURN "plain"
4596                }
4597                LET $a: STRING = ENSURE()
4598                ASSERT_EQ $a "plain"
4599                LET $b: STRING = ENSURE(true)
4600                ASSERT_EQ $b "checked"
4601                LET $opts: MAP<mode?: STRING> = PARSE_JSON("{\"mode\": \"fast\"}")
4602                LET $c: STRING = ENSURE(false, $opts)
4603                ASSERT_EQ $c "opts"
4604            "#},
4605                },
4606                Example {
4607                    name: "optional params must trail",
4608                    fence_meta: Some("expect_error:\"optional ? params must be trailing\""),
4609                    code: indoc! {r#"
4610                # A required param after an optional one fails at definition.
4611                FUNC BAD($a?: STRING, $b: STRING): STRING {
4612                    RETURN $b
4613                }
4614            "#},
4615                },
4616                Example {
4617                    name: "async func is a handle guarantee",
4618                    fence_meta: None,
4619                    code: indoc! {r#"
4620                # Side by side: identical bodies, identical handling. The
4621                # ASYNC marker only guarantees the HANDLE declaration.
4622                ASYNC FUNC FETCH(): HANDLE<STRING> {
4623                  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
4624                  RETURN $t
4625                }
4626                FUNC MAKE(): HANDLE<STRING> {
4627                  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
4628                  RETURN $t
4629                }
4630
4631                # Both run synchronously to RETURN; the inner ASYNC spawns.
4632                LET $a: HANDLE<STRING> = FETCH()
4633                LET $b: HANDLE<STRING> = MAKE()
4634                LET $x: STRING = AWAIT $a
4635                LET $y: STRING = AWAIT $b
4636                ASSERT_EQ $x "hi"
4637                ASSERT_EQ $y "hi"
4638            "#},
4639                },
4640                Example {
4641                    name: "call with pipes",
4642                    fence_meta: None,
4643                    code: indoc! {r#"
4644                # A pipe handle travels into a function as a typed argument
4645                # and is usable as a binding target in both directions.
4646                # `LET $p: PIPE` mints the handle; `$p` passes it on.
4647                FUNC DRAIN($q: PIPE): STRING {
4648                  WITH_IO [stdin=$q] READ_LINE $line
4649                  RETURN $line
4650                }
4651
4652                LET $p: PIPE
4653                WITH_IO [stdout=$p] ECHO "payload"
4654
4655                LET $got: STRING = DRAIN($p)
4656                ASSERT_EQ $got "payload"
4657            "#},
4658                },
4659            ],
4660        },
4661        CommandMeta {
4662            in_index: true,
4663            name: KEYWORD_RETURN,
4664            syntax: "RETURN [<expr>]",
4665            summary: "Return a value from a function, task, or inline block.",
4666            description: indoc! {r#"
4667                Ends the nearest enclosing boundary with a value: a function
4668                call, an `ASYNC` task (bound by `LET $out: STRING = AWAIT $t`), or an
4669                inline `LET` block. Bare `RETURN` with no expression yields
4670                `""`.
4671
4672                Falling off the end without RETURN yields "". RETURN with no
4673                enclosing boundary (including at top level) is an error; use
4674                EXIT or ECHO there.
4675            "#},
4676            args: &[],
4677            flags: &[],
4678            default_output: None,
4679            examples: &[Example {
4680                name: "return",
4681                fence_meta: None,
4682                code: indoc! {r#"
4683                FUNC PICK($flag: BOOL): STRING {
4684                  IF $flag {
4685                    RETURN "yes"
4686                  }
4687                  RETURN "no"
4688                }
4689
4690                LET $res: STRING = PICK(true)
4691                ASSERT_EQ $res "yes"
4692
4693                # Fallthrough without RETURN yields its own value.
4694                LET $no: STRING = PICK(false)
4695                ASSERT_EQ $no "no"
4696            "#},
4697            }],
4698        },
4699        CommandMeta {
4700            in_index: true,
4701            name: KEYWORD_WHILE,
4702            syntax: "WHILE <bool-expr> { <commands> }",
4703            summary: "Loop while a condition holds.",
4704            description: indoc! {r#"
4705                Re-evaluates a Bool condition each iteration (same is_truthy rule as IF;
4706                non-Bool is a type error).
4707
4708                Each iteration runs in a fresh scope; mutate outer state with $var = ...
4709                so the next check observes it. BREAK exits the loop; CONTINUE skips to
4710                the next check.
4711            "#},
4712            args: &[],
4713            flags: &[],
4714            default_output: None,
4715            examples: &[Example {
4716                name: "while loop",
4717                fence_meta: None,
4718                code: indoc! {r#"
4719                # The condition re-evaluates every iteration: three passes, then stop.
4720                LET $n: INT = 0
4721                WHILE $n < 3 {
4722                  WRITE tick.txt "{{ $n }}"
4723                  $n = $n + 1
4724                }
4725
4726                ASSERT_EQ $n 3
4727                LET $tick: STRING = READ tick.txt
4728                ASSERT_EQ $tick "2"
4729            "#},
4730            }],
4731        },
4732        CommandMeta {
4733            in_index: true,
4734            name: KEYWORD_BREAK,
4735            syntax: KEYWORD_BREAK,
4736            summary: "Exit the innermost loop.",
4737            description: indoc! {r#"
4738                Exits the innermost enclosing FOR or WHILE loop.
4739
4740                BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.
4741            "#},
4742            args: &[],
4743            flags: &[],
4744            default_output: None,
4745            examples: &[
4746                Example {
4747                    name: "break",
4748                    fence_meta: None,
4749                    code: indoc! {r#"
4750                # BREAK leaves after the first pass: only "a" is written.
4751                FOR $x: STRING IN ["a", "b"] {
4752                  WRITE picked.txt "{{ $x }}"
4753                  BREAK
4754                }
4755
4756                LET $body: STRING = READ picked.txt
4757                ASSERT_EQ $body "a"
4758            "#},
4759                },
4760                Example {
4761                    name: "break nested",
4762                    fence_meta: None,
4763                    code: indoc! {r#"
4764                # Inner BREAK exits only the inner loop: the outer runs
4765                # both passes, and each inner stops before 2.
4766                LET $hits: LIST<STRING> = []
4767                FOR $o: STRING IN ["x", "y"] {
4768                  FOR $i: INT IN [1, 2, 3] {
4769                    IF $i == 2 {
4770                      BREAK
4771                    }
4772                    LIST_APPEND $hits "{{ $o }}{{ $i }}"
4773                  }
4774                }
4775
4776                LET $want: LIST<STRING> = ["x1", "y1"]
4777                ASSERT_EQ $hits $want
4778            "#},
4779                },
4780            ],
4781        },
4782        CommandMeta {
4783            in_index: true,
4784            name: KEYWORD_CONTINUE,
4785            syntax: KEYWORD_CONTINUE,
4786            summary: "Skip to the next loop iteration.",
4787            description: indoc! {r#"
4788                Skips the rest of the innermost enclosing FOR or WHILE body and starts
4789                the next iteration.
4790
4791                CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.
4792            "#},
4793            args: &[],
4794            flags: &[],
4795            default_output: None,
4796            examples: &[
4797                Example {
4798                    name: "continue",
4799                    fence_meta: None,
4800                    code: indoc! {r#"
4801                # CONTINUE skips the write on "a": only "b" lands.
4802                FOR $x: STRING IN ["a", "b"] {
4803                  IF $x == "a" {
4804                    CONTINUE
4805                  }
4806                  WRITE picked.txt "{{ $x }}"
4807                }
4808
4809                LET $body: STRING = READ picked.txt
4810                ASSERT_EQ $body "b"
4811            "#},
4812                },
4813                Example {
4814                    name: "continue nested",
4815                    fence_meta: None,
4816                    code: indoc! {r#"
4817                # Inner CONTINUE skips only the inner 2: the outer runs
4818                # both passes, and each inner still reaches 3.
4819                LET $hits: LIST<STRING> = []
4820                FOR $o: STRING IN ["x", "y"] {
4821                  FOR $i: INT IN [1, 2, 3] {
4822                    IF $i == 2 {
4823                      CONTINUE
4824                    }
4825                    LIST_APPEND $hits "{{ $o }}{{ $i }}"
4826                  }
4827                }
4828
4829                LET $want: LIST<STRING> = ["x1", "x3", "y1", "y3"]
4830                ASSERT_EQ $hits $want
4831            "#},
4832                },
4833            ],
4834        },
4835        CommandMeta {
4836            in_index: true,
4837            name: KEYWORD_IMPORT,
4838            syntax: "IMPORT [<module>, ...] | IMPORT <module> | IMPORT [\"<path>\" AS <ALIAS>] | IMPORT [<module | \"<path>\" AS <ALIAS> | [F, ... FROM (\"<path>\" | <module>) (AS <ALIAS>)?]>, ...]",
4839            summary: "Bring module functions into bare-call scope; import script files and types.",
4840            description: indoc! {r#"
4841                Bare calls:
4842                - Every call names its module (`STD::GLOB(...)`)
4843                  unless the module is imported. `IMPORT [STD]` lets
4844                  the rest of the scope call `GLOB(...)` bare.
4845                - Calls resolve at parse time: `SCRIPT` definitions
4846                  first, then imported modules. Unknown modules,
4847                  unknown functions, and unimported bare calls are
4848                  parse errors, never runtime surprises.
4849
4850                Scope:
4851                - A file or harvest `IMPORT` applies from its line to
4852                  the enclosing block exit, then unwinds like `LET`
4853                  scoping: reads inside the block resolve, reads past
4854                  it fail closed. Top-level imports persist for the
4855                  unit. Module-only imports (`IMPORT [STD]`) register
4856                  names with no step and no scope.
4857                - An `IMPORT` that never executes leaves its alias
4858                  unknown: reads must follow the import in execution
4859                  order.
4860                - Guards gate execution: a guarded `IMPORT` runs only
4861                  where its guard holds. Same-frame duplicates reject
4862                  at parse unless every entry is guard-gated;
4863                  all-guarded duplicates resolve per platform when
4864                  their guards are disjoint, and fail ambiguous on
4865                  overlap.
4866                - Two imported modules exporting one name is an
4867                  ambiguity error: qualify the call instead.
4868
4869                File imports:
4870                - Form: `IMPORT ["./lib.oxdock" AS LIB]` (any file
4871                  extension). The alias is mandatory and becomes the
4872                  namespace (`LIB::FOO`), with no filename inference.
4873                - Only `EXPORT`ed top-level `FUNC`s cross the
4874                  boundary. Unexported means private; variables are
4875                  never exportable.
4876                - Types cross qualified: a whole-file import exposes
4877                  every exported alias as `ALIAS::NAME` only
4878                  (`LET $p: LIB::PERSON` after
4879                  `IMPORT ["./lib.oxfile" AS LIB]`), mirroring func
4880                  views. Nothing bare leaks from an aliased import,
4881                  so same-named types in different files coexist;
4882                  harvests below stay the explicit way to request a
4883                  bare name.
4884                - Each file initializes once; every alias shares the
4885                  module's top-level bindings.
4886                - The file must exist when the run starts. Generated
4887                  imports are rejected before the first step.
4888
4889                Mixed brackets:
4890                - Brackets mix both kinds across lines if needed
4891                  (`IMPORT [STD, "a.oxdock" AS A]`). Each module entry
4892                  registers in order; each file entry runs in order.
4893                - Without an alias a file entry is a parse error.
4894                - Value positions (`LET`, `ASYNC`,
4895                  `WITH_IO`/`TIMEOUT` inners) take exactly one file
4896                  entry and no modules.
4897
4898                Selective harvests:
4899                - Form: `IMPORT [FOO FROM "x.oxdock"]`,
4900                  optionally `AS ALIAS`. Only the named top-level
4901                  functions register, bare or namespaced under the
4902                  alias. Harvested names must be `EXPORT`ed.
4903                - Single name needs no inner brackets
4904                  (`IMPORT [FOO FROM "x.oxdock"]`); several names from
4905                  one file combine in one bracket with explicit kinds
4906                  (`IMPORT [TYPE A, TYPE B FROM "x.oxdock"]`, file or
4907                  host alike: `IMPORT [FUNC FOO, FUNC BAR FROM
4908                  "x.oxdock"]`). Bare names always read as modules, so
4909                  a bare multi-name fails naming the explicit-kind
4910                  fix. Prefer one import per file over grouping
4911                  harvests.
4912                - Types and functions combine in one entry
4913                  (`IMPORT [TYPE PERSON, FUNC FOO FROM "x.oxdock"]`).
4914                  Harvested types must be `EXPORT TYPE`d. Unaliased
4915                  harvests persist bare globally (collision-checked),
4916                  so `FUNC` signatures keep working; aliased harvests
4917                  persist qualified-only, like whole-file imports.
4918                - The file body never executes, so harvesting is
4919                  side-effect free. The file's own nested imports
4920                  still load. Harvests produce no value and never
4921                  appear in value positions.
4922
4923                Host library types:
4924                - Form: `IMPORT [TYPE PIPE FROM STD]`. The import
4925                  validates the type resolves globally and records no
4926                  file. Host types stay global with or without the
4927                  harvest; the explicit form only documents the
4928                  dependency and fails fast on typos.
4929                - Bare `FROM` names a library; quoted `FROM`
4930                  names a file path. Quoted `FROM "STD"` still parses
4931                  for backcompat, but bare is preferred.
4932
4933                Paths:
4934                - Workspace-side, against the importing file's
4935                  directory (entry parent at top level; off-workspace
4936                  entries resolve like stdin against the root).
4937                - Relative operation paths resolve against the
4938                  defining file's own jail: each module top-level
4939                  runs isolated in the snapshot jail, and its
4940                  WORKSPACE and WORKDIR statements establish the
4941                  context its FUNCs restore on every call (#322).
4942                - Missing files fail before the first step runs.
4943                  Write-then-import in one script is rejected; check
4944                  libraries into the tree, or combine them at runtime
4945                  and run a child interpreter (see the child run
4946                  examples below).
4947
4948                Module rules (every file import is a module):
4949                - Context: never inherits the caller's namespace. Env
4950                  resets to the seed plus the module init's own
4951                  contributions (declared `INHERIT_ENV` names re-read
4952                  from the host on every call). Workspace selection
4953                  and cwd reset to the module top-level jail: the
4954                  init body runs isolated in the snapshot jail, and
4955                  the selection plus cwd it leaves behind become the
4956                  default every FUNC of that file restores on entry,
4957                  unless the FUNC body overrides them. A module
4958                  function needing the caller directory takes it as
4959                  a path argument.
4960                - Determinism: behavior is a pure function of the
4961                  file. The same file behaves identically no matter
4962                  who imports it or which workspace the importer
4963                  sits in.
4964                - State: one init per file, shared by every alias.
4965                  Top-level `LET` bindings drain into a single store
4966                  visible to all of the module's functions.
4967                - Workspace: `WORKSPACE` and `WORKDIR` at a module
4968                  top-level establish that module's jail for its
4969                  FUNCs; `WORKSPACE` and `WORKDIR` inside a FUNC
4970                  body override the file default for that call.
4971                  Caller and callee selections never leak across
4972                  the call in either direction.
4973                - Conditional top-level: `IF` bodies unwind on exit,
4974                  so a `WORKSPACE` inside one never becomes the jail.
4975                  Guard-gated steps (`[env:FLAG]`) run in place, so
4976                  they persist: use guards for conditional config.
4977                - Exports: only `EXPORT`ed top-level `FUNC`s and
4978                  `EXPORT TYPE` aliases cross. Variables never cross.
4979                - Imports: whole-file or harvest, only exported
4980                  functions and types cross. Stateful harvests are
4981                  rejected (import the file to share its module).
4982                  Nested imports load automatically.
4983                - Cycles: circular imports and depth over 32 fail
4984                  before the first step runs.
4985
4986                Exports and tools:
4987                - `EXPORT` marks top-level `FUNC`s as externally
4988                  callable (`EXPORT FOO`, `EXPORT [FOO, BAR]`) and as
4989                  the file importable interface. Re-exports promote
4990                  an import (`IMPORT ["x.oxdock" AS A]` then `EXPORT
4991                  A::FOO`).
4992                - `EXPORT TYPE` marks aliases the same way
4993                  (`EXPORT TYPE PERSON`, `EXPORT TYPE [A, B]`, mixed
4994                  `EXPORT [TYPE A, FUNC B]`). Only exported aliases
4995                  cross, so `FUNC` signatures survive imports.
4996                - Serving resolves re-exports through the registry;
4997                  unexported names fail tool setup instead of serving
4998                  a dead tool. The MCP server skips `TYPE` exports
4999                  when building tools while still resolving imported
5000                  types for signatures. Single-file scope otherwise;
5001                  see the MCP host for consumption.
5002            "#},
5003            args: &[],
5004            flags: &[],
5005            default_output: None,
5006            examples: &[
5007                Example {
5008                    name: "import",
5009                    fence_meta: None,
5010                    code: indoc! {r#"
5011                # Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
5012                WRITE a.txt "hi \{{ env:WHO }}!"
5013                IMPORT [STD]
5014                FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
5015                ASSERT_CONTAINS stdout "hi World!"
5016            "#},
5017                },
5018                Example {
5019                    name: "module top-level jail",
5020                    fence_meta: Some("roots:unified"),
5021                    code: indoc! {r#"
5022                # A module top-level establishes its own jail: the lib
5023                # selects WORKSPACE LOCAL and a WORKDIR up front, and
5024                # its FUNC restores both on entry while the entry sits
5025                # elsewhere. Unified roots: the child inherits one
5026                # workspace, so parent and child see the same files.
5027                IMPORT [STD]
5028                WRITE lib.oxfile """
5029                    IMPORT [STD]
5030                    WORKSPACE LOCAL
5031                    MKDIR modsub
5032                    WORKDIR modsub
5033                    EXPORT [FUNC WHERE]
5034                    FUNC WHERE(): STRING {
5035                        LET $c: STRING = CWD()
5036                        RETURN $c
5037                    }
5038                    """
5039                WRITE main.oxfile """
5040                    IMPORT [STD, "lib.oxfile" AS LIB]
5041                    MKDIR entry-sub
5042                    WORKDIR entry-sub
5043                    LET $caller: STRING = CWD()
5044                    LET $callee: STRING = LIB::WHERE()
5045                    ASSERT_NE $caller $callee
5046                    LET $base: STRING = STD::PATH_BASE($callee)
5047                    ECHO "base \{{ $base }}"
5048                    """
5049                LET $exe: STRING = INTERPRETER()
5050                LET $out: STRING = RUN [$exe, "main.oxfile"]
5051                ASSERT_CONTAINS $out "base modsub"
5052            "#},
5053                },
5054                Example {
5055                    name: "blocks unwind, guards persist",
5056                    fence_meta: None,
5057                    code: indoc! {r#"
5058                # Blocks unwind on exit: the WORKDIR inside IF reverts,
5059                # so it never becomes a module jail. Bare guarded blocks
5060                # unwind the same way. Guards only skip, never push a
5061                # scope, so a guard-gated step persists.
5062                IMPORT [STD]
5063                WORKSPACE LOCAL
5064                LET $root: STRING = CWD()
5065                LET $go: BOOL = true
5066                IF $go {
5067                    MKDIR inner
5068                    WORKDIR inner
5069                }
5070                LET $after_if: STRING = CWD()
5071                ASSERT_EQ $root $after_if
5072                [bool:true] WORKDIR inner
5073                LET $after_guard: STRING = CWD()
5074                ASSERT_NE $root $after_guard
5075                MKDIR bare
5076                [bool:true] {
5077                    WORKDIR bare
5078                }
5079                LET $after_bare: STRING = CWD()
5080                ASSERT_EQ $after_guard $after_bare
5081            "#},
5082                },
5083                Example {
5084                    name: "import missing file fails upfront",
5085                    fence_meta: Some("expect_error:\"must exist when the run starts\""),
5086                    code: indoc! {r#"
5087                # Generated imports are rejected: a file that does not
5088                # exist when the run starts cannot be analyzed, so the
5089                # import fails before the first step runs.
5090                WORKSPACE LOCAL
5091                WRITE lib.oxdock 'FUNC F($x: STRING): STRING { RETURN $x } EXPORT F'
5092                IMPORT ["lib.oxdock" AS LIB]
5093            "#},
5094                },
5095                Example {
5096                    name: "import missing alias fails",
5097                    fence_meta: Some("expect_error:\"mandatory alias\""),
5098                    code: indoc! {r#"
5099                # A file entry without AS is a parse error.
5100                IMPORT ["./lib.oxdock"]
5101            "#},
5102                },
5103                Example {
5104                    name: "module cannot export a variable",
5105                    fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
5106                    code: indoc! {r#"
5107                # Only top-level FUNCs are exportable, never variables.
5108                LET $FOO: STRING = "x"
5109                EXPORT FOO
5110            "#},
5111                },
5112                Example {
5113                    name: "import re-export unknown alias fails",
5114                    fence_meta: Some("expect_error:\"does not match any top-level FUNC\""),
5115                    code: indoc! {r#"
5116                # Re-exports name a visible import alias.
5117                IMPORT ["x.oxdock" AS A]
5118                EXPORT NOSUCH::FOO
5119            "#},
5120                },
5121                Example {
5122                    name: "export type aliases",
5123                    fence_meta: None,
5124                    code: indoc! {r#"
5125                # TYPE aliases declare shapes once; EXPORT TYPE shares
5126                # them so importing files can use the same spelling.
5127                TYPE PERSON = MAP<name: STRING>
5128
5129                FUNC GREET($p: PERSON): STRING {
5130                    RETURN "hi {{ $p.name }}"
5131                }
5132                EXPORT GREET
5133                EXPORT TYPE PERSON
5134
5135                LET $p: PERSON = {name: "Ada"}
5136                LET $greeting: STRING = GREET($p)
5137                ASSERT_EQ $greeting "hi Ada"
5138            "#},
5139                },
5140                Example {
5141                    name: "import type from library",
5142                    fence_meta: None,
5143                    code: indoc! {r#"
5144                # One bracket mixes entry kinds: STD brings functions bare,
5145                # each harvest names a type. Types resolve globally with
5146                # or without the harvests; the explicit form only documents
5147                # the dependency, so this grouping is example only. Bare
5148                # FROM names a library; quoted FROM names a file path.
5149                IMPORT [STD, [TYPE PIPE FROM STD], [TYPE DURATION FROM STD]]
5150
5151                LET $p: PIPE
5152                WITH_IO [stdout=$p] ECHO hello
5153                WITH_IO [stdin=$p] READ_LINE $line
5154                ASSERT_EQ $line "hello"
5155
5156                LET $d: DURATION = "5s"
5157                LET $files: LIST<STRING> = GLOB("*.oxdock")
5158            "#},
5159                },
5160                Example {
5161                    name: "run rendered modules in a child",
5162                    fence_meta: Some("roots:unified"),
5163                    code: indoc! {r#"
5164                # Dynamic assembly with files: the parent writes a
5165                # library and an entry script, then runs the entry in a
5166                # fresh interpreter. Child-side {{ }} stays escaped so
5167                # the parent does not interpolate it while writing. The
5168                # child runs by path so entry-relative IMPORT resolves.
5169                # Unified roots: the child inherits one workspace, so
5170                # parent and child see the same files.
5171                IMPORT [STD]
5172                WRITE lib.oxfile """
5173                    FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
5174                    EXPORT GREET
5175                    """
5176                WRITE main.oxfile """
5177                    IMPORT ["lib.oxfile" AS LIB]
5178                    LET $g: STRING = LIB::GREET("Ada")
5179                    ECHO "says \{{ $g }}"
5180                    """
5181                LET $exe: STRING = INTERPRETER()
5182                LET $out: STRING = RUN [$exe, "main.oxfile"]
5183                ASSERT_CONTAINS $out "says hi Ada"
5184            "#},
5185                },
5186                Example {
5187                    name: "dynamic module assembly",
5188                    fence_meta: Some("roots:unified"),
5189                    code: indoc! {r#"
5190                # A function that assembles a module: MAKE_GREETER bakes
5191                # its argument into a generated file with a bare {{ }},
5192                # then a child run imports the result. Bare {{ }} injects
5193                # parent values at write time; escaped \{{ }} survives for
5194                # the child to interpolate. Bind imported calls with LET:
5195                # {{ }} placeholders resolve pure functions only.
5196                IMPORT [STD]
5197
5198                # The renderer: parent values land in the module source.
5199                FUNC MAKE_GREETER($who: STRING): STRING {
5200                    WRITE greeter.oxfile """
5201                        FUNC GREET(): STRING { RETURN "hi {{ $who }}" }
5202                        EXPORT GREET
5203                        """
5204                    RETURN "greeter.oxfile"
5205                }
5206
5207                # The entry: imports the rendered module by its path.
5208                WRITE main.oxfile """
5209                    IMPORT ["greeter.oxfile" AS G]
5210                    LET $g: STRING = G::GREET()
5211                    ECHO "says \{{ $g }}"
5212                    """
5213
5214                # Assemble, then run the entry in a fresh interpreter.
5215                LET $made: STRING = MAKE_GREETER("Ada")
5216                ASSERT_EQ $made "greeter.oxfile"
5217                LET $exe: STRING = INTERPRETER()
5218                LET $out: STRING = RUN [$exe, "main.oxfile"]
5219                ASSERT_CONTAINS $out "says hi Ada"
5220            "#},
5221                },
5222                Example {
5223                    name: "export unknown type fails",
5224                    fence_meta: Some("expect_error:\"does not match any top-level TYPE\""),
5225                    code: indoc! {r#"
5226                # Only declared TYPE aliases are exportable.
5227                TYPE PERSON = MAP<name: STRING>
5228                EXPORT TYPE ANIMAL
5229            "#},
5230                },
5231                Example {
5232                    name: "undeclared type fails",
5233                    fence_meta: Some("expect_error:\"unknown type\""),
5234                    code: indoc! {r#"
5235                # TYPE names must be declared before use.
5236                LET $p: PERSON = {name: "Ada"}
5237            "#},
5238                },
5239            ],
5240        },
5241    ]
5242}
5243
5244// ── Display ────────────────────────────────────────────────────────────────
5245
5246impl fmt::Display for StepKind {
5247    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5248        match self {
5249            StepKind::InheritEnv { keys } => {
5250                write!(f, "{} [{}]", KEYWORD_INHERIT_ENV, keys.join(", "))
5251            }
5252            StepKind::Workdir(a) => write!(f, "{} {}", KEYWORD_WORKDIR, fmt_value(a, quote_arg)),
5253            StepKind::Workspace(t) => write!(f, "{} {}", KEYWORD_WORKSPACE, t),
5254            StepKind::Env { key, value } => {
5255                write!(f, "{} {}={}", KEYWORD_ENV, key, fmt_value(value, quote_arg))
5256            }
5257            StepKind::Run(c) => write!(f, "{} {}", KEYWORD_RUN, fmt_value(c, quote_run)),
5258            StepKind::RunExec { argv } => {
5259                let parts: Vec<String> = argv.iter().map(fmt_exec_arg).collect();
5260                write!(f, "{} [{}]", KEYWORD_RUN, parts.join(", "))
5261            }
5262            StepKind::Echo(m) => write!(f, "{} {}", KEYWORD_ECHO, fmt_value(m, quote_msg)),
5263            StepKind::Copy {
5264                from_workspace,
5265                from_host,
5266                to_host,
5267                from,
5268                to,
5269            } => {
5270                let mut head = String::from(KEYWORD_COPY);
5271                if let Some(target) = from_workspace {
5272                    head.push_str(&format!(" --from-workspace {target}"));
5273                }
5274                if *from_host {
5275                    head.push_str(" --from-host");
5276                }
5277                if *to_host {
5278                    head.push_str(" --to-host");
5279                }
5280                write!(
5281                    f,
5282                    "{head} {} {}",
5283                    fmt_value(from, quote_arg),
5284                    fmt_value(to, quote_arg)
5285                )
5286            }
5287            StepKind::Symlink {
5288                from_workspace,
5289                from,
5290                to,
5291            } => {
5292                if let Some(target) = from_workspace {
5293                    write!(
5294                        f,
5295                        "{} --from-workspace {} {} {}",
5296                        KEYWORD_SYMLINK,
5297                        target,
5298                        fmt_value(from, quote_arg),
5299                        fmt_value(to, quote_arg)
5300                    )
5301                } else {
5302                    write!(
5303                        f,
5304                        "{} {} {}",
5305                        KEYWORD_SYMLINK,
5306                        fmt_value(from, quote_arg),
5307                        fmt_value(to, quote_arg)
5308                    )
5309                }
5310            }
5311            StepKind::Mkdir(a) => write!(f, "{} {}", KEYWORD_MKDIR, fmt_value(a, quote_arg)),
5312            StepKind::Install { from, to } => write!(
5313                f,
5314                "{} {} {}",
5315                KEYWORD_INSTALL,
5316                fmt_value(from, quote_arg),
5317                fmt_value(to, quote_arg)
5318            ),
5319            StepKind::SetExecutable { path } => {
5320                write!(
5321                    f,
5322                    "{} {}",
5323                    KEYWORD_SET_EXECUTABLE,
5324                    fmt_value(path, quote_arg)
5325                )
5326            }
5327            StepKind::Archive { src, dst, raw } => {
5328                if *raw {
5329                    write!(
5330                        f,
5331                        "{} --raw {} {}",
5332                        KEYWORD_ARCHIVE,
5333                        fmt_value(src, quote_arg),
5334                        fmt_value(dst, quote_arg)
5335                    )
5336                } else {
5337                    write!(
5338                        f,
5339                        "{} {} {}",
5340                        KEYWORD_ARCHIVE,
5341                        fmt_value(src, quote_arg),
5342                        fmt_value(dst, quote_arg)
5343                    )
5344                }
5345            }
5346            StepKind::Unarchive {
5347                src,
5348                dst,
5349                max_bytes,
5350            } => {
5351                write!(f, "{KEYWORD_UNARCHIVE}")?;
5352                if let Some(n) = max_bytes {
5353                    write!(f, " --max-bytes {}", fmt_value(n, quote_arg))?;
5354                }
5355                write!(
5356                    f,
5357                    " {} {}",
5358                    fmt_value(src, quote_arg),
5359                    fmt_value(dst, quote_arg)
5360                )
5361            }
5362            StepKind::Ls(a) => {
5363                write!(f, "{KEYWORD_LS}")?;
5364                if let Some(x) = a {
5365                    write!(f, " {}", fmt_value(x, quote_arg))?;
5366                }
5367                Ok(())
5368            }
5369            StepKind::Read(a) => {
5370                write!(f, "{KEYWORD_READ}")?;
5371                if let Some(x) = a {
5372                    write!(f, " {}", fmt_value(x, quote_arg))?;
5373                }
5374                Ok(())
5375            }
5376            StepKind::ReadLine { var } => write!(f, "{} ${}", KEYWORD_READ_LINE, var),
5377            StepKind::Prompt {
5378                var,
5379                message,
5380                default,
5381            } => {
5382                write!(
5383                    f,
5384                    "{} ${} {}",
5385                    KEYWORD_PROMPT,
5386                    var,
5387                    fmt_value(message, quote_arg)
5388                )?;
5389                if let Some(d) = default {
5390                    write!(f, " {}", fmt_value(d, quote_arg))?;
5391                }
5392                Ok(())
5393            }
5394            StepKind::Write { path, contents } => {
5395                write!(f, "{} {}", KEYWORD_WRITE, fmt_value(path, quote_arg))?;
5396                if let Some(b) = contents {
5397                    write!(f, " {}", fmt_value(b, quote_msg))?;
5398                }
5399                Ok(())
5400            }
5401            StepKind::Append { path, contents } => {
5402                write!(f, "{} {}", KEYWORD_APPEND, fmt_value(path, quote_arg))?;
5403                if let Some(b) = contents {
5404                    write!(f, " {}", fmt_value(b, quote_msg))?;
5405                }
5406                Ok(())
5407            }
5408            StepKind::AppendLine { path, contents } => {
5409                write!(
5410                    f,
5411                    "{} {} {}",
5412                    KEYWORD_APPEND_LINE,
5413                    fmt_value(path, quote_arg),
5414                    fmt_value(contents, quote_msg)
5415                )
5416            }
5417            StepKind::Remove { path, recursive } => {
5418                if *recursive {
5419                    write!(
5420                        f,
5421                        "{} --recursive {}",
5422                        KEYWORD_REMOVE,
5423                        fmt_value(path, quote_arg)
5424                    )
5425                } else {
5426                    write!(f, "{} {}", KEYWORD_REMOVE, fmt_value(path, quote_arg))
5427                }
5428            }
5429            StepKind::Expand { path, overrides } => {
5430                write!(f, "{KEYWORD_EXPAND}")?;
5431                if let Some(p) = path {
5432                    write!(f, " {}", fmt_value(p, quote_arg))?;
5433                }
5434                for (k, v) in overrides {
5435                    write!(f, " {}={}", k, fmt_value(v, quote_arg))?;
5436                }
5437                Ok(())
5438            }
5439            StepKind::AssertEq {
5440                hash,
5441                actual,
5442                expected,
5443            }
5444            | StepKind::AssertNe {
5445                hash,
5446                actual,
5447                expected,
5448            } => {
5449                let verb = match self {
5450                    StepKind::AssertEq { .. } => KEYWORD_ASSERT_EQ,
5451                    _ => KEYWORD_ASSERT_NE,
5452                };
5453                if let Some(d) = hash {
5454                    write!(f, "{verb} --hash {d} {}", fmt_assert_target(actual))?;
5455                } else {
5456                    write!(
5457                        f,
5458                        "{verb} {} {}",
5459                        fmt_assert_target(actual),
5460                        fmt_value(
5461                            expected
5462                                .as_ref()
5463                                .expect("Display of ASSERT without --hash needs expected"),
5464                            quote_msg
5465                        )
5466                    )?;
5467                }
5468                Ok(())
5469            }
5470            StepKind::AssertContains { haystack, needle } => write!(
5471                f,
5472                "{} {} {}",
5473                KEYWORD_ASSERT_CONTAINS,
5474                fmt_assert_target(haystack),
5475                fmt_value(needle, quote_msg)
5476            ),
5477            StepKind::WithIo { bindings, cmd } => {
5478                let p: Vec<String> = bindings.iter().map(fmt_io).collect();
5479                write!(f, "{} [{}] {}", KEYWORD_WITH_IO, p.join(", "), cmd)
5480            }
5481            StepKind::WithIoBlock { bindings } => {
5482                let p: Vec<String> = bindings.iter().map(fmt_io).collect();
5483                write!(f, "{} [{}] {{...}}", KEYWORD_WITH_IO, p.join(", "))
5484            }
5485            StepKind::CopyGit {
5486                rev,
5487                from,
5488                to,
5489                include_dirty,
5490            } => {
5491                if *include_dirty {
5492                    write!(
5493                        f,
5494                        "{} --include-dirty {} {} {}",
5495                        KEYWORD_COPY_GIT,
5496                        fmt_value(rev, quote_arg),
5497                        fmt_value(from, quote_arg),
5498                        fmt_value(to, quote_arg)
5499                    )
5500                } else {
5501                    write!(
5502                        f,
5503                        "{} {} {} {}",
5504                        KEYWORD_COPY_GIT,
5505                        fmt_value(rev, quote_arg),
5506                        fmt_value(from, quote_arg),
5507                        fmt_value(to, quote_arg)
5508                    )
5509                }
5510            }
5511            StepKind::Exit(code) => write!(f, "{} {}", KEYWORD_EXIT, fmt_raw_arg(code)),
5512            StepKind::Fail {
5513                code,
5514                message,
5515                body,
5516            } => {
5517                write!(f, "{}", KEYWORD_FAIL)?;
5518                if let Some(c) = code {
5519                    write!(f, " {}", fmt_raw_arg(c))?;
5520                }
5521                if let Some(m) = message {
5522                    // Quoting decides (`FAIL 2` is a silent code,
5523                    // `FAIL "2"` prints): a bare int-like message with
5524                    // no code alongside would reparse as the code, so
5525                    // pin quotes to keep the round-trip from inverting
5526                    // a message into a silent code.
5527                    let rendered = match m {
5528                        Arg::String(s, _)
5529                            if code.is_none()
5530                                && crate::command::strip_digit_separators(s)
5531                                    .parse::<i64>()
5532                                    .is_ok() =>
5533                        {
5534                            quote_dsl_string(s)
5535                        }
5536                        _ => fmt_value(m, quote_msg),
5537                    };
5538                    write!(f, " {rendered}")?;
5539                }
5540                if body.is_empty() {
5541                    // Only `FAIL {}` reaches here with neither code nor
5542                    // message (bare `FAIL` is a parse error): render the
5543                    // braces back so the empty block round-trips instead
5544                    // of collapsing into unparseable `FAIL`.
5545                    if code.is_none() && message.is_none() {
5546                        return write!(f, " {{}}");
5547                    }
5548                    return Ok(());
5549                }
5550                write!(f, " {{")?;
5551                for s in body {
5552                    write!(f, "\n    {}", s)?;
5553                }
5554                write!(f, "\n}}")
5555            }
5556            StepKind::Sleep { duration } => {
5557                write!(f, "{} {}", KEYWORD_SLEEP, fmt_raw_arg(duration))
5558            }
5559            StepKind::ListAppend { list, item } => {
5560                write!(f, "{} ${} {}", KEYWORD_LIST_APPEND, list, fmt_raw_arg(item))
5561            }
5562            StepKind::For {
5563                key_var,
5564                key_type,
5565                var,
5566                var_type,
5567                in_expr,
5568                body,
5569            } => {
5570                match key_var {
5571                    Some(k) => {
5572                        let kt = key_type.as_deref().unwrap_or(crate::tag::STRING_TYPE_NAME);
5573                        write!(
5574                            f,
5575                            "{} ${}: {}, ${}: {} IN {} {{",
5576                            KEYWORD_FOR, k, kt, var, var_type, in_expr
5577                        )?
5578                    }
5579                    None => write!(
5580                        f,
5581                        "{} ${}: {} IN {} {{",
5582                        KEYWORD_FOR, var, var_type, in_expr
5583                    )?,
5584                }
5585                for s in body {
5586                    write!(f, "\n    {}", s)?;
5587                }
5588                write!(f, "\n}}")
5589            }
5590            StepKind::If {
5591                cond,
5592                then_body,
5593                else_ifs,
5594                else_body,
5595            } => {
5596                write!(f, "{} {} {{", KEYWORD_IF, cond)?;
5597                for s in then_body {
5598                    write!(f, "\n    {}", s)?;
5599                }
5600                write!(f, " }}")?;
5601                for (c, b) in else_ifs {
5602                    write!(f, " {} {} {} {{", KEYWORD_ELSE, KEYWORD_IF, c)?;
5603                    for s in b {
5604                        write!(f, "\n    {}", s)?;
5605                    }
5606                    write!(f, " }}")?;
5607                }
5608                if let Some(b) = else_body {
5609                    write!(f, " {} {{", KEYWORD_ELSE)?;
5610                    for s in b {
5611                        write!(f, "\n    {}", s)?;
5612                    }
5613                    write!(f, " }}")?;
5614                }
5615                Ok(())
5616            }
5617            StepKind::Switch {
5618                discriminant,
5619                cases,
5620                default_body,
5621            } => {
5622                match discriminant {
5623                    Some(disc) => write!(f, "{} {} {{", KEYWORD_SWITCH, disc)?,
5624                    None => write!(f, "{} {{", KEYWORD_SWITCH)?,
5625                }
5626                for (exprs, body) in cases {
5627                    write!(f, " {} ", KEYWORD_CASE)?;
5628                    for (i, expr) in exprs.iter().enumerate() {
5629                        if i > 0 {
5630                            write!(f, ", ")?;
5631                        }
5632                        write!(f, "{}", expr)?;
5633                    }
5634                    write!(f, " {{")?;
5635                    for s in body {
5636                        write!(f, "\n    {}", s)?;
5637                    }
5638                    write!(f, " }}")?;
5639                }
5640                if let Some(b) = default_body {
5641                    write!(f, " {} {{", KEYWORD_DEFAULT)?;
5642                    for s in b {
5643                        write!(f, "\n    {}", s)?;
5644                    }
5645                    write!(f, " }}")?;
5646                }
5647                write!(f, " }}")
5648            }
5649            StepKind::Bind {
5650                var,
5651                decl_type,
5652                is_const,
5653                rhs,
5654            } => {
5655                let keyword = if *is_const {
5656                    KEYWORD_CONST
5657                } else {
5658                    KEYWORD_LET
5659                };
5660                let name = sigil_var(var);
5661                match rhs {
5662                    BindRhs::Expr(expr) => {
5663                        // Bare pipe declarations round-trip without an initializer.
5664                        if matches!(expr, Expr::FreshPipe) {
5665                            write!(f, "{} {}: {}", keyword, name, decl_type)
5666                        } else {
5667                            write!(f, "{} {}: {} = {}", keyword, name, decl_type, expr)
5668                        }
5669                    }
5670                    BindRhs::Capture(cmd) => {
5671                        write!(f, "{} {}: {} = {}", keyword, name, decl_type, cmd)
5672                    }
5673                    BindRhs::Async(body) => {
5674                        write!(
5675                            f,
5676                            "{} {}: {} = {} {{",
5677                            keyword, name, decl_type, KEYWORD_ASYNC
5678                        )?;
5679                        for s in body {
5680                            write!(f, "\n    {}", s)?;
5681                        }
5682                        write!(f, "\n}}")
5683                    }
5684                    BindRhs::Await { task_var } => {
5685                        write!(
5686                            f,
5687                            "{} {}: {} = {} ${}",
5688                            keyword, name, decl_type, KEYWORD_AWAIT, task_var
5689                        )
5690                    }
5691                }
5692            }
5693            StepKind::Set { var, expr } => write!(f, "${} = {}", var, expr),
5694            StepKind::AsyncBlock { body } => {
5695                write!(f, "{} {{", KEYWORD_ASYNC)?;
5696                for s in body {
5697                    write!(f, "\n    {}", s)?;
5698                }
5699                write!(f, "\n}}")
5700            }
5701            StepKind::Await { var } => {
5702                write!(f, "{} ${}", KEYWORD_AWAIT, var)
5703            }
5704            StepKind::Cancel { var } => {
5705                write!(f, "{} ${}", KEYWORD_CANCEL, var)
5706            }
5707            StepKind::Timeout { duration, body } => {
5708                let budget = fmt_raw_arg(duration);
5709                // Single-command form cannot carry an inner guard (the
5710                // grammar has no guard slot there), so guarded singles
5711                // take block form rather than silently dropping it.
5712                if body.len() == 1 && body[0].guard.is_none() {
5713                    write!(f, "{} {} {}", KEYWORD_TIMEOUT, budget, body[0].kind)
5714                } else {
5715                    write!(f, "{} {} {{", KEYWORD_TIMEOUT, budget)?;
5716                    for s in body {
5717                        write!(f, "\n    {}", s)?;
5718                    }
5719                    write!(f, "\n}}")
5720                }
5721            }
5722            StepKind::Isolated { body } => {
5723                if body.len() == 1 && body[0].guard.is_none() {
5724                    write!(f, "{} {}", KEYWORD_ISOLATED, body[0].kind)
5725                } else {
5726                    write!(f, "{} {{", KEYWORD_ISOLATED)?;
5727                    for s in body {
5728                        write!(f, "\n    {}", s)?;
5729                    }
5730                    write!(f, "\n}}")
5731                }
5732            }
5733            StepKind::IsolatedInheritEnv { keys } => {
5734                // Deliberately the prelude spelling: the node only ever
5735                // renders nested inside ISOLATED Display, where readers
5736                // see the enclosing block for what it is.
5737                write!(f, "{} [{}]", KEYWORD_INHERIT_ENV, keys.join(", "))
5738            }
5739            StepKind::RemoteBlock {
5740                target,
5741                vars,
5742                env,
5743                body,
5744            } => {
5745                let mut entries: Vec<String> = vars.iter().map(|v| sigil_var(v)).collect();
5746                entries.extend(env.iter().map(|e| format!("env:{e}")));
5747                if entries.is_empty() {
5748                    write!(f, "{} {target} {{", KEYWORD_REMOTE)?;
5749                } else {
5750                    write!(f, "{} {target} [{}] {{", KEYWORD_REMOTE, entries.join(", "))?;
5751                }
5752                for s in body {
5753                    write!(f, "\n    {}", s)?;
5754                }
5755                write!(f, "\n}}")
5756            }
5757            StepKind::FuncDef {
5758                name,
5759                params,
5760                return_type,
5761                is_async,
5762                body,
5763                docs,
5764            } => {
5765                // Doc blocks render back as `#` lines so Display
5766                // reparses to identical docs (first line is the
5767                // summary, the rest follow verbatim).
5768                if let Some((_, full)) = docs {
5769                    for doc_line in full.split('\n') {
5770                        writeln!(f, "# {doc_line}")?;
5771                    }
5772                }
5773                let ps: Vec<String> = params
5774                    .iter()
5775                    .map(|(p, t, optional)| {
5776                        format!(
5777                            "{}{}: {}",
5778                            sigil_var(p),
5779                            if *optional { "?" } else { "" },
5780                            t
5781                        )
5782                    })
5783                    .collect();
5784                if *is_async {
5785                    write!(
5786                        f,
5787                        "{} {} {}({}): {} {{",
5788                        KEYWORD_ASYNC,
5789                        KEYWORD_FUNC,
5790                        name,
5791                        ps.join(", "),
5792                        return_type
5793                    )?;
5794                } else {
5795                    write!(
5796                        f,
5797                        "{} {}({}): {} {{",
5798                        KEYWORD_FUNC,
5799                        name,
5800                        ps.join(", "),
5801                        return_type
5802                    )?;
5803                }
5804                for s in body {
5805                    write!(f, "\n    {}", s)?;
5806                }
5807                write!(f, "\n}}")
5808            }
5809            StepKind::Call { name, args } => {
5810                let ps: Vec<String> = args.iter().map(|a| format!("{}", a)).collect();
5811                write!(f, "{}({})", name, ps.join(", "))
5812            }
5813            StepKind::ImportFile { path, alias } => {
5814                write!(f, "{} [\"{}\" AS {}]", KEYWORD_IMPORT, path, alias)
5815            }
5816            StepKind::ImportFuncs {
5817                path,
5818                alias,
5819                func_names,
5820                type_names,
5821            } => {
5822                let mut parts: Vec<String> = Vec::new();
5823                for t in type_names {
5824                    parts.push(format!("{KEYWORD_TYPE} {t}"));
5825                }
5826                for n in func_names {
5827                    parts.push(n.clone());
5828                }
5829                match alias {
5830                    Some(alias) => write!(
5831                        f,
5832                        "{} [[{} FROM \"{}\" AS {}]]",
5833                        KEYWORD_IMPORT,
5834                        parts.join(", "),
5835                        path,
5836                        alias
5837                    ),
5838                    None => write!(
5839                        f,
5840                        "{} [[{} FROM \"{}\"]]",
5841                        KEYWORD_IMPORT,
5842                        parts.join(", "),
5843                        path
5844                    ),
5845                }
5846            }
5847            StepKind::Return { expr, is_bare } => {
5848                if *is_bare {
5849                    write!(f, "{KEYWORD_RETURN}")
5850                } else {
5851                    write!(f, "{} {}", KEYWORD_RETURN, expr)
5852                }
5853            }
5854            StepKind::TypeAlias { name, target } => {
5855                write!(f, "{} {} = {}", KEYWORD_TYPE, name, target)
5856            }
5857            StepKind::While { cond, body } => {
5858                write!(f, "{} {} {{", KEYWORD_WHILE, cond)?;
5859                for s in body {
5860                    write!(f, "\n    {}", s)?;
5861                }
5862                write!(f, "\n}}")
5863            }
5864            StepKind::Break => write!(f, "{KEYWORD_BREAK}"),
5865            StepKind::Continue => write!(f, "{KEYWORD_CONTINUE}"),
5866        }
5867    }
5868}
5869
5870/// One lowered instruction token: a positional argument, or a pre-split
5871/// `KEY=value` assignment from the unified grammar rule. Assignments reach
5872/// ENV/EXPAND lowerings intact; every other command sees them collapsed to
5873/// canonical `key=value` text (see `lower_instruction_pair`).
5874pub(crate) enum InsToken {
5875    Pos(Arg),
5876    Assign(String, Arg),
5877}
5878
5879pub(crate) fn lower_env_tokens(ctx: &SpanContext, tokens: Vec<InsToken>) -> ParseResult<StepKind> {
5880    if tokens.is_empty() {
5881        return Err(ParseError::validation(
5882            KEYWORD_ENV,
5883            "ENV requires KEY=value".to_string(),
5884            ctx,
5885        ));
5886    }
5887    match tokens.as_slice() {
5888        [InsToken::Assign(key, value)] => {
5889            // Same KEY=value check the ENV lower applies on the
5890            // `lower_command` path, over the joined assignment form.
5891            if crate::command::split_assignment(&format!("{key}={}", value.render()))
5892                .map_err(|e| ParseError::validation(KEYWORD_ENV, e.to_string(), ctx))?
5893                .is_none()
5894            {
5895                return Err(ParseError::validation(
5896                    KEYWORD_ENV,
5897                    "ENV requires KEY=value format".to_string(),
5898                    ctx,
5899                ));
5900            }
5901            Ok(StepKind::Env {
5902                key: key.clone(),
5903                value: value.clone(),
5904            })
5905        }
5906        [InsToken::Pos(Arg::String(text, _))] => match crate::command::split_assignment(text)
5907            .map_err(|e| ParseError::validation(KEYWORD_ENV, e.to_string(), ctx))?
5908        {
5909            Some((key, value)) => Ok(StepKind::Env { key, value }),
5910            None => Err(ParseError::validation(
5911                KEYWORD_ENV,
5912                "ENV requires KEY=value format".to_string(),
5913                ctx,
5914            )),
5915        },
5916        _ => Err(ParseError::validation(
5917            KEYWORD_ENV,
5918            "ENV requires KEY=value format".to_string(),
5919            ctx,
5920        )),
5921    }
5922}
5923
5924/// Parser-direct `EXPAND` lowering: positional tokens are the optional path,
5925/// assignments are overrides. Split quoted values can never masquerade as
5926/// extra paths : tokenize time already proved they are one value.
5927pub(crate) fn lower_expand_tokens(
5928    ctx: &SpanContext,
5929    tokens: Vec<InsToken>,
5930) -> ParseResult<StepKind> {
5931    let mut path = None;
5932    let mut overrides = Vec::new();
5933    for token in tokens {
5934        match token {
5935            InsToken::Assign(key, value) => {
5936                if key.is_empty() {
5937                    return Err(ParseError::validation(
5938                        KEYWORD_EXPAND,
5939                        "EXPAND requires KEY=value format for overrides".to_string(),
5940                        ctx,
5941                    ));
5942                }
5943                overrides.push((key, value));
5944            }
5945            InsToken::Pos(arg) => match &arg {
5946                Arg::String(text, quoted) if !quoted && text.contains('=') => {
5947                    let Some((key, value)) = crate::command::split_assignment(text)
5948                        .map_err(|e| ParseError::validation(KEYWORD_EXPAND, e.to_string(), ctx))?
5949                    else {
5950                        return Err(ParseError::validation(
5951                            KEYWORD_EXPAND,
5952                            "EXPAND requires KEY=value format for overrides".to_string(),
5953                            ctx,
5954                        ));
5955                    };
5956                    overrides.push((key, value));
5957                }
5958                _ => {
5959                    if path.is_none() {
5960                        // Path-typed positional, checked like every other
5961                        // `lower_command` path arg (literals always pass;
5962                        // resolution stays runtime).
5963                        ArgType::Path.check_arg(&arg).map_err(|e| {
5964                            ParseError::validation(KEYWORD_EXPAND, e.to_string(), ctx)
5965                        })?;
5966                        path = Some(arg);
5967                    } else {
5968                        return Err(ParseError::validation(
5969                            KEYWORD_EXPAND,
5970                            "EXPAND accepts at most one path".to_string(),
5971                            ctx,
5972                        ));
5973                    }
5974                }
5975            },
5976        }
5977    }
5978    Ok(StepKind::Expand { path, overrides })
5979}
5980
5981/// Wrapper-shared validators, promoted verbatim from the retired pest
5982/// backend, so every parse entry point enforces identical bodies.
5983/// Pure outcome logic over [`StepKind`]: contexts only feed error spans.
5984#[derive(Default)]
5985pub(crate) struct IoBindingSet {
5986    stdin: Option<IoBinding>,
5987    stdout: Option<IoBinding>,
5988    stderr: Option<IoBinding>,
5989    tty: Option<IoBinding>,
5990    rows: Option<IoBinding>,
5991    cols: Option<IoBinding>,
5992}
5993
5994impl IoBindingSet {
5995    pub(crate) fn insert(&mut self, binding: IoBinding) {
5996        match binding.stream {
5997            IoStream::Stdin => self.stdin = Some(binding),
5998            IoStream::Stdout => self.stdout = Some(binding),
5999            IoStream::Stderr => self.stderr = Some(binding),
6000            IoStream::Tty => self.tty = Some(binding),
6001            IoStream::Rows(_) => self.rows = Some(binding),
6002            IoStream::Cols(_) => self.cols = Some(binding),
6003        }
6004    }
6005
6006    pub(crate) fn into_vec(self) -> Vec<IoBinding> {
6007        let mut out = Vec::new();
6008        if let Some(binding) = self.stdin {
6009            out.push(binding);
6010        }
6011        if let Some(binding) = self.stdout {
6012            out.push(binding);
6013        }
6014        if let Some(binding) = self.stderr {
6015            out.push(binding);
6016        }
6017        if let Some(binding) = self.tty {
6018            out.push(binding);
6019        }
6020        if let Some(binding) = self.rows {
6021            out.push(binding);
6022        }
6023        if let Some(binding) = self.cols {
6024            out.push(binding);
6025        }
6026        out
6027    }
6028}
6029
6030pub(crate) fn merge_bindings(defaults: &[IoBinding], overrides: &[IoBinding]) -> Vec<IoBinding> {
6031    let mut set = IoBindingSet::default();
6032    for binding in defaults {
6033        set.insert(binding.clone());
6034    }
6035    for binding in overrides {
6036        set.insert(binding.clone());
6037    }
6038    set.into_vec()
6039}
6040
6041pub(crate) fn and_guard_exprs(
6042    left: Option<GuardExpr>,
6043    right: Option<GuardExpr>,
6044) -> Option<GuardExpr> {
6045    match (left, right) {
6046        (None, None) => None,
6047        (Some(expr), None) | (None, Some(expr)) => Some(expr),
6048        (Some(lhs), Some(rhs)) => Some(GuardExpr::all(vec![lhs, rhs])),
6049    }
6050}
6051
6052pub(crate) fn has_stdout_pipe(bindings: &[IoBinding]) -> bool {
6053    bindings
6054        .iter()
6055        .any(|b| b.stream == IoStream::Stdout && b.pipe.is_some())
6056}
6057
6058/// Reject async machinery inside a capture body: background tasks are
6059/// captured via `LET $o: STRING = AWAIT $t`, never inline.
6060pub(crate) fn reject_async_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
6061    let bad = match kind {
6062        StepKind::AsyncBlock { .. }
6063        | StepKind::Bind {
6064            rhs: BindRhs::Async(_) | BindRhs::Await { .. },
6065            ..
6066        }
6067        | StepKind::Await { .. }
6068        | StepKind::Cancel { .. } => true,
6069        _ => {
6070            let mut bad = false;
6071            kind.walk_child_kinds(&mut |child| {
6072                bad = bad || reject_async_in_capture(ctx, child).is_err();
6073            });
6074            bad
6075        }
6076    };
6077    if bad {
6078        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));
6079    }
6080    Ok(())
6081}
6082
6083/// Reject `WITH_IO [stdout=$var]` anywhere inside a capture body: the
6084/// capture sink owns stdout.
6085pub(crate) fn reject_pipe_stdout_in_capture(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
6086    if let StepKind::WithIo { bindings, .. } = kind
6087        && has_stdout_pipe(bindings)
6088    {
6089        return Err(ParseError::structural(
6090            "let",
6091            "LET capture cannot use WITH_IO [stdout=$var]; the capture sink owns stdout"
6092                .to_string(),
6093            ctx,
6094        ));
6095    }
6096    let mut result = Ok(());
6097    kind.walk_child_kinds(&mut |child| {
6098        if result.is_ok() {
6099            result = reject_pipe_stdout_in_capture(ctx, child);
6100        }
6101    });
6102    result
6103}
6104
6105/// Rewrite prelude-shaped `INHERIT_ENV` nodes anywhere inside an `ISOLATED`
6106/// body into `IsolatedInheritEnv`: the nested allowlist reads the isolated
6107/// snapshot, never the host.
6108pub(crate) fn rewrite_isolated_inherit(body: &mut [Step]) {
6109    for step in body {
6110        rewrite_isolated_inherit_kind(&mut step.kind);
6111    }
6112}
6113
6114/// Single-kind half of [`rewrite_isolated_inherit`]: rewrite the node
6115/// itself, then recurse through whatever it contains (`WITH_IO` wraps and
6116/// captures hold one kind; loop/if bodies hold steps).
6117pub(crate) fn rewrite_isolated_inherit_kind(kind: &mut StepKind) {
6118    if let StepKind::InheritEnv { keys } = kind {
6119        *kind = StepKind::IsolatedInheritEnv { keys: keys.clone() };
6120    }
6121    match kind {
6122        StepKind::For { body, .. }
6123        | StepKind::While { body, .. }
6124        | StepKind::Timeout { body, .. }
6125        | StepKind::Fail { body, .. }
6126        | StepKind::Isolated { body }
6127        | StepKind::AsyncBlock { body } => rewrite_isolated_inherit(body),
6128        StepKind::Bind {
6129            rhs: BindRhs::Async(body),
6130            ..
6131        } => rewrite_isolated_inherit(body),
6132        StepKind::If {
6133            then_body,
6134            else_ifs,
6135            else_body,
6136            ..
6137        } => {
6138            rewrite_isolated_inherit(then_body);
6139            for (_, branch) in else_ifs {
6140                rewrite_isolated_inherit(branch);
6141            }
6142            if let Some(else_body) = else_body {
6143                rewrite_isolated_inherit(else_body);
6144            }
6145        }
6146        StepKind::Switch {
6147            cases,
6148            default_body,
6149            ..
6150        } => {
6151            for (_, branch) in cases {
6152                rewrite_isolated_inherit(branch);
6153            }
6154            if let Some(default_body) = default_body {
6155                rewrite_isolated_inherit(default_body);
6156            }
6157        }
6158        StepKind::WithIo { cmd, .. } => {
6159            rewrite_isolated_inherit_kind(cmd);
6160        }
6161        StepKind::Bind {
6162            rhs: BindRhs::Capture(cmd),
6163            ..
6164        } => {
6165            rewrite_isolated_inherit_kind(cmd);
6166        }
6167        _ => {}
6168    }
6169}
6170
6171pub(crate) fn contains_inherit_env(kind: &StepKind) -> bool {
6172    if matches!(kind, StepKind::InheritEnv { .. }) {
6173        return true;
6174    }
6175    let mut found = false;
6176    kind.walk_child_kinds(&mut |child| {
6177        found = found || contains_inherit_env(child);
6178    });
6179    found
6180}
6181
6182/// Reject an `INHERIT_ENV` nested anywhere inside another command: the
6183/// prelude directive only reads at statement level (and, rewritten,
6184/// inside `ISOLATED` bodies, which never reach here).
6185pub(crate) fn reject_nested_inherit_env(ctx: &SpanContext, kind: &StepKind) -> ParseResult<()> {
6186    if contains_inherit_env(kind) {
6187        return Err(ParseError::structural(
6188            "inherit_env",
6189            "INHERIT_ENV cannot be nested inside other commands".to_string(),
6190            ctx,
6191        ));
6192    }
6193    Ok(())
6194}
6195
6196pub(crate) fn check_tty_wrapping(
6197    bindings: &[IoBinding],
6198    cmd: Option<&StepKind>,
6199    span: &SpanContext,
6200) -> ParseResult<()> {
6201    let has_tty = bindings.iter().any(|b| matches!(b.stream, IoStream::Tty));
6202    let has_geometry = bindings
6203        .iter()
6204        .any(|b| matches!(b.stream, IoStream::Rows(_) | IoStream::Cols(_)));
6205    if has_geometry && !has_tty {
6206        return Err(ParseError::structural(
6207            "with_io",
6208            "WITH_IO [rows]/[cols] need [tty] on the same step: geometry without a terminal has nothing to size".to_string(),
6209            span,
6210        ));
6211    }
6212    if !has_tty {
6213        return Ok(());
6214    }
6215    if bindings
6216        .iter()
6217        .any(|b| matches!(b.stream, IoStream::Stderr))
6218    {
6219        return Err(ParseError::structural(
6220            "with_io",
6221            "WITH_IO [tty] cannot bind stderr: the pty master carries stdout and stderr interleaved, so the two streams cannot demultiplex".to_string(),
6222            span,
6223        ));
6224    }
6225    match cmd {
6226        Some(StepKind::Run(_) | StepKind::RunExec { .. }) | None => Ok(()),
6227        Some(_) => Err(ParseError::structural(
6228            "with_io",
6229            "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(),
6230            span,
6231        )),
6232    }
6233}
6234
6235/// Reject `WITH_IO` steps directly inside an `ASYNC` body: pipe wiring
6236/// belongs outside the task (`WITH_IO [...] ASYNC ...`), never inside.
6237pub(crate) fn reject_with_io_in_async(ctx: &SpanContext, body: &[Step]) -> ParseResult<()> {
6238    for step in body {
6239        if matches!(&step.kind, StepKind::WithIo { .. }) {
6240            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));
6241        }
6242    }
6243    Ok(())
6244}
6245
6246/// Validate `EXPORT` names at end of parse. Forward references are
6247/// allowed (EXPORT may precede its FUNCs, TYPEs, and CONSTs), so this
6248/// runs against the completed top-level scope. Bare names must match
6249/// a top-level `FUNC`; qualified `MOD::NAME` names must match a known
6250/// module member (opaque modules skip the member check; the runtime
6251/// registry resolves them or fails serving). `EXPORT CONST` names must
6252/// match a top-level `CONST` binding, or forward one with a qualified
6253/// `$ALIAS::NAME` naming a visible import (same gate as func
6254/// re-exports; existence resolves where the import loads, since parse
6255/// performs no IO). `LET` bindings never satisfy an export.
6256/// Duplicates are rejected at the EXPORT site. Promoted
6257/// verbatim (the pest finish pass delegates).
6258#[allow(clippy::too_many_arguments)]
6259pub(crate) fn validate_exports(
6260    ctx: &SpanContext,
6261    exports: &super::parser::Exports,
6262    top: &HashSet<String>,
6263    top_types: &HashSet<String>,
6264    top_consts: &HashSet<String>,
6265    modules: &ModuleTable,
6266    top_imports: &[String],
6267) -> ParseResult<()> {
6268    for name in &exports.funcs {
6269        let valid = match crate::constants::split_qualified(name) {
6270            None => top.contains(name),
6271            Some((module, base)) if module == crate::constants::SCRIPT_MODULE_NAME => {
6272                top.contains(base)
6273            }
6274            Some((module, _base)) => match modules.modules.get(module) {
6275                None => {
6276                    // File-import aliases (#115) never enter the module
6277                    // table: a re-export names an imported function for
6278                    // the entry's own tool surface. The alias must be a
6279                    // visible import; whether the file actually exports
6280                    // the name is checked where the import loads (closure
6281                    // validation, then serving), since parse performs no
6282                    // IO. Anything else is an unknown module.
6283                    top_imports.iter().any(|m| m == module)
6284                }
6285                Some(None) => true,
6286                Some(Some(funcs)) => funcs.func_names.contains(_base),
6287            },
6288        };
6289        if !valid {
6290            return Err(ParseError::validation(
6291                crate::constants::KEYWORD_EXPORT,
6292                format!("EXPORT `{name}` does not match any top-level FUNC or known module member"),
6293                ctx,
6294            ));
6295        }
6296    }
6297    for name in &exports.types {
6298        // `EXPORT TYPE` names the alias bare. Qualified `ALIAS::TYPE`
6299        // is rejected here instead of stranding a reader later: no
6300        // downstream path serves it (MCP takes bare only, closure
6301        // validation matches top-level TYPEs in the file, harvests
6302        // address bare names). Bare re-exports of imported types
6303        // (whole-file types land bare) defer when the file has
6304        // imports, so `EXPORT PERSON` after `IMPORT ["lib" AS LIB]`
6305        // can promote the imported type.
6306        if crate::constants::split_qualified(name).is_some() {
6307            return Err(ParseError::validation(
6308                crate::constants::KEYWORD_EXPORT,
6309                format!(
6310                    "EXPORT TYPE `{name}` must be bare: qualified ALIAS::TYPE re-exports are not served; import the file and re-export the bare name"
6311                ),
6312                ctx,
6313            ));
6314        }
6315        if !top_types.contains(name) && top_imports.is_empty() {
6316            return Err(ParseError::validation(
6317                crate::constants::KEYWORD_EXPORT,
6318                format!("EXPORT TYPE `{name}` does not match any top-level TYPE"),
6319                ctx,
6320            ));
6321        }
6322    }
6323    for name in &exports.consts {
6324        // `CONST` exports name the binding with `$`, exactly like a
6325        // read (`EXPORT CONST $N`): the binding must be a top-level
6326        // `CONST` in this file. `LET` bindings never satisfy an export,
6327        // even when the spelling matches.
6328        // Qualified `$ALIAS::NAME` forwards re-export an imported
6329        // file's `CONST` under this file's alias (same gate as func
6330        // re-exports): the alias must be a visible import here, and
6331        // whether the target file exports the name is checked where
6332        // the import loads (closure validation, then serving), since
6333        // parse performs no IO. `SCRIPT::` is not a `CONST`
6334        // namespace (local `CONST`s always read through `$`), so it is
6335        // rejected here instead of stranding a reader later.
6336        let valid = match crate::constants::split_qualified(name) {
6337            None => top_consts.contains(name),
6338            Some((module, _)) if module == crate::constants::SCRIPT_MODULE_NAME => false,
6339            Some((module, _base)) => top_imports.iter().any(|m| m == module),
6340        };
6341        if !valid {
6342            let msg = match crate::constants::split_qualified(name) {
6343                Some((module, _)) if module == crate::constants::SCRIPT_MODULE_NAME => format!(
6344                    "EXPORT CONST `{name}` must name a top-level CONST (`$NAME`) or `$ALIAS::NAME` for a visible import: `SCRIPT::` is not a CONST namespace"
6345                ),
6346                Some((module, _)) => format!(
6347                    "EXPORT CONST `{name}` names unknown import alias `{module}`: import a file as `{module}` to re-export its CONSTs"
6348                ),
6349                None => format!(
6350                    "EXPORT CONST `{name}` does not match any top-level CONST (LET bindings are never exportable)"
6351                ),
6352            };
6353            return Err(ParseError::validation(
6354                crate::constants::KEYWORD_EXPORT,
6355                msg,
6356                ctx,
6357            ));
6358        }
6359    }
6360    Ok(())
6361}
6362
6363/// REMOTE whole-script validators and body-symbol collectors,
6364/// promoted verbatim from the pest backend (which delegates) so both
6365/// parse pathways enforce identical blocks.
6366/// Reject `COPY --from-host` / `--to-host` outside `REMOTE` bodies.
6367/// Transfer declarations only mean something where a session hoists them;
6368/// anywhere else they would silently behave as local copies.
6369pub(crate) fn validate_remote_copy_placement(steps: &[Step], ctx: &SpanContext) -> ParseResult<()> {
6370    fn visit_kind(kind: &StepKind, in_remote: bool, ctx: &SpanContext) -> ParseResult<()> {
6371        if let StepKind::Copy {
6372            from_host, to_host, ..
6373        } = kind
6374            && (*from_host || *to_host)
6375            && !in_remote
6376        {
6377            return Err(ParseError::structural(
6378                "copy",
6379                "COPY --from-host and --to-host are only valid inside a REMOTE block".to_string(),
6380                ctx,
6381            ));
6382        }
6383        let child_remote = in_remote || matches!(kind, StepKind::RemoteBlock { .. });
6384        let mut result = Ok(());
6385        kind.walk_child_kinds(&mut |child| {
6386            if result.is_ok() {
6387                result = visit_kind(child, child_remote, ctx);
6388            }
6389        });
6390        result
6391    }
6392    for step in steps {
6393        visit_kind(&step.kind, false, ctx)?;
6394    }
6395    Ok(())
6396}
6397
6398/// True when any step in the slice (transitively, through nested bodies)
6399/// is a `REMOTE` block. `REMOTE` blocks never nest: the inner block would
6400/// have no session, no inventory, and no defined sync boundary.
6401pub(crate) fn contains_remote_block(steps: &[Step]) -> bool {
6402    steps.iter().any(|step| contains_remote_kind(&step.kind))
6403}
6404
6405pub(crate) fn contains_remote_kind(kind: &StepKind) -> bool {
6406    if matches!(kind, StepKind::RemoteBlock { .. }) {
6407        return true;
6408    }
6409    let mut found = false;
6410    kind.walk_child_kinds(&mut |child| {
6411        found = found || contains_remote_kind(child);
6412    });
6413    found
6414}
6415
6416/// Collect transitively defined `FUNC` names and invoked call names from a
6417/// `REMOTE` body. Statement calls, expression calls (including compiled
6418/// math ops and inline blocks), and calls nested in any sub-body are all
6419/// covered through the uniform [`StepKind`] walkers. Only user-defined
6420/// `SCRIPT` symbols matter downstream: qualified module calls pass through.
6421pub(crate) fn collect_remote_body_symbols(
6422    steps: &[Step],
6423    defs: &mut HashSet<String>,
6424    calls: &mut Vec<String>,
6425) {
6426    for step in steps {
6427        collect_remote_kind_symbols(&step.kind, defs, calls);
6428    }
6429}
6430
6431pub(crate) fn collect_remote_kind_symbols(
6432    kind: &StepKind,
6433    defs: &mut HashSet<String>,
6434    calls: &mut Vec<String>,
6435) {
6436    if let StepKind::FuncDef { name, .. } = kind {
6437        defs.insert(name.clone());
6438    }
6439    if let StepKind::Call { name, .. } = kind {
6440        calls.push(name.clone());
6441    }
6442    kind.walk_step_exprs(&mut |expr| match expr {
6443        Expr::Call { name, .. } => calls.push(name.clone()),
6444        Expr::CompiledMath(ops) => {
6445            for op in ops {
6446                if let MathOp::Call { name, .. } = op {
6447                    calls.push(name.clone());
6448                }
6449            }
6450        }
6451        Expr::Block(steps) => collect_remote_body_symbols(steps, defs, calls),
6452        _ => {}
6453    });
6454}
6455
6456/// Expression lowering core, promoted verbatim from the retired pest
6457/// backend: folding constructors, RPN compilation, boundary rejection,
6458/// and numeric classification. The parser calls
6459/// these directly, so folding and overflow behavior are single-sourced.
6460/// Reject a staged `UnsignedIntBoundary` in any position where unary `-`
6461/// cannot consume it (every compound constructor calls this on children).
6462/// Expression lowering core (promoted verbatim from the retired pest
6463/// backend): operates on `Expr`, never on token pairs.
6464pub(crate) fn reject_boundary(ctx: &SpanContext, expr: &Expr) -> ParseResult<()> {
6465    if matches!(expr, Expr::UnsignedIntBoundary(_)) {
6466        return Err(ParseError::structural(
6467            "expr",
6468            "integer overflow: 9223372036854775808 exceeds i64::MAX".to_string(),
6469            ctx,
6470        ));
6471    }
6472    Ok(())
6473}
6474
6475/// Apply unary `-`: fold literals, consume the `i64::MIN` boundary, else
6476/// compile to RPN `Neg` (or AST `0 - x` fallback for non-math operands).
6477/// Shared with the v2 backend.
6478pub(crate) fn apply_unary_neg(ctx: &SpanContext, expr: Expr) -> ParseResult<Expr> {
6479    match expr {
6480        Expr::Literal(v) => match (v.as_i64(), v.as_f64()) {
6481            (Some(n), _) => match n.checked_neg() {
6482                Some(neg) => Ok(Expr::Literal(Value::int(neg))),
6483                None => Ok(Expr::CompiledMath(vec![MathOp::PushConst(v), MathOp::Neg])),
6484            },
6485            (None, Some(f)) => Ok(Expr::Literal(Value::float(-f))),
6486            (None, None) => {
6487                let other = Expr::Literal(v);
6488                if let Some(mut ops) = expr_to_rpn(&other) {
6489                    ops.push(MathOp::Neg);
6490                    Ok(Expr::CompiledMath(ops))
6491                } else {
6492                    // Non-math operand (list/map/logical): `0 - x` evaluates via
6493                    // the shared arithmetic helper to a runtime Type Error.
6494                    Ok(Expr::Arithmetic {
6495                        op: ArithOp::Sub,
6496                        left: Box::new(Expr::Literal(Value::int(0))),
6497                        right: Box::new(other),
6498                    })
6499                }
6500            }
6501        },
6502        Expr::UnsignedIntBoundary(n) => {
6503            if n == i64::MAX as u64 + 1 {
6504                Ok(Expr::Literal(Value::int(i64::MIN)))
6505            } else {
6506                Err(ParseError::structural(
6507                    "expr",
6508                    format!("integer overflow: {} exceeds i64::MAX", n),
6509                    ctx,
6510                ))
6511            }
6512        }
6513        other => {
6514            if let Some(mut ops) = expr_to_rpn(&other) {
6515                ops.push(MathOp::Neg);
6516                Ok(Expr::CompiledMath(ops))
6517            } else {
6518                // Non-math operand (list/map/logical): `0 - x` evaluates via
6519                // the shared arithmetic helper to a runtime Type Error.
6520                Ok(Expr::Arithmetic {
6521                    op: ArithOp::Sub,
6522                    left: Box::new(Expr::Literal(Value::int(0))),
6523                    right: Box::new(other),
6524                })
6525            }
6526        }
6527    }
6528}
6529
6530/// Try parse-time constant folding for binary arithmetic/comparison.
6531/// Returns `Some(literal)` on success, `None` when not both literals or
6532/// when the op would error at runtime (div-zero/overflow/non-finite:
6533/// leave for the RPN evaluator so the error surfaces at runtime).
6534fn try_fold_arith(op: ArithOp, left: &Expr, right: &Expr) -> Option<Expr> {
6535    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
6536        return None;
6537    };
6538    fold_arith_values(op, lv, rv).map(Expr::Literal)
6539}
6540
6541fn fold_arith_values(op: ArithOp, left: &Value, right: &Value) -> Option<Value> {
6542    match (left.as_i64(), right.as_i64()) {
6543        (Some(a), Some(b)) => {
6544            let v = match op {
6545                ArithOp::Add => a.checked_add(b)?,
6546                ArithOp::Sub => a.checked_sub(b)?,
6547                ArithOp::Mul => a.checked_mul(b)?,
6548                ArithOp::Div => a.checked_div(b)?,
6549            };
6550            Some(Value::int(v))
6551        }
6552        _ => {
6553            let (af, bf) = (as_f64(left)?, as_f64(right)?);
6554            fold_float(op, af, bf)
6555        }
6556    }
6557}
6558
6559fn fold_float(op: ArithOp, a: f64, b: f64) -> Option<Value> {
6560    if !a.is_finite() || !b.is_finite() {
6561        return None;
6562    }
6563    let v = match op {
6564        ArithOp::Add => a + b,
6565        ArithOp::Sub => a - b,
6566        ArithOp::Mul => a * b,
6567        ArithOp::Div => {
6568            if b == 0.0 {
6569                return None;
6570            }
6571            a / b
6572        }
6573    };
6574    if v.is_finite() {
6575        Some(Value::float(v))
6576    } else {
6577        None
6578    }
6579}
6580
6581fn try_fold_compare(op: CompareOp, left: &Expr, right: &Expr) -> Option<Expr> {
6582    let (Expr::Literal(lv), Expr::Literal(rv)) = (left, right) else {
6583        return None;
6584    };
6585    match (lv.as_i64(), rv.as_i64()) {
6586        (Some(a), Some(b)) => {
6587            let r = match op {
6588                CompareOp::Eq => a == b,
6589                CompareOp::Ne => a != b,
6590                CompareOp::Lt => a < b,
6591                CompareOp::Le => a <= b,
6592                CompareOp::Gt => a > b,
6593                CompareOp::Ge => a >= b,
6594            };
6595            Some(Expr::Literal(Value::bool(r)))
6596        }
6597        _ => {
6598            if let (Some(a), Some(b)) = (lv.as_bool(), rv.as_bool()) {
6599                return match op {
6600                    CompareOp::Eq => Some(Expr::Literal(Value::bool(a == b))),
6601                    CompareOp::Ne => Some(Expr::Literal(Value::bool(a != b))),
6602                    _ => None,
6603                };
6604            }
6605            let (af, bf) = (as_f64(lv)?, as_f64(rv)?);
6606            let r = match op {
6607                CompareOp::Eq => af == bf,
6608                CompareOp::Ne => af != bf,
6609                CompareOp::Lt => af < bf,
6610                CompareOp::Le => af <= bf,
6611                CompareOp::Gt => af > bf,
6612                CompareOp::Ge => af >= bf,
6613            };
6614            Some(Expr::Literal(Value::bool(r)))
6615        }
6616    }
6617}
6618
6619fn as_f64(v: &Value) -> Option<f64> {
6620    if let Some(n) = v.as_i64() {
6621        return Some(n as f64);
6622    }
6623    match v.as_f64() {
6624        Some(f) if f.is_finite() => Some(f),
6625        _ => None,
6626    }
6627}
6628
6629/// Shared with the v2 backend: fold, compile to RPN, or keep the AST node.
6630pub(crate) fn make_arith(
6631    ctx: &SpanContext,
6632    op: ArithOp,
6633    left: Expr,
6634    right: Expr,
6635) -> ParseResult<Expr> {
6636    reject_boundary(ctx, &left)?;
6637    reject_boundary(ctx, &right)?;
6638    if let Some(folded) = try_fold_arith(op, &left, &right) {
6639        return Ok(folded);
6640    }
6641    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
6642        lops.append(&mut rops);
6643        lops.push(match op {
6644            ArithOp::Add => MathOp::Add,
6645            ArithOp::Sub => MathOp::Sub,
6646            ArithOp::Mul => MathOp::Mul,
6647            ArithOp::Div => MathOp::Div,
6648        });
6649        return Ok(Expr::CompiledMath(lops));
6650    }
6651    Ok(Expr::Arithmetic {
6652        op,
6653        left: Box::new(left),
6654        right: Box::new(right),
6655    })
6656}
6657
6658/// Shared with the v2 backend: fold, compile to RPN, or keep the AST node.
6659pub(crate) fn make_compare(
6660    ctx: &SpanContext,
6661    op: CompareOp,
6662    left: Expr,
6663    right: Expr,
6664) -> ParseResult<Expr> {
6665    reject_boundary(ctx, &left)?;
6666    reject_boundary(ctx, &right)?;
6667    if let Some(folded) = try_fold_compare(op, &left, &right) {
6668        return Ok(folded);
6669    }
6670    if let (Some(mut lops), Some(mut rops)) = (expr_to_rpn(&left), expr_to_rpn(&right)) {
6671        lops.append(&mut rops);
6672        lops.push(match op {
6673            CompareOp::Eq => MathOp::Eq,
6674            CompareOp::Ne => MathOp::Ne,
6675            CompareOp::Lt => MathOp::Lt,
6676            CompareOp::Le => MathOp::Le,
6677            CompareOp::Gt => MathOp::Gt,
6678            CompareOp::Ge => MathOp::Ge,
6679        });
6680        return Ok(Expr::CompiledMath(lops));
6681    }
6682    Ok(Expr::Compare {
6683        op,
6684        left: Box::new(left),
6685        right: Box::new(right),
6686    })
6687}
6688
6689/// Convert an operand subtree to flat RPN. Returns `None` for shapes with
6690/// no RPN encoding (`Not`/`Logical`/`List`/`Map`/`FreshPipe`/stray boundary): callers
6691/// fall back to AST nodes evaluated recursively.
6692/// Shared with the v2 backend.
6693///
6694pub(crate) fn expr_to_rpn(expr: &Expr) -> Option<Vec<MathOp>> {
6695    match expr {
6696        Expr::Literal(v) => Some(vec![MathOp::PushConst(v.clone())]),
6697        Expr::Var { name } => Some(vec![MathOp::Load { name: name.clone() }]),
6698        Expr::ConstRef { alias, name } => Some(vec![MathOp::LoadConstRef {
6699            alias: alias.clone(),
6700            name: name.clone(),
6701        }]),
6702        Expr::Env(key) => Some(vec![MathOp::LoadEnv(key.clone())]),
6703        Expr::KeyPath { base, keys } => Some(vec![MathOp::LoadKeyPath {
6704            base: base.clone(),
6705            keys: keys.clone(),
6706        }]),
6707        Expr::Call { name, args } => {
6708            let mut ops = Vec::new();
6709            for arg in args {
6710                ops.extend(expr_to_rpn(arg)?);
6711            }
6712            ops.push(MathOp::Call {
6713                name: name.clone(),
6714                arity: args.len(),
6715            });
6716            Some(ops)
6717        }
6718        Expr::Inspect { name } => Some(vec![MathOp::Inspect { name: name.clone() }]),
6719        Expr::Arithmetic { op, left, right } => {
6720            let mut ops = expr_to_rpn(left)?;
6721            ops.extend(expr_to_rpn(right)?);
6722            ops.push(match op {
6723                ArithOp::Add => MathOp::Add,
6724                ArithOp::Sub => MathOp::Sub,
6725                ArithOp::Mul => MathOp::Mul,
6726                ArithOp::Div => MathOp::Div,
6727            });
6728            Some(ops)
6729        }
6730        Expr::Compare { op, left, right } => {
6731            let mut ops = expr_to_rpn(left)?;
6732            ops.extend(expr_to_rpn(right)?);
6733            ops.push(match op {
6734                CompareOp::Eq => MathOp::Eq,
6735                CompareOp::Ne => MathOp::Ne,
6736                CompareOp::Lt => MathOp::Lt,
6737                CompareOp::Le => MathOp::Le,
6738                CompareOp::Gt => MathOp::Gt,
6739                CompareOp::Ge => MathOp::Ge,
6740            });
6741            Some(ops)
6742        }
6743        Expr::CompiledMath(ops) => Some(ops.clone()),
6744        Expr::FreshPipe => None,
6745        Expr::Not(_) | Expr::Logical { .. } | Expr::List(_) | Expr::Map(_) | Expr::Block(_) => None,
6746        Expr::UnsignedIntBoundary(_) => None,
6747    }
6748}
6749
6750/// Pure numeric classification (the token backend gates
6751/// `_`-separator shape before calling: the classifier strips them, so
6752/// `1__0` must never reach it as numeric). Returns the literal,
6753/// `UnsignedIntBoundary` staging, or the exact pest error text.
6754pub(crate) fn classify_numeric_text(text: &str) -> Result<Expr, String> {
6755    let clean = text.replace('_', "");
6756    if clean.contains('.') {
6757        let parsed: f64 = clean
6758            .parse()
6759            .map_err(|_| format!("invalid float literal {text:?}"))?;
6760        if !parsed.is_finite() {
6761            return Err(format!("invalid float literal {text:?}"));
6762        }
6763        return Ok(Expr::Literal(Value::float(parsed)));
6764    }
6765    let digits: u64 = clean
6766        .parse()
6767        .map_err(|_| format!("integer overflow: {text:?} exceeds i64::MAX"))?;
6768    if digits <= i64::MAX as u64 {
6769        Ok(Expr::Literal(Value::int(digits as i64)))
6770    } else if digits == i64::MAX as u64 + 1 {
6771        Ok(Expr::UnsignedIntBoundary(digits))
6772    } else {
6773        Err(format!("integer overflow: {text:?} exceeds i64::MAX"))
6774    }
6775}
6776
6777#[cfg(test)]
6778mod tests {
6779    use super::*;
6780    use crate::command::{
6781        format_byte_count, format_duration, parse_byte_count, parse_duration,
6782        strip_digit_separators,
6783    };
6784    use crate::parser::parse_script;
6785
6786    fn parse_err(script: &str) -> String {
6787        parse_script(script, lower_command)
6788            .expect_err("script must fail to parse")
6789            .to_string()
6790    }
6791
6792    #[test]
6793    fn malformed_with_io_binding_names_the_bad_binding() {
6794        let err = parse_err("WITH_IO [stdout=discard] ECHO \"test\"\n");
6795        assert!(err.contains("invalid syntax for command WITH_IO"), "{err}");
6796        assert!(!err.contains("unknown command"), "{err}");
6797        assert!(err.contains("stdout=discard"), "{err}");
6798        assert!(err.contains("[stdout=$p]"), "{err}");
6799    }
6800
6801    #[test]
6802    fn connect_is_unknown_command() {
6803        // `CONNECT` left core for the NET plugin: the builtin name no
6804        // longer resolves. Use `NET_CONNECT` with explicit pipes.
6805        let err = parse_err("CONNECT 127.0.0.1:8080\n");
6806        assert!(err.contains("unknown command"), "{err}");
6807        assert!(err.contains("CONNECT"), "{err}");
6808    }
6809
6810    #[test]
6811    fn listen_is_unknown_command() {
6812        // `LISTEN` left core for the NET plugin: the builtin name no
6813        // longer resolves. Use `NET_LISTEN` for a listener handle.
6814        let err = parse_err("LISTEN 127.0.0.1:8080\n");
6815        assert!(err.contains("unknown command"), "{err}");
6816        assert!(err.contains("LISTEN"), "{err}");
6817    }
6818
6819    #[test]
6820    fn await_without_task_variable_points_at_syntax() {
6821        let err = parse_err("AWAIT ECHO \"test\"\n");
6822        assert!(err.contains("invalid syntax for command AWAIT"), "{err}");
6823        assert!(!err.contains("unknown command"), "{err}");
6824        assert!(err.contains("AWAIT $t"), "{err}");
6825        assert!(err.contains("ECHO"), "{err}");
6826    }
6827
6828    #[test]
6829    fn bare_let_without_type_points_at_typed_syntax() {
6830        let err = parse_err("LET $x = 1\n");
6831        assert!(err.contains("LET requires explicit types"), "{err}");
6832        assert!(err.contains("LET $var: TYPE = <expr>"), "{err}");
6833    }
6834
6835    #[test]
6836    fn workspace_accepts_all_four_targets_uppercase_only() {
6837        // WORKSPACE targets are uppercase-only, like every other DSL
6838        // keyword argument: lowercase spellings are rejected.
6839        for (spelling, target) in [
6840            ("SNAPSHOT", WorkspaceTarget::Snapshot),
6841            ("LOCAL", WorkspaceTarget::Local),
6842            ("CACHE", WorkspaceTarget::Cache { local: false }),
6843            ("SYSTEM", WorkspaceTarget::System),
6844        ] {
6845            let steps =
6846                parse_script(&format!("WORKSPACE {spelling}\n"), lower_command).expect("parses");
6847            assert_eq!(steps.len(), 1);
6848            assert_eq!(steps[0].kind, StepKind::Workspace(target.clone()));
6849            assert_eq!(steps[0].kind.to_string(), format!("WORKSPACE {target}"));
6850        }
6851        for spelling in ["snapshot", "local", "cache", "system"] {
6852            let err = parse_err(&format!("WORKSPACE {spelling}\n"));
6853            assert!(
6854                err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
6855                "{spelling}: {err}"
6856            );
6857        }
6858        let err = parse_err("WORKSPACE REMOTE\n");
6859        assert!(
6860            err.contains("expected one of SNAPSHOT|LOCAL|CACHE|SYSTEM"),
6861            "{err}"
6862        );
6863
6864        // `--local` selects the project-tree cache and round-trips
6865        // through Display; anywhere else it is rejected.
6866        let steps = parse_script("WORKSPACE CACHE --local\n", lower_command).expect("parses");
6867        assert_eq!(
6868            steps[0].kind,
6869            StepKind::Workspace(WorkspaceTarget::Cache { local: true })
6870        );
6871        assert_eq!(steps[0].kind.to_string(), "WORKSPACE CACHE --local");
6872        for bad in [
6873            "WORKSPACE SNAPSHOT --local\n",
6874            "WORKSPACE LOCAL --local\n",
6875            "WORKSPACE SYSTEM --local\n",
6876        ] {
6877            let err = parse_err(bad);
6878            assert!(err.contains("--local requires CACHE"), "{bad}: {err}");
6879        }
6880    }
6881
6882    #[test]
6883    fn archive_unarchive_parse_and_round_trip() {
6884        let steps = parse_script("ARCHIVE bundle bundle.tar.gz\n", lower_command).expect("parses");
6885        match &steps[0].kind {
6886            StepKind::Archive { src, dst, raw } => {
6887                assert_eq!(src.as_str(), "bundle");
6888                assert_eq!(dst.as_str(), "bundle.tar.gz");
6889                assert!(!raw);
6890            }
6891            other => panic!("expected Archive, got {other:?}"),
6892        }
6893        assert_eq!(
6894            steps[0].kind.to_string(),
6895            "ARCHIVE bundle \"bundle.tar.gz\""
6896        );
6897
6898        let steps =
6899            parse_script("ARCHIVE --raw tool.bin tool.tar\n", lower_command).expect("parses");
6900        assert!(
6901            matches!(&steps[0].kind, StepKind::Archive { raw: true, .. }),
6902            "unexpected lowering: {:?}",
6903            steps[0].kind
6904        );
6905        assert_eq!(
6906            steps[0].kind.to_string(),
6907            "ARCHIVE --raw \"tool.bin\" \"tool.tar\""
6908        );
6909
6910        let steps =
6911            parse_script("UNARCHIVE pack.tar.gz unpacked\n", lower_command).expect("parses");
6912        match &steps[0].kind {
6913            StepKind::Unarchive {
6914                src,
6915                dst,
6916                max_bytes,
6917            } => {
6918                assert_eq!(src.as_str(), "pack.tar.gz");
6919                assert_eq!(dst.as_str(), "unpacked");
6920                assert_eq!(max_bytes, &None);
6921            }
6922            other => panic!("expected Unarchive, got {other:?}"),
6923        }
6924        assert_eq!(
6925            steps[0].kind.to_string(),
6926            "UNARCHIVE \"pack.tar.gz\" unpacked"
6927        );
6928
6929        let steps = parse_script(
6930            "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
6931            lower_command,
6932        )
6933        .expect("parses");
6934        match &steps[0].kind {
6935            StepKind::Unarchive {
6936                src,
6937                dst,
6938                max_bytes,
6939            } => {
6940                assert_eq!(src.as_str(), "pack.tar.gz");
6941                assert_eq!(dst.as_str(), "unpacked");
6942                assert_eq!(max_bytes.as_ref().map(|a| a.as_str()), Some("100_000"));
6943            }
6944            other => panic!("expected Unarchive, got {other:?}"),
6945        }
6946        assert_eq!(
6947            steps[0].kind.to_string(),
6948            "UNARCHIVE --max-bytes \"100_000\" \"pack.tar.gz\" unpacked"
6949        );
6950
6951        for script in [
6952            "ARCHIVE bundle bundle.tar.gz\n",
6953            "ARCHIVE --raw tool.bin tool.tar\n",
6954            "UNARCHIVE pack.tar.gz unpacked\n",
6955            "UNARCHIVE pack.tar.gz unpacked --max-bytes 100_000\n",
6956        ] {
6957            let first = parse_script(script, lower_command).expect("parses");
6958            let rendered = first[0].kind.to_string() + "\n";
6959            let second = parse_script(&rendered, lower_command).expect("reparses");
6960            // Quoting is parse provenance (Display normalizes it), so the
6961            // fixpoint is on rendering, not on full equality.
6962            assert_eq!(
6963                second[0].kind.to_string(),
6964                first[0].kind.to_string(),
6965                "Display must fixpoint for {script:?}"
6966            );
6967        }
6968
6969        for bad in ["ARCHIVE only-src\n", "ARCHIVE\n", "UNARCHIVE only-src\n"] {
6970            let err = parse_err(bad);
6971            assert!(
6972                err.contains("ARCHIVE") || err.contains("UNARCHIVE"),
6973                "{bad}: {err}"
6974            );
6975        }
6976    }
6977
6978    #[test]
6979    fn copy_from_workspace_selects_source_root() {
6980        for (spelling, target) in [
6981            ("SNAPSHOT", WorkspaceTarget::Snapshot),
6982            ("LOCAL", WorkspaceTarget::Local),
6983            ("CACHE", WorkspaceTarget::Cache { local: false }),
6984            ("SYSTEM", WorkspaceTarget::System),
6985        ] {
6986            let steps = parse_script(
6987                &format!("COPY --from-workspace {spelling} a.txt b.txt\n"),
6988                lower_command,
6989            )
6990            .expect("parses");
6991            assert!(
6992                matches!(&steps[0].kind, StepKind::Copy { from_workspace: Some(t), .. } if *t == target),
6993                "unexpected lowering for {spelling}: {:?}",
6994                steps[0].kind
6995            );
6996        }
6997        // The `=` form carries the value inline on one token: `--`
6998        // tokens never match `assignment`, so `strip_flags` splits it.
6999        for script in [
7000            "COPY --from-workspace=CACHE a.txt b.txt\n",
7001            "COPY --from-workspace=\"CACHE\" a.txt b.txt\n",
7002        ] {
7003            let steps = parse_script(script, lower_command).expect("parses");
7004            assert!(
7005                matches!(
7006                    &steps[0].kind,
7007                    StepKind::Copy {
7008                        from_workspace: Some(WorkspaceTarget::Cache { local: false }),
7009                        ..
7010                    }
7011                ),
7012                "unexpected lowering for {script:?}: {:?}",
7013                steps[0].kind
7014            );
7015        }
7016        // An absent flag means the build-context default.
7017        let steps = parse_script("COPY a.txt b.txt\n", lower_command).expect("parses");
7018        assert!(
7019            matches!(
7020                &steps[0].kind,
7021                StepKind::Copy {
7022                    from_workspace: None,
7023                    ..
7024                }
7025            ),
7026            "unexpected lowering: {:?}",
7027            steps[0].kind
7028        );
7029        // Unknown and lowercase values are rejected uppercase-only.
7030        for bad in ["REMOTE", "local"] {
7031            let err = parse_err(&format!("COPY --from-workspace {bad} a.txt b.txt\n"));
7032            assert!(err.contains("unknown workspace source"), "{bad}: {err}");
7033        }
7034    }
7035
7036    #[test]
7037    fn symlink_from_workspace_selects_source_root() {
7038        for (spelling, target) in [
7039            ("SNAPSHOT", WorkspaceTarget::Snapshot),
7040            ("LOCAL", WorkspaceTarget::Local),
7041            ("CACHE", WorkspaceTarget::Cache { local: false }),
7042            ("SYSTEM", WorkspaceTarget::System),
7043        ] {
7044            let steps = parse_script(
7045                &format!("SYMLINK --from-workspace {spelling} a.txt b.txt\n"),
7046                lower_command,
7047            )
7048            .expect("parses");
7049            assert!(
7050                matches!(&steps[0].kind, StepKind::Symlink { from_workspace: Some(t), .. } if *t == target),
7051                "unexpected lowering for {spelling}: {:?}",
7052                steps[0].kind
7053            );
7054            let roundtrip = steps[0].kind.to_string();
7055            assert!(
7056                roundtrip.contains("--from-workspace"),
7057                "display should round-trip the flag: {roundtrip}"
7058            );
7059        }
7060        let steps = parse_script("SYMLINK a.txt b.txt\n", lower_command).expect("parses");
7061        assert!(
7062            matches!(
7063                &steps[0].kind,
7064                StepKind::Symlink {
7065                    from_workspace: None,
7066                    ..
7067                }
7068            ),
7069            "unexpected lowering: {:?}",
7070            steps[0].kind
7071        );
7072        for bad in ["REMOTE", "local"] {
7073            let err = parse_err(&format!("SYMLINK --from-workspace {bad} a.txt b.txt\n"));
7074            assert!(err.contains("unknown workspace source"), "{bad}: {err}");
7075        }
7076        // The `=` form carries the value inline, like COPY.
7077        let steps = parse_script(
7078            "SYMLINK --from-workspace=LOCAL a.txt b.txt\n",
7079            lower_command,
7080        )
7081        .expect("parses");
7082        assert!(
7083            matches!(
7084                &steps[0].kind,
7085                StepKind::Symlink {
7086                    from_workspace: Some(WorkspaceTarget::Local),
7087                    ..
7088                }
7089            ),
7090            "unexpected lowering: {:?}",
7091            steps[0].kind
7092        );
7093    }
7094
7095    #[test]
7096    fn dash_dash_equals_tokens_bypass_assignment() {
7097        // `--` tokens never match `assignment`: flags keep their `=`
7098        // form as one argument, while other commands see the same text.
7099        let steps = parse_script("ENV --foo=bar\n", lower_command).expect("parses");
7100        let StepKind::Env { key, value } = &steps[0].kind else {
7101            panic!("expected Env, got {:?}", steps[0].kind);
7102        };
7103        assert_eq!(key, "--foo");
7104        assert_eq!(value.as_str(), "bar");
7105
7106        let steps = parse_script("RUN echo --foo=bar\n", lower_command).expect("parses");
7107        let StepKind::Run(cmd) = &steps[0].kind else {
7108            panic!("expected Run, got {:?}", steps[0].kind);
7109        };
7110        assert!(
7111            cmd.as_str().contains("--foo=bar"),
7112            "unexpected RUN lowering: {cmd:?}"
7113        );
7114
7115        let digest = "08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c";
7116        let steps = parse_script(&format!("ASSERT_EQ --hash={digest} $body\n"), lower_command)
7117            .expect("parses");
7118        let StepKind::AssertEq { hash, .. } = &steps[0].kind else {
7119            panic!("expected AssertEq, got {:?}", steps[0].kind);
7120        };
7121        assert_eq!(hash.as_deref(), Some(digest));
7122
7123        // EXPAND still treats `--k=v` positionals as overrides.
7124        let steps = parse_script("EXPAND --k=v\n", lower_command).expect("parses");
7125        let StepKind::Expand { path, overrides } = &steps[0].kind else {
7126            panic!("expected Expand, got {:?}", steps[0].kind);
7127        };
7128        assert!(path.is_none());
7129        assert_eq!(overrides.len(), 1);
7130        assert_eq!(overrides[0].0.as_str(), "--k");
7131    }
7132
7133    #[test]
7134    fn assert_ne_lowers_and_round_trips() {
7135        let steps = parse_script("ASSERT_NE $status 404\n", lower_command).expect("parses");
7136        let StepKind::AssertNe {
7137            hash,
7138            actual,
7139            expected,
7140        } = &steps[0].kind
7141        else {
7142            panic!("expected AssertNe, got {:?}", steps[0].kind);
7143        };
7144        assert!(hash.is_none());
7145        assert!(
7146            matches!(actual, AssertTarget::Value(_)),
7147            "unexpected actual: {actual:?}"
7148        );
7149        assert!(
7150            matches!(expected, Some(Arg::Expr(_))),
7151            "numeric expected lowers to an expression: {expected:?}"
7152        );
7153        let roundtrip = steps[0].kind.to_string();
7154        assert!(
7155            roundtrip.contains(Command::AssertNe.as_str()) && roundtrip.contains("404"),
7156            "display should round-trip the command: {roundtrip}"
7157        );
7158
7159        let err = parse_script("ASSERT_NE $status\n", lower_command).expect_err("needs expected");
7160        assert!(
7161            err.to_string().contains("requires an expected value"),
7162            "unexpected error: {err}"
7163        );
7164
7165        let err = parse_script("ASSERT_NE --hash abc123 $status \"junk\"\n", lower_command)
7166            .expect_err("hash plus expected must fail");
7167        assert!(
7168            err.to_string().contains("cannot be combined"),
7169            "unexpected error: {err}"
7170        );
7171
7172        // Parity: the shared lowering rejects the combination for EQ too.
7173        let err = parse_script("ASSERT_EQ --hash abc123 $status \"junk\"\n", lower_command)
7174            .expect_err("hash plus expected must fail");
7175        assert!(
7176            err.to_string().contains("cannot be combined"),
7177            "unexpected error: {err}"
7178        );
7179    }
7180
7181    #[test]
7182    fn space_before_paren_is_not_a_call() {
7183        // The call head and `(` must be contiguous: `ECHO (1 + 2)` is an
7184        // instruction, never a function invocation.
7185        let steps = parse_script("ECHO (1 + 2)\n", lower_command).expect("parses");
7186        assert_eq!(steps.len(), 1);
7187        assert!(
7188            !matches!(steps[0].kind, crate::ast::StepKind::Call { .. }),
7189            "space before paren must not route to a call: {:?}",
7190            steps[0].kind
7191        );
7192    }
7193
7194    #[test]
7195    fn unknown_type_tag_parses_as_custom() {
7196        // Open type tags: declarations carry plain names and resolve
7197        // against the descriptor table at runtime, so host types need no
7198        // grammar change (see the custom_types core tests).
7199        let steps = parse_script("LET $x: FOO = 1\n", lower_command).expect("custom tag parses");
7200        let StepKind::Bind {
7201            decl_type,
7202            rhs: BindRhs::Expr(_),
7203            ..
7204        } = &steps[0].kind
7205        else {
7206            panic!("expected Bind, got {:?}", steps[0].kind);
7207        };
7208        assert_eq!(decl_type, "FOO");
7209    }
7210
7211    #[test]
7212    fn bare_for_without_types_is_rejected() {
7213        let err = parse_err("FOR $i IN [1] { ECHO hi }\n");
7214        assert!(err.contains("FOR requires explicit types"), "{err}");
7215    }
7216
7217    #[test]
7218    fn mutate_statement_parses_without_keyword() {
7219        let steps = parse_script("$y = 2\n", lower_command).expect("mutation parses");
7220        assert!(matches!(steps[0].kind, StepKind::Set { .. }));
7221    }
7222
7223    #[test]
7224    fn keypath_mutation_target_is_rejected() {
7225        // `$M.a = ...` must fail instead of dropping `.a` and
7226        // silently rebinding the whole `$M`.
7227        for script in ["$M.a = 2\n", "$C.0 = 2\n"] {
7228            let err = parse_err(script);
7229            assert!(err.contains("cannot assign to"), "{script}: {err}");
7230            assert!(err.contains("never mutation targets"), "{script}: {err}");
7231        }
7232    }
7233
7234    #[test]
7235    fn set_keyword_is_rejected_with_mutation_hint() {
7236        let err = parse_err("SET $y = 2\n");
7237        assert!(err.contains("not a keyword"), "{err}");
7238        assert!(err.contains("$var = <expr>"), "{err}");
7239    }
7240
7241    #[test]
7242    fn structural_fallthrough_commits_per_keyword() {
7243        for (script, cmd) in [
7244            ("CANCEL foo\n", "CANCEL"),
7245            ("TIMEOUT foo\n", "TIMEOUT"),
7246            ("FOR foo\n", "FOR"),
7247            ("IF foo\n", "IF"),
7248            ("LET foo\n", "LET"),
7249            // NOTE: INHERIT_ENV is dual-registered as a leaf command
7250            // (`INHERIT_ENV <key>...`), so `INHERIT_ENV foo` lowers
7251            // successfully instead of erroring : excluded here.
7252            ("ASYNC\n", "ASYNC"),
7253            ("ELSE foo\n", "ELSE"),
7254        ] {
7255            let err = parse_err(script);
7256            assert!(
7257                err.contains(&format!("invalid syntax for command {cmd}")),
7258                "{cmd}: {err}"
7259            );
7260            assert!(!err.contains("unknown command"), "{cmd}: {err}");
7261        }
7262    }
7263
7264    #[test]
7265    fn syntax_strings_open_with_their_keyword() {
7266        // `Command::syntax` is a `const fn` returning `&'static str`,
7267        // so it cannot `format!` the keyword constants in. This lock
7268        // is the divergence guard instead: renaming a keyword fails
7269        // here until its syntax string follows.
7270        for cmd in crate::COMMANDS {
7271            let keyword = cmd.as_str();
7272            let syntax = cmd.syntax();
7273            assert!(
7274                syntax.starts_with(keyword),
7275                "syntax for {keyword} diverges from its keyword: {syntax:?}"
7276            );
7277        }
7278        for meta in all_metadata() {
7279            // Pseudo-entry: documents `$var = <expr>`, which opens
7280            // with a variable, never its non-keyword name.
7281            if meta.name == "MUTATION" {
7282                continue;
7283            }
7284            assert!(
7285                meta.syntax.starts_with(meta.name),
7286                "syntax for {} diverges from its keyword: {:?}",
7287                meta.name,
7288                meta.syntax
7289            );
7290        }
7291    }
7292
7293    #[test]
7294    fn leaf_arity_errors_carry_invalid_syntax_prefix() {
7295        let err = parse_err("SLEEP 1s 2s\n");
7296        assert!(err.contains("invalid syntax for command SLEEP"), "{err}");
7297        assert!(!err.contains("unknown command"), "{err}");
7298    }
7299
7300    #[test]
7301    fn list_append_lowers_variable_and_item() {
7302        let steps = parse_script("LIST_APPEND $items \"hi\"\n", lower_command).expect("parses");
7303        let StepKind::ListAppend { list, item } = &steps[0].kind else {
7304            panic!("expected ListAppend, got {:?}", steps[0].kind);
7305        };
7306        assert_eq!(list, "items");
7307        assert!(matches!(item, Arg::String(s, _) if s == "hi"));
7308        assert_eq!(steps[0].kind.to_string(), "LIST_APPEND $items \"hi\"");
7309    }
7310
7311    #[test]
7312    fn list_append_accepts_call_shaped_item() {
7313        // A bare full-region call in arg position stays typed
7314        // (evaluated at runtime) instead of appending the source
7315        // text: same owner as assignment values and RUN-exec items.
7316        let steps = parse_script(
7317            "FUNC MAKE(): STRING { RETURN \"made\" }\nLIST_APPEND $items MAKE()\n",
7318            lower_command,
7319        )
7320        .expect("parses");
7321        let StepKind::ListAppend { list, item } = &steps[1].kind else {
7322            panic!("expected ListAppend, got {:?}", steps[1].kind);
7323        };
7324        assert_eq!(list, "items");
7325        assert!(
7326            matches!(item, Arg::Expr(Expr::Call { name, .. }) if name == "SCRIPT::MAKE"),
7327            "{item:?}"
7328        );
7329    }
7330
7331    #[test]
7332    fn list_append_rejects_unknown_call_shaped_item() {
7333        // Unknown callees fail loud (unknown-function, with span),
7334        // never silently append. Well-formed-statement errors win:
7335        // see `func_def_malformed_params_name_the_shape`.
7336        let err = parse_err("LIST_APPEND $items NOPE()\n");
7337        assert!(err.contains("unknown function `NOPE`"), "{err}");
7338    }
7339
7340    #[test]
7341    fn list_append_rejects_wrong_arity() {
7342        for script in [
7343            "LIST_APPEND\n",
7344            "LIST_APPEND $items\n",
7345            "LIST_APPEND $items \"a\" \"b\"\n",
7346        ] {
7347            let err = parse_err(script);
7348            assert!(
7349                err.contains("invalid syntax for command LIST_APPEND"),
7350                "{script}: {err}"
7351            );
7352            assert!(!err.contains("unknown command"), "{script}: {err}");
7353        }
7354    }
7355
7356    #[test]
7357    fn list_append_rejects_non_variable_target() {
7358        let err = parse_err("LIST_APPEND items \"a\"\n");
7359        assert!(
7360            err.contains("invalid syntax for command LIST_APPEND"),
7361            "{err}"
7362        );
7363        assert!(!err.contains("unknown command"), "{err}");
7364        // Bare uppercase words are literal text, never variable
7365        // targets: a `CONST` list cannot be named here at all.
7366        let err = parse_err("LIST_APPEND ITEMS \"a\"\n");
7367        assert!(
7368            err.contains("invalid syntax for command LIST_APPEND"),
7369            "{err}"
7370        );
7371        assert!(!err.contains("unknown command"), "{err}");
7372    }
7373
7374    #[test]
7375    fn read_line_rejects_bare_word_target() {
7376        // The `$var` shape lives in the lower function now that the
7377        // central vocabulary holds value types only: a missing sigil
7378        // fails lowering with the command-specific error. Bare
7379        // uppercase is literal text, never a variable target.
7380        let err = parse_err("READ_LINE reply\n");
7381        assert!(err.contains("READ_LINE requires a $variable"), "{err}");
7382        assert!(!err.contains("unknown command"), "{err}");
7383        let err = parse_err("READ_LINE X\n");
7384        assert!(err.contains("READ_LINE requires a $variable"), "{err}");
7385        assert!(!err.contains("unknown command"), "{err}");
7386    }
7387
7388    #[test]
7389    fn genuinely_unknown_command_keeps_bare_message() {
7390        let err = parse_err("FROBNICATE hi\n");
7391        assert!(err.contains("unknown command: FROBNICATE"), "{err}");
7392        assert!(!err.contains("did you mean"), "{err}");
7393    }
7394
7395    #[test]
7396    fn lowercase_command_suggests_uppercase() {
7397        // Lowercase never reaches lowering through `parse_script` (the
7398        // grammar rejects it with its own uppercase hint), so exercise the
7399        // public `lower_command` dispatcher directly.
7400        let err = lower_command("echo", vec![Arg::String("hi".to_string(), false)])
7401            .expect_err("must fail")
7402            .to_string();
7403        assert!(err.contains("unknown command: echo"), "{err}");
7404        assert!(err.contains("did you mean `ECHO`"), "{err}");
7405    }
7406
7407    #[test]
7408    fn func_def_requires_typed_uppercase_name() {
7409        let steps = parse_script(
7410            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\n",
7411            lower_command,
7412        )
7413        .expect("func def parses");
7414        let StepKind::FuncDef {
7415            name,
7416            params,
7417            return_type,
7418            is_async,
7419            body,
7420            docs,
7421        } = &steps[0].kind
7422        else {
7423            panic!("expected FuncDef, got {:?}", steps[0].kind);
7424        };
7425        assert_eq!(name, "GREET");
7426        assert_eq!(
7427            params,
7428            &vec![("name".to_string(), "STRING".to_string(), false)],
7429            "{params:?}"
7430        );
7431        assert_eq!(return_type, "STRING", "{return_type:?}");
7432        assert!(!is_async, "plain FUNC is not async");
7433        assert!(matches!(body[0].kind, StepKind::Return { .. }));
7434        assert!(docs.is_none(), "undocumented FUNC carries no docs");
7435    }
7436
7437    #[test]
7438    fn lowercase_func_name_is_rejected() {
7439        let err = parse_err("FUNC greet($x: STRING) {\n  RETURN $x\n}\n");
7440        assert!(err.contains("FUNC"), "{err}");
7441    }
7442
7443    #[test]
7444    fn func_def_optional_params_parse_with_flag() {
7445        let steps = parse_script(
7446            "FUNC F($a: STRING, $b?: INT): STRING {\n  RETURN $a\n}\n",
7447            lower_command,
7448        )
7449        .expect("optional params parse");
7450        let StepKind::FuncDef { params, .. } = &steps[0].kind else {
7451            panic!("expected FuncDef, got {:?}", steps[0].kind);
7452        };
7453        assert_eq!(
7454            params,
7455            &vec![
7456                ("a".to_string(), "STRING".to_string(), false),
7457                ("b".to_string(), "INT".to_string(), true),
7458            ],
7459            "{params:?}"
7460        );
7461        assert_eq!(
7462            steps[0].kind.to_string(),
7463            "FUNC F($a: STRING, $b?: INT): STRING {\n    RETURN $a\n}",
7464            "display marks the optional"
7465        );
7466    }
7467
7468    #[test]
7469    fn func_def_optional_params_must_trail() {
7470        let err = parse_err("FUNC F($a?: INT, $b: STRING): STRING {\n  RETURN $b\n}\n");
7471        assert!(err.contains("optional ? params must be trailing"), "{err}");
7472        assert!(err.contains("`$b`"), "{err}");
7473    }
7474
7475    #[test]
7476    fn func_def_param_type_must_be_uppercase() {
7477        let err = parse_err("FUNC F($q: string): STRING {\n  RETURN $q\n}\n");
7478        assert!(err.contains("needs an uppercase type"), "{err}");
7479        assert!(err.contains("`string`"), "{err}");
7480    }
7481
7482    #[test]
7483    fn func_def_malformed_params_name_the_shape() {
7484        for (script, expected) in [
7485            (
7486                "FUNC F($x?): STRING {\n  RETURN \"hi\"\n}\n",
7487                "needs `: TYPE` after the name",
7488            ),
7489            (
7490                "FUNC F(bar): STRING {\n  RETURN \"hi\"\n}\n",
7491                "must be `$name: TYPE` separated by commas",
7492            ),
7493            (
7494                "FUNC F($x: STRING,): STRING {\n  RETURN $x\n}\n",
7495                "must not end with a trailing comma",
7496            ),
7497        ] {
7498            let err = parse_err(script);
7499            assert!(err.contains(expected), "{script}: {err}");
7500        }
7501        // `FUNC FOO() ECHO hi` still misses to generic: the
7502        // header-only invalid syntax echoes just the header.
7503        let err = parse_err("FUNC FOO() ECHO hi\n");
7504        assert!(err.contains("invalid syntax for command FUNC"), "{err}");
7505        assert!(err.contains("got `FOO() ECHO hi`"), "{err}");
7506    }
7507
7508    #[test]
7509    fn call_and_while_lower_correctly() {
7510        let steps = parse_script(
7511            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\nGREET(\"ada\")\n",
7512            lower_command,
7513        )
7514        .expect("call parses");
7515        assert!(
7516            matches!(&steps[1].kind, StepKind::Call { name, .. } if name == "SCRIPT::GREET"),
7517            "{:?}",
7518            steps[1].kind
7519        );
7520        let steps = parse_script(
7521            "FUNC GREET($a: STRING, $b: STRING): STRING {\n  RETURN $a\n}\nGREET(\"ada\", \"bex\")\n",
7522            lower_command,
7523        )
7524        .expect("spaced call parses");
7525        assert!(
7526            matches!(&steps[1].kind, StepKind::Call { name, args } if name == "SCRIPT::GREET" && args.len() == 2),
7527            "{:?}",
7528            steps[1].kind
7529        );
7530        let steps = parse_script(
7531            indoc! {r#"
7532                WHILE !$done {
7533                  BREAK
7534                }
7535            "#},
7536            lower_command,
7537        )
7538        .expect("while parses");
7539        let StepKind::While { body, .. } = &steps[0].kind else {
7540            panic!("expected While, got {:?}", steps[0].kind);
7541        };
7542        assert!(matches!(body[0].kind, StepKind::Break));
7543    }
7544
7545    #[test]
7546    fn let_capture_call_and_async_call_lower() {
7547        // A bare `NAME(...)` on the LET RHS stays an expression assignment;
7548        // only ASYNC/TIMEOUT/command captures produce AssignCapture.
7549        let steps = parse_script(
7550            indoc! {r#"
7551                FUNC GREET($name: STRING): STRING {
7552                  RETURN $name
7553                }
7554                LET $r: STRING = GREET("ada")
7555            "#},
7556            lower_command,
7557        )
7558        .expect("capture call parses");
7559        let StepKind::Bind {
7560            var,
7561            rhs: BindRhs::Expr(expr),
7562            ..
7563        } = &steps[1].kind
7564        else {
7565            panic!("expected Bind, got {:?}", steps[1].kind);
7566        };
7567        assert_eq!(var, "r");
7568        assert!(
7569            matches!(expr, Expr::Call { name, .. } if name == "SCRIPT::GREET"),
7570            "{expr:?}"
7571        );
7572        let steps = parse_script(
7573            "FUNC GREET($name: STRING): STRING {\n  RETURN $name\n}\nLET $t: HANDLE<STRING> = ASYNC GREET(\"a\")\n",
7574            lower_command,
7575        )
7576        .expect("async call parses");
7577        assert!(
7578            matches!(
7579                &steps[1].kind,
7580                StepKind::Bind {
7581                    rhs: BindRhs::Async(_),
7582                    ..
7583                }
7584            ),
7585            "{:?}",
7586            steps[1].kind
7587        );
7588    }
7589
7590    #[test]
7591    fn multiline_call_args_span_lines() {
7592        // Regression: long invocations (e.g. 4-arg SSH_SERVE with an
7593        // options map) may put one argument per line. Bracket interiors
7594        // tolerate linebreaks while statement structure stays single-line.
7595        let steps = parse_script(
7596            "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",
7597            lower_command,
7598        )
7599        .expect("multiline call parses");
7600        let StepKind::Bind {
7601            rhs: BindRhs::Expr(expr),
7602            ..
7603        } = &steps[1].kind
7604        else {
7605            panic!("expected Bind, got {:?}", steps[1].kind);
7606        };
7607        let Expr::Call { name, args } = expr else {
7608            panic!("expected Call expr, got {expr:?}");
7609        };
7610        assert_eq!(name, "SCRIPT::SERVE");
7611        assert_eq!(args.len(), 4);
7612        assert!(matches!(&args[3], Expr::Map(entries) if entries.len() == 1));
7613        // Display stays single-line; reparsing the same text is identical.
7614        let rendered = steps[1].to_string();
7615        assert!(!rendered.contains('\n'), "{rendered}");
7616        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";
7617        let again = parse_script(script, lower_command).expect("reparse ok");
7618        assert_eq!(again, steps);
7619    }
7620
7621    #[test]
7622    fn multiline_bare_call_and_list_span_lines() {
7623        let steps = parse_script(
7624            indoc! {r#"
7625                FUNC GREET($a: STRING): STRING {
7626                  RETURN $a
7627                }
7628                GREET(
7629                  "ada"
7630                )
7631            "#},
7632            lower_command,
7633        )
7634        .expect("multiline bare call parses");
7635        let StepKind::Call { name, args } = &steps[1].kind else {
7636            panic!("expected Call, got {:?}", steps[1].kind);
7637        };
7638        assert_eq!(name, "SCRIPT::GREET");
7639        assert_eq!(args.len(), 1);
7640        let steps = parse_script(
7641            indoc! {r#"
7642                LET $l: LIST = [
7643                  "a",
7644                  "b"
7645                ]
7646            "#},
7647            lower_command,
7648        )
7649        .expect("multiline list parses");
7650        let StepKind::Bind {
7651            rhs: BindRhs::Expr(expr),
7652            ..
7653        } = &steps[0].kind
7654        else {
7655            panic!("expected Bind, got {:?}", steps[0].kind);
7656        };
7657        assert!(
7658            matches!(expr, Expr::List(items) if items.len() == 2),
7659            "{expr:?}"
7660        );
7661    }
7662
7663    #[test]
7664    fn parse_duration_units() {
7665        use std::time::Duration;
7666        assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
7667        assert_eq!(parse_duration("10s").unwrap(), Duration::from_secs(10));
7668        assert_eq!(parse_duration("2m").unwrap(), Duration::from_secs(120));
7669        assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
7670        assert_eq!(parse_duration("30").unwrap(), Duration::from_secs(30));
7671        // One optional space separates number from unit, like bytes.
7672        assert_eq!(parse_duration("30 s").unwrap(), Duration::from_secs(30));
7673        assert_eq!(parse_duration("2 m").unwrap(), Duration::from_secs(120));
7674    }
7675
7676    #[test]
7677    fn parse_duration_rejects_garbage() {
7678        assert!(parse_duration("").is_err());
7679        assert!(parse_duration("banana").is_err());
7680        assert!(parse_duration("10x").is_err());
7681        assert!(parse_duration("0s").is_err());
7682        assert!(parse_duration("0").is_err());
7683        assert!(parse_duration("-5s").is_err());
7684        // Three parts or a split digit run stay rejected.
7685        assert!(parse_duration("30 s s").is_err());
7686        assert!(parse_duration("3 0s").is_err());
7687    }
7688
7689    #[test]
7690    fn parse_byte_count_units() {
7691        assert_eq!(parse_byte_count("500").unwrap(), 500);
7692        assert_eq!(parse_byte_count("500B").unwrap(), 500);
7693        assert_eq!(parse_byte_count("10KB").unwrap(), 10_000);
7694        assert_eq!(parse_byte_count("2MB").unwrap(), 2_000_000);
7695        assert_eq!(parse_byte_count("1GB").unwrap(), 1_000_000_000);
7696        assert_eq!(parse_byte_count("1TB").unwrap(), 1_000_000_000_000);
7697        assert_eq!(parse_byte_count("10KIB").unwrap(), 10 * 1_024);
7698        assert_eq!(parse_byte_count("2MIB").unwrap(), 2 * 1_024 * 1_024);
7699        assert_eq!(parse_byte_count("1GIB").unwrap(), 1_024 * 1_024 * 1_024);
7700        assert_eq!(
7701            parse_byte_count("1TIB").unwrap(),
7702            1_024 * 1_024 * 1_024 * 1_024
7703        );
7704        // Case-insensitive: `1gb`, `1GB`, and `1Gb` agree.
7705        assert_eq!(parse_byte_count("1gb").unwrap(), 1_000_000_000);
7706        assert_eq!(parse_byte_count("1Gb").unwrap(), 1_000_000_000);
7707        assert_eq!(parse_byte_count("1gib").unwrap(), 1_024 * 1_024 * 1_024);
7708        assert_eq!(parse_byte_count("1Gib").unwrap(), 1_024 * 1_024 * 1_024);
7709        // Rust-literal grouping: separators ride between digits only.
7710        assert_eq!(parse_byte_count("1_000").unwrap(), 1_000);
7711        assert_eq!(
7712            parse_byte_count("1_000_000_000_000").unwrap(),
7713            1_000_000_000_000
7714        );
7715        assert_eq!(parse_byte_count("1_0KB").unwrap(), 10_000);
7716        assert_eq!(
7717            parse_byte_count("1_0GiB").unwrap(),
7718            10 * 1_024 * 1_024 * 1_024
7719        );
7720        // One optional space separates number from unit, never digits.
7721        assert_eq!(parse_byte_count("1 GB").unwrap(), 1_000_000_000);
7722        assert_eq!(parse_byte_count("10 KiB").unwrap(), 10_240);
7723        assert_eq!(parse_byte_count("  2MB  ").unwrap(), 2_000_000);
7724        // A leading `+` rides spaced or glued; `-` stays rejected.
7725        assert_eq!(parse_byte_count("+1 GB").unwrap(), 1_000_000_000);
7726        assert!(parse_byte_count("-1 GB").is_err());
7727    }
7728
7729    #[test]
7730    fn parse_byte_count_rejects_garbage() {
7731        for bad in [
7732            "",
7733            "banana",
7734            "10x",
7735            "1G",
7736            "1K",
7737            "1.5GB",
7738            "-5",
7739            "-5GB",
7740            "0",
7741            "0GB",
7742            "_100",
7743            "100_",
7744            "1__000",
7745            "_",
7746            "1_GB",
7747            // A space splits tokens, never digit runs or units.
7748            "1 G B",
7749            "1 2",
7750            "1 0",
7751            // Absurd magnitudes fail loudly instead of wrapping.
7752            "1000000000000000000000000",
7753            "1000000000TB",
7754        ] {
7755            assert!(parse_byte_count(bad).is_err(), "{bad:?} must fail");
7756        }
7757    }
7758
7759    #[test]
7760    fn format_byte_count_round_trips() {
7761        for text in [
7762            "500", "500B", "10KB", "2MB", "1GB", "1TB", "10KIB", "2MIB", "1GIB", "1TIB", "1500B",
7763        ] {
7764            let parsed = parse_byte_count(text).unwrap();
7765            let rendered = format_byte_count(parsed);
7766            assert_eq!(
7767                parse_byte_count(&rendered).unwrap(),
7768                parsed,
7769                "round-trip failed for {text}"
7770            );
7771        }
7772        assert_eq!(format_byte_count(1_024 * 1_024 * 1_024), "1GiB");
7773        assert_eq!(format_byte_count(1_000_000_000), "1GB");
7774    }
7775
7776    #[test]
7777    fn strip_digit_separators_passes_signs_through() {
7778        // Signs belong to signed domains: the strip keeps them so
7779        // `-1_000` reads as -1000 wherever ints coerce, while unsigned
7780        // callers (byte counts) still reject at parse time.
7781        assert_eq!(strip_digit_separators("-1_000"), "-1000");
7782        assert_eq!(strip_digit_separators("+1_000_000"), "+1000000");
7783        assert_eq!(strip_digit_separators("-1_000.5"), "-1000.5");
7784        assert_eq!(strip_digit_separators("1_000"), "1000");
7785        for untouched in ["+", "-", "", "1__0", "abc", "+-5", "--5"] {
7786            assert_eq!(strip_digit_separators(untouched), untouched);
7787        }
7788        // Unsigned byte counts reject `-` at parse time but take `+`
7789        // like every other Rust-parsed number in the DSL.
7790        assert!(parse_byte_count("-1_000").is_err());
7791        assert_eq!(parse_byte_count("+1GB").unwrap(), 1_000_000_000);
7792    }
7793
7794    #[test]
7795    fn format_byte_count_is_lossless() {
7796        // The canonical form parses back to the exact input value:
7797        // formatting never loses information, only spelling.
7798        // Zero is unrepresentable by design (like durations): the
7799        // parser rejects it, so it cannot round-trip.
7800        for n in [
7801            1,
7802            500,
7803            999,
7804            1_000,
7805            1_024,
7806            1_500,
7807            1_000_000,
7808            1_048_576,
7809            1_000_000_000,
7810            1_073_741_824,
7811            1_000_000_000_000,
7812            1_099_511_627_776,
7813            u64::MAX,
7814        ] {
7815            assert_eq!(
7816                parse_byte_count(&format_byte_count(n)).unwrap(),
7817                n,
7818                "lossless round-trip failed for {n}"
7819            );
7820        }
7821    }
7822
7823    #[test]
7824    fn format_duration_round_trips() {
7825        for text in ["500ms", "10s", "2m", "1h", "90s", "1500ms"] {
7826            let parsed = parse_duration(text).unwrap();
7827            let rendered = format_duration(&parsed);
7828            assert_eq!(
7829                parse_duration(&rendered).unwrap(),
7830                parsed,
7831                "round-trip failed for {text}"
7832            );
7833        }
7834        assert_eq!(format_duration(&parse_duration("90s").unwrap()), "90s");
7835        assert_eq!(format_duration(&parse_duration("2m").unwrap()), "2m");
7836    }
7837
7838    #[test]
7839    fn structural_metadata_covers_all_structural_kinds() {
7840        use crate::ast::Value;
7841
7842        // Tripwire: adding a structural StepKind variant without registering
7843        // documentation fails to compile here (non-exhaustive match). Leaf
7844        // commands map to None; they are covered by declare_commands!.
7845        fn metadata_name(kind: &StepKind) -> Option<&'static str> {
7846            match kind {
7847                StepKind::WithIo { .. } | StepKind::WithIoBlock { .. } => Some(KEYWORD_WITH_IO),
7848                StepKind::For { .. } => Some(KEYWORD_FOR),
7849                StepKind::If { .. } => Some(KEYWORD_IF),
7850                StepKind::Switch { .. } => Some(KEYWORD_SWITCH),
7851                StepKind::Bind { is_const, rhs, .. } => Some(match rhs {
7852                    BindRhs::Await { .. } => {
7853                        if *is_const {
7854                            KEYWORD_CONST
7855                        } else {
7856                            KEYWORD_AWAIT
7857                        }
7858                    }
7859                    BindRhs::Async(_) => {
7860                        if *is_const {
7861                            KEYWORD_CONST
7862                        } else {
7863                            KEYWORD_ASYNC
7864                        }
7865                    }
7866                    _ => {
7867                        if *is_const {
7868                            KEYWORD_CONST
7869                        } else {
7870                            KEYWORD_LET
7871                        }
7872                    }
7873                }),
7874                StepKind::Set { .. } => Some("MUTATION"),
7875                StepKind::AsyncBlock { .. } => Some(KEYWORD_ASYNC),
7876                StepKind::Await { .. } => Some(KEYWORD_AWAIT),
7877                StepKind::Cancel { .. } => Some(KEYWORD_CANCEL),
7878                StepKind::Timeout { .. } => Some(KEYWORD_TIMEOUT),
7879                StepKind::Fail { .. } => Some(KEYWORD_FAIL),
7880                StepKind::Isolated { .. } => Some(KEYWORD_ISOLATED),
7881                StepKind::IsolatedInheritEnv { .. } => Some(KEYWORD_ISOLATED),
7882                StepKind::RemoteBlock { .. } => Some(KEYWORD_REMOTE),
7883                StepKind::FuncDef { .. } => Some(KEYWORD_FUNC),
7884                // Bare `NAME(...)` calls share the `FUNC` reference page;
7885                // there is no call keyword to document on its own.
7886                StepKind::Call { .. } => None,
7887                // Both import forms are documented on the `IMPORT` page.
7888                StepKind::ImportFile { .. } | StepKind::ImportFuncs { .. } => Some(KEYWORD_IMPORT),
7889                StepKind::Return { .. } => Some(KEYWORD_RETURN),
7890                StepKind::While { .. } => Some(KEYWORD_WHILE),
7891                StepKind::Break => Some(KEYWORD_BREAK),
7892                StepKind::Continue => Some(KEYWORD_CONTINUE),
7893                // Aliases are declared by `TYPE` but documented with the
7894                // type-word prose on the `LET` page (define-once,
7895                // use-everywhere); no dedicated reference page.
7896                StepKind::TypeAlias { .. } => Some(KEYWORD_LET),
7897                StepKind::RunExec { .. } => None,
7898                StepKind::Workdir(_)
7899                | StepKind::Workspace(_)
7900                | StepKind::Env { .. }
7901                | StepKind::InheritEnv { .. }
7902                | StepKind::Run(_)
7903                | StepKind::Echo(_)
7904                | StepKind::Copy { .. }
7905                | StepKind::Symlink { .. }
7906                | StepKind::Mkdir(_)
7907                | StepKind::Archive { .. }
7908                | StepKind::Unarchive { .. }
7909                | StepKind::Install { .. }
7910                | StepKind::SetExecutable { .. }
7911                | StepKind::Ls(_)
7912                | StepKind::Read(_)
7913                | StepKind::ReadLine { .. }
7914                | StepKind::Prompt { .. }
7915                | StepKind::Write { .. }
7916                | StepKind::Append { .. }
7917                | StepKind::AppendLine { .. }
7918                | StepKind::Remove { .. }
7919                | StepKind::Expand { .. }
7920                | StepKind::AssertEq { .. }
7921                | StepKind::AssertContains { .. }
7922                | StepKind::AssertNe { .. }
7923                | StepKind::CopyGit { .. }
7924                | StepKind::Exit(_)
7925                | StepKind::Sleep { .. }
7926                | StepKind::ListAppend { .. } => None,
7927            }
7928        }
7929
7930        // Exercise the matcher once per structural variant so the arms cannot
7931        // rot (a new variant breaks compilation above first).
7932        let dummies: Vec<StepKind> = vec![
7933            StepKind::WithIo {
7934                bindings: Vec::new(),
7935                cmd: Box::new(StepKind::Echo(crate::ast::Arg::String(
7936                    "x".to_string(),
7937                    false,
7938                ))),
7939            },
7940            StepKind::For {
7941                key_var: None,
7942                key_type: None,
7943                var: "i".to_string(),
7944                var_type: crate::tag::STRING_TYPE_NAME.to_string(),
7945                in_expr: Expr::Literal(Value::bool(true)),
7946                body: Vec::new(),
7947            },
7948            StepKind::If {
7949                cond: Box::new(Expr::Literal(Value::bool(true))),
7950                then_body: Vec::new(),
7951                else_ifs: Vec::new(),
7952                else_body: None,
7953            },
7954            StepKind::Switch {
7955                discriminant: None,
7956                cases: Vec::new(),
7957                default_body: None,
7958            },
7959            StepKind::Bind {
7960                var: "v".to_string(),
7961                decl_type: crate::tag::BOOL_TYPE_NAME.to_string(),
7962                is_const: false,
7963                rhs: BindRhs::Expr(Expr::Literal(Value::bool(true))),
7964            },
7965            StepKind::Bind {
7966                var: "v".to_string(),
7967                decl_type: crate::tag::BOOL_TYPE_NAME.to_string(),
7968                is_const: true,
7969                rhs: BindRhs::Expr(Expr::Literal(Value::bool(true))),
7970            },
7971            StepKind::Set {
7972                var: "v".to_string(),
7973                expr: Expr::Literal(Value::bool(true)),
7974            },
7975            StepKind::Bind {
7976                var: "v".to_string(),
7977                decl_type: crate::tag::STRING_TYPE_NAME.to_string(),
7978                is_const: false,
7979                rhs: BindRhs::Capture(Box::new(StepKind::Echo(crate::ast::Arg::String(
7980                    "x".to_string(),
7981                    false,
7982                )))),
7983            },
7984            StepKind::Bind {
7985                var: "o".to_string(),
7986                decl_type: crate::tag::STRING_TYPE_NAME.to_string(),
7987                is_const: false,
7988                rhs: BindRhs::Await {
7989                    task_var: "t".to_string(),
7990                },
7991            },
7992            StepKind::AsyncBlock { body: Vec::new() },
7993            StepKind::Bind {
7994                var: "t".to_string(),
7995                decl_type: crate::tag::HANDLE_TYPE_NAME.to_string(),
7996                is_const: false,
7997                rhs: BindRhs::Async(Vec::new()),
7998            },
7999            StepKind::Await {
8000                var: "t".to_string(),
8001            },
8002            StepKind::Cancel {
8003                var: "t".to_string(),
8004            },
8005            StepKind::Timeout {
8006                duration: Arg::String("1s".to_string(), false),
8007                body: Vec::new(),
8008            },
8009            StepKind::Fail {
8010                code: None,
8011                message: None,
8012                body: Vec::new(),
8013            },
8014            StepKind::Isolated { body: Vec::new() },
8015            StepKind::IsolatedInheritEnv { keys: Vec::new() },
8016            StepKind::RemoteBlock {
8017                target: "prod".to_string(),
8018                vars: Vec::new(),
8019                env: Vec::new(),
8020                body: Vec::new(),
8021            },
8022            StepKind::FuncDef {
8023                name: "F".to_string(),
8024                params: Vec::new(),
8025                return_type: "STRING".to_string(),
8026                is_async: false,
8027                body: Vec::new(),
8028                docs: None,
8029            },
8030            StepKind::Call {
8031                name: "F".to_string(),
8032                args: Vec::new(),
8033            },
8034            StepKind::Return {
8035                expr: Box::new(Expr::Literal(Value::bool(true))),
8036                is_bare: false,
8037            },
8038            StepKind::While {
8039                cond: Box::new(Expr::Literal(Value::bool(true))),
8040                body: Vec::new(),
8041            },
8042            StepKind::Break,
8043            StepKind::Continue,
8044            StepKind::TypeAlias {
8045                name: "PERSON".to_string(),
8046                target: "MAP<name: STRING>".to_string(),
8047            },
8048        ];
8049        let registry = all_structural_metadata();
8050        for kind in &dummies {
8051            // Bare calls share the FUNC reference page and map to None.
8052            let Some(name) = metadata_name(kind) else {
8053                continue;
8054            };
8055            assert!(
8056                registry.iter().any(|meta| meta.name == name),
8057                "no structural metadata entry for {}",
8058                name
8059            );
8060        }
8061    }
8062}