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