oxdock-mcp

v0.46.0-alpha
oxdock-mcp Checked 6 hours ago

MCP tool hosting for exported OxDock script functions over stdio JSON-RPC.

Bash gives you strings and exit codes. OxDock gives you typed values, guarded paths, managed pipes, and identical behavior on Linux/macOS/Windows (the things you'd re-implement badly in every growing bash script). And with hot-loading MCP tooling, *English-to-OxDock* just skips the boilerplate of getting there. Workspaces (SNAPSHOT, LOCAL, CACHE, SYSTEM) and scoped blocks with selective environment inheritance give every run an isolated root that reverts on scope exit.

Summary extracted from the README.

OxDock is a Dockerfile-inspired DSL for native builds, multi-node pipelines, and sealed remote execution.

Bash gives you strings and exit codes. OxDock gives you typed values, guarded paths, managed pipes, and identical behavior on Linux/macOS/Windows (the things you'd re-implement badly in every growing bash script). And with hot-loading MCP tooling, English-to-OxDock just skips the boilerplate of getting there. Workspaces (SNAPSHOT, LOCAL, CACHE, SYSTEM) and scoped blocks with selective environment inheritance give every run an isolated root that reverts on scope exit. When plain shell is the right tool, RUN still reaches it, and platform guards keep the OS-specific bits fenced: the two combine instead of competing.

Unlike Docker's Linux-VM requirement on non-Linux hosts, OxDock runs directly on Linux, macOS, and Windows. Execute scripts on bare metal, inside containers, or dispatched across remote machines simultaneously. No daemons. No hypervisors. See Containers as orchestrated steps.

Platform gating selects OS-specific steps, and remote targets bind over any stdio transport. Only RUN touches the host shell.

The syntax is line-oriented with optional semicolon terminators and a static type system checking scripts before the first step runs. Plain Rust functions become script functions with one attribute: #[oxdock_func] exports them into namespaced modules scripts call as DEMO::NAME(...). See Extending OxDock from Rust.

Documentation

Jump to the Command Reference below for the full command list with runnable examples, or view the standard library Built-in functions.

Browse by section:

Quick start | Lexical structure | Guards and scoped blocks | Command Reference | Value types | Built-in functions | Contexts | Selective environment inheritance | Path Separators | Workspaces & Filesystem | Errors stop the pipeline | Plugin references | Runtime architecture | Machine model | Why this shape | Variants | Goals | Dynamically embed assets at compile time | Run scripts inline | Extend the language | Extending OxDock from Rust | MCP hosting | GitHub Actions Integration | Testing & Coverage | Glossary | Citation | License

Quick start

Standalone CLI installation

Linux / macOS:

curl -fsSL https://raw.githubusercontent.com/jzombie/rust-oxdock/main/install.sh | bash

Installs to ~/.local/bin. Set INSTALL_DIR to choose another destination.

Windows (PowerShell, not Command Prompt):

(irm 'https://raw.githubusercontent.com/jzombie/rust-oxdock/main/install.ps1') | iex

Installs to %LOCALAPPDATA%\Microsoft\WindowsApps, already on PATH. Set $env:INSTALL_DIR to choose another destination.

For a reproducible install, pin an explicit release:

(export VERSION=v0.46.0-alpha; curl -fsSL https://raw.githubusercontent.com/jzombie/rust-oxdock/main/install.sh | bash)
$env:VERSION = 'v0.46.0-alpha'; (irm 'https://raw.githubusercontent.com/jzombie/rust-oxdock/main/install.ps1') | iex

Build from source via Cargo (same full module surface as the release downloads: NET, SSH, MARKDOWN, plus --mcp hosting):

From the registry:

cargo install oxdock@0.46.0-alpha

From a local checkout:

cargo install --path oxdock

Add to Rust project

cargo add oxdock@0.46.0-alpha

Run a script with the CLI

oxdock <PATH>

New here? hello.oxfile demonstrates guards, ENV, and native commands, and verifies itself with assertions: oxdock hello.oxfile from a checkout runs it green.

The same script also runs standalone through the CLI. It builds artifacts and verifies them with native assertions. Every fenced oxdock example in this README is executed against the implementation by crates/oxdock-logic-tests/tests/docs_conformance.rs, so what you read here is guaranteed to match what the DSL actually does:

// Script-local variable: usable by templates and guards below.
ENV PROJECT=OxDock

// Creates the directory and any missing parents.
MKDIR dist

// Interpolate the variable into the file body via a template.
WRITE dist/hello.txt Built with {{ env:PROJECT }}

// Fail the script unless the artifact exists with exactly these bytes.
LET $body: STRING = READ dist/hello.txt
ASSERT_EQ $body "Built with OxDock"

// LS prints "<dir>:" then the entry names.
LS dist
ASSERT_CONTAINS stdout "dist:"
ASSERT_CONTAINS stdout "hello.txt"

Save the script above as ./build.oxfile and run it by path (install once, see above):

oxdock ./build.oxfile

DSL Reference

Prototype status: OxDock is still being prototyped. DSL syntax and Rust APIs may change without deprecation warnings until the first stable release.

Scripts are sequences of instructions, one per line (; separates two; quoted separators stay literal). Instructions may be prefixed with guards ([...]) that decide whether they run, and grouped into scoped blocks ({ ... }). The language is defined by the parser in crates/oxdock-parser/src/parser.rs, fed by the two context-free lexers in crates/oxdock-parser/src/tok.rs: one parser serves string scripts and braced-macro token streams alike.

Lexical structure

  • Commands are uppercase and case-sensitive: WORKDIR, not workdir. Lowercase or mixed-case spellings are parse errors with an uppercase hint.
  • One instruction per line; a semicolon (;) splits multiple instructions on a single line.
  • Paths and arguments use forward slashes (/) for portability (see Path Separators).
  • Scripts start with host-mirrored essentials (PATH, HOME, temp bindings, loader anchors); anything beyond those needs INHERIT_ENV to opt specific keys in (see Selective environment inheritance).

Declared variable types

Every variable binding declares its type at the binding site. LET $name: TYPE = ... creates the binding, $name = ... mutates it, and bodies use the bare $name reference. The leading $ keeps mutation distinct from KEY=value command assignments. Repeating LET for the same name in the same scope is a redeclaration error. Loop variables are declared the same way: FOR $item: STRING IN .... Valid types: scalars (STRING, INT, FLOAT, BOOL, DURATION, PATH), handles (PIPE, HANDLE, SEMAPHORE, PERMIT), ANY, and rendered shapes (LIST<STRING>, MAP<name: STRING, age: INT>, arbitrary nesting, spacing insignificant). Bare LIST and MAP are runtime words, never declarations: unknown collections declare LIST<ANY> and MAP<ANY>. A field with a ? suffix is optional (MAP<held: BOOL, permit?: PERMIT>): missing optional keys pass, missing required keys fail. TYPE NAME = <shape> binds one immutable name per run that every declaration form accepts.

LET $count: INT = 1
$count = 2
LET $msg: STRING = hello

FOR $item: STRING IN ["a", "b"] {
    ECHO "{{ $item }}"
}

WRITE count.txt "{{ $count }}"
LET $c: STRING = READ count.txt
ASSERT_EQ $c "2"

Shapes enforce at the binding: a bad element fails naming its position.

# A list of unknown maps and an inline record bind shaped values.
LET $ms: LIST<MAP<ANY>> = [{a: 1}]
LET $p: MAP<name: STRING, age: INT> = {name: "x", age: 3}
ASSERT_EQ $p.name "x"

# TYPE binds one reusable name; uses enforce structurally.
TYPE PERSON = MAP<name: STRING, age: INT>
LET $q: PERSON = {name: "y", age: 4}
LET $team: LIST<PERSON> = [$q]
LET $n: STRING = $team.0.name
ASSERT_EQ $n "y"

The env:KEY expression reads the script environment into a plain value. A $var reference never reads the environment, even when the names match:

ENV FOO="bar"
LET $e: STRING = env:FOO
WRITE env.txt "{{ $e }}"
LET $v: STRING = READ env.txt
ASSERT_EQ $v "bar"

Three spellings read distinct stores. $name reads a binding, whether LET or CONST; env:KEY reads script env; bare words never read a binding. Bare words stay literal text in command arguments (and fail elsewhere, naming the $ form to use). RUN shell words stay literal too, so only {{ $name }} templates read bindings there.

# LET bindings read through the dollar sigil.
LET $note: STRING = "let-hello"
ECHO $note
ASSERT_CONTAINS stdout "let-hello"

# Script env reads through the env prefix.
ENV DOC_MOOD="env-hello"
ECHO env:DOC_MOOD
ASSERT_CONTAINS stdout "env-hello"

# Bare words stay literal in command arguments.
CONST $BADGE: STRING = "const-hello"
ECHO BADGE
ASSERT_CONTAINS stdout "BADGE"

# CONST reads sigiled, like LET.
ECHO $BADGE
ASSERT_CONTAINS stdout "const-hello"

# CONST reads through templates.
ECHO "{{ $BADGE }}"
ASSERT_CONTAINS stdout "const-hello"

# CONST reads sigiled in expression positions.
LET $badge: STRING = $BADGE
ASSERT_EQ $badge "const-hello"

# RUN keeps shell words literal, so only templates read CONST.
LET $raw: STRING = RUN echo BADGE
ASSERT_CONTAINS $raw "BADGE"

# RUN reads CONST through templates.
LET $cooked: STRING = RUN echo "{{ $BADGE }}"
ASSERT_CONTAINS $cooked "const-hello"

Functions and commands

Parentheses mark the boundary between computing a value and running a pipeline step. Builtin functions (INSPECT, LOAD_TOML, LOAD_JSON, GLOB, INT, FLOAT, PATH_TYPE) evaluate to an in-memory value and never write to standard output. They compute or query (Value::Map, Value::String, Value::Int, Value::Float, Value::List) with zero stream side effects, so they appear only where values are expected: on the right-hand side of LET, inside IF conditions, or nested in other calls. Commands (READ, ECHO, RUN, WRITE, ASSERT_EQ) are line-starting statements with space-separated arguments. They drive the I/O pipeline, streaming bytes to stdout or mutating state, which makes their output available to pipes and LET capture. When a function evaluates, process stdout stays completely untouched. When a command runs, streaming bytes is the payload:

// Functions compute values; stdout stays untouched.
IMPORT [STD]
LET $t: STRING = PATH_TYPE("missing.txt")
ASSERT_EQ $t "absent"

LET $n: INT = INT("41") + 1
ASSERT_EQ $n 42
ASSERT_EQ stdout ""

Statements and semicolons

// One line, two instructions: the semicolon splits them.
ECHO one; ECHO two
ASSERT_CONTAINS stdout "one"
ASSERT_CONTAINS stdout "two"

RUN shell and exec forms

Shell form (RUN <command...>) joins its arguments and runs the string in the system shell. Exec form (RUN ["exe", "arg", ...]) spawns the executable directly with no shell. Exec form has no shell expansion, globbing, redirection, or pipes. Quoted {{ ... }} templates still interpolate per element, and guards and wrappers (ASYNC, TIMEOUT, WITH_IO) apply to both forms.

RUN ["cargo", "--version"]
ASSERT_CONTAINS stdout "cargo"

Comments

Three comment styles are supported: // line comments, nestable /* ... */ block comments, and # comments. A # comment occupies a whole line (optionally indented) and may also trail values inside multi-line (), [], and {} brackets; inside a command payload a # is ordinary text. Similarly, // ends a RUN argument list but survives inside quoted strings:

// Slash comment at end of line.
# Hash comment occupies the whole line.

/* block comments
   /* nest */
   like this */
ECHO visible-after-comments
ASSERT_CONTAINS stdout "visible-after-comments"
ECHO hash-mid-line # stays-in-payload
ASSERT_CONTAINS stdout "hash-mid-line # stays-in-payload"

RUN echo run-args-stop-at-slashes // removed-as-comment
ASSERT_CONTAINS stdout "run-args-stop-at-slashes"

RUN echo "quoted // kept"
ASSERT_CONTAINS stdout "quoted // kept"

Comment markers inside quoted strings are always preserved.

Two scope notes. Only # blocks count as FUNC documentation (collected into func_docs and served verbatim as MCP tool descriptions); // comments never feed docs. Script docs are provider content: only serve scripts you trust over MCP, since a script author controls the descriptions an MCP client shows its model, and served scripts must not print secrets, since tool stdout and stderr stream to the client as notifications. And inside braced oxdock! { } macros only # whole-line comments exist: // and /* ... */ are stripped by Rust before the macro runs, so they neither parse, document, nor affect ELSE chains there.

Command flags

Commands that take flags accept the value either after a space or joined with =: --from-workspace LOCAL and --from-workspace=LOCAL mean the same thing. Boolean flags take no value. Quoted arguments are never treated as flags, even when they start with --.

WRITE flag-src.txt flag-content
COPY --from-workspace=LOCAL flag-src.txt flag-copy.txt
LET $body: STRING = READ flag-copy.txt
ASSERT_EQ $body "flag-content"

Quoting and escaping

Arguments accept single- or double-quoted strings; the escape sequences \" and \' embed a quote, and any other backslash escape keeps the escaped character while dropping the backslash. Quoted fragments containing whitespace, ;, newlines, //, or /* retain their quotes when RUN reconstructs the command string:

// Single and double quotes behave identically.
ECHO 'single quotes'
ASSERT_CONTAINS stdout "single quotes"
ECHO "double quotes"
ASSERT_CONTAINS stdout "double quotes"

// \" embeds a quote; the backslash itself is consumed.
ECHO "escaped \" quote"
ASSERT_CONTAINS stdout 'escaped " quote'

// Quoted separators stay literal: no instruction splits here.
ECHO 'semi;colon'
ASSERT_CONTAINS stdout "semi;colon"

Triple-quoted blocks span source lines for prompts, configs, and templates. A newline right after the opening delimiter strips once, shared indentation dedents to the closing delimiter baseline, and the newline before a lone closing delimiter strips once. Interpolation and backslash escapes resolve at runtime like double-quoted strings, while single and double quotes need no escaping and \"\"\" embeds a delimiter:

# Block literals hold multi-line text without joins.
LET $prompt: STRING = """
    SELECT *
    FROM users
    """
ASSERT_EQ $prompt "SELECT *\nFROM users"

# Blocks round-trip through files byte identical.
WRITE query.txt $prompt
LET $back: STRING = READ query.txt
ASSERT_EQ $back $prompt

# Placeholders interpolate inside blocks like quoted strings.
LET $table: STRING = "users"
LET $filtered: STRING = """
    SELECT * FROM {{ $table }}
    """
ASSERT_EQ $filtered "SELECT * FROM users"

Guards and scoped blocks

A guard is a bracketed expression that gates the instruction or block that follows it. Inside the brackets:

  • Guard predicates are namespaced key:value pairs: os:macos / os:linux / os:windows, arch:x86_64 (any documented target-architecture value), bool:true, env:KEY, and comparisons like eq(env:KEY, value). family:unix and family:windows are accepted aliases, lowered at parse to any(os:macos, os:linux) and os:windows, so every platform check runs under os:.
  • Matching is case-sensitive throughout.
  • Combine predicates with calls or commas: any(expr, expr, ...) takes at least two branches for disjunction (no infix operator), all(expr, expr, ...) spells out conjunction, and a comma-separated list means AND: [env:A, os:linux].
  • Negate any predicate with not(...): [not(env:SKIP)]. Parentheses group expressions: [any(env:A, os:linux), os:macos].

Guards attach to the next instruction. Several guard lines in a row chain onto the same target, and a guard immediately followed by { opens a guarded block whose guard applies to every enclosed instruction.

Guard evaluation checks the script environment only: ENV entries, INHERIT_ENV opt-ins, and builtin keys. Non-essential host variables stay invisible unless inherited, so guards interact naturally with INHERIT_ENV and ENV.

Environment guards

// Copy the key from the host environment (the runner injects it).
INHERIT_ENV [DEPLOY_TARGET]

// Passes when the variable exists with any non-empty value.
[env:DEPLOY_TARGET] ECHO deploy-target-visible
ASSERT_CONTAINS stdout "deploy-target-visible"

// Equality against the inherited value.
[eq(env:DEPLOY_TARGET, staging)] ECHO deploying-to-staging
ASSERT_CONTAINS stdout "deploying-to-staging"

// Inequality: skipped below, because DEPLOY_TARGET IS staging.
[ne(env:DEPLOY_TARGET, staging)] ECHO deploying-elsewhere

Platform guards

// Exactly one block runs depending on the host OS; every command
// inside a guarded block inherits the block's guard. A shared
// counter incremented in each block proves exactly one ran.
LET $ran: INT = 0

[family:windows] {
  WRITE os-report.txt windows
  ECHO windows-detected
  LET $rep: STRING = READ os-report.txt
  ASSERT_EQ $rep "windows"
  ASSERT_CONTAINS stdout "windows-detected"
  $ran = $ran + 1
}

[family:unix] {
  WRITE os-report.txt unix-family
  ECHO unix-detected
  LET $rep: STRING = READ os-report.txt
  ASSERT_EQ $rep "unix-family"
  ASSERT_CONTAINS stdout "unix-detected"
  $ran = $ran + 1
}

ASSERT_EQ $ran 1

Architecture guards

# Gate blocks on the host target architecture. Exactly one block
# runs on any host, and each block proves its own execution.
[arch:x86_64] {
  WRITE arch-report.txt x86_64
  ECHO arch-detected
  LET $rep: STRING = READ arch-report.txt
  ASSERT_EQ $rep "x86_64"
  ASSERT_CONTAINS stdout "arch-detected"
}

[arch:aarch64] {
  WRITE arch-report.txt aarch64
  ECHO arch-detected
  LET $rep: STRING = READ arch-report.txt
  ASSERT_EQ $rep "aarch64"
  ASSERT_CONTAINS stdout "arch-detected"
}

[not(any(arch:x86_64, arch:aarch64))] {
  WRITE arch-report.txt other-arch
  ECHO arch-detected
  LET $rep: STRING = READ arch-report.txt
  ASSERT_EQ $rep "other-arch"
  ASSERT_CONTAINS stdout "arch-detected"
}

# One block always runs, so this holds on every host.
ASSERT_CONTAINS stdout "arch-detected"

Negation, disjunction, and combination

// Bring the runner-injected value into the script environment.
INHERIT_ENV [OXDOCK_DOC_FEATURE_A]

// Absence is testable, but every guard reference must still be
// declared: inheriting a host-absent name stays absent, it only
// satisfies the static gate.
INHERIT_ENV [OXDOCK_DOC_UNDEFINED_VAR, OXDOCK_DOC_FEATURE_B]

// not(...) inverts the predicate: passes because the variable does NOT exist.
[not(env:OXDOCK_DOC_UNDEFINED_VAR)] ECHO negation-passes-for-undefined
ASSERT_CONTAINS stdout "negation-passes-for-undefined"

// any(...) passes when ANY branch holds; A exists, so this runs.
[any(env:OXDOCK_DOC_FEATURE_A, env:OXDOCK_DOC_FEATURE_B)] ECHO or-matched-a-branch
ASSERT_CONTAINS stdout "or-matched-a-branch"

// Comma combines with AND: (A or linux) AND A: true here on every OS.
[any(env:OXDOCK_DOC_FEATURE_A, os:linux), env:OXDOCK_DOC_FEATURE_A] ECHO rendered-and-or-guard
ASSERT_CONTAINS stdout "rendered-and-or-guard"

Multi-line guards

Bracket expressions may span lines. Chained guard lines apply conjunctively to the next instruction; here both variables are declared but host-absent, so the gated instruction is skipped:

IMPORT [STD]

// Declare both names: inheriting host-absent names stays absent,
// satisfying the static gate while keeping the runtime skip.
INHERIT_ENV [OXDOCK_DOC_CHAIN_ONE, OXDOCK_DOC_CHAIN_TWO]

// Brackets may span lines; chained lines AND together and gate
// the next command.
[
  env:OXDOCK_DOC_CHAIN_ONE,
  env:OXDOCK_DOC_CHAIN_TWO
]

// Neither variable is defined, so this WRITE is skipped entirely.
WRITE chained.txt applied

// The artifact was never created.
LET $t: STRING = PATH_TYPE("chained.txt")
ASSERT_EQ $t "absent"

Scoped blocks

Braced blocks scope everything: LET variables, ENV values, WORKDIR, and WORKSPACE all revert when the block exits. Files created inside a block persist on disk, and pipes registered with WITH_IO stay open. Those are the only things that cross a scope boundary. (A bare { ... } needs an always-true guard: [bool:true]. Single commands, including single WITH_IO lines like READ_LINE, never open a scope.)

LET $a: STRING = "some_value"
ENV MODE="production"
MKDIR scoped_area
WORKDIR scoped_area

// Guarded block: LET, ENV, and WORKDIR below are scoped and revert
// when the block closes.
[bool:true] {
    LET $a: STRING = "inner_value"
    ENV MODE="staging"
    WRITE inner.txt "{{ $a }}-{{ env:MODE }}"
}

// $a is back to "some_value", MODE is back to "production",
// and cwd is back at scoped_area. Files persist.
LET $in_body: STRING = READ inner.txt
ASSERT_EQ $in_body "inner_value-staging"
WRITE outer.txt "{{ $a }}-{{ env:MODE }}"
LET $out_body: STRING = READ outer.txt
ASSERT_EQ $out_body "some_value-production"

Pipes cross scope boundaries the same way files do: a handle bound inside stays usable after the block exits.

LET $p: PIPE
[bool:true] {
    WITH_IO [stdout=$p] ECHO "piped-out"
}
WITH_IO [stdin=$p] READ_LINE $line
ASSERT_EQ $line "piped-out"

IF/ELSE branches, FOR loop bodies, TIMEOUT bodies, ASYNC bodies, and WITH_IO [..] { ... } blocks are all scopes under the same rule: only files and pipes leak out.

EXIT in nested blocks

EXIT <code> stops the pipeline immediately with an EXIT requested with code <code> error. Steps after it never run, at any nesting depth. Files written before the EXIT persist, which the fence below asserts; state unwinding and task teardown follow the same scope rules as everywhere else.

WRITE before.txt "persisted"
LET $b: STRING = READ before.txt
ASSERT_EQ $b "persisted"

[bool:true] {
    EXIT 3
    WRITE unreachable.txt "never"
}

Command Reference

See the changelog for what changed in each release.

Command Syntax
WORKDIR WORKDIR <path>
WORKSPACE WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]
ENV ENV KEY=value
INHERIT_ENV INHERIT_ENV [<key>, ...]
ECHO ECHO <message>
RUN RUN <command...> | RUN ["exe", "arg", ...]
COPY COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>
COPY_GIT COPY_GIT [--include-dirty] <rev> <src> <dst>
SYMLINK SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>
MKDIR MKDIR <path>
INSTALL INSTALL <source> <dest>
SET_EXECUTABLE SET_EXECUTABLE <path>
ARCHIVE ARCHIVE [--raw] <src> <dst>
UNARCHIVE UNARCHIVE <src> <dst> [--max-bytes <bytes>]
LS LS [<path>]
READ READ [<path>]
READ_LINE READ_LINE $var
PROMPT PROMPT $var <message> [<default>]
WRITE WRITE <path> [<contents>]
APPEND APPEND <path> [<contents>]
APPEND_LINE APPEND_LINE <path> <contents>
REMOVE REMOVE [--recursive] <path>
EXPAND EXPAND [<path>] [<KEY=val> ...]
ASSERT_EQ ASSERT_EQ [--hash <sha256>] <actual> <expected>
ASSERT_NE ASSERT_NE [--hash <sha256>] <actual> <expected>
ASSERT_CONTAINS ASSERT_CONTAINS <haystack> <needle>
EXIT EXIT <code>
SLEEP SLEEP <duration>
LIST_APPEND LIST_APPEND $list <item>
WITH_IO WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...
FOR FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }
IF IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]
SWITCH SWITCH [<expr>] { CASE <expr>[, <expr> ...] { <commands> } ... [DEFAULT { <commands> }] }
LET 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> }
CONST CONST $NAME: TYPE = <expr> | CONST $NAME: PIPE | CONST $NAME: TYPE = ASYNC { <commands> } | CONST $NAME: TYPE = <command> | CONST $NAME: TYPE = AWAIT $TASK | CONST $NAME: TYPE = { <commands> }
ASYNC ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE<T> = ASYNC { <commands> }
AWAIT AWAIT $var | LET $out: STRING = AWAIT $var
CANCEL CANCEL $var
TIMEOUT TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var
FAIL FAIL [<code>] [<message>] [{ <commands> }]
ISOLATED ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>
REMOTE REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }
FUNC FUNC NAME([$param: TYPE, ...]): RET { <commands> } | ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }
RETURN RETURN [<expr>]
WHILE WHILE <bool-expr> { <commands> }
BREAK BREAK
CONTINUE CONTINUE
IMPORT IMPORT [<module>, ...] | IMPORT <module> | IMPORT ["<path>" AS <ALIAS>] | IMPORT [<module | "<path>" AS <ALIAS> | [F, ... FROM ("<path>" | <module>) (AS <ALIAS>)?]>, ...]

WITH_IO

Reroute standard streams.

Syntax: WITH_IO [<stream>[=$var], ...] <command> | WITH_IO [bindings] { <commands> } | WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...

Reroutes the standard streams of the next command or, in block form, of every enclosed command.

Bindings map streams (stdin, stdout, stderr) to a PIPE-typed variable (stdout=$p, stdin=$p), resolved from the variable when the step runs. Both stdout and stderr pipes capture output the same way. Declare the handle first with LET $p: PIPE.

A RUN step can opt into a pseudo-terminal with the bare tty flag instead of a new command: WITH_IO [tty] RUN [...] spawns the child under a pty sized from the host terminal when it names none (24x80 fallback off-terminal; rows = <int> / cols = <int> override each side). Unnamed sides track the host window while the step runs (signal-driven on Unix, polled where no window signal exists); explicit sides stay pinned.

The master carries the child's interleaved stdout and stderr as one stream, so it routes exclusively to stdout (step capture or a stdout = $p pipe): stderr bindings alongside tty are rejected, and tty outside a RUN step is rejected. Pty-backed descriptors never promote to OS kernel pipes, even inside ASYNC single-RUN bodies.

stdin = $p feeds the master; bare [tty] with a real terminal stdin feeds host keys the same way (raw, transparent) and stays closed headless. Host interrupt keys reach the child instead of cancelling the step, so bind a step TIMEOUT for a guaranteed exit.

Expect pty translation in assertions: newlines arrive as carriage return plus newline, and prompts echo input. On Windows, lone line feeds in fed input expand to carriage-return line feeds for console submission, so portable scripts need no per-platform line endings.

An input pipe that EOFs contributes a terminal-echoed end-of-transmission marker on some platforms: prefer ASSERT_CONTAINS over byte-exact assertions on fed sessions.

Pipes hold bytes in memory and spill to a temp file above 8 MiB, so a producer can finish before the consumer starts.

If WITH_IO wraps an ASYNC block whose body is a single RUN, guarded or not, the pipe is a zero copy OS kernel pipe instead: pair it with a consumer that runs while the producer is alive, since output past the 64 KiB kernel buffer stalls until drained. That promotion never crosses a function boundary: pipes created, bound, or passed by variable inside FUNC bodies are always script pipes, even when the surrounding task would otherwise promote.

A second producer or consumer on a live handle is an explicit error. A handle bound as output can later feed another command's stdin, connecting commands without touching the terminal. Binding stdout and stderr to the same live handle fails deterministically. Merge streams in shell via 2>&1 instead.

Nested blocks stack defaults; inline bindings override inherited ones for their command only; closing a block restores previous wiring.

Examples:

Example: with_io block

LET $log: PIPE
WITH_IO [stdout=$log] {
  ECHO first
  ECHO second
}
WITH_IO [stdin=$log] WRITE captured.txt

# The piped bytes landed in the file.
LET $body: STRING = READ captured.txt
ASSERT_CONTAINS $body "first"
ASSERT_CONTAINS $body "second"

Example: variable pipe binding

# Declare the pipe first: `LET $p: PIPE` mints a fresh
# backend without touching a stream. A plain string here
# would be a TypeMismatch.
LET $p: PIPE
WITH_IO [stdout=$p] ECHO hello
WITH_IO [stdin=$p] READ_LINE $line
ASSERT_EQ $line "hello"

Example: pty terminal binding

# A RUN step under bare `tty` sees a terminal: newlines
# arrive translated, so assert with CONTAINS, never EQ.
LET $p: PIPE
WITH_IO [tty, stdout=$p] RUN "echo hello-tty"
WITH_IO [stdin=$p] READ_LINE $line
ASSERT_CONTAINS $line "hello-tty"

FOR

Iterate over a list or map.

Syntax: FOR $item: TYPE IN <expr> { <commands> } | FOR $key: STRING, $value: TYPE IN <expr> { <commands> }

The loop variable receives each element (lists) or value (maps); with two variables, the first receives the key.

Loop variables are declared with explicit types and scoped per iteration; they do not leak outward. The body may be a braced block or a single-line { ... } command.

GLOB("...") patterns must be quoted (* is not a bare word, so GLOB(*) is a parse error); GLOB returns a root-relative sorted list, empty when nothing matches, and rejects .. escapes.

Examples:

Example: for loop

# Each element binds in turn; the loop body sees every one.
LET $items: LIST<STRING> = ["a", "b"]
FOR $item: STRING IN $items {
  ECHO $item
}
ASSERT_CONTAINS stdout "a"
ASSERT_CONTAINS stdout "b"

# Key and value bind together for maps.
LET $map: MAP<x: INT> = {"x": 1}
FOR $k: STRING, $v: INT IN $map {
  ECHO "{{ $k }}={{ $v }}"
}
ASSERT_CONTAINS stdout "x=1"

Example: expand every match

# Single-line body; $x is a template path, WHO an override.
IMPORT [STD]
WRITE a.txt "hi \{{ env:WHO }}!"
FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }

ASSERT_CONTAINS stdout "hi World!"

IF

Conditional execution.

Syntax: IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]

The condition is evaluated as a boolean expression.

Prefix ! negates (IF !false); && binds tighter than ||, and both short-circuit, so IF true || $missing never evaluates the right side. Only Bool values are accepted as conditions.

Examples:

Example: if else

IMPORT [STD]

# True branch runs; the false branch is skipped.
IF true {
  WRITE yes.txt taken
} ELSE {
  WRITE yes.txt skipped
}

# ELSE IF selects the first true branch.
IF false {
  WRITE skipped.txt no
} ELSE IF true {
  WRITE fallback.txt taken
}

# !false evaluates to true, so this branch runs.
IF !false {
  WRITE negated.txt taken
}

LET $yes_body: STRING = READ yes.txt
LET $fallback_body: STRING = READ fallback.txt
LET $negated_body: STRING = READ negated.txt
ASSERT_EQ $yes_body "taken"
ASSERT_EQ $fallback_body "taken"
ASSERT_EQ $negated_body "taken"
LET $t: STRING = PATH_TYPE("skipped.txt")
ASSERT_EQ $t "absent"

Example: logical condition combination

IMPORT [STD]
LET $role: STRING = "admin"
LET $level: INT = 3

# || is true when either side holds; && needs both.
IF $role == "owner" || $level >= 5 {
    WRITE unexpected.txt no
} ELSE {
    WRITE fallback.txt or-false
}

LET $fb: STRING = READ fallback.txt
ASSERT_EQ $fb "or-false"
LET $t1: STRING = PATH_TYPE("unexpected.txt")
ASSERT_EQ $t1 "absent"

IF $role == "admin" || $level >= 5 {
    WRITE chosen.txt or-true
}

LET $ch: STRING = READ chosen.txt
ASSERT_EQ $ch "or-true"

IF $role == "admin" && $level >= 5 {
    WRITE unexpected-too.txt no
} ELSE {
    WRITE and.txt and-false
}

LET $an: STRING = READ and.txt
ASSERT_EQ $an "and-false"
LET $t2: STRING = PATH_TYPE("unexpected-too.txt")
ASSERT_EQ $t2 "absent"

SWITCH

Multi-way branch on a value or a condition list.

Syntax: SWITCH [<expr>] { CASE <expr>[, <expr> ...] { <commands> } ... [DEFAULT { <commands> }] }

Compares one discriminant against each CASE value list in order with strict == (same rule as IF conditions: numerics compare across INT and FLOAT, every other cross-type pair is unequal). The first matching arm runs exclusively: later arms never run and there is no fallthrough, so group values with commas (CASE "help", "h") instead of stacking bodies.

With no discriminant (SWITCH { ... }), each CASE carries its own boolean condition (a call counts: any expression evaluating to BOOL), and the first true arm runs. Conditions evaluate in order and stop at the first match, so later calls never run. A final DEFAULT arm runs when nothing matched; without one, no match is a no-op.

BREAK exits the SWITCH early (the remainder of the arm is skipped and an enclosing loop is unaffected); CONTINUE continues an enclosing loop; RETURN and EXIT propagate as usual.

Examples:

Example: switch on a value

# The first arm whose value list contains the discriminant
# runs; no later arm runs.
LET $cmd: STRING = "help"
SWITCH $cmd {
  CASE "help", "h" {
    WRITE chosen.txt help
  }
  CASE "summarize" {
    WRITE chosen.txt summarize
  }
  DEFAULT {
    WRITE chosen.txt fallback
  }
}

LET $body: STRING = READ chosen.txt
ASSERT_EQ $body "help"

Example: switch on conditions

# With no discriminant each CASE is its own condition;
# calls work as conditions too.
LET $n: INT = 2
SWITCH {
  CASE $n > 5 {
    WRITE band.txt high
  }
  CASE $n > 1 {
    WRITE band.txt mid
  }
  DEFAULT {
    WRITE band.txt low
  }
}

LET $band: STRING = READ band.txt
ASSERT_EQ $band "mid"

Example: break and continue inside switch

# BREAK exits the SWITCH early: the trailing FAIL
# never runs, so reaching it fails the script.
# CONTINUE passes through to the enclosing loop.
LET $items: LIST<STRING> = ["a", "skip", "b"]
FOR $item: STRING IN $items {
  SWITCH $item {
    CASE "skip" {
      CONTINUE
    }
    CASE "a" {
      ECHO saw-a
      BREAK
      FAIL "trap: BREAK must skip trailing steps"
    }
    DEFAULT {
      ECHO saw-other
    }
  }
}

ASSERT_CONTAINS stdout "saw-a"
ASSERT_CONTAINS stdout "saw-other"

Example: switch arms with nested loops

# Loops nested in arms obey the innermost rule: inner
# BREAK ends only the inner FOR, inner CONTINUE skips
# only its iteration, and the arm keeps running past both.
LET $hits: LIST<STRING> = []
SWITCH "b" {
  CASE "b" {
    FOR $o: STRING IN ["x", "y"] {
      FOR $i: INT IN [1, 2, 3] {
        IF $i == 2 {
          BREAK
        }
        LIST_APPEND $hits "b{{ $o }}{{ $i }}"
      }
    }
    LIST_APPEND $hits "b-after"
  }
  DEFAULT {
    LIST_APPEND $hits "b-wrong"
  }
}

SWITCH "c" {
  CASE "c" {
    FOR $o: STRING IN ["x", "y"] {
      FOR $i: INT IN [1, 2, 3] {
        IF $i == 2 {
          CONTINUE
        }
        LIST_APPEND $hits "c{{ $o }}{{ $i }}"
      }
    }
    LIST_APPEND $hits "c-after"
  }
  DEFAULT {
    LIST_APPEND $hits "c-wrong"
  }
}

LET $want: LIST<STRING> = ["bx1", "by1", "b-after", "cx1", "cx3", "cy1", "cy3", "c-after"]
ASSERT_EQ $hits $want

Example: overlapping arms run first match only

# Overlapping arms never both run: the first match wins,
# so order arms most specific first. There is no
# fallthrough to the next CASE; CONTINUE would continue
# an enclosing loop, not advance to the next arm.
LET $n: INT = 10
SWITCH {
  CASE $n > 1 {
    WRITE band.txt wide
  }
  CASE $n > 5 {
    WRITE band.txt narrow
  }
  DEFAULT {
    WRITE band.txt low
  }
}

LET $band: STRING = READ band.txt
ASSERT_EQ $band "wide"

Example: no fallthrough without break

# C falls through without break: this SWITCH does not.
# One value matches two arms and neither uses BREAK,
# yet only the first arm runs.
LET $hits: LIST<STRING> = []
SWITCH 1 {
  CASE 1 {
    LIST_APPEND $hits "first"
  }
  CASE 1 {
    LIST_APPEND $hits "second"
  }
  DEFAULT {
    LIST_APPEND $hits "default"
  }
}

LET $want: LIST<STRING> = ["first"]
ASSERT_EQ $hits $want

Example: continue never advances to the next arm

# 3 satisfies both CASE conditions, but only the first matching
# arm runs. CONTINUE then jumps straight to the next loop
# iteration: skipping both "small-unreached" in the arm and
# "after" in the loop body (whereas BREAK would only exit the
# SWITCH and still run "after").
IMPORT [STD]
LET $hits: LIST<STRING> = []
FOR $n: INT IN [3] {
  SWITCH {
    CASE $n < 5 {
      LIST_APPEND $hits "small"
      CONTINUE
      LIST_APPEND $hits "small-unreached"
    }
    CASE $n < 10 {
      LIST_APPEND $hits "mid"
    }
  }
  LIST_APPEND $hits "after"
}

LET $want: LIST<STRING> = ["small"]
ASSERT_EQ $hits $want

# Exactly one append ran: neither the rest of the arm
# ("small-unreached"), the also-matching second arm
# ("mid"), nor the trailing step ("after") executed.
LET $count: INT = LEN($hits)
ASSERT_EQ $count 1

Example: strict equality, not C coercion

# No C-style coercion: STRING "1" never equals INT 1.
# Numerics still compare across INT and FLOAT.
LET $hits: LIST<STRING> = []
SWITCH "1" {
  CASE 1 {
    LIST_APPEND $hits "coerced"
  }
  DEFAULT {
    LIST_APPEND $hits "no-coercion"
  }
}

SWITCH 2 {
  CASE 2.0 {
    LIST_APPEND $hits "numeric-match"
  }
  DEFAULT {
    LIST_APPEND $hits "numeric-miss"
  }
}

LET $want: LIST<STRING> = ["no-coercion", "numeric-match"]
ASSERT_EQ $hits $want

Example: later conditions never evaluate

# Each CASE without a discriminant is a call, and calls
# stop at the first true arm. PROBE writes a marker, so
# its absence proves it never ran.
IMPORT [STD]
FUNC PROBE($v: BOOL): BOOL {
  WRITE probed.txt hit
  RETURN $v
}
LET $n: INT = 2
SWITCH {
  CASE $n > 1 {
    WRITE band.txt mid
  }
  CASE PROBE(true) {
    WRITE band.txt probed
  }
  DEFAULT {
    WRITE band.txt low
  }
}

LET $band: STRING = READ band.txt
ASSERT_EQ $band "mid"
LET $t: STRING = PATH_TYPE("probed.txt")
ASSERT_EQ $t "absent"

Example: no match without default is a no-op

# No arm matches and no DEFAULT: nothing runs and nothing
# fails, so the write never happens.
IMPORT [STD]
SWITCH "zzz" {
  CASE "a" {
    WRITE picked.txt a
  }
  CASE "b" {
    WRITE picked.txt b
  }
}

LET $t: STRING = PATH_TYPE("picked.txt")
ASSERT_EQ $t "absent"

LET

Bind script-local variables.

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> }

Declares a script-local variable with an explicit type (STRING, INT, FLOAT, BOOL, PIPE, LIST, MAP, HANDLE, DURATION, PATH). Duplicate LET in the same scope frame is a redeclaration error; mutate with $var = <expr>.

Variables are usable in templates ({{ $var }}), guards, and expressions. With ASYNC, spawns a background task and stores its handle (see ASYNC). The $ sigil on the name is mandatory.

No hoisting: a variable exists only after its LET runs, in execution order. Reading $var before its LET (or after the block that declared it exits) fails with undefined variable $var. Scopes are a stack of frames and resolution walks innermost outward, so nothing pre-declares names. Function bodies read outer variables through the same walk, but their own LETs never leak out (see FUNC).

The right-hand side is always an expression — literals, lists, maps, arithmetic (+ - * / with *// binding tighter, unary -, parentheses), comparisons (< <= > >= binding tighter than == !=), logical && (tighter) and || with short-circuit, ! negation, env:KEY reads, INSPECT($var) snapshots, GLOB("*.md"), INT(x) / FLOAT(x) conversions — never a {{ ... }} template; interpolation happens in string values, not here. The one exception is pipes: LET $p: PIPE with no = and no initializer mints a fresh anonymous backend, lazily materialized at first binding, so two declarations never share a channel.

Numbers are numeric literals: 42 binds INT, 3.14 binds FLOAT. Int x Int stays INT (checked, integer division, so 7 / 2 is 3); any Float operand promotes to FLOAT. Division by zero, overflow, and non-finite results are errors. Both numeric sides compare numerically (1 == 1.0 is true); otherwise ==/!= are strict (cross-type words are unequal, so "true" == true is false) and ordering on non-numerics is a Type Error. Constant subtrees fold at parse time and dynamic arithmetic compiles to flat RPN with identical semantics.

Float equality is exact with no epsilon. Floats store decimals in binary, so a value is exact only when its reduced fraction has a power-of-2 denominator: 0.5 (1/2), 0.25 (1/4), 0.75 (3/4) are exact, while 0.1 (1/10), 0.2 (1/5), 0.3 (3/10) repeat forever in binary (like 1/3 in decimal) and truncate, so 0.1 + 0.2 == 0.3 is false (the sum is 0.30000000000000004). Rule of thumb: endings .5, .25, .75, .125, .625, .875 are exact; .1, .2, .3 and similar are approximations. Bound approximations instead of comparing them: IF $sum > 0.299999 && $sum < 0.300001.

Comparisons do not chain: a < b < c is a parse error, not (a < b) < c. Chaining would compare a BOOL against a number (a runtime Type Error in C-style parsing) or evaluate the middle term twice (Python-style chaining), so the grammar accepts exactly one comparison operator per level. Write the conjunction explicitly: $a < $b && $b < $c. The same holds for equality ($a == $b == $c is rejected).

Captured command output is a string, so convert before math: LET $total: INT = $total + INT($size_str) (INT trims ASCII whitespace; FLOAT accepts int strings and rejects non-finite).

Bare words need no quotes: LET $d: STRING = 30s binds the same string as quoted.

When the right-hand side is a synchronous command (LET $out: STRING = ECHO hi), the command runs to completion and its exact stdout bytes are captured into the variable as a string (no newline stripping; commands with no stdout capture as ""; non-UTF8 stdout is an error). Combining capture with an explicit WITH_IO [stdout=$var] is a parse error.

Coming from Bash, the capture line looks familiar but behaves strictly:

Bash output=$(...) OxDock LET $out: STRING = ...
Trailing newlines Stripped (all of them) Preserved byte-exact
Variable type Always an untyped string Declared: STRING, INT, FLOAT, ...
Math on output Implicit: $((var + 1)) Explicit: INT($out) + 1
Failing command Continues with empty output unless set -e Step fails immediately, binds nothing

LET $out: TYPE = AWAIT $var binds the background task's explicit RETURN value instead (tasks stream their stdout live, so there is no output left to capture); a task that succeeded without RETURN yields INT 0, like a process exit status.

An inline block (LET $var: TYPE = { <commands> }) runs its steps in a fresh scope and binds the nearest RETURN value, like a zero-arg function body: fallthrough without RETURN binds "", and BREAK/CONTINUE escaping the block are errors. Think IIFE: the block executes immediately where it stands and its value is the result. The block reads outer variables but its own LETs never leak out. A {k: v} shape still parses as a map literal; anything else in braces is a block.

The split is deliberate: synchronous commands capture stdout because they run inline to completion on the same thread; background tasks never capture stdout because concurrent output has no well-defined value. Task results travel only through RETURN (or INT 0 for void tasks).

LET $e: STRING = env:FOO reads the script environment into a plain string.

Examples:

Example: let

LET $name: STRING = "world"
ECHO "hello, {{ $name }}"
ASSERT_CONTAINS stdout "hello, world"

LET $items: LIST<STRING> = ["a", "b"]
ASSERT_CONTAINS $items "a"
ASSERT_CONTAINS $items "b"

LET $count: INT = 42
ASSERT_EQ $count 42

Example: bool coercion

# BOOL spellings coerce case-insensitively. Empty is
# not a boolean: absent flags state a default through
# BOOL_OR instead of converting here.
LET $t: BOOL = "TRUE"
ASSERT_EQ $t true
LET $f: BOOL = "no"
ASSERT_EQ $f false

Example: bool coercion rejects empty

# Empty never reads as false: an empty string fails
# BOOL coercion instead of picking a polarity.
ENV EMPTY_FLAG=""
LET $e: BOOL = "{{ env:EMPTY_FLAG }}"

Expected error: expected BOOL

Example: no hoisting

# Reading before the LET runs is an error, not an empty value.
ECHO $too_early
LET $too_early: STRING = "too late"

Expected error: undefined variable

Example: glob binding

# The RHS is an expression: GLOB(...) runs and binds a list.
IMPORT [STD]
WRITE a.txt "x"
LET $files: LIST<STRING> = GLOB("*.txt")
FOR $f: STRING IN $files { ECHO $f }

ASSERT_CONTAINS stdout "a.txt"

Example: scoped variable reverts

# LET inside a braced block reverts when the block exits.
LET $a: STRING = "outer"

[bool:true] {
    LET $a: STRING = "inner"
    WRITE inner.txt "{{ $a }}"
}

WRITE outer.txt "{{ $a }}"

LET $in_body: STRING = READ inner.txt
ASSERT_EQ $in_body "inner"

LET $out_body: STRING = READ outer.txt
ASSERT_EQ $out_body "outer"

Example: capture command output

# Capture keeps the trailing newline.
LET $out: STRING = ECHO hi
ASSERT_EQ $out "hi\n"

Example: inline block

LET $who: STRING = "ada"

# An inline block binds its RETURN value like a function body.
LET $res: STRING = {
    LET $loud: STRING = "{{ $who }}!"
    RETURN $loud
}
ASSERT_EQ $res "ada!"

# Any declared type works: the block value checks like any RHS.
LET $n: INT = {
    RETURN 40 + 2
}
ASSERT_EQ $n 42

Example: arithmetic over captured output

# Captured output converts explicitly: INT() then arithmetic.
IMPORT [STD]
LET $size_str: STRING = ECHO 41
LET $total: INT = INT($size_str) + 1
ASSERT_EQ $total 42

# FLOAT() promotes instead of truncating.
LET $ratio: FLOAT = 1 + 2.5
ASSERT_EQ $ratio 3.5

# Int x Int stays INT: integer division truncates.
LET $half: INT = 7 / 2
ASSERT_EQ $half 3

Example: float equality is exact

# Binary fractions compare cleanly; decimal fractions may not:
# 0.1 + 0.2 is 0.30000000000000004, so == is false.
IMPORT [STD]
LET $exact: BOOL = 0.5 + 0.25 == 0.75
LET $decimal: BOOL = 0.1 + 0.2 == 0.3
IF $exact {
    WRITE exact.txt yes
}
IF $decimal {
    WRITE unexpected.txt no
}

LET $ok: STRING = READ exact.txt
ASSERT_EQ $ok "yes"

LET $t: STRING = PATH_TYPE("unexpected.txt")
ASSERT_EQ $t "absent"

Example: bound inexact decimals

# Never test inexact decimals for equality; bound them.
LET $sum: FLOAT = 0.1 + 0.2
IF $sum > 0.299999 && $sum < 0.300001 {
    WRITE bounded.txt yes
}

LET $ok: STRING = READ bounded.txt
ASSERT_EQ $ok "yes"

Example: inspect a variable

# INSPECT($var) snapshots a variable into a MAP: declared
# type plus live details (pipe backend stats here), so
# scripts can branch on engine state.
IMPORT [STD]
LET $p: PIPE
WITH_IO [stdout=$p] ECHO hello
LET $info: MAP<ANY> = INSPECT($p)
IF $info.is_os_pipe {
    WRITE unexpected.txt "should be a script pipe"
}

ASSERT_EQ $info.type "PIPE"
LET $t: STRING = PATH_TYPE("unexpected.txt")
ASSERT_EQ $t "absent"

CONST

Bind deeply immutable script-local values.

Syntax: CONST $NAME: TYPE = <expr> | CONST $NAME: PIPE | CONST $NAME: TYPE = ASYNC { <commands> } | CONST $NAME: TYPE = <command> | CONST $NAME: TYPE = AWAIT $TASK | CONST $NAME: TYPE = { <commands> }

Declares a script-local constant with an explicit type. The right-hand side accepts every LET form (expression, capture, ASYNC, AWAIT, inline block, bare PIPE).

Immutability is deep and total: reassignment ($var = ...), LIST_APPEND, and MAP_SET/MERGE_MAPS on a CONST value all fail. Nested containers freeze with the binding, so reaching a list or map through a CONST never exposes a mutable handle. Reads use $NAME, exactly like LET reads.

CONST and LET share one namespace: declaring either twice in the same scope frame is a redeclaration error. A CONST name cannot collide with a reserved word or another binding. FUNC names live in a separate namespace and may share the spelling; only EXPORTs share one registry, so at most one of a same-named FUNC/CONST pair may be exported. Shadowing an outer binding in an inner block stays legal and the inner declaration reverts on block exit.

A file's top-level CONSTs read inside that file's own FUNC bodies: immutable file state is visible by scope, while mutable state crosses only as explicit arguments. Visibility is declaration-ordered: a call landing before the CONST executes fails instead of reading uninitialized memory. $ALIAS::NAME reads work in bodies exactly like at top level. Writes stay forbidden everywhere: a body mutating a file CONST fails with the same message as a top-level write.

CONST is the only variable binding an EXPORT can name (EXPORT CONST $NAME, EXPORT [CONST $A, $B]): LET bindings never cross the module boundary. Importers read the value as $ALIAS::NAME (see IMPORT).

Examples:

Example: const

# CONST reads through `$`, like LET.
CONST $NAME: STRING = "world"
ECHO "hello, {{ $NAME }}"
ASSERT_CONTAINS stdout "hello, world"

# Containers freeze with the binding.
CONST $ITEMS: LIST<STRING> = ["a", "b"]
ASSERT_CONTAINS {{ $ITEMS }} "a"

# File CONSTs read inside the file's own FUNCs.
CONST $GREETING: STRING = "hi"
FUNC SHOUT(): STRING {
    RETURN $GREETING
}
LET $s: STRING = SHOUT()
ASSERT_EQ $s "hi"

Example: const alias reads across modules

# Exported CONSTs cross only as alias reads, never bare.
IMPORT [STD]
WRITE lib.oxfile """
    CONST $VERSION: STRING = "1.2.3"
    CONST $BUILD: INT = 4
    EXPORT CONST $VERSION
    EXPORT [CONST $BUILD]
    """

# The entry reads the exports at top level, in math, and in templates.
WRITE main.oxfile """
    IMPORT ["lib.oxfile" AS LIB]
    LET $v: STRING = $LIB::VERSION
    ASSERT_EQ $v "1.2.3"
    LET $e: INT = $LIB::BUILD * 2
    ASSERT_EQ $e 8
    LET $w: STRING = "v\{{ $LIB::VERSION }}"
    ASSERT_EQ $w "v1.2.3"
    ECHO "export-ok \{{ $LIB::VERSION }}"
    """

# A child run proves the import from a fresh interpreter.
LET $exe: STRING = INTERPRETER()
LET $out: STRING = RUN [$exe, "main.oxfile"]
ASSERT_CONTAINS $out "export-ok 1.2.3"

Example: const alias reads inside func bodies

# Alias reads work inside importer FUNC bodies exactly like at top level.
IMPORT [STD]
WRITE lib.oxfile """
    CONST $VERSION: STRING = "1.2.3"
    EXPORT CONST $VERSION
    """

# The importer FUNCs return alias reads from expressions and templates.
WRITE main.oxfile """
    IMPORT ["lib.oxfile" AS LIB]
    FUNC SHOW(): STRING {
        RETURN $LIB::VERSION
    }
    FUNC LABELED(): STRING {
        RETURN "v\{{ $LIB::VERSION }}"
    }
    LET $s: STRING = SHOW()
    ASSERT_EQ $s "1.2.3"
    LET $t: STRING = LABELED()
    ASSERT_EQ $t "v1.2.3"
    ECHO "body-ok \{{ $LIB::VERSION }}"
    """

# A child run proves body reads from a fresh interpreter.
LET $exe: STRING = INTERPRETER()
LET $out: STRING = RUN [$exe, "main.oxfile"]
ASSERT_CONTAINS $out "body-ok 1.2.3"

Example: const rejects mutation

# SET on a CONST fails instead of rebinding.
CONST $N: INT = 1
$N = 2

Expected error: cannot mutate CONST

Example: const rejects append

# LIST_APPEND on a CONST fails instead of pushing.
CONST $ITEMS: LIST<STRING> = ["a"]
LIST_APPEND $ITEMS "b"

Expected error: cannot mutate CONST

Example: const freeze detaches from its source

# Freezing detaches: the LET source stays mutable.
LET $inner: LIST<STRING> = ["a"]
CONST $C: LIST<ANY> = [$inner]
LIST_APPEND $inner "b"
ASSERT_CONTAINS $inner "b"

# Equality ignores CONST-ness: the frozen copy equals an unfrozen twin.
LET $twin: LIST<ANY> = [["a"]]
ASSERT_EQ $C $twin

Example: const nested freeze

# Nested containers freeze with the binding.
CONST $C: LIST<ANY> = [["a"]]
LET $nested: LIST<STRING> = $C.0
LIST_APPEND $nested "b"

Expected error: cannot mutate CONST

Example: const alias shares frozenness

# Aliases share frozenness: copying a CONST never thaws it.
CONST $C: LIST<STRING> = ["a"]
LET $alias: LIST<STRING> = $C
LIST_APPEND $alias "b"

Expected error: cannot mutate CONST

Example: const map set fails

# MAP_SET on a CONST fails instead of deriving.
IMPORT [STD]
CONST $M: MAP<ANY> = {a: 1}
LET $z: MAP<ANY> = MAP_SET($M, "x", 1)

Expected error: cannot mutate CONST

Example: const merge maps fails

# MERGE_MAPS over a CONST fails instead of merging.
IMPORT [STD]
CONST $M: MAP<ANY> = {a: 1}
LET $n: MAP<ANY> = MERGE_MAPS([$M], "overwrite")

Expected error: cannot mutate CONST

MUTATION

Mutate a declared variable.

Syntax: $var = <expr>

Reassigns an existing variable, converting the new value to the type declared at LET time through the same narrow coercion pairs as declaration. Strings never parse to numbers implicitly: $n = "42" is a TypeMismatch for an INT, write $n = INT("42") instead. Expressions never convert: "100" + 1 is a Type Error, use INT() / FLOAT() to cross that boundary explicitly.

The leading $ distinguishes mutation from KEY=value command assignments. Assigning an undeclared variable or a mismatched type is an error.

Mutation writes through to the scope where the variable was declared, so it survives block exit: LET $x outside a block followed by $x = ... inside still reads back the new value afterwards, for every type. This is the counterpart to LET shadowing, where LET $x inside the block declares a separate inner variable that reverts on exit.

Reassignment rebinds the variable to a new value: values captured earlier keep the old word (see the rebinding example below).

Examples:

Example: mutate

# Mutation writes through: the binding holds the new value.
LET $count: INT = 1
$count = 2
ASSERT_EQ $count 2

Example: rebind keeps earlier captures

# Reassignment rebinds: a map built from `$s` still
# reads the original string after `$s` moves on.
LET $s: STRING = "test"
LET $m: MAP<ANY> = {a: $s}
$s = "changed"
ASSERT_EQ $m.a "test"

# Appending to one list binding never touches its clones.
LET $a: LIST<STRING> = ["1"]
LET $b: LIST<STRING> = $a
LIST_APPEND $a "2"
LET $want: LIST<STRING> = ["1"]
ASSERT_EQ $b $want

Example: convert before math

# Captured output is a string: `"100" + 1` is a Type Error.
# Convert explicitly, then mutate with arithmetic.
IMPORT [STD]
LET $raw: STRING = ECHO 100
LET $n: INT = INT($raw)
$n = $n + 1

# The declared slot stays strict: strings parse only
# through the explicit converter, never on assignment.
$n = INT("42")
ASSERT_EQ $n 42

# Same crossing for decimals via FLOAT().
LET $frac_str: STRING = ECHO 2.5
LET $f: FLOAT = FLOAT($frac_str) + 0.25
ASSERT_EQ $f 2.75

Example: reject keypath target

# Rebind the whole variable to update one entry.
IMPORT [STD]
LET $M: MAP<ANY> = {a: 1}
$M = MAP_SET($M, "a", 2)
ASSERT_EQ $M.a 2

# Key paths read in expressions but are never mutation targets.
$M.a = 3

Expected error: cannot assign to $M.a

ASYNC

Run steps in a background thread.

Syntax: ASYNC <command...> | ASYNC { <commands> } | LET $var: HANDLE<T> = ASYNC { <commands> }

Runs a command or block of commands in a background thread with subshell isolation.

Mutations (ENV, WORKDIR) stay within the block. With LET, stores a task handle for AWAIT. Task output streams live to the parent stdout; a task publishes a value with an explicit RETURN, which LET $out: TYPE = AWAIT $task binds.

WITH_IO must wrap ASYNC from the outside (LET $p: PIPE first, then WITH_IO [stdout=$p] ASYNC ...) so pipe endpoints allocate on the main thread before the worker spawns. Placing WITH_IO directly inside ASYNC is rejected at parse time.

Examples:

Example: async

# Inline and block forms both run in the background; AWAIT joins them.
ASYNC ECHO "warming-up"
LET $a: HANDLE<VOID> = ASYNC ECHO "first"
LET $b: HANDLE<VOID> = ASYNC {
    ECHO "second"
}
AWAIT $a
AWAIT $b
ASSERT_CONTAINS stdout "first"
ASSERT_CONTAINS stdout "second"

Example: async task handle

LET $task: HANDLE<VOID> = ASYNC {
    ECHO "built"
}
AWAIT $task
ASSERT_CONTAINS stdout "built"

AWAIT

Join a background task.

Syntax: AWAIT $var | LET $out: STRING = AWAIT $var

Blocks until the named task completes. Propagates errors if the task failed.

Task output streams live during the run; joining binds nothing by itself. LET $out: TYPE = AWAIT $var binds the task's explicit RETURN value instead, or INT 0 when the task succeeded without one (add RETURN <expr> to the task body to yield a value).

Examples:

Example: await

LET $task: HANDLE<VOID> = ASYNC ECHO "done"
AWAIT $task
ASSERT_CONTAINS stdout "done"

Example: await capture

LET $task: HANDLE<STRING> = ASYNC {
    ECHO "logged"
    RETURN "returned"
}

# AWAIT binds the RETURN value, not the streamed output.
LET $out: STRING = AWAIT $task
ASSERT_EQ $out "returned"

CANCEL

Synchronously cancel a background task.

Syntax: CANCEL $var

Kills the named background task spawned via LET $var: HANDLE<T> = ASYNC ....

Blocking: returns only after the task thread has been joined and its OS process reaped, so no residual filesystem or stream mutation follows. A later AWAIT $var reports cancellation. Only named tasks can be cancelled.

Examples:

Example: cancel

LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
CANCEL $task

Example: await after cancel reports cancellation

# A cancelled task stays cancelled: joining it reports.
LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
CANCEL $task
AWAIT $task

Expected error: was cancelled

TIMEOUT

Enforce an execution deadline.

Syntax: TIMEOUT <duration> <command...> | TIMEOUT <duration> { <commands> } | TIMEOUT <duration> AWAIT $var

Aborts the wrapped step or block with a deadline error if it exceeds the duration (e.g. 500ms, 10s, 2m; a bare number means seconds).

A blocking foreground process is killed.

ASYNC nests in either order with order-dependent deadline semantics: LET $task: HANDLE<VOID> = ASYNC TIMEOUT 30s RUN "build" enforces the deadline inside the background thread (a later AWAIT $task surfaces the TIMEOUT error), while TIMEOUT 30s AWAIT $task preempts a hung task from the awaiting side.

Examples:

Example: timeout

TIMEOUT 30s WRITE heartbeat.txt alive
LET $beat: STRING = READ heartbeat.txt
ASSERT_EQ $beat "alive"

Example: timeout block

TIMEOUT 30s {
    WRITE a.txt one
    WRITE b.txt two
}
LET $a: STRING = READ a.txt
LET $b: STRING = READ b.txt
ASSERT_EQ $a "one"
ASSERT_EQ $b "two"

Example: deadline aborts the step

# 50ms expires long before the sleep does: the step dies
# with a deadline error instead of running out the clock.
TIMEOUT 50ms SLEEP 30s

Expected error: TIMEOUT after

Example: timeout variable duration

# Durations resolve at runtime, so variables work too.
LET $budget: DURATION = "30s"
TIMEOUT $budget WRITE heartbeat.txt alive

LET $beat: STRING = READ heartbeat.txt
ASSERT_EQ $beat "alive"

Example: timeout await

# AWAIT form bounds a task join instead of a step.
LET $quick: HANDLE<VOID> = ASYNC {
    ECHO hi
}
TIMEOUT 30s AWAIT $quick

FAIL

Print a failure message and exit.

Syntax: FAIL [<code>] [<message>] [{ <commands> }]

Prints the message to stderr (the ECHO plus EXIT idiom as one step, rerouted to the error stream), runs the optional block first, then exits through the EXIT path with EXIT requested with code <code>.

With no code the exit code is 1; with a code it clamps to 0..=255 like EXIT. The block runs first in a child scope that reads caller locals, with its stdout rerouted to stderr, so usage text, cleanup, and callee output all land on the error stream while stdout stays empty: the only form a FUNC cannot express, since functions take values, never blocks. At least one of message or block is required.

A lone bare int is a silent code (FAIL 2 exits 2 with no output); quoting decides, so FAIL "2" prints 2 and exits 1.

Output: Stderr

Examples:

Example: fail

# The message prints to stderr, never stdout, so a
# failure cannot pollute captured output. No code
# means exit 1.
FAIL "cargo not found in image"

Expected error: EXIT requested with code 1

Example: fail code

# An explicit code exits with that code (clamped to
# 0..=255 like EXIT); the message still prints to
# stderr.
FAIL 2 "cargo not found in image"

Expected error: EXIT requested with code 2

Example: fail block

# The block runs first with its stdout rerouted to
# stderr: usage text and cleanup land on the error
# stream beside the message, and stdout stays empty.
# Callee output reroutes too: a FUNC called here
# inherits the swapped handle.
FAIL "unknown command" {
    ECHO usage-text
}

Expected error: EXIT requested with code 1

ISOLATED

Run steps with the seeded script environment.

Syntax: ISOLATED { INHERIT_ENV [...] <commands> } | ISOLATED <command...>

Resets the script environment for the block to the session seed: spawned children see the sandbox defaults plus names the block re-adds through its leading INHERIT_ENV.

The allowlist resolves against the outer scope, never the host. Absent names stay absent silently, matching top-level INHERIT_ENV.

Script variables, pipes, and files flow through untouched; only env: is reset. Files share the session workspace: blocks selecting the same WORKSPACE target resolve to the same directory with no per-block overlay, so one block's writes are visible to another.

Blocks nest (each level re-seeds from the same seed, so nesting only narrows through the allowlists) and combine with ASYNC and FUNC. Scope exit restores the prior environment.

Examples:

Example: isolated scope

# The block sees a clean env; plain steps still run and
# outer bindings survive untouched.
ENV MODE=outer
ISOLATED {
    ENV MODE=inner
    WRITE inner.txt "{{ env:MODE }}"
}
LET $back: STRING = "{{ env:MODE }}"
ASSERT_EQ $back "outer"
LET $body: STRING = READ inner.txt
ASSERT_EQ $body "inner"

Example: reseeded child env

# The block resets to the session seed: plain steps and
# spawns run with zero prelude. PATH needs no
# declaration: contract seed rows are always admitted.
WRITE top-path.txt "{{ env:PATH }}"
ISOLATED {
    WRITE inner-path.txt "{{ env:PATH }}"
    RUN "echo seed-ok"
}
LET $top: STRING = READ top-path.txt
LET $inner: STRING = READ inner-path.txt
ASSERT_EQ $inner $top
ASSERT_CONTAINS stdout "seed-ok"

Example: outer customs stay out

# Outer customs never enter the block: without an
# allowlist entry the static gate rejects the read
# before the first step runs.
ENV OUTER_CUSTOM=outer-val
ISOLATED {
    WRITE inner-custom.txt "{{ env:OUTER_CUSTOM }}"
}

Expected error: env:OUTER_CUSTOM

Example: absent names stay absent

# Listing a name the outer scope lacks is not an error:
# the block simply runs without it.
ISOLATED {
    INHERIT_ENV [OXDOC_DEFINITELY_ABSENT_12345]
    ECHO still-runs
}
ASSERT_CONTAINS stdout "still-runs"

Example: nesting narrows

# Each level snapshots the already-scrubbed parent, so
# an inner block cannot recover what the outer dropped.
ENV KEEP=yes
ISOLATED {
    INHERIT_ENV [KEEP]
    ISOLATED {
        ENV KEEP=inner
        WRITE deep.txt "{{ env:KEEP }}"
    }
    LET $mid: STRING = "{{ env:KEEP }}"
    ASSERT_EQ $mid "yes"
}
LET $deep: STRING = READ deep.txt
ASSERT_EQ $deep "inner"

REMOTE

Run a sealed block on a remote target.

Syntax: REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }

Runs the braced block on the named remote target, which the host binds at startup (--remote). The block is sealed: only header-listed $var and env:NAME entries cross, the guest starts empty, and results return through declared transfers or WITH_IO pipes.

The target is a static literal, never a variable. Unknown targets fail before execution starts.

Bodies check twice: the host static pass validates the body before anything ships, and the guest re-validates on arrival through the same entry point, so a body type error fails locally, never mid-run on the remote.

A failing guest fails the host step: EXIT in the body exits the guest, and the host relays the code to its own process exit status (see EXIT).

Examples:

Example: sealed header values cross, outer scope does not

# Only header-listed names arrive: `$version` is visible
# on the guest, `$secret` was never sent.
LET $version: STRING = "1.2.3"
LET $secret: STRING = "host-only"
REMOTE prod [$version] {
    WRITE version.txt "{{ $version }}"
    COPY --to-host ./version.txt back.txt
}

# The pushed file proves the guest saw the injected value.
LET $back: STRING = READ back.txt
ASSERT_EQ $back "1.2.3"

Example: background tasks stream through shared pipes

# Two background REMOTEs share one capture pipe while a
# WITH_IO block holds the write end open.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    LET $a: HANDLE<VOID> = ASYNC REMOTE prod {
        ECHO "from-a"
    }
    LET $b: HANDLE<VOID> = ASYNC REMOTE prod {
        ECHO "from-b"
    }
    AWAIT $a
    AWAIT $b
}

# EOF ends the drain: no sentinel line, no baked-in count.
LET $n: INT = 0
WHILE !EOF($cap) {
    WITH_IO [stdin=$cap] READ_LINE $line
    $n = $n + 1
}
ASSERT_EQ $n 2

Example: declared files cross both directions

# Fetches ride in, pushes ride back. Anything undeclared
# never leaves its side.
WRITE send.txt "payload"
REMOTE prod {
    COPY --from-host ./send.txt got.txt
    LET $v: STRING = READ got.txt
    ASSERT_EQ $v "payload"
    WRITE back.txt "returned"
    COPY --to-host ./back.txt back.txt
}

# The push landed on the host; guest staging is gone.
LET $b: STRING = READ back.txt
ASSERT_EQ $b "returned"

Example: guest workspace selection stays on the guest

# WORKSPACE switches inside the block resolve against the
# guest staging dir, which serves as both the SNAPSHOT
# root and the LOCAL build context. The host selection
# restores when the block exits.
REMOTE prod {
    WORKSPACE SNAPSHOT
    WRITE out.txt "from-snapshot"
    COPY --to-host ./out.txt snap.txt
}

LET $s: STRING = READ snap.txt
ASSERT_EQ $s "from-snapshot"

Example: guest cache persists across execs

# WORKSPACE CACHE addresses guest-local persistent
# storage: the second block reads what the first wrote,
# while the guest staging starts empty every time.
REMOTE prod {
    WORKSPACE CACHE
    WRITE marker.txt "run-marker"
}
REMOTE prod {
    WORKSPACE CACHE
    LET $m: STRING = READ marker.txt
    ASSERT_EQ $m "run-marker"
}

Example: pushes outside staging fail closed

# WORKSPACE SYSTEM exposes the whole guest machine, but
# transfers stay staging scoped: a push source outside
# staging fails loudly instead of crossing.
REMOTE prod {
    WORKSPACE SYSTEM
    COPY --to-host /no/such/file.txt got.txt
}

Expected error: escapes staging

Example: guest exit fails the step, host survives

# EXIT in the body exits the guest with code 3. The
# host is unaffected: it keeps executing after the
# guest is already dead, and the failure surfaces as
# a host step error carrying the same code. The CLI
# then exits with it, so the guest code reaches the OS.
LET $t: HANDLE<VOID> = ASYNC REMOTE prod {
    EXIT 3
}
WRITE host-alive.txt "still here"
AWAIT $t

Expected error: REMOTE 'prod' exited with code 3

Example: remote block without a runner

# Without a bound session, the block bails instead of
# executing anywhere unexpected.
REMOTE prod {
    ECHO "do something on remote"
}

Expected error: has no registered session

FUNC

Define a user function.

Syntax: FUNC NAME([$param: TYPE, ...]): RET { <commands> } | ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }

Defines a user function with UPPERCASE name and explicitly typed parameters. FUNC runs synchronously; ASYNC FUNC is the same with a structural guarantee: the declaration must be HANDLE<T>, so every RETURN hands out a task handle.

Params bind by position, converting each argument to its declared parameter type before the body runs. A trailing $name?: TYPE marks an optional param: callers may omit trailing optionals, which fill with zero values (false, "", 0, 0.0, [], {}) before the body binds. A required param after an optional one fails at definition, and an optional param with no zero value (records with required fields, unions, handles, custom types) fails at definition naming the fix: drop the ? or pass the argument explicitly. Bodies run isolated: a fresh variable scope plus the callee definition-site jail (workspace, cwd, and env reset; only explicit arguments cross, #322). Module bodies restore the workspace selection and cwd their own top-level left behind, so a lib declaring WORKSPACE at the top serves its FUNCs from there no matter which workspace the caller sits in; entry bodies restore the workspace selection and cwd sealed at their definition site (defaulting to the snapshot jail when none was set before definition). A FUNC-level WORKSPACE or WORKDIR statement overrides the file default for that call, and the caller context returns on every exit path. Conditional top-level configuration uses guards ([env:FLAG] WORKSPACE LOCAL): IF bodies unwind on exit and never become the jail; see IMPORT. LETs inside do not leak. A nested FUNC definition is scoped to its block and reverts on exit. Names share one namespace with native and host-registered functions, which a FUNC may never shadow.

Functions resolve like variables: a name is visible from its definition line, so recursion works but mutual recursion does not (the second name does not exist while the first body lowers). Calls name their module (STD::GLOB(...)) unless imported; see IMPORT.

Invoke any function with one syntax: NAME(...) as a statement (discarding the value) or LET $var: TYPE = NAME(...) to capture the RETURN value (fallthrough without RETURN is a static error unless RET is VOID).

ASYNC FUNC does not spawn on call. The body runs synchronously on the caller thread up to its inner ASYNC step, which spawns the background task and yields its handle immediately; the function then hands that handle out with RETURN $t. The caller joins it separately with AWAIT.

Examples:

Example: func def call

FUNC GREET($name: STRING): STRING {
  RETURN $name
}

LET $res: STRING = GREET("ada")
ASSERT_EQ $res "ada"

# Statement form: parens stay, the value drops.
GREET("bex")

Example: bind then interpolate

# Script FUNCs run as steps, never inside {{ }}.
FUNC GREET($name: STRING): STRING {
  RETURN $name
}

# Call as a step to capture the RETURN.
LET $res: STRING = GREET("ada")

# {{ }} reads the bound var.
LET $msg: STRING = "says {{ $res }}"

ASSERT_EQ $msg "says ada"

Example: script funcs never resolve in placeholders

# Placeholders carry no step context: pure registry only.
FUNC GREET($name: STRING): STRING {
  RETURN $name
}

# Bind the argument as a step var to keep quoting flat.
LET $who: STRING = "ada"

# This fails naming the pure-only boundary.
ECHO "{{ SCRIPT::GREET($who) }}"

Expected error: placeholder function 'SCRIPT::GREET' is a script function

Example: optional params fill zero values

IMPORT [STD]
# Trailing `?` params may be omitted; they fill with
# zero values (false, empty map) before the body binds,
# so plain IF works on an omitted BOOL.
FUNC ENSURE($check?: BOOL, $opts?: MAP<mode?: STRING>): STRING {
    IF $check {
        RETURN "checked"
    }
    IF HAS_KEY($opts, "mode") {
        RETURN "opts"
    }
    RETURN "plain"
}
LET $a: STRING = ENSURE()
ASSERT_EQ $a "plain"
LET $b: STRING = ENSURE(true)
ASSERT_EQ $b "checked"
LET $opts: MAP<mode?: STRING> = PARSE_JSON("{\"mode\": \"fast\"}")
LET $c: STRING = ENSURE(false, $opts)
ASSERT_EQ $c "opts"

Example: optional params must trail

# A required param after an optional one fails at definition.
FUNC BAD($a?: STRING, $b: STRING): STRING {
    RETURN $b
}

Expected error: optional ? params must be trailing

Example: async func is a handle guarantee

# Side by side: identical bodies, identical handling. The
# ASYNC marker only guarantees the HANDLE declaration.
ASYNC FUNC FETCH(): HANDLE<STRING> {
  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
  RETURN $t
}
FUNC MAKE(): HANDLE<STRING> {
  LET $t: HANDLE<STRING> = ASYNC { RETURN "hi" }
  RETURN $t
}

# Both run synchronously to RETURN; the inner ASYNC spawns.
LET $a: HANDLE<STRING> = FETCH()
LET $b: HANDLE<STRING> = MAKE()
LET $x: STRING = AWAIT $a
LET $y: STRING = AWAIT $b
ASSERT_EQ $x "hi"
ASSERT_EQ $y "hi"

Example: call with pipes

# A pipe handle travels into a function as a typed argument
# and is usable as a binding target in both directions.
# `LET $p: PIPE` mints the handle; `$p` passes it on.
FUNC DRAIN($q: PIPE): STRING {
  WITH_IO [stdin=$q] READ_LINE $line
  RETURN $line
}

LET $p: PIPE
WITH_IO [stdout=$p] ECHO "payload"

LET $got: STRING = DRAIN($p)
ASSERT_EQ $got "payload"

RETURN

Return a value from a function, task, or inline block.

Syntax: RETURN [<expr>]

Ends the nearest enclosing boundary with a value: a function call, an ASYNC task (bound by LET $out: STRING = AWAIT $t), or an inline LET block. Bare RETURN with no expression yields "".

Falling off the end without RETURN yields "". RETURN with no enclosing boundary (including at top level) is an error; use EXIT or ECHO there.

Examples:

Example: return

FUNC PICK($flag: BOOL): STRING {
  IF $flag {
    RETURN "yes"
  }
  RETURN "no"
}

LET $res: STRING = PICK(true)
ASSERT_EQ $res "yes"

# Fallthrough without RETURN yields its own value.
LET $no: STRING = PICK(false)
ASSERT_EQ $no "no"

WHILE

Loop while a condition holds.

Syntax: WHILE <bool-expr> { <commands> }

Re-evaluates a Bool condition each iteration (same is_truthy rule as IF; non-Bool is a type error).

Each iteration runs in a fresh scope; mutate outer state with $var = ... so the next check observes it. BREAK exits the loop; CONTINUE skips to the next check.

Examples:

Example: while loop

# The condition re-evaluates every iteration: three passes, then stop.
LET $n: INT = 0
WHILE $n < 3 {
  WRITE tick.txt "{{ $n }}"
  $n = $n + 1
}

ASSERT_EQ $n 3
LET $tick: STRING = READ tick.txt
ASSERT_EQ $tick "2"

BREAK

Exit the innermost loop.

Syntax: BREAK

Exits the innermost enclosing FOR or WHILE loop.

BREAK outside a loop, or across a FUNC or ASYNC boundary, is an error.

Examples:

Example: break

# BREAK leaves after the first pass: only "a" is written.
FOR $x: STRING IN ["a", "b"] {
  WRITE picked.txt "{{ $x }}"
  BREAK
}

LET $body: STRING = READ picked.txt
ASSERT_EQ $body "a"

Example: break nested

# Inner BREAK exits only the inner loop: the outer runs
# both passes, and each inner stops before 2.
LET $hits: LIST<STRING> = []
FOR $o: STRING IN ["x", "y"] {
  FOR $i: INT IN [1, 2, 3] {
    IF $i == 2 {
      BREAK
    }
    LIST_APPEND $hits "{{ $o }}{{ $i }}"
  }
}

LET $want: LIST<STRING> = ["x1", "y1"]
ASSERT_EQ $hits $want

CONTINUE

Skip to the next loop iteration.

Syntax: CONTINUE

Skips the rest of the innermost enclosing FOR or WHILE body and starts the next iteration.

CONTINUE outside a loop, or across a FUNC or ASYNC boundary, is an error.

Examples:

Example: continue

# CONTINUE skips the write on "a": only "b" lands.
FOR $x: STRING IN ["a", "b"] {
  IF $x == "a" {
    CONTINUE
  }
  WRITE picked.txt "{{ $x }}"
}

LET $body: STRING = READ picked.txt
ASSERT_EQ $body "b"

Example: continue nested

# Inner CONTINUE skips only the inner 2: the outer runs
# both passes, and each inner still reaches 3.
LET $hits: LIST<STRING> = []
FOR $o: STRING IN ["x", "y"] {
  FOR $i: INT IN [1, 2, 3] {
    IF $i == 2 {
      CONTINUE
    }
    LIST_APPEND $hits "{{ $o }}{{ $i }}"
  }
}

LET $want: LIST<STRING> = ["x1", "x3", "y1", "y3"]
ASSERT_EQ $hits $want

IMPORT

Bring module functions into bare-call scope; import script files and types.

Syntax: IMPORT [<module>, ...] | IMPORT <module> | IMPORT ["<path>" AS <ALIAS>] | IMPORT [<module | "<path>" AS <ALIAS> | [F, ... FROM ("<path>" | <module>) (AS <ALIAS>)?]>, ...]

Bare calls:

  • Every call names its module (STD::GLOB(...)) unless the module is imported. IMPORT [STD] lets the rest of the scope call GLOB(...) bare.
  • Calls resolve at parse time: SCRIPT definitions first, then imported modules. Unknown modules, unknown functions, and unimported bare calls are parse errors, never runtime surprises.

Scope:

  • A file or harvest IMPORT applies from its line to the enclosing block exit, then unwinds like LET scoping: reads inside the block resolve, reads past it fail closed. Top-level imports persist for the unit. Module-only imports (IMPORT [STD]) register names with no step and no scope.
  • An IMPORT that never executes leaves its alias unknown: reads must follow the import in execution order.
  • Guards gate execution: a guarded IMPORT runs only where its guard holds. Same-frame duplicates reject at parse unless every entry is guard-gated; all-guarded duplicates resolve per platform when their guards are disjoint, and fail ambiguous on overlap.
  • Two imported modules exporting one name is an ambiguity error: qualify the call instead.

File imports:

  • Form: IMPORT ["./lib.oxdock" AS LIB] (any file extension). The alias is mandatory and becomes the namespace (LIB::FOO), with no filename inference.
  • Only EXPORTed top-level FUNCs cross the boundary. Unexported means private; variables are never exportable.
  • Types cross qualified: a whole-file import exposes every exported alias as ALIAS::NAME only (LET $p: LIB::PERSON after IMPORT ["./lib.oxfile" AS LIB]), mirroring func views. Nothing bare leaks from an aliased import, so same-named types in different files coexist; harvests below stay the explicit way to request a bare name.
  • Each file initializes once; every alias shares the module's top-level bindings.
  • The file must exist when the run starts. Generated imports are rejected before the first step.

Mixed brackets:

  • Brackets mix both kinds across lines if needed (IMPORT [STD, "a.oxdock" AS A]). Each module entry registers in order; each file entry runs in order.
  • Without an alias a file entry is a parse error.
  • Value positions (LET, ASYNC, WITH_IO/TIMEOUT inners) take exactly one file entry and no modules.

Selective harvests:

  • Form: IMPORT [FOO FROM "x.oxdock"], optionally AS ALIAS. Only the named top-level functions register, bare or namespaced under the alias. Harvested names must be EXPORTed.
  • Single name needs no inner brackets (IMPORT [FOO FROM "x.oxdock"]); several names from one file combine in one bracket with explicit kinds (IMPORT [TYPE A, TYPE B FROM "x.oxdock"], file or host alike: IMPORT [FUNC FOO, FUNC BAR FROM "x.oxdock"]). Bare names always read as modules, so a bare multi-name fails naming the explicit-kind fix. Prefer one import per file over grouping harvests.
  • Types and functions combine in one entry (IMPORT [TYPE PERSON, FUNC FOO FROM "x.oxdock"]). Harvested types must be EXPORT TYPEd. Unaliased harvests persist bare globally (collision-checked), so FUNC signatures keep working; aliased harvests persist qualified-only, like whole-file imports.
  • The file body never executes, so harvesting is side-effect free. The file's own nested imports still load. Harvests produce no value and never appear in value positions.

Host library types:

  • Form: IMPORT [TYPE PIPE FROM STD]. The import validates the type resolves globally and records no file. Host types stay global with or without the harvest; the explicit form only documents the dependency and fails fast on typos.
  • Bare FROM names a library; quoted FROM names a file path. Quoted FROM "STD" still parses for backcompat, but bare is preferred.

Paths:

  • Workspace-side, against the importing file's directory (entry parent at top level; off-workspace entries resolve like stdin against the root).
  • Relative operation paths resolve against the defining file's own jail: each module top-level runs isolated in the snapshot jail, and its WORKSPACE and WORKDIR statements establish the context its FUNCs restore on every call (#322).
  • Missing files fail before the first step runs. Write-then-import in one script is rejected; check libraries into the tree, or combine them at runtime and run a child interpreter (see the child run examples below).

Module rules (every file import is a module):

  • Context: never inherits the caller's namespace. Env resets to the seed plus the module init's own contributions (declared INHERIT_ENV names re-read from the host on every call). Workspace selection and cwd reset to the module top-level jail: the init body runs isolated in the snapshot jail, and the selection plus cwd it leaves behind become the default every FUNC of that file restores on entry, unless the FUNC body overrides them. A module function needing the caller directory takes it as a path argument.
  • Determinism: behavior is a pure function of the file. The same file behaves identically no matter who imports it or which workspace the importer sits in.
  • State: one init per file, shared by every alias. Top-level LET bindings drain into a single store visible to all of the module's functions.
  • Workspace: WORKSPACE and WORKDIR at a module top-level establish that module's jail for its FUNCs; WORKSPACE and WORKDIR inside a FUNC body override the file default for that call. Caller and callee selections never leak across the call in either direction.
  • Conditional top-level: IF bodies unwind on exit, so a WORKSPACE inside one never becomes the jail. Guard-gated steps ([env:FLAG]) run in place, so they persist: use guards for conditional config.
  • Exports: only EXPORTed top-level FUNCs and EXPORT TYPE aliases cross. Variables never cross.
  • Imports: whole-file or harvest, only exported functions and types cross. Stateful harvests are rejected (import the file to share its module). Nested imports load automatically.
  • Cycles: circular imports and depth over 32 fail before the first step runs.

Exports and tools:

  • EXPORT marks top-level FUNCs as externally callable (EXPORT FOO, EXPORT [FOO, BAR]) and as the file importable interface. Re-exports promote an import (IMPORT ["x.oxdock" AS A] then EXPORT A::FOO).
  • EXPORT TYPE marks aliases the same way (EXPORT TYPE PERSON, EXPORT TYPE [A, B], mixed EXPORT [TYPE A, FUNC B]). Only exported aliases cross, so FUNC signatures survive imports.
  • Serving resolves re-exports through the registry; unexported names fail tool setup instead of serving a dead tool. The MCP server skips TYPE exports when building tools while still resolving imported types for signatures. Single-file scope otherwise; see the MCP host for consumption.

Examples:

Example: import

# Calls name their module (STD::GLOB); IMPORT [STD] drops the prefix.
WRITE a.txt "hi \{{ env:WHO }}!"
IMPORT [STD]
FOR $x: STRING IN GLOB("*.txt") { EXPAND $x WHO=World }
ASSERT_CONTAINS stdout "hi World!"

Example: module top-level jail

# A module top-level establishes its own jail: the lib
# selects WORKSPACE LOCAL and a WORKDIR up front, and
# its FUNC restores both on entry while the entry sits
# elsewhere. Unified roots: the child inherits one
# workspace, so parent and child see the same files.
IMPORT [STD]
WRITE lib.oxfile """
    IMPORT [STD]
    WORKSPACE LOCAL
    MKDIR modsub
    WORKDIR modsub
    EXPORT [FUNC WHERE]
    FUNC WHERE(): STRING {
        LET $c: STRING = CWD()
        RETURN $c
    }
    """
WRITE main.oxfile """
    IMPORT [STD, "lib.oxfile" AS LIB]
    MKDIR entry-sub
    WORKDIR entry-sub
    LET $caller: STRING = CWD()
    LET $callee: STRING = LIB::WHERE()
    ASSERT_NE $caller $callee
    LET $base: STRING = STD::PATH_BASE($callee)
    ECHO "base \{{ $base }}"
    """
LET $exe: STRING = INTERPRETER()
LET $out: STRING = RUN [$exe, "main.oxfile"]
ASSERT_CONTAINS $out "base modsub"

Example: blocks unwind, guards persist

# Blocks unwind on exit: the WORKDIR inside IF reverts,
# so it never becomes a module jail. Bare guarded blocks
# unwind the same way. Guards only skip, never push a
# scope, so a guard-gated step persists.
IMPORT [STD]
WORKSPACE LOCAL
LET $root: STRING = CWD()
LET $go: BOOL = true
IF $go {
    MKDIR inner
    WORKDIR inner
}
LET $after_if: STRING = CWD()
ASSERT_EQ $root $after_if
[bool:true] WORKDIR inner
LET $after_guard: STRING = CWD()
ASSERT_NE $root $after_guard
MKDIR bare
[bool:true] {
    WORKDIR bare
}
LET $after_bare: STRING = CWD()
ASSERT_EQ $after_guard $after_bare

Example: import missing file fails upfront

# Generated imports are rejected: a file that does not
# exist when the run starts cannot be analyzed, so the
# import fails before the first step runs.
WORKSPACE LOCAL
WRITE lib.oxdock 'FUNC F($x: STRING): STRING { RETURN $x } EXPORT F'
IMPORT ["lib.oxdock" AS LIB]

Expected error: must exist when the run starts

Example: import missing alias fails

# A file entry without AS is a parse error.
IMPORT ["./lib.oxdock"]

Expected error: mandatory alias

Example: module cannot export a variable

# Only top-level FUNCs are exportable, never variables.
LET $FOO: STRING = "x"
EXPORT FOO

Expected error: does not match any top-level FUNC

Example: import re-export unknown alias fails

# Re-exports name a visible import alias.
IMPORT ["x.oxdock" AS A]
EXPORT NOSUCH::FOO

Expected error: does not match any top-level FUNC

Example: export type aliases

# TYPE aliases declare shapes once; EXPORT TYPE shares
# them so importing files can use the same spelling.
TYPE PERSON = MAP<name: STRING>

FUNC GREET($p: PERSON): STRING {
    RETURN "hi {{ $p.name }}"
}
EXPORT GREET
EXPORT TYPE PERSON

LET $p: PERSON = {name: "Ada"}
LET $greeting: STRING = GREET($p)
ASSERT_EQ $greeting "hi Ada"

Example: import type from library

# One bracket mixes entry kinds: STD brings functions bare,
# each harvest names a type. Types resolve globally with
# or without the harvests; the explicit form only documents
# the dependency, so this grouping is example only. Bare
# FROM names a library; quoted FROM names a file path.
IMPORT [STD, [TYPE PIPE FROM STD], [TYPE DURATION FROM STD]]

LET $p: PIPE
WITH_IO [stdout=$p] ECHO hello
WITH_IO [stdin=$p] READ_LINE $line
ASSERT_EQ $line "hello"

LET $d: DURATION = "5s"
LET $files: LIST<STRING> = GLOB("*.oxdock")

Example: run rendered modules in a child

# Dynamic assembly with files: the parent writes a
# library and an entry script, then runs the entry in a
# fresh interpreter. Child-side {{ }} stays escaped so
# the parent does not interpolate it while writing. The
# child runs by path so entry-relative IMPORT resolves.
# Unified roots: the child inherits one workspace, so
# parent and child see the same files.
IMPORT [STD]
WRITE lib.oxfile """
    FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
    EXPORT GREET
    """
WRITE main.oxfile """
    IMPORT ["lib.oxfile" AS LIB]
    LET $g: STRING = LIB::GREET("Ada")
    ECHO "says \{{ $g }}"
    """
LET $exe: STRING = INTERPRETER()
LET $out: STRING = RUN [$exe, "main.oxfile"]
ASSERT_CONTAINS $out "says hi Ada"

Example: dynamic module assembly

# A function that assembles a module: MAKE_GREETER bakes
# its argument into a generated file with a bare {{ }},
# then a child run imports the result. Bare {{ }} injects
# parent values at write time; escaped \{{ }} survives for
# the child to interpolate. Bind imported calls with LET:
# {{ }} placeholders resolve pure functions only.
IMPORT [STD]

# The renderer: parent values land in the module source.
FUNC MAKE_GREETER($who: STRING): STRING {
    WRITE greeter.oxfile """
        FUNC GREET(): STRING { RETURN "hi {{ $who }}" }
        EXPORT GREET
        """
    RETURN "greeter.oxfile"
}

# The entry: imports the rendered module by its path.
WRITE main.oxfile """
    IMPORT ["greeter.oxfile" AS G]
    LET $g: STRING = G::GREET()
    ECHO "says \{{ $g }}"
    """

# Assemble, then run the entry in a fresh interpreter.
LET $made: STRING = MAKE_GREETER("Ada")
ASSERT_EQ $made "greeter.oxfile"
LET $exe: STRING = INTERPRETER()
LET $out: STRING = RUN [$exe, "main.oxfile"]
ASSERT_CONTAINS $out "says hi Ada"

Example: export unknown type fails

# Only declared TYPE aliases are exportable.
TYPE PERSON = MAP<name: STRING>
EXPORT TYPE ANIMAL

Expected error: does not match any top-level TYPE

Example: undeclared type fails

# TYPE names must be declared before use.
LET $p: PERSON = {name: "Ada"}

Expected error: unknown type

WORKDIR

Change the working directory.

Syntax: WORKDIR <path>

Sets the current working directory.

Relative paths resolve against the current directory; / resets to the workspace root. Paths cannot escape the workspace.

Arguments:

Name Type Required Description
path PATH yes Directory to change to

Examples:

Example: change working directory

# Later relative paths resolve under the new directory.
WORKDIR project/src
WRITE generated.txt generated-under-workdir

LET $body: STRING = READ generated.txt
ASSERT_EQ $body "generated-under-workdir"

Example: workdir in a scoped block

# The block reverts to the starting directory on exit.
IMPORT [STD]
LET $outside: STRING = CWD()
MKDIR project

[bool:true] {
    WORKDIR project
    WRITE inner.txt inner
}

LET $back: STRING = CWD()
ASSERT_EQ $back $outside
LET $body: STRING = READ project/inner.txt
ASSERT_EQ $body "inner"

WORKSPACE

Switch workspace roots.

Syntax: WORKSPACE (SNAPSHOT|LOCAL|CACHE|SYSTEM) [--local]

Switches the workspace root. The selection reverts at scope exit like WORKDIR.

  • SNAPSHOT: the materialized build snapshot (the default). One session-shared directory: every selection resolves to it, in any block.
  • LOCAL: the local workspace directory.
  • CACHE: a persistent per-project directory shared across runs, never evicted. It lives under the OS user cache (OXDOCK_CACHE_DIR pins an exact directory); WORKSPACE CACHE --local keeps it in <project>/.cache/workspace instead.
  • SYSTEM: full filesystem access. Scripts using it are not hermetic.

Arguments:

Name Type Required Description
target SNAPSHOT|LOCAL|CACHE|SYSTEM yes Target root

Flags:

Flag Type Description
--local BOOL Use the project-local cache directory instead of the OS user cache (CACHE only)

Examples:

Example: switch roots

IMPORT [STD]
WORKSPACE LOCAL

LET $t: STRING = PATH_TYPE(".")
ASSERT_EQ $t "dir"

Example: workspace cache in a scoped block

[bool:true] {
    WORKSPACE CACHE
    WRITE cached.txt cached-content
}

COPY --from-workspace CACHE cached.txt restored.txt
LET $body: STRING = READ restored.txt
ASSERT_EQ $body "cached-content"

ENV

Set an environment variable.

Syntax: ENV KEY=value

Inserts or updates an env var.

The value uses the unified string-value rules shared by every command: "..." or '...' quotes keep exact bytes (spaces, tabs), a lone $var evaluates that variable, {{ ... }} placeholders interpolate, unquoted words join with single spaces, and the first = splits key from value (KEY=a=b stores a=b).

A $var inside larger text stays literal — write {{ $var }} to interpolate there.

Arguments:

Name Type Required Description
assignment STRING yes KEY=value pair; the value resolves as STRING

Examples:

Example: set env

ENV APP_MODE=production
LET $mode: STRING = env:APP_MODE
ASSERT_EQ $mode "production"

Example: quoted value with spaces

# Quotes keep the space: SET_FORTH stores `outer scope`.
ENV SET_FORTH="outer scope"
WRITE out.txt "{{ env:SET_FORTH }}"

LET $body: STRING = READ out.txt
ASSERT_EQ $body "outer scope"

Example: variable value

# A lone $var evaluates, like ECHO $var.
LET $who: STRING = "Alice"
ENV GREETING=$who
WRITE out.txt "{{ env:GREETING }}"

LET $body: STRING = READ out.txt
ASSERT_EQ $body "Alice"

Example: all value forms agree

# A bare variable, a quoted literal, and a template all
# store plain strings through the same value rules.
LET $x: STRING = "Ada"
ENV A=$x
ENV B="hello world"
ENV C="{{ $x }} concatenated"
WRITE check.txt "{{ env:A }}|{{ env:B }}|{{ env:C }}"

LET $body: STRING = READ check.txt
ASSERT_EQ $body "Ada|hello world|Ada concatenated"

Example: scoped env reverts

# ENV inside a braced block reverts when the block exits
ENV MODE=production

[bool:true] {
    ENV MODE=staging
    WRITE inner.txt "{{ env:MODE }}"
}

WRITE outer.txt "{{ env:MODE }}"

LET $inner_body: STRING = READ inner.txt
ASSERT_EQ $inner_body "staging"

LET $outer_body: STRING = READ outer.txt
ASSERT_EQ $outer_body "production"

Example: shell reads env per platform

# A shell command reads its own environment, with
# per-platform spelling: quoted "$VAR" passes the parser
# through untouched on Unix ...
ENV PROXY_PORT=23791

[family:unix] LET $o: STRING = RUN echo serving on "$PROXY_PORT"

# ... while cmd expands %VAR% on Windows.
[family:windows] LET $o: STRING = RUN echo serving on %PROXY_PORT%

ASSERT_CONTAINS $o "23791"

INHERIT_ENV

Inherit env vars from host.

Syntax: INHERIT_ENV [<key>, ...]

Declares which host environment variables to inherit into the script.

Must appear before any other commands. Several directives may appear so platform-specific names ride explicit guards ([family:windows] INHERIT_ENV [USERPROFILE]); each guarded line runs only when its guard passes.

Sandbox defaults need no declaration: loader bindings, terminal defaults, the host lookup path, and the user's profile locations seed automatically. See OxDock Environment Variable Contracts for the exact list, which grows with the engine.

Secrets and tool config stay opt-in here: a token or a CARGO_HOME override arrives only through this directive.

Arguments:

Name Type Required Description
keys STRING... no Host variables to inherit

Examples:

Example: inherit env

[family:unix] INHERIT_ENV [HOME]
LET $path: STRING = env:PATH
[family:unix] ASSERT_CONTAINS $path ":"
[family:windows] ASSERT_CONTAINS $path ";"

ECHO

Print to stdout.

Syntax: ECHO <message>

Outputs message to stdout.

Arguments:

Name Type Required Description
message STRING... yes Text

Output: Stdout

Examples:

Example: echo

ECHO build-complete
ASSERT_CONTAINS stdout "build-complete"

Example: variables

# {{ }} interpolates inside text; a lone $var evaluates on its own.
LET $x: STRING = "World"
ECHO "braced:{{ $x }}"
ECHO $x
ASSERT_EQ stdout "braced:World\nWorld\n"

Example: interpolation

# `{{ env:KEY }}` reads the script environment; `$NAME`
# reads either binding. Spelling rules:
# `script_env:` is always case-sensitive; `env:` is
# case-sensitive too, except on Windows where it matches
# case-insensitively. Every read must be declared first:
# KEY here comes from the ENV below.
ENV USER=OxDock
CONST $WHO: STRING = "Ada"
ECHO "Hello {{ env:USER }}! Hi {{ $WHO }}! Again {{ script_env:USER }}!"
ASSERT_CONTAINS stdout "Hello OxDock! Hi Ada! Again OxDock!"

Example: undeclared env read fails

# No declaration anywhere: the whole-closure static gate
# rejects the read before the first step runs. (The
# error names the variable: undeclared environment
# variable `env:OXDOCK_DOC_NO_SUCH_KEY`.)
ECHO "Hello {{ env:OXDOCK_DOC_NO_SUCH_KEY }}!"

Expected error: env:OXDOCK_DOC_NO_SUCH_KEY

RUN

Execute shell command or direct executable.

Syntax: RUN <command...> | RUN ["exe", "arg", ...]

Shell form (RUN <command...>) runs the joined command string in the batch shell (sh -c / cmd /C). Never the operator's login shell: login shells re-pollute scrubbed children from system profiles and break script portability, so step execution is pinned to POSIX sh (interactive oxdock --shell still uses $SHELL).

Exec form (RUN ["exe", "arg", ...]) spawns the executable directly with no shell, so there is no shell expansion, globbing, redirection, or pipes; use it for portable commands.

Guards and wrappers (ASYNC, TIMEOUT, WITH_IO, LET) apply to both forms.

Arguments:

Name Type Required Description
command STRING... yes Command

Examples:

Example: run

# Spawned children resolve through the seeded host PATH:
# closed child env is the default, not ambient inherit.
RUN echo hello

# Captured runs prove the output, not just the exit status.
LET $o: STRING = RUN echo hello
ASSERT_CONTAINS $o "hello"

Example: run exec form

# No shell: `>` stays a literal argument, so no file is created.
# Toolchain spawns bridge the host home explicitly: rustup
# shims resolve toolchains through the host home.
IMPORT [STD]
[family:unix] INHERIT_ENV [HOME]
[family:windows] INHERIT_ENV [USERPROFILE]
RUN ["cargo", "--version", ">", "x.txt"]
ASSERT_CONTAINS stdout "cargo"

LET $t: STRING = PATH_TYPE("x.txt")
ASSERT_EQ $t "absent"

Example: run binding reads

# The shell line expands templates and `$var` reads before
# spawning: the shell sees values, never spellings.
CONST $WHO: STRING = "world"
LET $tpl: STRING = RUN echo "{{ $WHO }}"
ASSERT_CONTAINS $tpl "world"

# A bare `$var` outside a template reads the same way.
LET $sigil: STRING = RUN echo $WHO
ASSERT_CONTAINS $sigil "world"

# Bare words pass through untouched and never resolve.
LET $raw: STRING = RUN echo who
ASSERT_CONTAINS $raw "who"

COPY

Copy file into workspace.

Syntax: COPY [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] [--from-host | --to-host] <from> <to>

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.

Arguments:

Name Type Required Description
from PATH yes Source
to PATH yes Dest

Flags:

Flag Type Description
--from-workspace STRING Copy from the given workspace root instead of the build context
--from-host BOOL Fetch from the host workspace into the guest (REMOTE bodies only)
--to-host BOOL Push from the guest workspace back to the host (REMOTE bodies only)

Examples:

Example: copy

# Copy to a new name, then read back.
WRITE src.txt content
COPY src.txt dst.txt

LET $body: STRING = READ dst.txt
ASSERT_EQ $body "content"

Example: copy from workspace

# Same name, different contents per root: only LOCAL has ws-content.
WRITE shared.txt from-snapshot
WORKSPACE LOCAL
WRITE shared.txt ws-content

WORKSPACE SNAPSHOT
COPY --from-workspace LOCAL shared.txt ws-copy.txt

LET $body: STRING = READ ws-copy.txt
ASSERT_EQ $body "ws-content"

COPY_GIT

Copy from git revision.

Syntax: COPY_GIT [--include-dirty] <rev> <src> <dst>

Checkout and copy.

Arguments:

Name Type Required Description
rev STRING yes Rev
src PATH yes Src
dst PATH yes Dst

Flags:

Flag Type Description
--include-dirty BOOL Include dirty

Examples:

Example: git copy missing source errors

COPY_GIT HEAD src.txt dst.txt

Expected error: COPY source missing

Create symlink.

Syntax: SYMLINK [--from-workspace SNAPSHOT|LOCAL|CACHE|SYSTEM] <from> <to>

Creates symlink. A directory destination (existing, or a trailing-slash spell) receives the link under the source basename.

Arguments:

Name Type Required Description
from PATH yes Target
to PATH yes Link

Flags:

Flag Type Description
--from-workspace STRING Symlink from the given workspace root instead of the build context

Examples:

Example: symlink

# A symlink reads like its target.
WRITE original.txt content
SYMLINK original.txt link.txt

LET $body: STRING = READ link.txt
ASSERT_EQ $body "content"

Example: symlink from workspace

# Same name, different contents per root: only LOCAL has ws-content.
WRITE shared.txt from-snapshot
WORKSPACE LOCAL
WRITE shared.txt ws-content

WORKSPACE SNAPSHOT
SYMLINK --from-workspace LOCAL shared.txt ws-link.txt

LET $body: STRING = READ ws-link.txt
ASSERT_EQ $body "ws-content"

MKDIR

Create directory.

Syntax: MKDIR <path>

Creates dir with parents.

Arguments:

Name Type Required Description
path PATH yes Dir path

Examples:

Example: mkdir

IMPORT [STD]
MKDIR deeply/nested/tree

LET $t: STRING = PATH_TYPE("deeply/nested/tree")
ASSERT_EQ $t "dir"

INSTALL

Atomically install a verified binary as executable.

Syntax: INSTALL <source> <dest>

Stages the source as a temp file in the dest dir, sets executable mode, then renames into place.

Arguments:

Name Type Required Description
from PATH yes Source file
to PATH yes Dest file

Examples:

Example: install

# Place a verified binary with executable mode.
IMPORT [STD]
WRITE src.bin payload
INSTALL src.bin dst-bin/tool

LET $t: STRING = PATH_TYPE("dst-bin/tool")
ASSERT_EQ $t "file"

SET_EXECUTABLE

Mark a file executable.

Syntax: SET_EXECUTABLE <path>

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.

Arguments:

Name Type Required Description
path PATH yes File to mark executable

Examples:

Example: set-executable

# Mark a rendered script executable in place.
IMPORT [STD]
WRITE tool.sh "echo hi"
SET_EXECUTABLE tool.sh

LET $t: STRING = PATH_TYPE("tool.sh")
ASSERT_EQ $t "file"

ARCHIVE

Pack a file or directory into a tarball.

Syntax: ARCHIVE [--raw] <src> <dst>

Packs a file or directory into a tarball, gzip-compressed by default (--raw writes an uncompressed tar instead).

A lone file packs as a single top-level entry under its basename; a directory recurses, preserving empty dirs. Source modes ride in the headers on Unix, so system tar restores them elsewhere. Symlink sources refuse: archives cross trust boundaries, so links never resolve into member bytes. Hashing stays with HASH_SHA256, which reads the finished archive like any other file.

Arguments:

Name Type Required Description
src PATH yes File or directory to pack
dst PATH yes Archive file to write

Flags:

Flag Type Description
--raw BOOL Write an uncompressed tar instead of gzip

Examples:

Example: archive directory

# Stage a small tree to pack.
WRITE bundle/app.txt bundled-payload
WRITE bundle/nested/deep.txt deep-payload

# ARCHIVE packs it gzip-compressed by default.
ARCHIVE bundle bundle.tar.gz

# UNARCHIVE restores the tree under the destination.
UNARCHIVE bundle.tar.gz restored

# The payloads arrive byte-identical.
LET $body: STRING = READ restored/app.txt
ASSERT_EQ $body "bundled-payload"

LET $deep: STRING = READ restored/nested/deep.txt
ASSERT_EQ $deep "deep-payload"

Example: archive raw

# A lone file packs as a single top-level entry.
WRITE tool.bin tool-payload

# Raw archives skip gzip and stay readable by any tar.
ARCHIVE --raw tool.bin tool.tar
UNARCHIVE tool.tar tool-out

# The entry lands under its basename.
LET $body: STRING = READ tool-out/tool.bin
ASSERT_EQ $body "tool-payload"

UNARCHIVE

Unpack a tarball into a directory.

Syntax: UNARCHIVE <src> <dst> [--max-bytes <bytes>]

Unpacks a tarball under the destination directory, creating it first. Gzip and raw (ARCHIVE --raw) tarballs self-identify by magic bytes, so no flag is needed.

Member bytes meter against a 1 GiB default expansion cap across the whole archive: a decompression bomb trips it instead of filling the disk, and --max-bytes moves the ceiling either way (plain integer bytes). The tripped member stays truncated on disk while the step fails loudly.

Symlink and special members refuse naming the entry, and absolute or escaping paths fail closed before any byte lands: the member sanitizer plus the destination join check form two independent walls. Unix modes recorded in the headers restore on unpack; other platforms land default modes (confer executability with INSTALL there).

Arguments:

Name Type Required Description
src PATH yes Archive file to unpack
dst PATH yes Directory to unpack under

Flags:

Flag Type Description
--max-bytes STRING 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)

Examples:

Example: unarchive

# Pack a note, then restore it under a fresh destination.
WRITE pack/note.txt packed-note
ARCHIVE pack pack.tar.gz
UNARCHIVE pack.tar.gz unpacked

LET $body: STRING = READ unpacked/note.txt
ASSERT_EQ $body "packed-note"

Example: unarchive with a lower cap

# Small payloads clear even a tight ceiling.
WRITE pack/note.txt packed-note
ARCHIVE pack pack.tar.gz
UNARCHIVE pack.tar.gz capped --max-bytes 100KB

LET $body: STRING = READ capped/note.txt
ASSERT_EQ $body "packed-note"

LS

List directory.

Syntax: LS [<path>]

Lists entries.

Arguments:

Name Type Required Description
path PATH no Dir

Output: Stdout

Examples:

Example: ls

MKDIR inventory
WRITE inventory/a.txt a
LS inventory
ASSERT_CONTAINS stdout "a.txt"

READ

Read file to stdout.

Syntax: READ [<path>]

Outputs file contents.

Arguments:

Name Type Required Description
path PATH no File

Output: Stdout

Examples:

Example: read

WRITE note.txt "hello"
READ note.txt

LET $body: STRING = READ note.txt
ASSERT_EQ $body "hello"

READ_LINE

Read one line from stdin into a variable.

Syntax: READ_LINE $var

Reads bytes until newline without waiting for EOF, leaving the pipe open.

Trailing newline is stripped (shell-read parity). On premature EOF assigns accumulated bytes and returns.

Arguments:

Name Type Required Description
var STRING yes Target variable ($name); the line binds as STRING

Examples:

Example: read line

# The trailing newline is stripped: the variable holds exactly `first`.
LET $lines: PIPE
WITH_IO [stdout=$lines] ECHO "first"
WITH_IO [stdin=$lines] READ_LINE $reply
ASSERT_EQ $reply "first"

PROMPT

Prompt on the terminal into a variable.

Syntax: PROMPT $var <message> [<default>]

Prints {message} [{default}]: (or {message}: with no default) to stderr and reads one line from the terminal.

Empty input yields the default when one is given, else an empty string. EOF aborts loudly. Non-TTY stdin never reads: a default binds with a stderr note, while no default bails.

Arguments:

Name Type Required Description
var STRING yes Target variable ($name); the answer binds as STRING
message STRING yes Prompt message
default STRING no Default on empty input

Examples:

Example: prompt needs a terminal

# A redirected stdin can never answer: without a default the
# prompt fails instead of hanging or reading piped stdin.
LET $p: PIPE
WITH_IO [stdin=$p] PROMPT $dir "Install destination?"

Expected error: non-TTY

WRITE

Write to file.

Syntax: WRITE <path> [<contents>]

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.

Arguments:

Name Type Required Description
path PATH yes File
contents STRING... no Content

Examples:

Example: write

WRITE output.txt hello-world
LET $body: STRING = READ output.txt
ASSERT_EQ $body "hello-world"

APPEND

Append to file.

Syntax: APPEND <path> [<contents>]

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.

Arguments:

Name Type Required Description
path PATH yes File
contents STRING... no Content

Examples:

Example: append

WRITE log.txt line1
APPEND log.txt line2

# No separator or newline is added: the bytes concatenate
# exactly, so this asserts the unterminated form.
LET $all: STRING = READ log.txt
ASSERT_EQ $all "line1line2"

APPEND_LINE

Append one line to a file.

Syntax: APPEND_LINE <path> <contents>

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.

Arguments:

Name Type Required Description
path PATH yes File
contents STRING... yes Line content (the newline is added)

Examples:

Example: append-line

WRITE log.txt line1
APPEND_LINE log.txt line2
APPEND_LINE log.txt line3

# Each APPEND_LINE terminates its own write.
LET $all: STRING = READ log.txt
ASSERT_EQ $all "line1line2\nline3\n"

REMOVE

Remove a file, symlink, or directory.

Syntax: REMOVE [--recursive] <path>

Removes a file, symlink (the link itself), or empty dir. With --recursive removes a directory tree.

Arguments:

Name Type Required Description
path PATH yes Path to remove

Flags:

Flag Type Description
--recursive BOOL Remove a directory tree

Examples:

Example: remove

# WRITE then REMOVE leaves nothing behind.
IMPORT [STD]
WRITE scratch.txt content

# Assert original file is written
LET $o: STRING = PATH_TYPE("scratch.txt")
ASSERT_EQ $o "file"

REMOVE scratch.txt

# Assert file has been removed
LET $t: STRING = PATH_TYPE("scratch.txt")
ASSERT_EQ $t "absent"

EXPAND

Expand a template file (or stdin) to stdout.

Syntax: EXPAND [<path>] [<KEY=val> ...]

A template is any text file — or piped stdin when no path is given — containing {{ ... }} placeholders. EXPAND replaces each placeholder and prints the result to stdout.

Placeholders: {{ NAME }} reads a KEY=val override passed on this command; {{ env:NAME }} reads an override, falling back to the environment; {{ $var }} reads a script variable (dotted paths allowed). A missing key is an error, never a silent empty.

Calls: {{ MODULE::FUNC(args) }} invokes a pure registry function with $var.path references and STRING, INT, FLOAT, and BOOL literals as arguments. A bare {{ NAME(args) }} resolves exactly like a statement-position call: IMPORT [MODULE] brings the names into scope, unimported names fail naming the fix, ambiguity fails closed. Arguments check against the registered signature, so wrong arity or mistyped values fail at the call; unknown names fail listing the known functions. Only pure functions resolve here: stateful, script-defined, and pipe-backed entries fail naming themselves, since placeholder evaluation carries no step context. The same calls resolve in ordinary strings, so both paths agree.

Substitution runs in a single pass. EXPAND is not recursive and does not expand nested placeholders: a value that itself contains {{ ... }} is inserted verbatim and never expanded again.

A bare $var argument is a template path; KEY=val arguments are overrides whose values follow the unified string-value rules (same as ENV: quotes keep exact bytes, a lone $var evaluates, {{ ... }} interpolates).

NOTE: WRITE interpolates {{ ... }} while writing, so escape it (\{{ ... }}) when writing a template file for a later EXPAND.

With no path, the template arrives on stdin through a pipe. When piping from a shell, single-quote the template (echo '{{ $x }}'): double quotes let the shell swallow $x, so oxdock receives an empty {{ }} placeholder and errors.

Arguments:

Name Type Required Description
path PATH no Template file to expand; omit to expand stdin
overrides STRING... no Template overrides shadowing that key (unified string values)

Output: Stdout

Examples:

Example: expand

# Placeholders read overrides first, then the environment.
ENV NAME="Alice"
WRITE template.md "Hello {{ env:NAME }}!"
EXPAND template.md

ASSERT_CONTAINS stdout "Hello Alice!"

Example: override with spaces

# WRITE would interpolate {{ }} right away, so escape it.
# The file must literally contain {{ env:NAME }} for EXPAND.
WRITE template.md "Hello \{{ env:NAME }}!"
EXPAND template.md NAME="Alice Smith"

ASSERT_CONTAINS stdout "Hello Alice Smith!"

Example: variable override

# Same escaping: keep the placeholder literal until EXPAND.
# A lone $who evaluates, like ECHO $who.
LET $who: STRING = "Bob"
WRITE template.md "Hi \{{ env:WHO }}!"
EXPAND template.md WHO=$who

ASSERT_CONTAINS stdout "Hi Bob!"

Example: override forms agree

# A bare variable and a template-with-tail expand identically.
LET $x: STRING = "Ada"
WRITE template.md "Hi \{{ env:NAME }} and \{{ env:NAME2 }}!"
EXPAND template.md NAME=$x NAME2="{{ $x }} concatenated"

ASSERT_CONTAINS stdout "Hi Ada and Ada concatenated!"

Example: expand stdin

# No path: the template arrives on stdin through a pipe.
LET $tpl: PIPE
WITH_IO [stdout=$tpl] ECHO "Hello \{{ env:NAME }}!"
WITH_IO [stdin=$tpl] EXPAND NAME=Alice

ASSERT_CONTAINS stdout "Hello Alice!"

Example: override does not leak

# KEY=val overrides shadow env for that EXPAND only.
# They never update the environment itself.
ENV NAME="Alice"
WRITE template.md "Hi \{{ env:NAME }}!"

EXPAND template.md NAME="Bob"
ASSERT_CONTAINS stdout "Hi Bob!"

EXPAND template.md
ASSERT_CONTAINS stdout "Hi Alice!"

Example: function call

# Pure registry functions run inside placeholders.
# WRITE would interpolate {{ }} right away, so escape it.
IMPORT [STD]
WRITE template.md "Count: \{{ STD::TEXT_COUNT(\"one two two three\", \"two\") }}!"

EXPAND template.md
ASSERT_CONTAINS stdout "Count: 2!"

Example: bare override

# A bare name reads a KEY=val override with no prefix.
WRITE template.md "Hi \{{ NAME }}!"

EXPAND template.md NAME=Ada
ASSERT_CONTAINS stdout "Hi Ada!"

Example: variable placeholder

# `{{ $var }}` placeholders read script variables, dotted
# paths included. Escape at WRITE so EXPAND sees it.
LET $u: MAP<name: STRING> = {name: "Bo"}
WRITE template.md "Hi \{{ $u.name }}!"

EXPAND template.md
ASSERT_CONTAINS stdout "Hi Bo!"

Example: missing key fails

# A missing key is an error, never a silent empty.
WRITE template.md "Hi \{{ NAME }}!"

EXPAND template.md

Expected error: missing required step override argument

ASSERT_EQ

Assert strict equality.

Syntax: ASSERT_EQ [--hash <sha256>] <actual> <expected>

Compares two evaluated values with typed equality (no coercion: INT(42) never equals STRING("42")), aborting the pipeline with a step-numbered error showing expected vs actual otherwise. The mismatch error prints both values to stderr, so never assert against a live secret: a failure would write it into the log.

Both sides are values: $var, literals, templates, and calls evaluate in memory and never touch disk. Read files explicitly first (LET $text: STRING = READ "out.txt", then ASSERT_EQ $text ...). Bare stdout / stderr observe stream buffers; a $var holding a PIPE observes its backend bytes. --hash compares the SHA-256 of a string, pipe, or captured-stdout actual instead of the raw bytes (stderr is unsupported).

Arguments:

Name Type Required Description
actual <any> yes Value, stdout, stderr, or a $var holding a PIPE
expected <any>... no Expected (required unless --hash)

Flags:

Flag Type Description
--hash STRING SHA-256

Examples:

Example: assert eq

LET $status: INT = 200
ASSERT_EQ $status 200

Example: assert eq file

WRITE payload.bin stable-content
LET $body: STRING = READ payload.bin
ASSERT_EQ $body "stable-content"

Example: assert eq hash

# --hash compares the SHA-256 digest instead of raw bytes.
WRITE payload.bin stable-content
LET $body: STRING = READ payload.bin
ASSERT_EQ --hash 08135c1b6349b0e4f894c36221952f0de00e6b4d82f80895abf359755e77103c $body

ASSERT_NE

Assert strict inequality.

Syntax: ASSERT_NE [--hash <sha256>] <actual> <expected>

Compares two evaluated values with typed inequality (no coercion: INT(42) never equals STRING("42")), aborting the pipeline with a step-numbered error showing expected vs actual when they are equal; differing values pass silently. The match error prints both values to stderr, so never assert against a live secret: a failure would write it into the log.

Both sides are values: $var, literals, templates, and calls evaluate in memory and never touch disk. Read files explicitly first (LET $text: STRING = READ "out.txt", then ASSERT_NE $text ...). Bare stdout / stderr observe stream buffers; a $var holding a PIPE observes its backend bytes. --hash compares the SHA-256 of a string, pipe, or captured-stdout actual instead of the raw bytes (stderr is unsupported); the digest must differ from the given hash.

Arguments:

Name Type Required Description
actual <any> yes Value, stdout, stderr, or a $var holding a PIPE
expected <any>... no Value the actual must differ from (required unless --hash)

Flags:

Flag Type Description
--hash STRING SHA-256

Examples:

Example: assert ne

LET $status: INT = 200
ASSERT_NE $status 404

Example: assert ne file

WRITE payload.bin stable-content
LET $body: STRING = READ payload.bin
ASSERT_NE $body "other-content"

Example: assert ne hash

# --hash compares the SHA-256 digest instead of raw bytes.
WRITE payload.bin stable-content
LET $body: STRING = READ payload.bin
ASSERT_NE --hash 0000000000000000000000000000000000000000000000000000000000000000 $body

ASSERT_CONTAINS

Assert containment.

Syntax: ASSERT_CONTAINS <haystack> <needle>

Checks containment and aborts the pipeline with a step-numbered error otherwise: substring for strings, element match for lists, key presence for maps, substring over stream and pipe buffers.

Like ASSERT_EQ, both sides are values read without implicit I/O; read files explicitly first (LET $text: STRING = READ "cfg.txt"). Bare stdout / stderr observe stream buffers; a $var holding a PIPE observes its backend bytes.

Arguments:

Name Type Required Description
haystack <any> yes Value, stdout, stderr, or a $var holding a PIPE
needle <any>... yes Substring, element, or key

Examples:

Example: assert contains

ECHO build-complete
ASSERT_CONTAINS stdout "build-complete"

EXIT

Exit pipeline.

Syntax: EXIT <code>

Stops the pipeline immediately with an EXIT requested with code <code> error; steps after it never run, at any nesting depth.

Enclosing blocks still unwind their LET/ENV/WORKDIR/WORKSPACE state, anonymous background tasks are killed synchronously, and files written before the EXIT persist.

The code reaches the OS: the CLI exits with <code> clamped to 0..=255, and a guest EXIT relays through REMOTE the same way.

Arguments:

Name Type Required Description
code INT yes Code

Examples:

Example: exit

EXIT 0

Expected error: EXIT requested with code 0

SLEEP

Pause execution for a duration.

Syntax: SLEEP <duration>

Parks the step for the duration (e.g. 500ms, 10s, 2m).

Cooperative: checks for cancellation so an enclosing TIMEOUT or task teardown interrupts the sleep. Cross-platform alternative to shell sleep for testing time boundaries.

Arguments:

Name Type Required Description
duration DURATION yes How long to sleep

Examples:

Example: sleep

SLEEP 100ms

Example: sleep variable duration

# Durations resolve at runtime, so variables work too:
# quoted or bare, both bind the same string.
LET $pause: STRING = "100ms"
SLEEP $pause

LET $bare: STRING = 100ms
SLEEP $bare

LIST_APPEND

Append an item to a LIST variable in place.

Syntax: LIST_APPEND $list <item>

Appends the item to the LIST variable in place.

When the binding holds the only reference the push runs in amortized constant time. Aliased buffers detach first, so other holders keep their contents.

Arguments:

Name Type Required Description
list LIST yes Target LIST variable ($name)
item <any> yes Item to append (any value)

Examples:

Example: list append

# Appends accumulate in order.
LET $items: LIST<STRING> = []
LIST_APPEND $items "first"
LIST_APPEND $items "second"

LET $want: LIST<STRING> = ["first", "second"]
ASSERT_EQ $items $want

Value types

Value type: INT

64-bit signed integer, e.g. an exit code.

Value type: FLOAT

64-bit float, e.g. a ratio.

Value type: STRING

Arbitrary text. Quotes keep exact bytes, lone $var evaluates, {{ ... }} interpolates. Shared heap: cloning bumps a refcount, never copies the bytes.

Value type: BOOL

Boolean true or false.

Value type: LIST

Ordered list of values. Shared heap: cloning bumps a refcount. A CONST-owned list is deeply immutable: LIST_APPEND on it, or on any alias of it, fails with cannot mutate CONST, including for lists nested inside it. The CONST copy is detached, so mutating the LET source it was built from leaves the CONST unchanged. Equality ignores CONST-ness, so ASSERT_EQ never observes it.

Value type: MAP

String-keyed map of values. Shared heap: cloning bumps a refcount. Freezing mirrors LIST: a CONST-owned map is deeply immutable, so MAP_SET and MERGE_MAPS on it (or any alias of it) fail with cannot mutate CONST, including for maps nested inside it. The CONST copy is detached from the LET source it was built from.

Value type: PATH

Workspace path, resolved against cwd and guarded against escape.

Value type: DURATION

Positive time span: 500ms, 10s, 2m, 1h; bare number means seconds.

Value type: PIPE

Runtime-managed stream handle, never a raw descriptor. A PIPE names a runtime-managed byte stream with exactly one interface: declare it (LET $p: PIPE), wire it (WITH_IO), and pass or copy it across calls and module boundaries. Script code never manages descriptors, temp files, or platform plumbing. The backend materializes lazily on first binding (never eagerly at declaration), so the choice always has full usage context. Cloning shares the backend (explicit-sharing fan-out); equality is handle identity, never byte comparison.

Value type: HANDLE

Background task handle minted by LET $t: HANDLE<T> = ASYNC .... The payload names what AWAIT binds: HANDLE<T> yields T on capture, HANDLE<VOID> is join-only (bare AWAIT/CANCEL only). The handle itself is just a task id and carries no data: observe the task through AWAIT, CANCEL, or TASK_POLL, never through the handle. Copying it aliases the same task, and joining twice fails. Bare HANDLE is not a declaration type: write the payload or explicit HANDLE<ANY>.

Value type: SEMAPHORE

Counting semaphore for admission control. Cloning shares the backend (explicit-sharing fan-out); equality is handle identity, never the count.

Value type: PERMIT

Opaque admission permit minted by SEMAPHORE_TRY_ACQUIRE. Cloning shares the release obligation (first drops release nothing, the last releases once); equality is handle identity.

Built-in functions

The STD standard library: built-in functions available to every script. Callable as MODULE::NAME(...) in expressions (or bare NAME(...) with the module imported via IMPORT). Plugin modules (NET, SSH, MARKDOWN) add more functions the same way, and hosts can extend the language with their own modules (Extending OxDock from Rust). Introspectable from scripts with FUNCTIONS() and DESCRIBE(name).

STD::ARGV

Report the verbatim CLI tail after the script position.

Staged per run from Options.script_args (#226): everything after the script file (or --script <file>), with one leading -- stripped. Never merged with interpreter flags, so --dry-run after the script arrives here instead of enabling dry-run.

Signature: STD::ARGV(): LIST<STRING>

Contexts: AST only

Returns: LIST<STRING>

Examples:

Example: empty

# With no staged args the list is empty.
IMPORT [STD]
LET $args: LIST<STRING> = ARGV()
LET $n: INT = LEN($args)
ASSERT_EQ $n 0

STD::BASE64_DECODE

Decode standard base64 to a STRING.

Fails naming the input on invalid alphabet characters or non-UTF-8 payloads instead of rendering a silent empty. Pairs with BASE64_ENCODE for the round trip.

Signature: STD::BASE64_DECODE($text: STRING): STRING

Contexts: AST, RPN

Parameters:

  • $text (STRING): Base64 text to decode.

Returns: STRING

Examples:

Example: decode

# Decode standard base64 back to text.
IMPORT [STD]
LET $decoded: STRING = BASE64_DECODE("aGVsbG8=")
ASSERT_EQ $decoded "hello"

STD::BASE64_ENCODE

Encode a STRING as standard base64.

Padded RFC 4648 alphabet, so encoded output pastes into any standard decoder. Pairs with BASE64_DECODE for the round trip.

Signature: STD::BASE64_ENCODE($text: STRING): STRING

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to encode.

Returns: STRING

Examples:

Example: encode

# Encode text to standard base64.
IMPORT [STD]
LET $encoded: STRING = BASE64_ENCODE("hello")
ASSERT_EQ $encoded "aGVsbG8="

STD::BOOL

Convert a value to BOOL.

Trims ASCII whitespace; accepts true/false, 1/0, yes/no, on/off in any case. Passes Bool through. Empty and anything else fail: an empty string is not a boolean, so absent env names (which read empty) must go through BOOL_OR with a stated default instead of converting here.

Signature: STD::BOOL($val: BOOL|STRING): BOOL

Contexts: AST, RPN

Parameters:

  • $val (BOOL|STRING): Value to convert to BOOL.

Returns: BOOL

Examples:

Example: convert

IMPORT [STD]
LET $n: BOOL = BOOL("yes")
ASSERT_EQ $n true
LET $f: BOOL = BOOL("0")
ASSERT_EQ $f false

STD::BOOL_OR

Coerce text to BOOL, substituting a default for empty.

Returns BOOL. Blank input (a declared-but-absent env name, which reads empty) resolves to default instead of failing, so each flag site states its own absent polarity explicitly: negative-polarity flags (dry_run) default true, positive ones default false. No implicit polarity lives in the coercion. Non-blank garbage still fails naming the input, exactly like LET $x: BOOL coercion.

Signature: STD::BOOL_OR($text: STRING, $default: BOOL): BOOL

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to coerce (true/false, 1/0, yes/no/on/off, any case).
  • $default (BOOL): Absent-value default, used when the text is blank.

Returns: BOOL

Examples:

Example: absent-default

# Absent names read empty; the default settles the polarity.
IMPORT [STD]
INHERIT_ENV [OXDOCK_TEST_ABSENT_FLAG]
LET $dry: BOOL = BOOL_OR("{{ env:OXDOCK_TEST_ABSENT_FLAG }}", true)
ASSERT_EQ $dry true

# Present values coerce strictly, ignoring the default.
LET $off: BOOL = BOOL_OR("false", true)
ASSERT_EQ $off false

STD::CONTAINS

Report whether a STRING holds a substring or a LIST holds a member.

Dispatches on the haystack like LEN: STRING does a literal substring search (case-sensitive, no case-insensitive mode); LIST<ANY> compares members with strict values_equal (numeric INT and FLOAT compare across types, every other cross-type pair is unequal, matching SWITCH). Returns BOOL; misses are false, never failures.

Signature: STD::CONTAINS($haystack: STRING|LIST, $needle: ANY): BOOL

Contexts: AST, RPN

Parameters:

  • $haystack (STRING|LIST): Text to search or list to probe.
  • $needle (ANY): Literal substring or member to look for.

Returns: BOOL

Examples:

Example: contains

# Present needles report true; misses report false.
IMPORT [STD]
LET $hit: BOOL = CONTAINS("x86_64-linux-musl", "musl")
ASSERT_EQ $hit true

# A miss is false, not a failure.
LET $miss: BOOL = CONTAINS("x86_64-linux-gnu", "musl")
ASSERT_EQ $miss false

Example: contains list

# List membership uses strict equality across any element type.
IMPORT [STD]
LET $hit: BOOL = CONTAINS(["a", "b", "c"], "b")
ASSERT_EQ $hit true
LET $miss: BOOL = CONTAINS(["a", "b", "c"], "z")
ASSERT_EQ $miss false
LET $num: BOOL = CONTAINS([1, 2, 3], 2.0)
ASSERT_EQ $num true

# Stringified numbers never coerce to integers.
LET $strnum: BOOL = CONTAINS(["1", "2", "3"], 2)
ASSERT_EQ $strnum false

# Boolean lists match true and miss false with no coercion.
LET $bools: LIST<BOOL> = [true]
LET $bhit: BOOL = CONTAINS($bools, true)
ASSERT_EQ $bhit true
LET $bmiss: BOOL = CONTAINS($bools, false)
ASSERT_EQ $bmiss false
LET $nocoerce: BOOL = CONTAINS($bools, 1)
ASSERT_EQ $nocoerce false

STD::CWD

Current working directory as a workspace-absolute path.

Returns STRING because the result is already resolved: a PATH value is workspace-relative text awaiting guard checks at use time, while this directory is already checked and concrete, or absent entirely under a pending snapshot. Compare or display it as text.

Reports the snapshot-pending sentinel when no concrete directory exists yet, so snapshot scripts keep working unchanged.

Signature: STD::CWD(): STRING

Contexts: AST, RPN

Returns: STRING

Examples:

Example: cwd

IMPORT [STD]
WORKDIR sub
LET $c: STRING = CWD()
ASSERT_CONTAINS $c "sub"

STD::DESCRIBE

Describe one function by qualified name.

Returns a MAP with name, module, kind, params, returns, rpn, and summary. params is always a LIST (empty for parameterless functions) of entries carrying name, param_type, allowed, docs, options, and optional flags, so the shape holds for every entry. Bare names fail closed: DESCRIBE requires the qualified form (except INSPECT, which is syntax rather than a registry entry). Errors on unknown function.

Field table for the DESCRIBE result bundle: one source for the shape the host mints, so introspection, enforcement, and documentation cannot drift apart.

Signature: STD::DESCRIBE($name: STRING): MAP<name: STRING, module: STRING, kind: STRING, params: LIST<MAP<ANY>>, returns: STRING, rpn: BOOL, summary: STRING>

Contexts: AST only

Parameters:

  • $name (STRING): Qualified function name (MODULE::NAME).

Returns: MAP<name: STRING, module: STRING, kind: STRING, params: LIST<MAP<ANY>>, returns: STRING, rpn: BOOL, summary: STRING>

  • name (STRING): Qualified function name.
  • module (STRING): Owning module.
  • kind (STRING): Origin label (host or script).
  • params (LIST<MAP<ANY>>): Parameter entries (empty for parameterless functions).
  • returns (STRING): Structural return shape (empty when untagged).
  • rpn (BOOL): True when callable in RPN position.
  • summary (STRING): One-line description.

Examples:

Example: describe

IMPORT [STD]
LET $info: MAP<ANY> = DESCRIBE("STD::INT")
ASSERT_EQ $info.name "STD::INT"
ASSERT_EQ $info.returns "INT"

STD::EOF

True when a pipe sits at end of stream: closed with nothing buffered, so the next READ_LINE would bind "" via EOF rather than a line. Live writers, pinned keepers, and buffered bytes all answer false. Never blocks: a reader already blocked stays blocked, so branch on EOF before reading, not after. OS pairs and unbound handles answer best-effort (kernel bytes are invisible there; see INSPECT). Non-pipe arguments bail at the boundary: the parameter declares PIPE, so the extractor and the static pass reject them before the body runs.

Signature: STD::EOF($pipe: PIPE): BOOL

Contexts: AST only

Parameters:

  • $pipe (PIPE): Pipe handle to query for end of stream.

Returns: BOOL

Examples:

Example: drain to end

# Capture two lines, then drain to end of stream with no sentinel line.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "one"
    ECHO "two"
}

# The loop exits on close, and the count proves both lines drained.
LET $n: INT = 0
WHILE !EOF($cap) {
    WITH_IO [stdin=$cap] READ_LINE $line
    $n = $n + 1
}
ASSERT_EQ $n 2

STD::EXISTS

Report whether a workspace path exists in any form.

True for files, directories, and symlinks; false for absent or unresolvable paths, never an error. AST-only by design, like PATH_TYPE: there is no RPN arm for filesystem IO.

Signature: STD::EXISTS($path: STRING|PATH): BOOL

Contexts: AST only

Parameters:

  • $path (STRING|PATH): Workspace path to probe.

Returns: BOOL

Examples:

Example: probe

# Present entries read true; absent paths read false.
IMPORT [STD]
WRITE "entry.txt" "words"
LET $hit: BOOL = EXISTS("entry.txt")
ASSERT_EQ $hit true
LET $miss: BOOL = EXISTS("no-such-entry.txt")
ASSERT_EQ $miss false

STD::FLOAT

Convert a value to FLOAT.

Parses f64 (accepts int strings), bails on non-finite or non-numeric.

Signature: STD::FLOAT($val: FLOAT|INT|STRING): FLOAT

Contexts: AST, RPN

Parameters:

  • $val (FLOAT|INT|STRING): Value to convert to FLOAT.

Returns: FLOAT

Examples:

Example: convert

IMPORT [STD]
LET $f: FLOAT = FLOAT("1.5")
ASSERT_EQ $f 1.5
LET $whole: FLOAT = FLOAT(2)
ASSERT_EQ $whole 2.0

STD::FORMAT_BYTE_COUNT

Format a byte count canonically (500B, 10KB, 2MB, 1GB, binary 10KIB and friends): the inverse of PARSE_BYTE_COUNT, so formatted values reparse exactly. Negative inputs fail.

Signature: STD::FORMAT_BYTE_COUNT($bytes: INT): STRING

Contexts: AST, RPN

Parameters:

  • $bytes (INT): Byte count to format; negatives fail.

Returns: STRING

Examples:

Example: format and round-trip

# Byte counts render in the largest exact unit.
IMPORT [STD]
LET $pretty: STRING = FORMAT_BYTE_COUNT(1_048_576)
ASSERT_EQ $pretty "1MiB"

# The pair round-trips through the parser.
LET $back: INT = PARSE_BYTE_COUNT($pretty)
ASSERT_EQ $back 1_048_576

STD::FORMAT_DURATION

Format millisecond durations canonically (500ms, 10s, 2m, 1h): the inverse of PARSE_DURATION, so formatted values reparse exactly. Negative inputs fail.

Signature: STD::FORMAT_DURATION($millis: INT): STRING

Contexts: AST, RPN

Parameters:

  • $millis (INT): Milliseconds to format; negatives fail.

Returns: STRING

Examples:

Example: format and round-trip

# Durations render in the largest exact unit.
IMPORT [STD]
LET $pretty: STRING = FORMAT_DURATION(90_000)
ASSERT_EQ $pretty "90s"

# The pair round-trips through the parser.
LET $back: INT = PARSE_DURATION($pretty)
ASSERT_EQ $back 90_000

STD::FUNCTIONS

List all visible function names.

Sorted LIST of qualified MODULE::NAME entries: DSL-defined plus native plus host-registered names.

Signature: STD::FUNCTIONS(): LIST<STRING>

Contexts: AST only

Returns: LIST<STRING>

Examples:

Example: list

IMPORT [STD]
LET $names: LIST<STRING> = FUNCTIONS()
ASSERT_CONTAINS $names "STD::INT"

STD::GET

Read one map entry with a default for missing keys.

Pure MAP getter so optional flags cost one line instead of a HAS_KEY + index + rebind triple: present keys return their value verbatim (no coercion), absent keys return default.

Signature: STD::GET($map: MAP<ANY>, $key: STRING, $default: ANY): ANY

Contexts: AST, RPN

Parameters:

  • $map (MAP<ANY>): Map to read.
  • $key (STRING): Key to look up.
  • $default (ANY): Default for absent keys.

Returns: ANY

Examples:

Example: present and absent

IMPORT [STD]
LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
LET $hit: INT = GET($m, "a", 0)
ASSERT_EQ $hit 1
LET $miss: INT = GET($m, "b", 0)
ASSERT_EQ $miss 0

STD::GLOB

List workspace paths matching a glob pattern.

Sorted, root-relative LIST; empty on no match or .. escape.

Signature: STD::GLOB($pattern: STRING|PATH): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $pattern (STRING|PATH): Glob pattern matched against workspace paths.

Returns: LIST<STRING>

Examples:

Example: match

IMPORT [STD]
WRITE "notes-a.md" "a"
WRITE "notes-b.md" "b"
WRITE "other.txt" "c"
LET $found: LIST<STRING> = GLOB("notes-*.md")
ASSERT_EQ $found.0 "notes-a.md"
ASSERT_EQ $found.1 "notes-b.md"

STD::HASH_SHA256

Hash a workspace file or directory with SHA-256.

The argument is always a path: reads through the workspace guard like the file-loading builtins, so relative paths resolve against the script cwd. To hash a literal string's bytes instead, use ASSERT_EQ --hash <digest> <string>, which hashes the actual directly. Returns the 64 lowercase hex chars with no trailing newline.

Signature: STD::HASH_SHA256($path: STRING|PATH): STRING

Contexts: AST, RPN

Parameters:

  • $path (STRING|PATH): Workspace file or directory path to hash.

Returns: STRING

Examples:

Example: hash

IMPORT [STD]
WRITE payload.txt hello
LET $digest: STRING = HASH_SHA256("payload.txt")
ASSERT_EQ $digest "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

STD::HAS_KEY

Report whether a map holds a key.

Pure MAP probe so scripts can branch on optional fields without tripping the strict missing-key error.

Signature: STD::HAS_KEY($map: MAP<ANY>, $key: STRING): BOOL

Contexts: AST, RPN

Parameters:

  • $map (MAP<ANY>): Map to probe.
  • $key (STRING): Key to look up.

Returns: BOOL

Examples:

Example: probe

IMPORT [STD]
LET $m: MAP<ANY> = PARSE_JSON("{\"a\": 1}")
LET $hit: BOOL = HAS_KEY($m, "a")
ASSERT_EQ $hit true
LET $miss: BOOL = HAS_KEY($m, "b")
ASSERT_EQ $miss false

STD::INT

Convert a value to INT.

Trims ASCII whitespace and parses i64. Passes Int through; Float only when integral and finite; Bool as 1/0.

Signature: STD::INT($val: INT|FLOAT|STRING|BOOL): INT

Contexts: AST, RPN

Parameters:

  • $val (INT|FLOAT|STRING|BOOL): Value to convert to INT.

Returns: INT

Examples:

Example: convert

IMPORT [STD]
LET $n: INT = INT("42")
ASSERT_EQ $n 42
LET $flag: INT = INT(true)
ASSERT_EQ $flag 1

STD::INTERPRETER

Path of the running interpreter binary.

Returns the executing binary as a STRING, so one script can reinvoke the interpreter on another script without bridging an env var. The child re-parses from bytes in a separate process: no bindings cross back (only stdout and files), and each run pays a spawn. Prefer modules for reuse (statically gated, in-process); reach for reinvocation when the child must run isolated, or under a different binary than the parent.

Unsupported under Miri isolation: the lookup itself fails there instead of returning a path.

Signature: STD::INTERPRETER(): STRING

Contexts: AST only

Returns: STRING

Examples:

Example: self

# The running interpreter resolves to a non-empty path.
IMPORT [STD]
LET $exe: STRING = INTERPRETER()
LET $nonempty: BOOL = $exe != ""
ASSERT_EQ $nonempty true

Example: dynamic assembly

# Assemble the child script dynamically: the parent interpolates
# its own bindings into the pipe, then runs the interpreter on it.
# Unescaped {{ }} bakes in at render time; \{{ }} stays literal
# so the child expands it with its own bindings.
# The pipe delivers EOF when the producer step ends, so the child
# reads exactly one script.
IMPORT [STD]
LET $exe: STRING = INTERPRETER()
LET $who: STRING = "Ada"
LET $child: PIPE
WITH_IO [stdout=$child] ECHO """
    ECHO "hello {{ $who }}!"
    LET $who: STRING = "Grace"
    ECHO "child sees \{{ $who }}!"
    """
LET $out: STRING = WITH_IO [stdin=$child] RUN [$exe]
ASSERT_CONTAINS $out "hello Ada!"
ASSERT_CONTAINS $out "child sees Grace!"

STD::IS_DIR

Report whether a workspace path names a directory.

No-follow by design like PATH_TYPE: a symlink is neither a file nor a directory, so it reads false here. Missing or unresolvable paths read false, never error. AST-only by design, like PATH_TYPE: there is no RPN arm for filesystem IO.

Signature: STD::IS_DIR($path: STRING|PATH): BOOL

Contexts: AST only

Parameters:

  • $path (STRING|PATH): Workspace path to probe.

Returns: BOOL

Examples:

Example: probe

# Directories read true; files read false.
IMPORT [STD]
LET $hit: BOOL = IS_DIR(".")
ASSERT_EQ $hit true
WRITE "entry.txt" "words"
LET $miss: BOOL = IS_DIR("entry.txt")
ASSERT_EQ $miss false

STD::IS_EXEC

Report whether a name resolves to an executable file (#100).

Bare command names search env:PATH (IS_EXEC("tar") finds the first executable tar, plus tar.exe, on PATH); spellings containing a separator check that file directly. True means a real file with an executable bit on Unix, or a PATHEXT extension on Windows: each env:PATHEXT entry is probed in order (unset or empty probes nothing). Absolute PATH entries resolve through the workspace as usual, so host probing wants WORKSPACE SYSTEM and an inherited PATH; anything unresolvable reads false, never errors. AST-only by design, like PATH_TYPE: there is no RPN arm for filesystem IO.

Signature: STD::IS_EXEC($name: STRING|PATH): BOOL

Contexts: AST only

Parameters:

  • $name (STRING|PATH): Command name or file path to probe.

Returns: BOOL

Examples:

Example: probe

# Missing tools read false instead of failing the run.
IMPORT [STD]
LET $missing: BOOL = IS_EXEC("no-such-tool-xyz")
ASSERT_EQ $missing false

# Plain files are not executable on any platform.
WRITE tool.txt payload
LET $plain: BOOL = IS_EXEC("tool.txt")
ASSERT_EQ $plain false

STD::IS_FILE

Report whether a workspace path names an ordinary file.

No-follow by design like PATH_TYPE: a symlink is neither a file nor a directory, so it reads false here. Missing or unresolvable paths read false, never error. AST-only by design, like PATH_TYPE: there is no RPN arm for filesystem IO.

Signature: STD::IS_FILE($path: STRING|PATH): BOOL

Contexts: AST only

Parameters:

  • $path (STRING|PATH): Workspace path to probe.

Returns: BOOL

Examples:

Example: probe

# Ordinary files read true; missing paths read false.
IMPORT [STD]
WRITE "entry.txt" "words"
LET $hit: BOOL = IS_FILE("entry.txt")
ASSERT_EQ $hit true
LET $miss: BOOL = IS_FILE("no-such-entry.txt")
ASSERT_EQ $miss false

STD::IS_MAIN

Report whether the current context is the entry script.

True at entry top level and inside entry-owned functions; false inside module-owned functions and module init bodies. Lets a library file double as a runnable demo: guard the demo with IF IS_MAIN() so importing it stays side-effect free.

Signature: STD::IS_MAIN(): BOOL

Contexts: AST only

Returns: BOOL

Examples:

Example: main

# Entry top level runs as main.
IMPORT [STD]
LET $m: BOOL = IS_MAIN()
ASSERT_EQ $m true

Example: library doubles as demo

# A library doubles as a runnable demo: guard the demo with
# IF IS_MAIN() so importing it stays side effect free. The
# parent writes both files, then runs each in a fresh
# interpreter: direct execution prints the demo, importing
# it does not. Unified roots: the child inherits one
# workspace, so parent and child see the same files. The
# exact stdout match proves the demo line stays out of the
# importing run.
IMPORT [STD]

# The library under test: demo guarded by IS_MAIN.
WRITE lib.oxfile """
    IMPORT [STD]
    FUNC GREET($x: STRING): STRING { RETURN "hi \{{ $x }}" }
    EXPORT GREET
    IF IS_MAIN() {
        ECHO "demo: hi Ada"
    }
    """

# The importer: calls the library, prints only its own line.
WRITE main.oxfile """
    IMPORT ["lib.oxfile" AS LIB]
    LET $g: STRING = LIB::GREET("Bo")
    ECHO "imported: \{{ $g }}"
    """

# Direct run executes the demo.
LET $exe: STRING = INTERPRETER()
LET $direct: STRING = RUN [$exe, "lib.oxfile"]
ASSERT_CONTAINS $direct "demo: hi Ada"

# Importing run stays silent apart from its own line.
LET $via: STRING = RUN [$exe, "main.oxfile"]
ASSERT_EQ $via "imported: hi Bo\n"

STD::IS_TERMINAL

Report whether a standard stream is a terminal.

IS_TERMINAL("stdin"), IS_TERMINAL("stdout"), or IS_TERMINAL("stderr") answers for the step's stream as currently bound, so scripts can adapt prompts, colors, and progress output. Anything diverted from the terminal reports false without touching host handles: WITH_IO pipe bindings (script backends and OS pairs), LET-capture sinks, staged runner sinks, and any materialized stdin stream (only a directly inherited fd falls back to the process check). A transparent root tee still answers the session question via the process check. The name matches exactly (no case folding): anything else bails. AST-only: reads the step context like the other introspection functions.

Signature: STD::IS_TERMINAL($stream_name: STRING = "stdin" | "stdout" | "stderr"): BOOL

Contexts: AST only

Parameters:

  • $stream_name (STRING = "stdin" | "stdout" | "stderr"): Stream name: stdin, stdout, or stderr (exact match).

Returns: BOOL

Examples:

Example: null stdin

# A null stdin is never a terminal, in every harness.
IMPORT [STD]
LET $term: BOOL = IS_TERMINAL("stdin")
ASSERT_EQ $term false

STD::LEN

Count the elements of a text, list, or map as an INT.

Strings count Unicode scalars: multibyte characters count once each, so this is not the byte length ("héllo" binds 5, not 6). Lists count elements, maps count entries; empty values bind 0. The ${#var} and wc -m counterpart for scripts that size tags, digests, and table rows.

Signature: STD::LEN($value: STRING|LIST|MAP): INT

Contexts: AST, RPN

Parameters:

  • $value (STRING|LIST|MAP): Value to measure.

Returns: INT

Examples:

Example: length

# Plain text counts one per character.
IMPORT [STD]
LET $n: INT = LEN("hello")
ASSERT_EQ $n 5

# Multibyte characters count once each, not per byte.
LET $wide: INT = LEN("héllo")
ASSERT_EQ $wide 5

# Lists count elements, maps count entries.
LET $items: LIST<STRING> = ["a", "b", "c"]
LET $nitems: INT = LEN($items)
ASSERT_EQ $nitems 3
LET $row: MAP<name: STRING> = {name: "ada"}
LET $nkeys: INT = LEN($row)
ASSERT_EQ $nkeys 1
LET $empty: INT = LEN([])
ASSERT_EQ $empty 0

STD::LOAD_JSON

Load and parse a JSON file.

Reads a workspace file and parses JSON into a DSL value. Returns ANY by design: a top-level array or scalar parses to LIST or a scalar word. LET coercion still checks the actual value at assignment.

Signature: STD::LOAD_JSON($path: STRING|PATH): ANY

Contexts: AST, RPN

Parameters:

  • $path (STRING|PATH): Workspace file path to load and parse as JSON.

Returns: ANY

Examples:

Example: load

IMPORT [STD]
WRITE "data.json" "{\"a\": 1}"
LET $doc: MAP<ANY> = LOAD_JSON("data.json")
ASSERT_EQ $doc.a 1

STD::LOAD_TOML

Load and parse a TOML file.

Reads a workspace file and parses TOML into a DSL value.

Signature: STD::LOAD_TOML($path: STRING|PATH): MAP<ANY>

Contexts: AST, RPN

Parameters:

  • $path (STRING|PATH): Workspace file path to load and parse as TOML.

Returns: MAP<ANY>

Examples:

Example: load

IMPORT [STD]
WRITE "cfg.toml" "title = \"demo\""
LET $cfg: MAP<ANY> = LOAD_TOML("cfg.toml")
ASSERT_EQ $cfg.title "demo"

STD::MAP_SET

Insert one key into a map, returning the extended map.

Fails on duplicates so two entries sharing a key fail the run instead of silently shadowing each other.

A frozen (CONST-derived) map fails instead of deriving: CONST bindings never produce a mutable map, so snapshot explicitly through a LET copy of unfrozen data if derivation is intended.

Signature: STD::MAP_SET($map: MAP<ANY>, $key: STRING, $value: ANY): MAP<ANY>

Contexts: AST, RPN

Parameters:

  • $map (MAP<ANY>): Map to insert into.
  • $key (STRING): Key to insert; duplicates fail.
  • $value (ANY): Value to store.

Returns: MAP<ANY>

Examples:

Example: insert

IMPORT [STD]
LET $m: MAP<ANY> = MAP_SET({seed: 0}, "a", 1)
ASSERT_EQ $m.a 1

STD::MERGE_MAPS

Merge a LIST of MAPs in order under one duplicate policy.

fail_on_duplicate fails naming the repeated key, so two files claiming one placeholder fail the run instead of shadowing each other. overwrite lets later files win, for environment overlays. Non MAP elements fail naming their position.

A frozen (CONST-derived) list or element fails instead of deriving, mirroring MAP_SET: CONST bindings never produce a mutable map.

Signature: STD::MERGE_MAPS($maps: LIST<MAP<ANY>>, $policy: STRING = "fail_on_duplicate" | "overwrite"): MAP<ANY>

Contexts: AST, RPN

Parameters:

  • $maps (LIST<MAP<ANY>>): LIST of MAPs to merge in order.
  • $policy (STRING = "fail_on_duplicate" | "overwrite"): Duplicate policy.

Returns: MAP<ANY>

Examples:

Example: merge

IMPORT [STD]
LET $m: MAP<ANY> = MERGE_MAPS([{a: 1}, {b: 2}], "overwrite")
ASSERT_EQ $m.a 1
ASSERT_EQ $m.b 2

STD::PARSE_ARGS

Parse an argv tail against TYPE FLAGS.

Consumes a LIST<STRING> with the lexopt tokenizer and coerces flags through TYPE FLAGS. See the function reference for the coercion and omission rules.

Signature: STD::PARSE_ARGS($args: LIST<STRING>): MAP<flags: MAP, positionals?: LIST<STRING>>

Contexts: AST, RPN

Parameters:

  • $args (LIST<STRING>): Argv tail to parse, usually from STD::ARGV().

Returns: MAP<flags: MAP, positionals?: LIST<STRING>>

  • flags (MAP): Flags coerced to TYPE FLAGS.
  • positionals (LIST<STRING>, optional): Trailing values and entries after the first double dash. Omitted when empty.

Examples:

Example: flags and positionals

IMPORT [STD]
# One schema TYPE drives coercion; the pair binds both slots.
TYPE FLAGS = MAP<model: STRING, verbose?: BOOL>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $parsed: PARSED = PARSE_ARGS(["--model=gpt-4", "--verbose", "serve"])
LET $flags: FLAGS = $parsed.flags
ASSERT_EQ $flags.model "gpt-4"
ASSERT_EQ $flags.verbose true
ASSERT_EQ $parsed.positionals.0 "serve"

Example: optional stays absent

IMPORT [STD]
# Absent optionals stay absent; read them with a typed GET default.
TYPE FLAGS = MAP<model: STRING, propose?: BOOL>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
LET $flags: FLAGS = $parsed.flags
LET $propose: BOOL = GET($flags, "propose", false)
ASSERT_EQ $propose false

Example: flags only omits positionals

IMPORT [STD]
# Empty positionals are omitted, so a flags only shape binds clean.
TYPE FLAGS = MAP<model: STRING>
TYPE PARSED = MAP<flags: FLAGS>
LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
LET $flags: FLAGS = $parsed.flags
ASSERT_EQ $flags.model "x"

Example: literal defaults

IMPORT [STD]
# Defaults are literals only: INT, FLOAT, BOOL,
# and double-quoted STRING fill absent flags.
TYPE FLAGS = MAP<retries: INT = 2, ratio: FLOAT = 2.5, verbose: BOOL = true, model: STRING = "gpt-4">
TYPE PARSED = MAP<flags: FLAGS>
LET $parsed: PARSED = PARSE_ARGS([])
LET $flags: FLAGS = $parsed.flags
ASSERT_EQ $flags.retries 2
ASSERT_EQ $flags.verbose true
ASSERT_EQ $flags.model "gpt-4"
LET $ratio_ok: BOOL = $flags.ratio == 2.5
ASSERT_EQ $ratio_ok true

Example: variable default fails

IMPORT [STD]
# Defaults are literals: a variable in place
# of a literal fails instead of evaluating.
TYPE FLAGS = MAP<n: INT = $x>
TYPE PARSED = MAP<flags: FLAGS>
LET $p: PARSED = PARSE_ARGS([])

Expected error: expected default literal

Example: missing required

IMPORT [STD]
# Absent required flags fail naming the flag.
TYPE FLAGS = MAP<model: STRING>
TYPE PARSED = MAP<flags: FLAGS>
LET $parsed: PARSED = PARSE_ARGS([])

Expected error: missing required flag

Example: unknown flag

IMPORT [STD]
# Undeclared flags fail instead of passing through.
TYPE FLAGS = MAP<model: STRING>
TYPE PARSED = MAP<flags: FLAGS>
LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])

Expected error: unknown flag

Example: alias accepted

IMPORT [STD]
# One canonical key binds both spellings; the
# alias never appears as a separate key.
TYPE FLAGS = MAP<h: BOOL ALIAS help>
TYPE PARSED = MAP<flags: FLAGS>
LET $a: PARSED = PARSE_ARGS(["--help"])
ASSERT_EQ $a.flags.h true
LET $b: PARSED = PARSE_ARGS(["--h"])
ASSERT_EQ $b.flags.h true

Example: alias duplicate fails

IMPORT [STD]
# Canonical and alias together fail naming both.
TYPE FLAGS = MAP<h: BOOL ALIAS help>
TYPE PARSED = MAP<flags: FLAGS>
LET $p: PARSED = PARSE_ARGS(["--h", "--help"])

Expected error: duplicate flag

Example: alias missing names both

IMPORT [STD]
# Missing required flags name both spellings.
TYPE FLAGS = MAP<h: BOOL ALIAS help>
TYPE PARSED = MAP<flags: FLAGS>
LET $p: PARSED = PARSE_ARGS([])

Expected error: --h/--help

STD::PARSE_BYTE_COUNT

Parse a byte-count token to INT bytes.

Bare digits are bytes; suffixes B/KB/MB/GB/TB scale decimal and KIB/MIB/GIB/TIB binary, in any case. Plain INT values pass through (already bytes); integral finite FLOAT values convert. Pairs with FORMAT_BYTE_COUNT for the round trip.

# Units parse case-insensitively; bare digits are bytes.
IMPORT [STD]
LET $bytes: INT = PARSE_BYTE_COUNT("1Gb")
ASSERT_EQ $bytes 1_000_000_000

# Binary suffixes scale by powers of two.
LET $mebi: INT = PARSE_BYTE_COUNT("2mib")
ASSERT_EQ $mebi 2_097_152

# Digit runs group Rust-literal style.
LET $grouped: INT = PARSE_BYTE_COUNT("1_000_000")
ASSERT_EQ $grouped 1_000_000

# Plain numbers pass through as bytes already.
LET $plain: INT = PARSE_BYTE_COUNT(1_048_576)
ASSERT_EQ $plain 1_048_576

# Bare literals group too.
LET $bare: INT = PARSE_BYTE_COUNT(1_000_000)
ASSERT_EQ $bare 1_000_000

# One optional space separates number from unit.
LET $spaced: INT = PARSE_BYTE_COUNT("1 GB")
ASSERT_EQ $spaced 1_000_000_000

Signature: STD::PARSE_BYTE_COUNT($text: INT|FLOAT|STRING): INT

Contexts: AST, RPN

Parameters:

  • $text (INT|FLOAT|STRING): Byte-count token to parse, or bytes already.

Returns: INT

Examples:

Example: parse

IMPORT [STD]
LET $n: INT = PARSE_BYTE_COUNT("10KB")
ASSERT_EQ $n 10_000
LET $identity: INT = PARSE_BYTE_COUNT(512)
ASSERT_EQ $identity 512

STD::PARSE_DURATION

Parse a duration token to INT milliseconds.

Suffixes ms/s/m/h; a bare number means seconds. Pairs with FORMAT_DURATION for the round trip.

Signature: STD::PARSE_DURATION($text: STRING): INT

Contexts: AST, RPN

Parameters:

  • $text (STRING): Duration token to parse.

Returns: INT

Examples:

Example: parse

# A bare number means seconds, like TIMEOUT.
IMPORT [STD]
LET $ms: INT = PARSE_DURATION("2m")
ASSERT_EQ $ms 120_000

# Milliseconds stay exact.
LET $exact: INT = PARSE_DURATION("1500ms")
ASSERT_EQ $exact 1_500

# One optional space separates number from unit.
LET $spaced: INT = PARSE_DURATION("1 h")
ASSERT_EQ $spaced 3_600_000

STD::PARSE_FLAGS

Parse flags against TYPE FLAGS.

Consumes a LIST<STRING> and coerces flags through TYPE FLAGS. Returns the flags MAP directly; positional arguments fail.

Signature: STD::PARSE_FLAGS($args: LIST<STRING>): MAP

Contexts: AST, RPN

Parameters:

  • $args (LIST<STRING>): Argv tail to parse, usually from STD::ARGV().

Returns: MAP

Examples:

Example: flags only

IMPORT [STD]
# Flags only returns the flags MAP directly.
TYPE FLAGS = MAP<model: STRING, retries: INT = 2>
LET $flags: FLAGS = PARSE_FLAGS(["--model=x"])
ASSERT_EQ $flags.model "x"
ASSERT_EQ $flags.retries 2

STD::PARSE_JSON

Parse JSON text already held in memory.

Uses the same conversion as file loading, so fetch bodies, file contents, and captured text share one JSON value shape. Returns ANY by design, matching LOAD_JSON: a top-level array or scalar parses to LIST or a scalar word. LET coercion still checks the actual value at assignment.

Signature: STD::PARSE_JSON($text: STRING): ANY

Contexts: AST, RPN

Parameters:

  • $text (STRING): JSON text already held in memory.

Returns: ANY

Examples:

Example: parse

# Parse in-memory JSON text with the same conversion as file loading.
IMPORT [STD]
LET $body: STRING = "{\"a\": 1}"
LET $doc: ANY = PARSE_JSON($body)
ASSERT_EQ $doc.a 1

# Top-level arrays parse to LIST, which is why the return is ANY.
LET $items: LIST<ANY> = PARSE_JSON("[1, 2]")
ASSERT_EQ $items.0 1
ASSERT_EQ $items.1 2

STD::PARSE_POSITIONALS

Parse positionals in argv order.

Consumes a LIST<STRING> and returns positionals in argv order with no schema.

Signature: STD::PARSE_POSITIONALS($args: LIST<STRING>): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $args (LIST<STRING>): Argv tail to parse, usually from STD::ARGV().

Returns: LIST<STRING>

Examples:

Example: positionals only

IMPORT [STD]
# No schema needed: positionals are always strings in order.
TYPE POSITIONS = LIST<STRING>
LET $pos: POSITIONS = PARSE_POSITIONALS(["serve", "--", "--not-a-flag"])
ASSERT_EQ $pos.0 "serve"
ASSERT_EQ $pos.1 "--not-a-flag"

STD::PARSE_TOML

Parse TOML text already held in memory.

Uses the same conversion as file loading, so fetch bodies, file contents, and captured text share one JSON/TOML shape.

Signature: STD::PARSE_TOML($text: STRING): MAP<ANY>

Contexts: AST, RPN

Parameters:

  • $text (STRING): TOML text already held in memory.

Returns: MAP<ANY>

Examples:

Example: parse

IMPORT [STD]
LET $doc: MAP<ANY> = PARSE_TOML("title = \"demo\"")
ASSERT_EQ $doc.title "demo"

STD::PATH_BASE

Final segment of a path (PATH_BASE).

Pure lexical surgery with no filesystem access: backslashes normalize to slashes, trailing slashes trim (root stays /), then the text after the last slash binds. Empty input fails closed. Runs in templates like every pure builtin.

Signature: STD::PATH_BASE($path: STRING|PATH): STRING

Contexts: AST, RPN

Parameters:

  • $path (STRING|PATH): Path whose final segment to bind.

Returns: STRING

Examples:

Example: base

# Final segments bind without filesystem access.
IMPORT [STD]
LET $b: STRING = PATH_BASE("some-dir/some-file")
ASSERT_EQ $b "some-file"

# Trailing slashes trim before the split.
LET $d: STRING = PATH_BASE("some-dir/")
ASSERT_EQ $d "some-dir"

STD::PATH_JOIN

Join a directory and a file name with the host-native separator.

Both inputs accept STRING or workspace PATH words; the result is a STRING joined with the platform separator, so installers never hand-roll separators in templates. No filesystem access: missing parents fail later at the consumer. Stays STRING (not PATH) on purpose: the joined value is a not-yet-validated destination string like $dir itself, and PATH words re-canonicalize to forward slashes on template expansion, which would undo the native join.

Signature: STD::PATH_JOIN($dir: STRING|PATH, $name: STRING|PATH): STRING

Contexts: AST only

Parameters:

  • $dir (STRING|PATH): Directory half of the destination.
  • $name (STRING|PATH): File half of the destination.

Returns: STRING

Examples:

Example: join path

# Directory and file stem join with the native separator.
# Source `\` is one backslash at runtime; `/` works on Windows
# too, native just reads better there.
IMPORT [STD]
LET $p: STRING = PATH_JOIN("some-dir", "some-file")
[family:unix] ASSERT_EQ $p "some-dir/some-file"
[family:windows] ASSERT_EQ $p "some-dir\some-file"

STD::PATH_REL

Lexical relativization (PATH_REL): remainder of a path below a base.

Pure string surgery with no filesystem access: both sides normalize backslashes to slashes and trim trailing slashes, then base segments must prefix path segments on a segment boundary. Equal paths bind .; non-prefix inputs fail closed naming both sides. Absolute and relative shapes never mix. Runs in templates like every pure builtin.

Signature: STD::PATH_REL($base: STRING|PATH, $path: STRING|PATH): STRING

Contexts: AST, RPN

Parameters:

  • $base (STRING|PATH): Base prefix segments must match.
  • $path (STRING|PATH): Path below the base to relativize.

Returns: STRING

Examples:

Example: relativize

# Prefix bases strip to their remainder.
IMPORT [STD]
LET $r: STRING = PATH_REL("some-dir", "some-dir/some-file")
ASSERT_EQ $r "some-file"

# Equal paths bind dot.
LET $dot: STRING = PATH_REL("some-dir", "some-dir")
ASSERT_EQ $dot "."

STD::PATH_TYPE

Describe a filesystem entry.

Reports file, dir, symlink (no-follow), or absent. AST-only by design; there is no RPN arm for filesystem IO.

Signature: STD::PATH_TYPE($path: STRING|PATH): STRING

Contexts: AST only

Parameters:

  • $path (STRING|PATH): Workspace path of the entry to describe.

Returns: STRING

Examples:

Example: describe

IMPORT [STD]
WRITE "entry.txt" "words"
LET $kind: STRING = PATH_TYPE("entry.txt")
ASSERT_EQ $kind "file"
LET $missing: STRING = PATH_TYPE("no-such-entry.txt")
ASSERT_EQ $missing "absent"

STD::PATH_WRITABLE

Report whether an ordinary file can be created at a path.

Walks up to the nearest existing ancestor, requires it be a directory, and probes writability by creating and deleting a probe file, so retry loops never litter. The empty string is false. AST-only by design, like PATH_TYPE: there is no RPN arm for filesystem IO.

Signature: STD::PATH_WRITABLE($path: STRING|PATH): BOOL

Contexts: AST only

Parameters:

  • $path (STRING|PATH): Workspace path to probe for file creation.

Returns: BOOL

Examples:

Example: probe

# An absent nested path is writable when its ancestor is.
IMPORT [STD]
LET $fresh: BOOL = PATH_WRITABLE("probe-check/nested/file.txt")
ASSERT_EQ $fresh true

# The empty string never aliases the working directory.
LET $empty: BOOL = PATH_WRITABLE("")
ASSERT_EQ $empty false

STD::RAND

Draw a random FLOAT uniformly from [0, 1), optionally seeded.

Impure by design: unseeded calls return different values, so this runs on the AST script path only, never as a {{ }} placeholder call. A seed draws the same value on every run, for deterministic fixtures. Scale and shift the draw for wider ranges.

Signature: STD::RAND($options?: MAP<seed?: INT>): FLOAT

Contexts: AST only

Parameters:

  • $options? (MAP<seed?: INT>): Draw settings: seed. Omittable: a missing options MAP fills {}.
    • seed (INT, optional)

Returns: FLOAT

Examples:

Example: seeded draw

# A seed draws the same value on every run.
IMPORT [STD]
LET $one: FLOAT = RAND({seed: 7})
LET $two: FLOAT = RAND({seed: 7})
ASSERT_EQ $one $two

Example: unseeded draw

# Scale a unit draw into a backoff delay between 1 and 11 seconds.
IMPORT [STD]
LET $draw: FLOAT = RAND()
LET $delay: FLOAT = 1.0 + $draw * 10.0
IF $delay < 1.0 {
    FAIL "trap: RAND draw below range"
}
IF $delay >= 11.0 {
    FAIL "trap: RAND draw above range"
}
ECHO "retrying in {{ $delay }}s"

STD::SEMAPHORE_AVAILABLE

Read free permits under the lock, with no mutation.

Observability only (audit lines, healthchecks: active = max - free). Exact at read time and stale the instant the caller acts on it, so it must never drive admission: that is SEMAPHORE_TRY_ACQUIRE's job.

Signature: STD::SEMAPHORE_AVAILABLE($sem: SEMAPHORE): INT

Contexts: AST, RPN

Parameters:

  • $sem (SEMAPHORE): Semaphore handle from SEMAPHORE_NEW.

Returns: INT

Examples:

Example: readout

# Hold one permit on a cap of two.
IMPORT [STD]
LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)
LET $acq: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
ASSERT_EQ $acq.held true

# One held permit leaves exactly one free.
LET $free: INT = SEMAPHORE_AVAILABLE($sem)
ASSERT_EQ $free 1

STD::SEMAPHORE_NEW

Create a counting semaphore admitting at most max concurrent holders.

Non-positive maxima bail. The word names a shared backend: every clone observes the same count, and admission runs through SEMAPHORE_TRY_ACQUIRE, never through the SEMAPHORE_AVAILABLE readout.

Signature: STD::SEMAPHORE_NEW($max: INT): SEMAPHORE

Contexts: AST only

Parameters:

  • $max (INT): Maximum concurrent holders; must be positive.

Returns: SEMAPHORE

Examples:

Example: mint

# Mint a semaphore admitting at most two holders.
IMPORT [STD]
LET $sem: SEMAPHORE = SEMAPHORE_NEW(2)

# A fresh semaphore reports its full cap as available.
LET $free: INT = SEMAPHORE_AVAILABLE($sem)
ASSERT_EQ $free 2

STD::SEMAPHORE_TRY_ACQUIRE

Attempt one non-blocking acquire, always answering a MAP.

held is true with the permit under the permit key, or false with no permit key: branch on $m.held directly. The DSL has no null, so the absent key is the miss shape. Do not read $m.permit unless held: missing-key access bails strictly. Never waits, so no wait can wedge.

Signature: STD::SEMAPHORE_TRY_ACQUIRE($sem: SEMAPHORE): MAP<held: BOOL, permit?: PERMIT>

Contexts: AST only

Parameters:

  • $sem (SEMAPHORE): Semaphore handle from SEMAPHORE_NEW.

Returns: MAP<held: BOOL, permit?: PERMIT>

  • held (BOOL): true with the permit under permit, false with no permit key.
  • permit (PERMIT, optional): Permit handle; read only when held.

Examples:

Example: acquire

# First acquire holds with a permit to bind.
IMPORT [STD]
LET $sem: SEMAPHORE = SEMAPHORE_NEW(1)
LET $first: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
ASSERT_EQ $first.held true
LET $permit: PERMIT = $first.permit

# A capped semaphore answers held false with no permit key.
LET $second: MAP<held: BOOL, permit?: PERMIT> = SEMAPHORE_TRY_ACQUIRE($sem)
ASSERT_EQ $second.held false
LET $has_permit: BOOL = HAS_KEY($second, "permit")
ASSERT_EQ $has_permit false

STD::SHELL_JOIN_ARGS

Join argv words into one shell-parseable string.

Quotes each word with POSIX single-quote escaping through the shell-words crate, so the result re-splits to the same words. Inverse of SHELL_SPLIT_ARGS on the word side: splitting the result returns the input list unchanged.

Signature: STD::SHELL_JOIN_ARGS($words: LIST<STRING>): STRING

Contexts: AST, RPN

Parameters:

  • $words (LIST<STRING>): Words to join into a shell command string.

Returns: STRING

Examples:

Example: join args

# Plain words join with spaces and no quoting.
IMPORT [STD]
LET $plain: STRING = SHELL_JOIN_ARGS(["gh", "issue", "list"])
ASSERT_EQ $plain "gh issue list"

# Words with spaces quote, and the round trip is exact.
LET $words: LIST<STRING> = ["say", "hi there", "a'b"]
LET $joined: STRING = SHELL_JOIN_ARGS($words)
LET $back: LIST<STRING> = SHELL_SPLIT_ARGS($joined)
ASSERT_EQ $back.0 "say"
ASSERT_EQ $back.1 "hi there"
ASSERT_EQ $back.2 "a'b"

STD::SHELL_SPLIT_ARGS

Split a shell command string into argv words.

Parses POSIX shell word syntax (single and double quotes, backslash escapes) with the shell-words crate, the same splitter the remote plugins use. Returns a LIST<STRING>. Unbalanced quotes fail. Inverse of SHELL_JOIN_ARGS: joining the result re-splits to the same words.

Shell syntax only: plain prose with no quoting splits on whitespace like any shell would, which is rarely what prose wants.

Signature: STD::SHELL_SPLIT_ARGS($command: STRING): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $command (STRING): Shell command string to split into words.

Returns: LIST<STRING>

Examples:

Example: split args

# Quoted segments stay one word.
IMPORT [STD]
LET $argv: LIST<STRING> = SHELL_SPLIT_ARGS("gh issue comment 153 --body-file notes.md")
ASSERT_EQ $argv.0 "gh"
ASSERT_EQ $argv.3 "153"
ASSERT_EQ $argv.5 "notes.md"

# Quotes and escapes parse the shell way.
LET $quoted: LIST<STRING> = SHELL_SPLIT_ARGS("say \"hi there\" 'a b'")
ASSERT_EQ $quoted.0 "say"
ASSERT_EQ $quoted.1 "hi there"
ASSERT_EQ $quoted.2 "a b"

STD::TASK_POLL

Poll a background task without consuming it.

Reports the running state, the output tails accumulated so far, and the final outcome once finished. Repeated polls are safe, and a later AWAIT still joins normally. Polling after AWAIT fails like double-await: the handle is spent.

Map keys: state always names the phase ("running" or "finished"); ok is true unless the task failed; stdout_tail and stderr_tail carry bounded output with truncated_bytes counting dropped head bytes. Finished tasks add exit_code; clean finishes add result, failed ones add error instead.

Signature: STD::TASK_POLL($task: HANDLE): MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING>

Contexts: AST only

Parameters:

  • $task (HANDLE): Task handle from ASYNC.

Returns: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING>

  • state (STRING): Task phase: running or finished.
  • ok (BOOL): True unless the task failed.
  • stdout_tail (STRING): Bounded stdout tail, live while running.
  • stderr_tail (STRING): Bounded stderr tail, live while running.
  • truncated_bytes (INT): Dropped head bytes past the per-stream cap.
  • exit_code (INT, optional): Process exit code, present once finished.
  • result (ANY, optional): Task RETURN value, present on clean finish.
  • error (STRING, optional): Failure text, present on failed finish.

Examples:

Example: running poll

# A sleeping task is still running on the first poll.
IMPORT [STD]
LET $t: HANDLE<STRING> = ASYNC { SLEEP 30s; RETURN "done" }
LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
ASSERT_EQ $m.state "running"
ASSERT_EQ $m.ok true
# Clean up the sleeper so the run ends promptly.
CANCEL $t

Example: finished poll

# A finished task reports its value and final tails, then still awaits.
IMPORT [STD]
LET $t: HANDLE<STRING> = ASYNC { ECHO "hi"; SLEEP 1s; RETURN "done" }
# Do other work while the task runs; poll once it should be done.
SLEEP 2s
LET $m: MAP<state: STRING, ok: BOOL, stdout_tail: STRING, stderr_tail: STRING, truncated_bytes: INT, exit_code?: INT, result?: ANY, error?: STRING> = TASK_POLL($t)
ASSERT_EQ $m.state "finished"
ASSERT_EQ $m.result "done"
LET $o: STRING = AWAIT $t
ASSERT_EQ $o "done"

STD::TEXT_COUNT

Count non-overlapping literal occurrences of a needle.

Matches never share bytes, so "aaa" holds one "aa", matching grep -o 'aa' | wc -l. An empty needle fails closed instead of binding every character boundary. Matching is case-sensitive; there is no case-insensitive mode.

Signature: STD::TEXT_COUNT($text: STRING, $needle: STRING): INT

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to search.
  • $needle (STRING): Literal needle to count; empty fails closed.

Returns: INT

Examples:

Example: count

# Every non-overlapping occurrence counts once.
IMPORT [STD]
LET $n: INT = TEXT_COUNT("hello world", "o")
ASSERT_EQ $n 2

# Overlapping candidates never double count.
LET $once: INT = TEXT_COUNT("aaa", "aa")
ASSERT_EQ $once 1

STD::TEXT_COUNT_MATCHES

Count lines matching a regex pattern.

Lines split with universal newline handling, like TEXT_LINES, and each line reports independently: this is grep -c, so a line with two matches still counts once. Bad patterns fail closed naming the pattern and its position. Matching is case-sensitive unless the pattern carries an inline (?i) flag, which makes uppercase and lowercase letters match each other.

Signature: STD::TEXT_COUNT_MATCHES($text: STRING, $pattern: STRING): INT

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text whose lines to test.
  • $pattern (STRING): Regex pattern tested per line.

Returns: INT

Examples:

Example: count matches

# One line matches once no matter how many times it hits.
IMPORT [STD]
LET $n: INT = TEXT_COUNT_MATCHES("test a: test\ntest b: nope\ntest c: test", ": test")
ASSERT_EQ $n 2

# A miss binds zero, never an error.
LET $none: INT = TEXT_COUNT_MATCHES("test b: nope", ": test$")
ASSERT_EQ $none 0

STD::TEXT_ENDS_WITH

Report whether text ends with a literal suffix.

Returns BOOL; the endsWith(matrix.target, 'linux-musl') check in CI legs. Matching is case-sensitive; there is no case-insensitive mode.

Signature: STD::TEXT_ENDS_WITH($text: STRING, $suffix: STRING): BOOL

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to test.
  • $suffix (STRING): Literal suffix to look for.

Returns: BOOL

Examples:

Example: ends with

# Present suffixes report true; misses report false.
IMPORT [STD]
LET $hit: BOOL = TEXT_ENDS_WITH("x86_64-linux-musl", "linux-musl")
ASSERT_EQ $hit true

# A miss is false, not a failure.
LET $miss: BOOL = TEXT_ENDS_WITH("x86_64-linux-gnu", "linux-musl")
ASSERT_EQ $miss false

STD::TEXT_EXTRACT

Extract capture groups for the first regex match.

Returns a LIST<STRING> where index 0 is the full match and the rest are groups in order; non-participating groups bind empty so indexes stay stable. No match binds an empty list. Matching is case-sensitive unless the pattern carries an inline (?i) flag, which makes uppercase and lowercase letters match each other.

Signature: STD::TEXT_EXTRACT($text: STRING, $pattern: STRING): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to search.
  • $pattern (STRING): Regex pattern with capture groups.

Returns: LIST<STRING>

Examples:

Example: extract

# Index zero is the full match; groups follow in order.
IMPORT [STD]
LET $caps: LIST<STRING> = TEXT_EXTRACT("abc123", "([a-z]+)(\d+)")
ASSERT_EQ $caps.0 "abc123"
ASSERT_EQ $caps.1 "abc"
ASSERT_EQ $caps.2 "123"

STD::TEXT_FIELDS

Split text into whitespace-separated fields, ignoring empties.

Returns a LIST<STRING>; the checksum-line parser that replaces cut -d' ' -f1 in CI legs.

Signature: STD::TEXT_FIELDS($text: STRING): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to split into fields.

Returns: LIST<STRING>

Examples:

Example: fields

# Runs of whitespace separate fields; empties never appear.
IMPORT [STD]
LET $fields: LIST<STRING> = TEXT_FIELDS("  abc  def ")
ASSERT_EQ $fields.0 "abc"
ASSERT_EQ $fields.1 "def"

STD::TEXT_GREP

Keep the lines matching a regex pattern.

Splits with universal newline handling, like TEXT_LINES, and returns every matching line in order: plain grep, so a miss binds an empty list instead of failing. A trailing options MAP carries invert: TEXT_GREP($text, $pattern, {invert: true}) keeps every non-matching line instead, the grep -v shape. The MAP omits freely; a missing MAP keeps matches. Matching is case-sensitive unless the pattern carries an inline (?i) flag, which makes uppercase and lowercase letters match each other. Bad patterns fail closed naming the pattern and its position.

Signature: STD::TEXT_GREP($text: STRING, $pattern: STRING, $options?: MAP<invert?: BOOL>): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text whose lines to filter.
  • $pattern (STRING): Regex pattern keeping a line.
  • $options? (MAP<invert?: BOOL>): Filter settings: invert. Omittable: a missing options MAP fills {}.
    • invert (BOOL, optional)

Returns: LIST<STRING>

Examples:

Example: grep

# Matching lines come back as a list, in order.
IMPORT [STD]
LET $hits: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one")
ASSERT_EQ $hits.0 "one"
ASSERT_EQ $hits.1 "one more"

# A miss binds an empty list, never an error.
LET $miss: LIST<STRING> = TEXT_GREP("one\ntwo", "^z")
LET $joined: STRING = TEXT_JOIN($miss, ",")
ASSERT_EQ $joined ""

# The (?i) flag ignores case, so uppercase lines match too.
LET $folded: LIST<STRING> = TEXT_GREP("One\ntwo\nONE more", "(?i)^one")
ASSERT_EQ $folded.0 "One"
ASSERT_EQ $folded.1 "ONE more"

Example: grep invert

# The invert option keeps every non-matching line instead.
IMPORT [STD]
LET $kept: LIST<STRING> = TEXT_GREP("one\ntwo\none more", "^one", {invert: true})
ASSERT_EQ $kept.0 "two"

# A pattern matching every line binds an empty list, never an error.
LET $none: LIST<STRING> = TEXT_GREP("one\ntwo", "^", {invert: true})
LET $joined: STRING = TEXT_JOIN($none, ",")
ASSERT_EQ $joined ""

# Options ride into placeholders as MAP literals. Placeholder
# strings unescape only backslash and quote, so multiline text
# arrives through a variable.
LET $two_lines: STRING = "one\ntwo"
LET $msg: STRING = 'kept:{{ STD::TEXT_GREP($two_lines, "^one", {invert: true}) }}'
ASSERT_EQ $msg "kept:two"

STD::TEXT_JOIN

Join a LIST<STRING> with a literal separator into a STRING.

Signature: STD::TEXT_JOIN($elements: LIST<STRING>, $delimiter: STRING): STRING

Contexts: AST, RPN

Parameters:

  • $elements (LIST<STRING>): List elements to join.
  • $delimiter (STRING): Literal delimiter placed between elements.

Returns: STRING

Examples:

Example: join

# List items join with the separator between them.
IMPORT [STD]
LET $joined: STRING = TEXT_JOIN(["a", "b", "c"], ",")
ASSERT_EQ $joined "a,b,c"

STD::TEXT_LINES

Split text into lines with universal newline handling.

Normalizes through the line-ending crate first so LF, CRLF, CR, and mixed endings all split, then delegates the split itself to LineEnding::split instead of hand-rolled scanning. Returns a LIST<STRING>; eager-only like TEXT_SPLIT.

Signature: STD::TEXT_LINES($text: STRING): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to split into lines.

Returns: LIST<STRING>

Examples:

Example: lines

# Newlines split into line items.
IMPORT [STD]
LET $lines: LIST<STRING> = TEXT_LINES("one\ntwo\nthree")
ASSERT_EQ $lines.0 "one"
ASSERT_EQ $lines.1 "two"
ASSERT_EQ $lines.2 "three"

# Windows endings split the same way after normalization.
LET $crlf: LIST<STRING> = TEXT_LINES("one\r\ntwo\r\nthree")
ASSERT_EQ $crlf.0 "one"
ASSERT_EQ $crlf.1 "two"
ASSERT_EQ $crlf.2 "three"

# Old Mac endings split too, and mixed endings split together because the input normalizes to LF before splitting.
LET $mixed: LIST<STRING> = TEXT_LINES("a\r\nb\nc\rd")
ASSERT_EQ $mixed.0 "a"
ASSERT_EQ $mixed.1 "b"
ASSERT_EQ $mixed.2 "c"
ASSERT_EQ $mixed.3 "d"

STD::TEXT_LINES_RANGE

Read lines from through to as a LIST<STRING>: the sed -n 'A,Bp' window over universal newlines, for reading one file section without holding the surrounding text.

Lines are 1-based and inclusive on both ends. Ranges past the end clamp like sed instead of failing; a start before line 1 or past to fails closed, since no line reading satisfies it.

Signature: STD::TEXT_LINES_RANGE($text: STRING, $from: INT, $to: INT): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text whose lines to window.
  • $from (INT): First line, 1-based inclusive.
  • $to (INT): Last line, inclusive; past the end clamps.

Returns: LIST<STRING>

Examples:

Example: line range

# Lines 2 through 3 come back as a list, 1-based inclusive.
IMPORT [STD]
LET $window: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo\nthree\nfour", 2, 3)
ASSERT_EQ $window.0 "two"
ASSERT_EQ $window.1 "three"

# Ranges past the end clamp instead of failing.
LET $tail: LIST<STRING> = TEXT_LINES_RANGE("one\ntwo", 2, 9)
ASSERT_EQ $tail.0 "two"

STD::TEXT_MATCH

Report whether text matches a regex pattern.

Returns BOOL. Bad patterns fail closed naming the pattern and its position. Matching is case-sensitive unless the pattern carries an inline (?i) flag, which makes uppercase and lowercase letters match each other.

Signature: STD::TEXT_MATCH($text: STRING, $pattern: STRING): BOOL

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to test.
  • $pattern (STRING): Regex pattern to match.

Returns: BOOL

Examples:

Example: match

# Regex matches report true; misses report false.
IMPORT [STD]
LET $hit: BOOL = TEXT_MATCH("abc123", "\d+")
ASSERT_EQ $hit true

# A miss is false, not a failure.
LET $miss: BOOL = TEXT_MATCH("abc", "^\d+$")
ASSERT_EQ $miss false

STD::TEXT_REPLACE

Replace every literal occurrence of from with to.

Accepts STRING or PIPE; the return mirrors the input kind. Pipes scan through a from.len() sliding window, so needles split across chunk reads still rewrite. Literal sliding search, not a pattern: an empty from fails closed, and regex work with captures belongs to TEXT_REPLACE_REGEX. Matching is case-sensitive; there is no case-insensitive mode.

Signature: STD::TEXT_REPLACE($text: STRING|PIPE, $from: STRING, $to: STRING): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to rewrite.
  • $from (STRING): Literal text to search for; empty fails closed.
  • $to (STRING): Literal replacement text.

Returns: STRING|PIPE

Examples:

Example: replace

# Every literal occurrence rewrites in place.
IMPORT [STD]
LET $fixed: STRING = TEXT_REPLACE("hello world", "world", "there")
ASSERT_EQ $fixed "hello there"

Example: replace pipe mirrors

# Pipe input mints pipe output with the same rewrite.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "hello world"
}
LET $trimmed: PIPE = TEXT_TRIM($cap)
LET $out: PIPE = TEXT_REPLACE($trimmed, "world", "there")
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "hello there"

Example: replace template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'fixed:{{ STD::TEXT_REPLACE("hello world", "world", "there") }}'
ASSERT_EQ $msg "fixed:hello there"

STD::TEXT_REPLACE_REGEX

Replace every regex match, expanding $1 and $name captures.

Accepts STRING or PIPE; the return mirrors the input kind. Eager-only framing: matches span chunks, so pipe inputs stage through the spill substrate instead of streaming. Bad patterns fail closed naming the pattern and its position. Matching is case-sensitive unless the pattern carries an inline (?i) flag, which makes uppercase and lowercase letters match each other. The literal counterpart is TEXT_REPLACE.

Signature: STD::TEXT_REPLACE_REGEX($text: STRING|PIPE, $pattern: STRING, $replacement: STRING): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to rewrite.
  • $pattern (STRING): Regex pattern to match.
  • $replacement (STRING): Replacement with $1 and $name capture expansion.

Returns: STRING|PIPE

Examples:

Example: replace with captures

# Capture groups expand in the replacement.
IMPORT [STD]
LET $swapped: STRING = TEXT_REPLACE_REGEX("2026-10-13", "(\d+)-(\d+)-(\d+)", "$3/$2/$1")
ASSERT_EQ $swapped "13/10/2026"

Example: replace regex pipe mirrors

# Pipe input mints pipe output with the same rewrite.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "2026-10-13"
}
LET $trimmed: PIPE = TEXT_TRIM($cap)
LET $out: PIPE = TEXT_REPLACE_REGEX($trimmed, "(\d+)-(\d+)-(\d+)", "$3/$2/$1")
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "13/10/2026"

Example: replace regex template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'swapped:{{ STD::TEXT_REPLACE_REGEX("2026-10-13", "(\d+)-(\d+)-(\d+)", "$3/$2/$1") }}'
ASSERT_EQ $msg "swapped:13/10/2026"

STD::TEXT_SPLIT

Split text on a literal delimiter into a LIST<STRING>.

An empty delimiter splits into single characters. Eager-only by design: splitting into a list has no line framing to stream. Delimiters match case-sensitively; there is no case-insensitive mode.

Signature: STD::TEXT_SPLIT($text: STRING, $delimiter: STRING): LIST<STRING>

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to split.
  • $delimiter (STRING): Literal delimiter; empty splits into characters.

Returns: LIST<STRING>

Examples:

Example: split

# Delimiters split into list items.
IMPORT [STD]
LET $parts: LIST<STRING> = TEXT_SPLIT("a,b,c", ",")
ASSERT_EQ $parts.0 "a"
ASSERT_EQ $parts.1 "b"
ASSERT_EQ $parts.2 "c"

STD::TEXT_STARTS_WITH

Report whether text starts with a literal prefix.

Returns BOOL; the literal check behind tag and target branching such as matrix.target suffix and prefix tests. Matching is case-sensitive; there is no case-insensitive mode.

Signature: STD::TEXT_STARTS_WITH($text: STRING, $prefix: STRING): BOOL

Contexts: AST, RPN

Parameters:

  • $text (STRING): Text to test.
  • $prefix (STRING): Literal prefix to look for.

Returns: BOOL

Examples:

Example: starts with

# Present prefixes report true; misses report false.
IMPORT [STD]
LET $hit: BOOL = TEXT_STARTS_WITH("linux-musl-x64", "linux")
ASSERT_EQ $hit true

# A miss is false, not a failure.
LET $miss: BOOL = TEXT_STARTS_WITH("macos-arm", "linux")
ASSERT_EQ $miss false

STD::TEXT_TO_LOWER

Lowercase text with full Unicode mapping.

Accepts STRING or PIPE; the return mirrors the input kind. Pipes map chunk by chunk across a char-boundary carry, like TEXT_TO_UPPER.

Signature: STD::TEXT_TO_LOWER($text: STRING|PIPE): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to lowercase.

Returns: STRING|PIPE

Examples:

Example: lowercase

# Text folds to lowercase.
IMPORT [STD]
LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
ASSERT_EQ $quiet "hello"

Example: lowercase pipe mirrors

# Pipe input mints pipe output with the same fold.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "HELLO"
}
LET $out: PIPE = TEXT_TO_LOWER($cap)
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "hello"

Example: lowercase template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'quiet:{{ STD::TEXT_TO_LOWER("HELLO") }}'
ASSERT_EQ $msg "quiet:hello"

STD::TEXT_TO_UPPER

Uppercase text with full Unicode mapping.

Accepts STRING or PIPE; the return mirrors the input kind. Pipes map chunk by chunk across a char-boundary carry, so multibyte characters split across reads still fold correctly.

Signature: STD::TEXT_TO_UPPER($text: STRING|PIPE): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to uppercase.

Returns: STRING|PIPE

Examples:

Example: uppercase

# Text folds to uppercase.
IMPORT [STD]
LET $loud: STRING = TEXT_TO_UPPER("hello")
ASSERT_EQ $loud "HELLO"

Example: uppercase pipe mirrors

# Pipe input mints pipe output with the same fold.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "hello"
}
LET $out: PIPE = TEXT_TO_UPPER($cap)
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "HELLO"

Example: uppercase template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'loud:{{ STD::TEXT_TO_UPPER("hello") }}'
ASSERT_EQ $msg "loud:HELLO"

STD::TEXT_TRIM

Trim Unicode whitespace from both ends of text.

Accepts STRING or PIPE; the return mirrors the input kind. Pipes stream on a pump thread with O(chunk) memory: leading whitespace falls at the stream head while trailing whitespace holds in the spill substrate until the next segment proves it interior, so unbounded streams never buffer unbounded memory.

Signature: STD::TEXT_TRIM($text: STRING|PIPE): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to trim.

Returns: STRING|PIPE

Examples:

Example: trim

# Leading and trailing whitespace falls away.
IMPORT [STD]
LET $clean: STRING = TEXT_TRIM("  hello  ")
ASSERT_EQ $clean "hello"

Example: trim pipe mirrors

# Pipe input mints pipe output with the same transform.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "  hello  "
}
LET $out: PIPE = TEXT_TRIM($cap)
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "hello"

Example: trim template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'clean:{{ STD::TEXT_TRIM("  hello  ") }}'
ASSERT_EQ $msg "clean:hello"

Example: trim file template

# EXPAND templates resolve the same registry.
IMPORT [STD]
WRITE "tpl.txt" "clean:\{{ STD::TEXT_TRIM(\"  hello  \") }}"
LET $out: STRING = EXPAND "tpl.txt"
ASSERT_EQ $out "clean:hello"

STD::TEXT_TRIM_PREFIX

Strip one leading prefix, returning the input unchanged when absent.

Accepts STRING or PIPE; the return mirrors the input kind. Pipes decide on the first prefix.len() bytes and stream the rest untouched. Matching is case-sensitive; there is no case-insensitive mode. Used for tag prefix strips such as v1.2.3 to 1.2.3.

Signature: STD::TEXT_TRIM_PREFIX($text: STRING|PIPE, $prefix: STRING): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to strip.
  • $prefix (STRING): Leading prefix to remove once.

Returns: STRING|PIPE

Examples:

Example: strip prefix

# A present prefix falls away; absence returns the input unchanged.
IMPORT [STD]
LET $bare: STRING = TEXT_TRIM_PREFIX("v1.2.3", "v")
ASSERT_EQ $bare "1.2.3"

# Missing prefixes pass through untouched.
LET $same: STRING = TEXT_TRIM_PREFIX("1.2.3", "v")
ASSERT_EQ $same "1.2.3"

Example: strip prefix pipe mirrors

# Pipe input mints pipe output with the same strip.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "v1.2.3"
}
LET $trimmed: PIPE = TEXT_TRIM($cap)
LET $out: PIPE = TEXT_TRIM_PREFIX($trimmed, "v")
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "1.2.3"

Example: strip prefix template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_PREFIX("v1.2.3", "v") }}'
ASSERT_EQ $msg "bare:1.2.3"

STD::TEXT_TRIM_SUFFIX

Strip one trailing suffix, returning the input unchanged when absent.

Accepts STRING or PIPE; the return mirrors the input kind. Pipes hold a suffix.len() trailing window and stream the rest. Matching is case-sensitive; there is no case-insensitive mode.

Signature: STD::TEXT_TRIM_SUFFIX($text: STRING|PIPE, $suffix: STRING): STRING|PIPE

Contexts: AST, RPN

Parameters:

  • $text (STRING|PIPE): Text to strip.
  • $suffix (STRING): Trailing suffix to remove once.

Returns: STRING|PIPE

Examples:

Example: strip suffix

# A present suffix falls away; absence returns the input unchanged.
IMPORT [STD]
LET $bare: STRING = TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz")
ASSERT_EQ $bare "archive.tar"

# Missing suffixes pass through untouched.
LET $same: STRING = TEXT_TRIM_SUFFIX("archive.tar", ".gz")
ASSERT_EQ $same "archive.tar"

Example: strip suffix pipe mirrors

# Pipe input mints pipe output with the same strip.
IMPORT [STD]
LET $cap: PIPE
WITH_IO [stdout=$cap] {
    ECHO "archive.tar.gz"
}
LET $trimmed: PIPE = TEXT_TRIM($cap)
LET $out: PIPE = TEXT_TRIM_SUFFIX($trimmed, ".gz")
WITH_IO [stdin=$out] READ_LINE $line
ASSERT_EQ $line "archive.tar"

Example: strip suffix template

# String inputs run inside placeholders too.
IMPORT [STD]
LET $msg: STRING = 'bare:{{ STD::TEXT_TRIM_SUFFIX("archive.tar.gz", ".gz") }}'
ASSERT_EQ $msg "bare:archive.tar"

STD::TO_JSON

Encode a script value as JSON with one trailing newline.

Maps stay sorted; only template-safe shapes (STRING, INT, FLOAT, BOOL, LIST, MAP) survive, anything else fails here instead of rendering as a silent empty.

Signature: STD::TO_JSON($value: STRING|INT|FLOAT|BOOL|LIST|MAP): STRING

Contexts: AST, RPN

Parameters:

  • $value (STRING|INT|FLOAT|BOOL|LIST|MAP): Value to encode as JSON.

Returns: STRING

Examples:

Example: encode

IMPORT [STD]
LET $json: STRING = TO_JSON({a: 1})
ASSERT_EQ $json "{\"a\":1}\n"

STD::TYPES

List all known type names.

Sorted LIST of startup plus host-registered type descriptors. Reads the run's name directory, so it runs on the AST path like the other introspection functions.

Signature: STD::TYPES(): LIST<STRING>

Contexts: AST only

Returns: LIST<STRING>

Examples:

Example: list

IMPORT [STD]
LET $names: LIST<STRING> = TYPES()
ASSERT_CONTAINS $names "STRING"

STD::TYPE_DESCRIBE

Describe one type by name.

Returns a MAP with name, summary, and docs. Errors on unknown type. Reads the run's name directory, so it runs on the AST path.

Signature: STD::TYPE_DESCRIBE($name: STRING): MAP<name: STRING, summary: STRING, docs: STRING>

Contexts: AST only

Parameters:

  • $name (STRING): Type name to describe.

Returns: MAP<name: STRING, summary: STRING, docs: STRING>

  • name (STRING): Queried type name.
  • summary (STRING): One-line description.
  • docs (STRING): Full documentation text.

Examples:

Example: describe

IMPORT [STD]
LET $info: MAP<ANY> = TYPE_DESCRIBE("STRING")
ASSERT_EQ $info.name "STRING"

STD::TYPE_OF

Name the word a value holds, for data-driven branching.

Returns the registered type word (STRING, INT, FLOAT, BOOL, LIST, MAP, plus handle words like PIPE): the same name the value prints in arity and coercion errors, so scripts can branch on config shapes (a path string or a path list) without failing.

Signature: STD::TYPE_OF($value: ANY): STRING

Contexts: AST, RPN

Parameters:

  • $value (ANY): Value whose word to name.

Returns: STRING

Examples:

Example: name the word

IMPORT [STD]
LET $word: STRING = TYPE_OF(42)
ASSERT_EQ $word "INT"

STD::UNIQUE

Deduplicate a LIST, keeping the first occurrence of each member.

Membership uses strict values_equal (numeric INT and FLOAT compare across types, every other cross-type pair is unequal, matching CONTAINS and ==), so [1, 1.0] collapses to one element while ["1", 1] keeps both. Order is first occurrence; the empty list binds empty, never failing.

Signature: STD::UNIQUE($items: LIST<ANY>): LIST

Contexts: AST, RPN

Parameters:

  • $items (LIST<ANY>): List to deduplicate.

Returns: LIST

Examples:

Example: deduplicate

# First occurrences win, later repeats drop.
IMPORT [STD]
LET $seen: LIST<STRING> = UNIQUE(["a", "b", "a", "c", "b"])
ASSERT_EQ $seen.0 "a"
ASSERT_EQ $seen.1 "b"
ASSERT_EQ $seen.2 "c"
ASSERT_EQ LEN($seen) 3

# The empty list stays empty.
LET $empty: LIST<STRING> = UNIQUE([])
ASSERT_EQ LEN($empty) 0

Example: strict membership

# Numerics collapse across INT and FLOAT like CONTAINS.
IMPORT [STD]
LET $nums: LIST<ANY> = UNIQUE([1, 2.0, 1, 3])
ASSERT_EQ $nums.0 1
ASSERT_EQ $nums.1 2.0
ASSERT_EQ $nums.2 3
ASSERT_EQ LEN($nums) 3

# Stringified numbers never coerce to integers.
LET $mixed: LIST<ANY> = UNIQUE(["1", 1])
ASSERT_EQ $mixed.0 "1"
ASSERT_EQ $mixed.1 1
ASSERT_EQ LEN($mixed) 2

STD::VERSION

Report the running engine version.

Returns the workspace version baked in at compile time, so scripts and agents can branch on engine behavior instead of probing it.

Signature: STD::VERSION(): STRING

Contexts: AST, RPN

Returns: STRING

Examples:

Example: report

# The engine reports its own build version as a dotted string.
IMPORT [STD]
LET $v: STRING = VERSION()
ASSERT_CONTAINS $v "."

Contexts

Every function lists the contexts it runs in. AST is always available. RPN additionally requires a pure function or an explicit rpn opt in.

Context: AST

The parsed tree of a script, walked one step at a time. Statements, declarations, scopes, pipes, and IO live here. Every step knows its line number, so failures name it. Every function runs in this context.

Context: RPN

Arithmetic and comparison expressions compiled to a flat stack program of values with no statements, scopes, pipes, or step numbers. Pure functions run here with no flag. Stateful functions run here only when they opt in with #[oxdock_func(rpn)], which is reserved for read only queries that stay meaningful inside math (GLOB, LOAD_TOML, LOAD_JSON do this). A call that fails inside math reports the bare error with no step number.

Selective environment inheritance

Scripts no longer inherit the caller's environment wholesale. Except for the host-mirrored essentials documented in ENV_CONTRACTS.md, host variables stay private unless you opt in explicitly.

  • Add INHERIT_ENV [FOO, BAR, BAZ] at the very top of the script to copy those keys from the process environment before any other command runs.
  • The directive must be top-level: no guards, no surrounding blocks, and no repeats. Trying to nest or guard it triggers a parser error so scripts stay deterministic.
  • Subsequent ENV commands can override inherited values, similar to how Docker's ENV overrides --env flags.
  • Test harnesses and embedders can supply values programmatically; the environment-guards example injects DEPLOY_TARGET through the docs-conformance runner rather than the real process environment.

Keeping inheritance selective avoids leaking secrets by default while still allowing ergonomics for well-known keys (proxy settings, artifact caches, etc.).

Every variable the seed provides to spawned children is specified in ENV_CONTRACTS.md.

Path Separators

  • Cross-platform behavior: Paths in OxDock scripts are treated as filesystem paths and are resolved using Rust's Path/PathBuf APIs. That means you can use either /-separated paths or ./-prefixed relative paths in scripts and they will be interpreted correctly on Windows, macOS, and Linux.

  • Path separator preference / requirement: For consistency and portability, OxDock scripts should use the forward slash (/) as the path separator in script source. While the runtime resolves paths using platform APIs and will accept platform-specific absolute paths, using / in scripts (even on Windows) avoids needing to escape backslashes (\) and matches Docker-style examples. If you must reference a native Windows absolute path, prefer the C:/path/to form or escape backslashes carefully.

  • Relative paths: A leading ./ indicates a path relative to the current DSL working directory (the same semantics used by Docker). For example: COPY ./src ./out or SYMLINK ./dir ./dir-link will work on all platforms.

  • Absolute paths: Use platform-appropriate absolute paths (e.g., /usr/bin on Unix-like systems, C:\path\to on Windows). OxDock will use the host OS path semantics when resolving absolute paths.

  • Symlinks and Windows: Creating symlinks on Windows may require elevated permissions on some older OS versions; without permission the SYMLINK step fails with an error instead of falling back.

  • Globbing & shell expansion: OxDock does not implicitly perform shell globbing or shell-side expansion for file arguments. When you need shell semantics use RUN with the platform shell, or add explicit DSL commands that accept wildcards if you want portable behavior.

Workspaces & Filesystem

  • How workspaces are created: OxDock materializes a clean workspace as an isolated temporary directory. It does not implicitly populate that directory from Git; scripts can pull files in via COPY (from the build context) or COPY_GIT (from a specific revision). Treat this workspace as a scratchpad surface for experimentation: you can run scripts inside it, create or modify files, and prepare assets for publishing without affecting your main source tree or requiring --allow-dirty workflows.

  • Typical usage pattern: the temporary workspace is intended for short lived build and test iterations. Run scripts against it, inspect outputs, and discard when done. Because it is separate from the original repo it is safe to run multiple concurrent experiments without changing the original repo.

  • Four workspace roots: WORKSPACE SNAPSHOT (the default ephemeral temp location), WORKSPACE LOCAL (the local directory), WORKSPACE CACHE (a persistent per-project cache directory shared across runs), and WORKSPACE SYSTEM (full filesystem access, not hermetic). WORKSPACE selection reverts at scope exit like WORKDIR.

  • Persistent cache: WORKSPACE CACHE stores artifacts under the OS per-user cache, namespaced by application identity <app>, with a workspace group segment underneath. Concretely: macOS ~/Library/Caches/com.oxdock.<app>/workspace, Linux $XDG_CACHE_HOME/<app>/workspace (or ~/.cache/<app>/workspace), Windows %LOCALAPPDATA%\oxdock\<app>\cache\workspace.

  • Cache identity and lifecycle: identity resolves as explicit builder argument, OXDOCK_CACHE_APP, runtime CARGO_PKG_NAME, running binary name, then "oxdock"; OXDOCK_CACHE_DIR pins an exact directory instead (OS flavor only), and when no home directory is available the cache falls back to a temp dir (oxdock-cache-<app>). WORKSPACE CACHE --local keeps the cache in <project>/.cache/workspace instead, unconditionally. The directory is created on first use, survives restarts, and is never evicted by default.

  • Filesystem gating via oxdock-fs: all filesystem operations in the runtime are routed through the crate internal oxdock-fs abstraction. That module centralizes path resolution, canonicalization and access checks so reads and writes can be validated against the allowed workspace root and build context. WORKSPACE SYSTEM intentionally bypasses these checks; scripts using it are not hermetic.

  • What oxdock-fs protects you from: the guardrails are pragmatic. They prevent common mistakes such as accidentally writing outside the materialized workspace or reading files from arbitrary absolute paths. However, they are not a full sandbox. A determined process or script can still create destructive actions (for example, invoking native RUN commands that modify external state). If you require strict isolation, run OxDock inside a container or VM.

  • Performance: routing via oxdock-fs adds negligible overhead for typical workloads. The module focuses on correctness and containment with minimal runtime cost so interactive iteration remains fast.

Errors stop the pipeline

A pipeline is expected to run to completion. The engine is fail fast: the first failed step ends the run immediately, later steps do not execute, and the failure is reported with its step context. There is no retry, resume, or continue on error mode, and partial completion is not treated as success.

Choosing not to run work is different from failing it. Guards and branches select work, timeouts bound it, and EXIT <code> is the intentional form of an immediate stop. Files written before the stop persist, while unwinding and task teardown follow the normal scope rules.

When a script fails to parse

Parse errors tell you what went wrong, where, and what was expected. Every error names the line and column, echoes the source line, and points a caret at the offending text. A syntax error is never reported as unknown command: any line starting with a known command or keyword always explains the real problem instead. Each example below runs the real parser and pins its exact output.

A typo in the command name reports the line with a caret:

use indoc::indoc;
use oxdock::oxdock_parser;

let script = indoc! {"
    FROBNICATE hi
"};
let err = oxdock_parser::parse_script(script, oxdock_parser::lower_command)
    .expect_err("must fail");
let expected = indoc! {"
    unknown command \"FROBNICATE\"
      --> line 1, col 1-13
      1 | FROBNICATE hi
        | ^^^^^^^^^^^^^
"};
assert_eq!(err.to_string(), expected.trim_end());

A malformed line for a real command reports the expected syntax with an example. Here the LET is missing its required type:

use indoc::indoc;
use oxdock::oxdock_parser;

let script = indoc! {"
    LET $x = 1
"};
let err = oxdock_parser::parse_script(script, oxdock_parser::lower_command)
    .expect_err("must fail");
let expected = indoc! {"
    LET requires explicit types: LET $var: TYPE = <expr>
      --> line 1, col 1-10
      1 | LET $x = 1
        | ^^^^^^^^^^
"};
assert_eq!(err.to_string(), expected.trim_end());

A valid command with malformed WITH_IO bindings explains the binding rules instead of claiming the command does not exist:

use indoc::indoc;
use oxdock::oxdock_parser;

let script = indoc! {"
    WITH_IO [stdout=discard] ECHO hi
"};
let err = oxdock_parser::parse_script(script, oxdock_parser::lower_command)
    .expect_err("must fail");
let expected = indoc! {"
    WITH_IO needs `WITH_IO [bindings] <command>` or `WITH_IO [bindings] { <commands> }`: invalid binding `stdout=discard`; 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]`); got `[stdout=discard] ECHO hi`
      --> line 1, col 1-32
      1 | WITH_IO [stdout=discard] ECHO hi
        | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
"};
assert_eq!(err.to_string(), expected.trim_end());

Lowercase commands are caught at parse time with a correction note:

use indoc::indoc;
use oxdock::oxdock_parser;

let script = indoc! {"
    echo hi
"};
let err = oxdock_parser::parse_script(script, oxdock_parser::lower_command)
    .expect_err("must fail");
let expected = indoc! {"
    command must be uppercase: found `echo`, expected `ECHO`
      --> line 1, col 1-7
      1 | echo hi
        | ^^^^^^^
"};
assert_eq!(err.to_string(), expected.trim_end());

Reading an error, top to bottom: the first line states the kind and the fix (expected syntax or a did you mean hint), the --> line gives the statement's line, and the caret marks the statement to change (lexer-level mistakes such as unbalanced groups point at their exact position). Runtime failures name their position the same way: step N, line L, col C (the step index, then the statement's source coordinates), so a failing run points at the exact script line instead of an index alone.

Plugin references

Full function and type references for the bundled host plugins live in their own READMEs:

Runtime architecture

Four mechanisms keep script execution predictable: how values are stored, how bytes move between commands, how state stays isolated, and how the host stays sandboxed. Each one is shown running below.

Values: words, not objects

Every script value is a fixed 128 bit word that lives on the stack: a static type descriptor pointer plus a 64 bit payload. Only payload contents may live on the heap, never the word itself.

Scalars that fit (INT, FLOAT, BOOL, handles) ride inline, copied into the payload byte for byte with zero allocation, so arithmetic and loop counters run at register speed and never touch the allocator. Strings and host types ride behind a thin pointer to a single owned box holding the concrete Rust type, while containers (LIST, MAP) ride behind a thin pointer to a shared reference counted buffer. The pointer stays thin because every payload type is sized, so there are no fat pointers and no trait objects anywhere in the path.

A naive tagged enum needs 32 bytes per value (a 24 byte payload plus tag and padding), so the word form holds four values per 64 byte cache line instead of two.

Type checks compare one descriptor address, and operations (clone, drop, equality, formatting) call the descriptor directly, with no registry lookup and no lock. Each type owns one compile time descriptor singleton, so identity is pointer equality that fails closed. Host types extend the same path: #[oxdock_type] derives a static descriptor for the payload struct, and inline selects the zero allocation form for small Copy scalars.

There is no garbage collector because values form trees, not graphs. Each exclusive heap word owns its box exactly once: cloning allocates a fresh box with a deep copy, dropping frees it. Each container word co-owns its buffer instead: cloning a LIST or MAP bumps a reference count in constant time with no allocation, dropping releases one count. A LIST owns its items and a MAP owns its entries. Mutating a shared container detaches first, so clones never observe each other's writes: assignment behaves as a copy.

Nothing is mutably borrowed from two places, so cycles cannot form and plain deterministic cleanup suffices. Pointer casts always round trip through the same concrete box or buffer type, and inline words never enter the pointer domain, which keeps provenance intact. The lifecycle is checked under Miri.

No pauses, no write barriers, no background collector. Python, JavaScript, and Lua permit aliasing and cycles and need tracing collectors to reclaim them; here there is nothing to trace.

Design Stack word Scalar allocs Cache density Host extensibility
Tagged Rust enum 32 bytes 0 2 values per line Closed
Boxed trait objects 16 byte fat pointer 1 per scalar Medium Open
16 byte word (this design) 16 bytes 0 4 values per line Open, static descriptors
NaN boxing (LuaJIT, V8) 8 bytes 0 8 values per line Constrained

Two trade offs come with the form. Cloning a string still deep copies it, since only containers share buffers. And 16 bytes is roomier than 8 byte NaN boxing, which buys clean 64 bit integer and float storage plus safe abstraction boundaries without pointer masking.

Transport: pipes

Pipes are runtime-managed streams, not file descriptors. There is exactly one interface: declare (LET $p: PIPE), wire (WITH_IO [stdout=$p] or [stdin=$p]), and pass or copy the handle across calls, tasks, and module boundaries. Scripts never allocate descriptors, never manage temp files, and never write platform plumbing: the runtime owns backend selection, lifetime, and EOF. Buffers stay in memory and spill to a guarded temp file past 8 MiB, background single command tasks can promote a pipe to a zero copy OS kernel pair instead, the last drop closes, and keepers pin background gaps. The same spelling runs identically on Linux, macOS, and Windows.

LET $log: PIPE
WITH_IO [stdout=$log] ECHO hello
WITH_IO [stdin=$log] READ_LINE $line
ASSERT_EQ $line "hello"

Scope isolation

State mutations stay where the script puts them. Entering a braced block or a function call snapshots variables and settings, and exiting restores all of them, so nothing leaks outward. Background tasks fork the same way, so concurrent workers cannot observe each other's half finished mutations. Only pipes and filesystem effects cross these boundaries, by design.

# Calls snapshot caller state: the parameter shadows without clobbering.
LET $v: STRING = "outer"
FUNC SHADOW($v: STRING): STRING {
    LET $inner: STRING = "inner"
    RETURN $v
}

LET $out: STRING = SHADOW("param")
ASSERT_EQ $out "param"
ASSERT_EQ $v "outer"

# Background tasks fork the same way: worker mutations never escape.
LET $w: STRING = "outer"
LET $t: HANDLE<VOID> = ASYNC {
    $w = "inner"
    ECHO "task-ran"
}
AWAIT $t
ASSERT_EQ $w "outer"
ASSERT_CONTAINS stdout "task-ran"

Sandboxing

Every path resolves inside a guarded workspace root, and escapes are rejected before any filesystem call. Scripts start with only builtin keys (Cargo feature/cfg entries, WORKSPACE_GIT_COMMIT) and opt into host variables explicitly.

WRITE ../escape.txt "nope"

OxDock sandboxes by plumbing, not virtualization: scrubbed child environments, workspace-scoped paths, and typed verbs instead of raw shell let scripts communicate across trust barriers with no hypervisor. That same plumbing is what lets an agent talk to other environments in a controlled fashion: pipes, guarded paths, scrubbed environments, and the REMOTE and SSH transports are all declared channels, so every crossing goes through the boundary, never around it.

That is a competence boundary, not a security boundary. It keeps a clumsy agent from wandering; it does not contain a hostile payload. For untrusted code, run OxDock itself inside a container or VM.

Containers as orchestrated steps

Static orchestration checks in fixed Compose files and image artifacts. Scripts can do it programmatically instead. One example pattern: docker-pipeline.oxfile holds the Dockerfile in a variable, feeds it to docker build over stdin with zero files written, fans out concurrent docker run containers over pipes, and transforms between them in the DSL with assertions on every hop. Other layouts work the same way.

REMOTE is another pattern for the other direction: a controller script outside the container runs a sealed block inside it over a stdio transport such as docker exec -i (bound with --remote), with only header-listed values crossing and results returning through declared transfers or pipes. The plumbing is symmetric, so the reverse works the same way when the transport is set up: a guest inside orchestrates outward through the same declared channels, all under script control.

Prepare during the build

oxdock_embed! ships artifacts inside the binary. oxdock_prepare! runs the same script but emits no runtime module. Use it when assets only need to exist during the build, for codegen or include! workflows.

use oxdock_macros::oxdock_prepare;

oxdock_prepare! {
    name: PreparedAssets,
    script: {
        MKDIR gen
        WRITE gen/out.txt generated
        LET $o: STRING = READ gen/out.txt
        ASSERT_EQ $o "generated"
    },
    out_dir: "target/prebuilt_prepare",
}

fn main() {}

Stream bytes between steps

WITH_IO routes a step's stdout into a script pipe and back into another step's stdin. Run the producer under ASYNC so both ends stay live while bytes flow.

LET $msg: PIPE
WITH_IO [stdout=$msg] ASYNC ECHO piped-bytes
WITH_IO [stdin=$msg] WRITE piped.txt
READ piped.txt
ASSERT_CONTAINS stdout "piped-bytes"

Scripts start in SNAPSHOT

Scripts start in the SNAPSHOT workspace, an ephemeral isolated temp dir that leaves the source tree untouched. It is the only ephemeral root. Pull inputs with COPY or COPY_GIT. Each root below is entered inside a scoped block, which reverts to the previous root on exit.

IMPORT [STD]

# SNAPSHOT is the starting root.
WRITE snap.txt from-snapshot
LET $s: STRING = READ snap.txt
ASSERT_EQ $s "from-snapshot"

# LOCAL is a separate directory: snapshot files are absent there.
[bool:true] {
    WORKSPACE LOCAL
    LET $t: STRING = PATH_TYPE("snap.txt")
    ASSERT_EQ $t "absent"
    WRITE local.txt from-local
}

# The block reverted to SNAPSHOT: the local file is absent here.
LET $u: STRING = PATH_TYPE("local.txt")
ASSERT_EQ $u "absent"

# CACHE persists outside the snapshot and reads back through its own root.
[bool:true] {
    WORKSPACE CACHE
    WRITE cached.txt from-cache
}
COPY --from-workspace CACHE cached.txt restored.txt
LET $w: STRING = READ restored.txt
ASSERT_EQ $w "from-cache"

# CACHE --local is a different directory from the OS cache.
[bool:true] {
    WORKSPACE CACHE --local
    LET $x: STRING = PATH_TYPE("cached.txt")
    ASSERT_EQ $x "absent"
}

# SYSTEM keeps the current directory: relative paths keep working.
# Scripts using it are not hermetic.
[bool:true] {
    WORKSPACE SYSTEM
    WRITE sys.txt from-system
}
LET $y: STRING = READ sys.txt
ASSERT_EQ $y "from-system"

Machine model

How the machinery operates, for the curious. Behavior contracts live in the command and function reference. This section maps those contracts onto the moving parts: words, evaluators, and the stack program that runs math.

Words

Every script value is one 128 bit word: a descriptor pointer plus a 64 bit payload. The descriptor names the type and carries the vtable that clones, drops, compares, and renders the value. The payload is either inline bytes (for Copy scalars that fit in 64 bits, with zero allocation) or a pointer to one owned heap box (for containers and everything else). Words are fixed size and deterministic to move, which is what keeps the host boundary cheap: plain Rust functions returning Result<Value>, nothing to pin and nothing reference counted. The glossary defines each of these terms precisely.

Two evaluators

Scripts run under two evaluators. The AST evaluator walks the parsed tree one step at a time, with line numbers on every failure. The RPN evaluator runs arithmetic and comparison as a flat stack program with values only and no step numbers. Which functions may run where is the Contexts rule: everything runs on the tree, and only pure functions plus explicit rpn opt ins run on the stack program.

The stack program

Parsing lowers each arithmetic or comparison subtree in three passes. First, literal only subtrees fold to their value and vanish. Then the survivors flatten to postfix ops with resolved arities: loads for variables, env reads, and keypaths; prebuilt constants; calls; and one op per arithmetic or comparison operator. Anything without a stack encoding (!, && and ||, list and map literals, pipes) stays a tree node and runs on the AST path. The static pre-pass type checks the same program abstractly before the first step runs, so math shape errors surface early with the same step free wording the runtime reports. The program is built once per parse and runs again on every evaluation, so a WHILE condition pays lowering once no matter how many iterations it runs.

The demos below are computed, not copied: each placeholder lowers its expression through the real parser on every docs run, so the shown ops cannot drift from the implementation.

$a + 2 * $b is the classic shape: loads and one constant feeding two operators.

`$a + 2 * $b` lowers to 5 ops:
1. LoadVar($a)
2. PushConst(2)
3. LoadVar($b)
4. Mul
5. Add

1 + 2 * 3 never reaches the stack machine: both subtrees fold at parse time.

`1 + 2 * 3` folds to the literal `7` at parse time: no ops are emitted

!$ready has no stack encoding and stays on the tree path.

`!$ready` has no RPN encoding and stays a tree node: `!$ready`

One language for the whole build: farm steps out to npm, bundlers, or code generators and pull their artifacts back under cargo's control. Pipe bytes between steps (buffered in memory to 8 MiB, then spilled to a temp file), fan work out with ASYNC, or skip embedding entirely and run the same scripts as standalone CLI processes.

Why this shape

  • Effects arrive confined: reads resolve inside the workspace, env vars read empty unless declared, endpoints bind only when the runner maps them.
  • Declared dependencies make runs reproducible; the conformance suites pin the contract.
  • The engine stays fixed while process lives in editable text; only the vocabulary needs recompiling.

Variants

OxDock comes in two variants, each of which is independent of the other, but share the same core:

  • oxdock-macros: Provides a Rust build-time dependency which runs OxDock scripts during the compilation of a Rust program.
  • oxdock-cli: Command-line interface for running OxDock scripts from the command line.

Goals

OxDock has a simple goal to provide a simple DSL that works the same across macOS, Linux, and Windows, including support for background processes, symlinks, and boolean conditionals (such as env and platform-based command filtering), which runs the same whether it's used as a preprocessing step in a build-time Rust macro, or as a CLI program, regardless of platform it is building on.

Every internal command is engineered to run the same way across platforms, except for the RUN command, which calls native programs.

OxDock adds no additional runtime dependencies if used as a macro preprocessor.

Dynamically embed assets at compile time

Embed build-time dependencies from any language: scripts run inline during rustc, and their artifacts ship inside the binary with zero heap allocation, no_std included:

use oxdock_macros::oxdock_embed;

oxdock_embed! {
    // Generated struct for resource lookups via `SiteAssets::get(path)`.
    name: SiteAssets,

    // Manifest-relative staging directory. Run `cargo build` locally to generate
    // the files and `.oxdock_hash` fingerprint, then commit `prebuilt/` to git.
    // `cargo publish` vendors these files so downstream crates embed them
    // directly without re-running the script on read-only registry paths.
    // Set OXDOCK_EMBED_FORCE_REBUILD=1 to force re-execution.
    out_dir: "prebuilt",

    script: {
        // Executes in an isolated temporary workspace (`WORKSPACE SNAPSHOT`),
        // keeping the source tree clean unless `WORKSPACE LOCAL` is requested.
        ENV PROJECT=OxDock
        MKDIR dist

        // Exec form spawns cargo portably without a shell. Asserting the version string
        // in memory verifies the toolchain without baking volatile output into staged assets.
        LET $cargo: STRING = RUN ["cargo", "--version"]
        ASSERT_CONTAINS $cargo "cargo"

        // Assets stage under subdirectories relative to `out_dir` (e.g., prebuilt/dist/os.txt)
        WRITE dist/hello.txt "hello from {{ env:PROJECT }}"
        WRITE dist/project.txt "the-project"
        WRITE dist/manifest.txt "the-manifest"
    }
}

fn main() {
    // Verify we can read the resources we just created
    let hello = SiteAssets::get("dist/hello.txt").expect("hello must be embedded");
    assert_eq!(hello.data.as_ref(), b"hello from OxDock");

    let project = SiteAssets::get("dist/project.txt").expect("project must be embedded");
    assert_eq!(project.data.as_ref(), b"the-project");

    let manifest = SiteAssets::get("dist/manifest.txt").expect("manifest must be embedded");
    assert_eq!(manifest.data.as_ref(), b"the-manifest");
}

You can find an example of this workspace dogfooding this very design in its own CLI binary by searching for: usage-prebuilt.

For each artifact the macro emits a constant backed by include_bytes!, which bakes the file bytes into read-only binary data during compilation. At runtime get() scans a static table and returns a borrowed slice, so there are no file reads and no heap allocation. The support types only need alloc::borrow::Cow and core iterators, which is why it works in no_std.

Asset scripts resolve STD (via IMPORT [STD]) and SCRIPT functions only. There is no modules: prefix here, and that is structural, not missing: opaque modules defer membership to runtime, but asset scripts execute at compile time with no Engine to resolve against. Scripts needing host functions belong in build.rs through the Engine facade instead.

Run scripts inline

The oxdock! macro builds the same DSL into a Vec<Step> at compile time, so tests and tools can run scripts without a file. Pass the steps to a run_steps_* runner with a guarded root. The root types are re-exported from oxdock, so one dependency covers macros, runners, and roots: cargo add oxdock. Only portable commands are used below, so the script behaves identically on every OS.

use oxdock::{GuardedPath, PathResolver, oxdock, oxdock_parser, run_steps_with_context};

// A version stamping pipeline: variables, a function, a loop over a list,
// a conditional call, templates, and native assertions. The version comes
// from Cargo at compile time, never a literal.
let crate_version = env!("CARGO_PKG_VERSION");
let steps: Vec<oxdock_parser::Step> = oxdock! {
    ENV PROJECT=OxDock
    LET $version: STRING = #crate_version
    MKDIR dist

    FUNC STAMP($name: STRING, $version: STRING): STRING {
        ENV PROJECT=OxDock
        WRITE dist/{{ $name }}.txt {{ $name }} {{ env:PROJECT }} {{ $version }}
        RETURN $name
    }
    FOR $name: STRING IN ["alpha", "beta"] {
        STAMP($name, $version)
    }

    FUNC PICK($flag: BOOL): STRING {
        IF $flag {
            RETURN "alpha"
        }
        RETURN "beta"
    }
    LET $picked: STRING = PICK(true)
    WRITE dist/picked.txt {{ $picked }}

    LET $a: STRING = READ dist/alpha.txt
    LET $b: STRING = READ dist/beta.txt
    LET $p: STRING = READ dist/picked.txt
    ASSERT_EQ $a "alpha OxDock 0.46.0-alpha"
    ASSERT_EQ $b "beta OxDock 0.46.0-alpha"
    ASSERT_EQ $p "alpha"
};

let temp = GuardedPath::tempdir().expect("tempdir");
let root = temp.as_guarded_path().clone();
run_steps_with_context(&root, &root, &steps).expect("run script");

let resolver = PathResolver::new(root.as_path(), root.as_path()).expect("resolver");
let out = root.join("dist/alpha.txt").expect("out path");
assert_eq!(
    resolver.read_to_string(&out).expect("read out"),
    "alpha OxDock 0.46.0-alpha"
);

Use #var to inject Rust values into the script (any value that implements Display). DSL variables keep their $var form and are unaffected. Guards accept injected values too, so Rust flags can gate steps. The script below wires a pipe between steps, reads one line back into a variable, and expands every generated file.

use oxdock::{GuardedPath, PathResolver, oxdock, oxdock_parser, run_steps_with_context};

let project = "OxDock";
let verbose = true;
let steps: Vec<oxdock_parser::Step> = oxdock! {
    ENV PROJECT=#project
    MKDIR dist
    [bool:#verbose] WRITE dist/verbose.log "verbose on"

    LET $log: PIPE
    WITH_IO [stdout=$log] ECHO "built {{ env:PROJECT }}"
    WITH_IO [stdin=$log] READ_LINE $line
    WRITE dist/build.txt "{{ $line }}"

    IMPORT [STD]
    FOR $f: STRING IN GLOB("dist/*.txt") {
        EXPAND $f
    }

    ASSERT_CONTAINS stdout "built OxDock"
    LET $build: STRING = READ dist/build.txt
    LET $verbose: STRING = READ dist/verbose.log
    ASSERT_EQ $build "built OxDock"
    ASSERT_EQ $verbose "verbose on"
};

let temp = GuardedPath::tempdir().expect("tempdir");
let root = temp.as_guarded_path().clone();
run_steps_with_context(&root, &root, &steps).expect("run script");

let resolver = PathResolver::new(root.as_path(), root.as_path()).expect("resolver");
let out = root.join("dist/build.txt").expect("out path");
assert_eq!(
    resolver.read_to_string(&out).expect("read out"),
    "built OxDock"
);

The top level runners need the default cli feature. With --no-default-features, run the same steps through oxdock::oxdock_core::run_steps_* instead.

Scripts that call host functions declare their modules up front: the macro parses at compile time with only STD known, so modules: [DEMO], as the first line makes IMPORT [DEMO] and DEMO::... calls resolve (membership is checked at runtime). Scripts using only STD and SCRIPT functions omit it. See Extending OxDock from Rust for the complete example.

Extend the language

New types and functions take two attributes, a type registration, and a function module. Small Copy scalars can ride inline on the stack with zero allocation instead of heap boxing; both forms, with stateful functions, live under Extending OxDock from Rust below.

use oxdock::{Engine, HostModule, OxDockFn, OxDockType, Value, oxdock_func, oxdock_type};
use oxdock::oxdock_core::TypeTag;
use std::fmt;

/// Word count summary: computed in Rust, carried as one script value.
#[oxdock_type(name = "STATS")]
#[derive(Debug, Clone, PartialEq)]
struct Stats {
    words: usize,
    chars: usize,
}

impl fmt::Display for Stats {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{} words, {} chars", self.words, self.chars)
    }
}

/// Summarize a string: `STATS("hello brave world")` carries its counts.
#[oxdock_func(pure, name = "STATS")]
fn summarize(text: String) -> anyhow::Result<Value> {
    let words = text.split_whitespace().count();
    let chars = text.chars().count();
    Ok(Value::mint_heap(
        Stats::descriptor(),
        Stats { words, chars },
    ))
}

/// Read the word count back out: `WORD_COUNT($s)` is an `INT`.
#[oxdock_func(pure, returns = TypeTag::Int)]
fn word_count(summary: Value) -> anyhow::Result<Value> {
    let Some(stats) = summary.read_heap::<Stats>(Stats::descriptor()) else {
        anyhow::bail!("WORD_COUNT() expects a STATS value");
    };
    Ok(Value::int(stats.words as i64))
}

fn main() -> anyhow::Result<()> {
    let mut engine = Engine::new();
    engine.register_type::<Stats>();
    engine.register_module(HostModule {
        name: "DEMO".to_string(),
        funcs: vec![Summarize::registration(), WordCount::registration()],
        // Opaque custom types (`#[oxdock_type]` descriptors) this module's
        // functions mint or accept. Empty: the examples register types on
        // the engine directly, or use none.
        types: vec![],
        // Named MAP shapes for functions returning structured bundles
        // (field tables like `NET_LISTEN_INFO`). These return scalars and
        // opaque tags only, so none.
        record_schemas: vec![],
        // Shared state for function bodies, read with
        // `cx.module_state::<T>("MODULE")` and attached with
        // `.with_state(...)`. These are stateless, so none.
        states: vec![],
    });
    let temp = oxdock::GuardedPath::tempdir().unwrap();
    let root = temp.as_guarded_path().clone();
    let steps: Vec<oxdock::oxdock_parser::Step> = oxdock::oxdock! {
        modules: [DEMO],
        IMPORT [DEMO]
        LET $s: STATS = STATS("hello brave world")
        LET $n: INT = WORD_COUNT($s)
        ASSERT_EQ $n 3
    };
    let run = engine.run_steps_without_snapshot(&root, &steps)?;
    assert_eq!(format!("{}", run.bindings["s"]), "3 words, 17 chars");
    Ok(())
}

Extending OxDock from Rust

Scripts call host functions and custom types that Rust code registers under a module. Registration is a type plus a module on one facade, and scripts name the module: IMPORT [DEMO] lets the rest call MAKE_TAG() bare, or qualify as DEMO::MAKE_TAG(). This example runs as written: the shape first, the definitions it names right below it.

Complete example: define a type, define functions, run a script

use oxdock::{Engine, HostModule, OxDockFn, OxDockType, oxdock_func, oxdock_type};
use oxdock::oxdock_core::TypeTag;
use std::fmt;

// The script below is the DSL itself, not a string: the `oxdock!` macro
// builds it into steps at compile time.

fn main() -> anyhow::Result<()> {
    let mut engine = Engine::new();
    engine.register_type::<Tag>();
    engine.register_module(HostModule {
        name: "DEMO".to_string(),
        funcs: vec![MakeTag::registration(), ReadTag::registration()],
        // Opaque custom types (`#[oxdock_type]` descriptors) this module's
        // functions mint or accept. Empty: the examples register types on
        // the engine directly, or use none.
        types: vec![],
        // Named MAP shapes for functions returning structured bundles
        // (field tables like `NET_LISTEN_INFO`). These return scalars and
        // opaque tags only, so none.
        record_schemas: vec![],
        // Shared state for function bodies, read with
        // `cx.module_state::<T>("MODULE")` and attached with
        // `.with_state(...)`. These are stateless, so none.
        states: vec![],
    });

    let temp = oxdock::GuardedPath::tempdir().unwrap();
    let root_path = temp.as_guarded_path().clone();
    let steps: Vec<oxdock::oxdock_parser::Step> = oxdock::oxdock! {
        modules: [DEMO],
        IMPORT [DEMO]
        LET $t: TAG = MAKE_TAG()
        LET $s: STRING = READ_TAG($t)
        ASSERT_EQ $s "demo"
        WRITE tag.txt "{{ $s }}::{{ $t }}"
    };
    let run = engine.run_steps_without_snapshot(&root_path, &steps)?;
    assert!(run.bindings.contains_key("s"));

    let reader = oxdock::PathResolver::new(root_path.root(), root_path.root()).unwrap();
    let written = reader
        .read_to_string(&root_path.join("tag.txt").unwrap())
        .expect("script writes tag.txt");
    assert_eq!(written.trim(), "demo::tag:demo");
    Ok(())
}

// The type. `#[oxdock_type]` implements `OxDockType` on the payload struct
// itself. The default is the heap path: the word holds a thin pointer to
// an owned box. Heap payloads require `Clone + PartialEq + Display +
// Debug + Send + Sync`.

/// Opaque label type.
#[oxdock_type(name = "TAG")]
#[derive(Debug, Clone, PartialEq)]
struct Tag(String);

impl fmt::Display for Tag {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "tag:{}", self.0)
    }
}

// The functions. `#[oxdock_func(pure)]` implements `OxDockFn` on a
// registration marker named after the function (`make_tag` becomes
// `MakeTag`). The DSL name defaults to the uppercased Rust name.
// `Value::mint_heap` with the payload type's own descriptor mints a word
// of the registered type, and `read_heap` with that descriptor reads it
// back. No name lookup runs anywhere on this path.

/// Mint one opaque label.
#[oxdock_func(pure)]
fn make_tag() -> anyhow::Result<oxdock::Value> {
    Ok(oxdock::Value::mint_heap(Tag::descriptor(), Tag("demo".into())))
}

/// Read the payload back out through a descriptor-checked typed read.
#[oxdock_func(pure, returns = TypeTag::String)]
fn read_tag(val: oxdock::Value) -> anyhow::Result<oxdock::Value> {
    let Some(tag) = val.read_heap::<Tag>(Tag::descriptor()) else {
        anyhow::bail!("READ_TAG() expects a TAG value");
    };
    Ok(oxdock::Value::string(tag.0.clone()))
}

The shape is always the same. LET $t: TAG = MAKE_TAG() calls a host function like any native one: arity, depth budget, and the declared TAG coercion apply uniformly. READ_TAG($t) reclaims the payload through an id checked read. {{ $t }} renders the custom value through its Display, so interpolation, WRITE, and equality treat host values like native ones. TYPES() lists every registered name and TYPE_DESCRIBE("TAG") returns its summary and docs, so scripts introspect host surface exactly like native surface. Script TYPE aliases ride the same listing: TYPES() includes alias names and TYPE_DESCRIBE("PERSON") reports the canonical target spelling.

Host types stay opaque: literal syntax, $var.key traversal, and FOR iteration remain LIST and MAP only, so queryable containers expose host accessor functions (MATRIX_GET($m, $row, $col)) instead of new syntax.

Reference: stateful functions

Without pure, the first parameter must be cx: &mut StepCtx<P>, which exposes variables, environment, pipes, and IO. Override the DSL name and the declared return type explicitly when the defaults do not fit:

use oxdock::{HostModule, OxDockFn, StepCtx, oxdock_func};
use oxdock::oxdock_core::TypeTag;
use oxdock::oxdock_core::ProcessManager;

/// Read an environment variable, defaulting to empty.
#[oxdock_func(name = "ENV_OR", returns = TypeTag::String)]
fn env_or<P: ProcessManager>(
    cx: &mut StepCtx<P>,
    key: String,
) -> anyhow::Result<oxdock::Value> {
    Ok(oxdock::Value::string(cx.get_env(&key).unwrap_or_default()))
}

fn main() {
    let mut engine = oxdock::Engine::new();
    engine.register_module(HostModule {
        name: "DEMO".to_string(),
        funcs: vec![EnvOr::registration()],
        // Opaque custom types (`#[oxdock_type]` descriptors) this module's
        // functions mint or accept. Empty: the examples register types on
        // the engine directly, or use none.
        types: vec![],
        // Named MAP shapes for functions returning structured bundles
        // (field tables like `NET_LISTEN_INFO`). These return scalars and
        // opaque tags only, so none.
        record_schemas: vec![],
        // Shared state for function bodies, read with
        // `cx.module_state::<T>("MODULE")` and attached with
        // `.with_state(...)`. These are stateless, so none.
        states: vec![],
    });
}

Parameters accept Value, String, i64, f64, and bool, in either form. Stateful markers register exactly like pure ones. Pure functions run on the compiled math path too; stateful ones stay on the AST path unless they opt in with #[oxdock_func(rpn)] (as GLOB does).

Reference: inline types

#[oxdock_type(inline)] selects the zero allocation path for Copy scalars that fit in 64 bits: the word holds the value bytes directly. This is the same derivation the startup integer, float, boolean, and handle types use:

use oxdock::{OxDockType, oxdock_type};
use std::fmt;

/// Entity handle.
#[oxdock_type(name = "ENTITY", inline)]
#[derive(Debug, Clone, Copy, PartialEq)]
struct EntityId(u64);

impl fmt::Display for EntityId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "entity#{}", self.0)
    }
}

fn main() {
    let mut engine = oxdock::Engine::new();
    engine.register_type::<EntityId>();
    let val = oxdock::Value::mint_inline(EntityId::descriptor(), EntityId(7));
    assert_eq!(val.inline_bits(), 7);
    assert_eq!(format!("{val}"), "entity#7");
    assert_eq!(val.clone(), val);
}

Four limits decide what can ride inline:

  1. Fixed 64 bit slot. Anything larger panics at mint time (a runtime check, not a compile time one).
  2. Copy payloads only. Inline clones copy bits and drops do nothing, which resource owning types cannot satisfy.
  3. No variable length data. STRING, LIST, and MAP can never fit a fixed slot and stay behind the pointer.
  4. Widening punishes everything. A bigger slot means fewer words per cache line and costlier moves for the scalars that dominate scripts.

One boundary to keep straight: words stored inside a LIST or MAP live in that container's heap buffer, so inline describes the payload encoding, not a promise that every word sits on the stack.

Reference: queryable containers

Opaque types can still answer queries: pair the payload with host accessor functions and scripts read cells, lengths, and keys through ordinary calls, with no new syntax. The example below mints a grid and reads one cell through its accessor; from a script the same call spells LET $c: INT = MATRIX_GET($m, 0, 1). Key paths and FOR iteration stay unavailable by the boundary above.

use oxdock::{HostModule, OxDockFn, OxDockType, Value, oxdock_func, oxdock_type};
use oxdock::oxdock_core::TypeTag;
use std::fmt;

/// Integer grid with no literal syntax: scripts query it through functions.
#[oxdock_type(name = "MATRIX")]
#[derive(Debug, Clone, PartialEq)]
struct Matrix(Vec<Vec<i64>>);

impl fmt::Display for Matrix {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "matrix[{}x{}]", self.0.len(), self.0.first().map_or(0, Vec::len))
    }
}

/// Mint a fixed 1x2 grid.
#[oxdock_func(pure)]
fn make_matrix() -> anyhow::Result<Value> {
    Ok(Value::mint_heap(
        Matrix::descriptor(),
        Matrix(vec![vec![1, 2]]),
    ))
}

/// Read one cell by row and column.
#[oxdock_func(pure, returns = TypeTag::Int)]
fn matrix_get(board: Value, row: i64, col: i64) -> anyhow::Result<Value> {
    let Some(grid) = board.read_heap::<Matrix>(Matrix::descriptor()) else {
        anyhow::bail!("MATRIX_GET() expects a MATRIX value");
    };
    let cell = usize::try_from(row)
        .ok()
        .and_then(|r| grid.0.get(r))
        .and_then(|r| usize::try_from(col).ok().and_then(|c| r.get(c)))
        .copied()
        .ok_or_else(|| anyhow::anyhow!("index out of bounds"))?;
    Ok(Value::int(cell))
}

fn main() -> anyhow::Result<()> {
    let word = Value::mint_heap(Matrix::descriptor(), Matrix(vec![vec![1, 2]]));
    let cell = matrix_get(word, 0, 1).unwrap();
    assert_eq!(cell.as_i64(), Some(2));

    let mut engine = oxdock::Engine::new();
    engine.register_type::<Matrix>();
    engine.register_module(HostModule {
        name: "DEMO".to_string(),
        funcs: vec![
            MakeMatrix::registration(),
            MatrixGet::registration(),
        ],
        // Opaque custom types (`#[oxdock_type]` descriptors) this module's
        // functions mint or accept. Empty: the examples register types on
        // the engine directly, or use none.
        types: vec![],
        // Named MAP shapes for functions returning structured bundles
        // (field tables like `NET_LISTEN_INFO`). These return scalars and
        // opaque tags only, so none.
        record_schemas: vec![],
        // Shared state for function bodies, read with
        // `cx.module_state::<T>("MODULE")` and attached with
        // `.with_state(...)`. These are stateless, so none.
        states: vec![],
    });
    let temp = oxdock::GuardedPath::tempdir().unwrap();
    let root = temp.as_guarded_path().clone();
    let run = engine.run_script(
        &root,
        "IMPORT [DEMO]\nLET $m: MATRIX = MAKE_MATRIX()\nLET $c: INT = MATRIX_GET($m, 0, 1)\n",
    )?;
    assert_eq!(run.bindings["c"].as_i64(), Some(2));
    Ok(())
}

Reference: evaluation paths and the rpn flag

Two evaluators run scripts, and the distinction decides where a host function may run. The AST evaluator walks the parsed tree one step at a time. Every step knows its line number, so failures name it (step 1: INT() expects 1 argument(s), got 2). Scopes, pipes, declarations, and every statement form live here. The RPN evaluator runs arithmetic and comparison expressions compiled to a flat stack-machine program (PushConst, LoadVar, Call, Add, ...). A stack program carries values only: no statements, no scopes, no pipes, and no step numbers, so a failing call inside math reports the bare error (INT() expects 1 argument(s), got 2).

The tradeoff is expressiveness against compactness, not speed. The tree can say anything the language can say, with errors that point at the script. The stack program can only compute values, which is exactly what math needs and nothing more. That is why not everything runs on RPN: statements, declarations, scoping, and IO orchestration have no stack encoding, and step-numbered errors require the tree.

For host functions the rule follows from that split. Pure functions take only values and touch nothing, so they run on both paths with no flag. Stateful functions default to AST-only. Opt in with #[oxdock_func(rpn)] only for read-only queries that stay meaningful inside math (GLOB, LOAD_TOML, LOAD_JSON do this): the function still receives full step context, but its failures lose their step numbers. Side-effecting stateful functions stay out, since stack-order execution with step-less errors is the worst place for an effect to go wrong.

Why embedding Rust here stays simple

Compared against embedding Rust in Python, there are three structural reasons the host boundary stays small, and none of them are API polish.

No foreign runtime to host

Embedding Rust in Python means linking an interpreter, managing the GIL, and marshaling across two object models with different lifetimes. OxDock functions are plain Rust functions returning Result<Value>: the VM is just the calling convention, and values are fixed size words with deterministic lifetimes, so there is nothing to pin, nothing reference counted, and nothing kept alive across the boundary.

No binding layer

The Python path needs module registration plus type conversions negotiated with dynamic types. #[oxdock_func] derives the registration marker, the arity gate, and the String, i64, f64, bool, and Value extraction from the signature, and doc comments become introspectable metadata for free.

No build system dance

No maturin, no ABI tags, and no wheels built per interpreter. The host crate depends on oxdock-core and calls Engine::register_module. The one thing Python still wins is its C ABI as a stable interop target for other languages. The OxDock boundary is Rust only, which is exactly what keeps it cheap.

MCP hosting

A script serves its EXPORTed functions as MCP tools instead of running linear steps. One function, one tool:

# Adds two integers. Returns the sum.
FUNC ADD($a: INT, $b: INT): INT {
  RETURN $a + $b
}

# The export marks the tool without changing linear calls.
EXPORT [ADD]
LET $sum: INT = ADD(2, 3)
ASSERT_EQ $sum 5

Pass the script to the flag (--mcp hosting ships in default builds; only --no-default-features builds drop it):

cargo build -p oxdock
./target/debug/oxdock --mcp tools.oxdock

Register the server in OpenCode with an opencode.jsonc entry. Any key under mcp becomes the tool prefix:

{
  "mcp": {
    "oxdock-demo": {
      "type": "local",
      "command": ["/path/to/oxdock", "--mcp", "/path/to/tools.oxdock"],
      "enabled": true
    }
  }
}

Each entry serves over stdio JSON-RPC with live reload on file change. The function above appears as oxdock-demo_ADD: a call with {"a": 2, "b": 3} resolves {"result": 5}, and ECHO output streams live instead of landing in the result. Wire shapes, the detach pattern for long calls, and reload semantics live in crates/oxdock-mcp/README.md.

Only serve scripts you trust. Exports and # docs become the MCP tool surface verbatim (names, descriptions, schemas), so a script author controls what an MCP client shows its m