<!-- GENERATED by oxdock-render from oxdock-parser metadata. Do not edit by hand. -->
## Command Reference
See the [changelog](https://github.com/jzombie/rust-oxdock/blob/main/CHANGELOG.md) for what changed in each release.
| Command | Syntax |
| --- | --- |
| [`WORKDIR`](#workdir) | `WORKDIR <path>` |
| [`WORKSPACE`](#workspace) | `WORKSPACE (SNAPSHOT\|LOCAL\|CACHE\|SYSTEM) [--local]` |
| [`ENV`](#env) | `ENV KEY=value` |
| [`INHERIT_ENV`](#inherit_env) | `INHERIT_ENV [<key>, ...]` |
| [`ECHO`](#echo) | `ECHO <message>` |
| [`RUN`](#run) | `RUN <command...> \| RUN ["exe", "arg", ...]` |
| [`COPY`](#copy) | `COPY [--from-workspace SNAPSHOT\|LOCAL\|CACHE\|SYSTEM] [--from-host \| --to-host] <from> <to>` |
| [`COPY_GIT`](#copy_git) | `COPY_GIT [--include-dirty] <rev> <src> <dst>` |
| [`SYMLINK`](#symlink) | `SYMLINK [--from-workspace SNAPSHOT\|LOCAL\|CACHE\|SYSTEM] <from> <to>` |
| [`MKDIR`](#mkdir) | `MKDIR <path>` |
| [`INSTALL`](#install) | `INSTALL <source> <dest>` |
| [`SET_EXECUTABLE`](#set_executable) | `SET_EXECUTABLE <path>` |
| [`ARCHIVE`](#archive) | `ARCHIVE [--raw] <src> <dst>` |
| [`UNARCHIVE`](#unarchive) | `UNARCHIVE <src> <dst> [--max-bytes <bytes>]` |
| [`LS`](#ls) | `LS [<path>]` |
| [`READ`](#read) | `READ [<path>]` |
| [`READ_LINE`](#read_line) | `READ_LINE $var` |
| [`PROMPT`](#prompt) | `PROMPT $var <message> [<default>]` |
| [`WRITE`](#write) | `WRITE <path> [<contents>]` |
| [`APPEND`](#append) | `APPEND <path> [<contents>]` |
| [`APPEND_LINE`](#append_line) | `APPEND_LINE <path> <contents>` |
| [`REMOVE`](#remove) | `REMOVE [--recursive] <path>` |
| [`EXPAND`](#expand) | `EXPAND [<path>] [<KEY=val> ...]` |
| [`ASSERT_EQ`](#assert_eq) | `ASSERT_EQ [--hash <sha256>] <actual> <expected>` |
| [`ASSERT_NE`](#assert_ne) | `ASSERT_NE [--hash <sha256>] <actual> <expected>` |
| [`ASSERT_CONTAINS`](#assert_contains) | `ASSERT_CONTAINS <haystack> <needle>` |
| [`EXIT`](#exit) | `EXIT <code>` |
| [`SLEEP`](#sleep) | `SLEEP <duration>` |
| [`LIST_APPEND`](#list_append) | `LIST_APPEND $list <item>` |
| [`WITH_IO`](#with_io) | `WITH_IO [<stream>[=$var], ...] <command> \| WITH_IO [bindings] { <commands> } \| WITH_IO [tty[, stdin=$p][, rows=<int>][, cols=<int>]] RUN ...` |
| [`FOR`](#for) | `FOR $item: TYPE IN <expr> { <commands> } \| FOR $key: STRING, $value: TYPE IN <expr> { <commands> }` |
| [`IF`](#if) | `IF <expr> { <commands> } [ELSE IF <expr> { <commands> } ...] [ELSE { <commands> }]` |
| [`SWITCH`](#switch) | `SWITCH [<expr>] { CASE <expr>[, <expr> ...] { <commands> } ... [DEFAULT { <commands> }] }` |
| [`LET`](#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) | `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) | `ASYNC <command...> \| ASYNC { <commands> } \| LET $var: HANDLE<T> = ASYNC { <commands> }` |
| [`AWAIT`](#await) | `AWAIT $var \| LET $out: STRING = AWAIT $var` |
| [`CANCEL`](#cancel) | `CANCEL $var` |
| [`TIMEOUT`](#timeout) | `TIMEOUT <duration> <command...> \| TIMEOUT <duration> { <commands> } \| TIMEOUT <duration> AWAIT $var` |
| [`FAIL`](#fail) | `FAIL [<code>] [<message>] [{ <commands> }]` |
| [`ISOLATED`](#isolated) | `ISOLATED { INHERIT_ENV [...] <commands> } \| ISOLATED <command...>` |
| [`REMOTE`](#remote) | `REMOTE <target> [[$var, ...] [env:NAME, ...]] { <commands> }` |
| [`FUNC`](#func) | `FUNC NAME([$param: TYPE, ...]): RET { <commands> } \| ASYNC FUNC NAME([$param: TYPE, ...]): HANDLE<T> { <commands> }` |
| [`RETURN`](#return) | `RETURN [<expr>]` |
| [`WHILE`](#while) | `WHILE <bool-expr> { <commands> }` |
| [`BREAK`](#break) | `BREAK` |
| [`CONTINUE`](#continue) | `CONTINUE` |
| [`IMPORT`](#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**
```oxdock
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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
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**
```oxdock
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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
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**
```oxdock
# 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**
```oxdock expect_error:"expected BOOL"
# 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**
```oxdock expect_error:"undefined variable"
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# Capture keeps the trailing newline.
LET $out: STRING = ECHO hi
ASSERT_EQ $out "hi\n"
```
**Example: inline block**
```oxdock
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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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 `EXPORT`s 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 `CONST`s 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).
Qualified reads project like bare reads: `$ALIAS::NAME.key`,
numeric indices, and chains traverse the exported value in
every position bare key paths work. Projections stay frozen
like the copied value, and dangling dots fail at parse time.
**Examples:**
**Example: const**
```oxdock
# 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**
```oxdock roots:unified
# 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**
```oxdock roots:unified
# 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**
```oxdock expect_error:"cannot mutate CONST"
# SET on a CONST fails instead of rebinding.
CONST $N: INT = 1
$N = 2
```
**Expected error:** `cannot mutate CONST`
**Example: const rejects append**
```oxdock expect_error:"cannot mutate CONST"
# 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**
```oxdock
# 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**
```oxdock expect_error:"cannot mutate CONST"
# 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**
```oxdock expect_error:"cannot mutate CONST"
# 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**
```oxdock expect_error:"cannot mutate CONST"
# 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**
```oxdock expect_error:"cannot mutate CONST"
# 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**
```oxdock
# Mutation writes through: the binding holds the new value.
LET $count: INT = 1
$count = 2
ASSERT_EQ $count 2
```
**Example: rebind keeps earlier captures**
```oxdock
# 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**
```oxdock
# 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**
```oxdock expect_error:"cannot assign to $M.a"
# 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**
```oxdock
# 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**
```oxdock
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**
```oxdock
LET $task: HANDLE<VOID> = ASYNC ECHO "done"
AWAIT $task
ASSERT_CONTAINS stdout "done"
```
**Example: await capture**
```oxdock
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**
```oxdock
LET $task: HANDLE<VOID> = ASYNC SLEEP 30s
CANCEL $task
```
**Example: await after cancel reports cancellation**
```oxdock expect_error:"was cancelled"
# 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**
```oxdock
TIMEOUT 30s WRITE heartbeat.txt alive
LET $beat: STRING = READ heartbeat.txt
ASSERT_EQ $beat "alive"
```
**Example: timeout block**
```oxdock
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**
```oxdock expect_error:"TIMEOUT after"
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock expect_error:"EXIT requested with code 1"
# 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**
```oxdock expect_error:"EXIT requested with code 2"
# 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**
```oxdock expect_error:"EXIT requested with code 1"
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock expect_error:"env:OUTER_CUSTOM"
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock mock_remote:prod
# 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**
```oxdock mock_remote:prod
# 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**
```oxdock mock_remote:prod roots:unified
# 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**
```oxdock mock_remote:prod
# 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**
```oxdock mock_remote:prod
# 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**
```oxdock mock_remote:prod expect_error:"escapes staging"
# 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**
```oxdock mock_remote:prod expect_error:"REMOTE 'prod' exited with code 3"
# 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**
```oxdock expect_error:"has no registered session"
# 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**
```oxdock
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**
```oxdock
# 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**
```oxdock expect_error:"placeholder function 'SCRIPT::GREET' is a script function"
# 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**
```oxdock
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**
```oxdock expect_error:"optional ? params must be trailing"
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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 `EXPORT`ed top-level `FUNC`s 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 `EXPORT`ed.
- 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 TYPE`d. 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 `EXPORT`ed top-level `FUNC`s 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 `FUNC`s 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**
```oxdock
# 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**
```oxdock roots:unified
# 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**
```oxdock
# 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**
```oxdock expect_error:"must exist when the run starts"
# 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**
```oxdock expect_error:"mandatory alias"
# A file entry without AS is a parse error.
IMPORT ["./lib.oxdock"]
```
**Expected error:** `mandatory alias`
**Example: module cannot export a variable**
```oxdock expect_error:"does not match any top-level FUNC"
# 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**
```oxdock expect_error:"does not match any top-level FUNC"
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock roots:unified
# 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**
```oxdock roots:unified
# 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**
```oxdock expect_error:"does not match any top-level TYPE"
# 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**
```oxdock expect_error:"unknown type"
# 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`](#value-type-path) | yes | Directory to change to |
**Examples:**
**Example: change working directory**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
IMPORT [STD]
WORKSPACE LOCAL
LET $t: STRING = PATH_TYPE(".")
ASSERT_EQ $t "dir"
```
**Example: workspace cache in a scoped block**
```oxdock
[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`](#value-type-string) | yes | KEY=value pair; the value resolves as STRING |
**Examples:**
**Example: set env**
```oxdock
ENV APP_MODE=production
LET $mode: STRING = env:APP_MODE
ASSERT_EQ $mode "production"
```
**Example: quoted value with spaces**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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...`](#value-type-string) | no | Host variables to inherit |
**Examples:**
**Example: inherit env**
```oxdock
[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...`](#value-type-string) | yes | Text |
**Output:** Stdout
**Examples:**
**Example: echo**
```oxdock
ECHO build-complete
ASSERT_CONTAINS stdout "build-complete"
```
**Example: variables**
```oxdock
# {{ }} 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**
```oxdock
# `{{ 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**
```oxdock expect_error:"env:OXDOCK_DOC_NO_SUCH_KEY"
# 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...`](#value-type-string) | yes | Command |
**Examples:**
**Example: run**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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`](#value-type-path) | yes | Source |
| `to` | [`PATH`](#value-type-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**
```oxdock roots:unified
# 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**
```oxdock
# 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`](#value-type-string) | yes | Rev |
| `src` | [`PATH`](#value-type-path) | yes | Src |
| `dst` | [`PATH`](#value-type-path) | yes | Dst |
**Flags:**
| Flag | Type | Description |
| --- | --- | --- |
| `--include-dirty` | `BOOL` | Include dirty |
**Examples:**
**Example: git copy missing source errors**
```oxdock expect_error:"COPY source missing"
COPY_GIT HEAD src.txt dst.txt
```
**Expected error:** `COPY source missing`
### SYMLINK
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`](#value-type-path) | yes | Target |
| `to` | [`PATH`](#value-type-path) | yes | Link |
**Flags:**
| Flag | Type | Description |
| --- | --- | --- |
| `--from-workspace` | `STRING` | Symlink from the given workspace root instead of the build context |
**Examples:**
**Example: symlink**
```oxdock roots:unified
# 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**
```oxdock
# 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`](#value-type-path) | yes | Dir path |
**Examples:**
**Example: mkdir**
```oxdock
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`](#value-type-path) | yes | Source file |
| `to` | [`PATH`](#value-type-path) | yes | Dest file |
**Examples:**
**Example: install**
```oxdock roots:unified
# 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`](#value-type-path) | yes | File to mark executable |
**Examples:**
**Example: set-executable**
```oxdock roots:unified
# 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`](#value-type-path) | yes | File or directory to pack |
| `dst` | [`PATH`](#value-type-path) | yes | Archive file to write |
**Flags:**
| Flag | Type | Description |
| --- | --- | --- |
| `--raw` | `BOOL` | Write an uncompressed tar instead of gzip |
**Examples:**
**Example: archive directory**
```oxdock
# 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**
```oxdock
# 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`](#value-type-path) | yes | Archive file to unpack |
| `dst` | [`PATH`](#value-type-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**
```oxdock
# 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**
```oxdock
# 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`](#value-type-path) | no | Dir |
**Output:** Stdout
**Examples:**
**Example: ls**
```oxdock
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`](#value-type-path) | no | File |
**Output:** Stdout
**Examples:**
**Example: read**
```oxdock
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`](#value-type-string) | yes | Target variable (`$name`); the line binds as STRING |
**Examples:**
**Example: read line**
```oxdock
# 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`](#value-type-string) | yes | Target variable (`$name`); the answer binds as STRING |
| `message` | [`STRING`](#value-type-string) | yes | Prompt message |
| `default` | [`STRING`](#value-type-string) | no | Default on empty input |
**Examples:**
**Example: prompt needs a terminal**
```oxdock expect_error:"non-TTY"
# 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`](#value-type-path) | yes | File |
| `contents` | [`STRING...`](#value-type-string) | no | Content |
**Examples:**
**Example: write**
```oxdock
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`](#value-type-path) | yes | File |
| `contents` | [`STRING...`](#value-type-string) | no | Content |
**Examples:**
**Example: append**
```oxdock
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`](#value-type-path) | yes | File |
| `contents` | [`STRING...`](#value-type-string) | yes | Line content (the newline is added) |
**Examples:**
**Example: append-line**
```oxdock
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`](#value-type-path) | yes | Path to remove |
**Flags:**
| Flag | Type | Description |
| --- | --- | --- |
| `--recursive` | `BOOL` | Remove a directory tree |
**Examples:**
**Example: remove**
```oxdock
# 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`](#value-type-path) | no | Template file to expand; omit to expand stdin |
| `overrides` | [`STRING...`](#value-type-string) | no | Template overrides shadowing that key (unified string values) |
**Output:** Stdout
**Examples:**
**Example: expand**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# `{{ $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**
```oxdock expect_error:"missing required step override argument"
# 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**
```oxdock
LET $status: INT = 200
ASSERT_EQ $status 200
```
**Example: assert eq file**
```oxdock
WRITE payload.bin stable-content
LET $body: STRING = READ payload.bin
ASSERT_EQ $body "stable-content"
```
**Example: assert eq hash**
```oxdock
# --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**
```oxdock
LET $status: INT = 200
ASSERT_NE $status 404
```
**Example: assert ne file**
```oxdock
WRITE payload.bin stable-content
LET $body: STRING = READ payload.bin
ASSERT_NE $body "other-content"
```
**Example: assert ne hash**
```oxdock
# --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**
```oxdock
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`](#value-type-int) | yes | Code |
**Examples:**
**Example: exit**
```oxdock expect_error:"EXIT requested with code 0"
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`](#value-type-duration) | yes | How long to sleep |
**Examples:**
**Example: sleep**
```oxdock
SLEEP 100ms
```
**Example: sleep variable duration**
```oxdock
# 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`](#value-type-list) | yes | Target LIST variable (`$name`) |
| `item` | `<any>` | yes | Item to append (any value) |
**Examples:**
**Example: list append**
```oxdock
# 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.
<!-- GENERATED by oxdock-render from STD function metadata. Do not edit by hand. -->
## 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`](https://github.com/jzombie/rust-oxdock#plugin-references)) add more functions the same way, and hosts can extend the language with their own modules ([Extending OxDock from Rust](https://github.com/jzombie/rust-oxdock#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`](#context-ast) only
**Returns:** `LIST<STRING>`
**Examples:**
**Example: empty**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Base64 text to decode.
**Returns:** `STRING`
**Examples:**
**Example: decode**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to encode.
**Returns:** `STRING`
**Examples:**
**Example: encode**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$val` (`BOOL|STRING`): Value to convert to `BOOL`.
**Returns:** `BOOL`
**Examples:**
**Example: convert**
```oxdock
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`](#context-ast), [`RPN`](#context-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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Returns:** `STRING`
**Examples:**
**Example: cwd**
```oxdock
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`](#context-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**
```oxdock
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`](#context-ast) only
**Parameters:**
- `$pipe` (`PIPE`): Pipe handle to query for end of stream.
**Returns:** `BOOL`
**Examples:**
**Example: drain to end**
```oxdock
# 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`](#context-ast) only
**Parameters:**
- `$path` (`STRING|PATH`): Workspace path to probe.
**Returns:** `BOOL`
**Examples:**
**Example: probe**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$val` (`FLOAT|INT|STRING`): Value to convert to `FLOAT`.
**Returns:** `FLOAT`
**Examples:**
**Example: convert**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$bytes` (`INT`): Byte count to format; negatives fail.
**Returns:** `STRING`
**Examples:**
**Example: format and round-trip**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$millis` (`INT`): Milliseconds to format; negatives fail.
**Returns:** `STRING`
**Examples:**
**Example: format and round-trip**
```oxdock
# 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`](#context-ast) only
**Returns:** `LIST<STRING>`
**Examples:**
**Example: list**
```oxdock
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`](#context-ast), [`RPN`](#context-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**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$pattern` (`STRING|PATH`): Glob pattern matched against workspace paths.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: match**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$path` (`STRING|PATH`): Workspace file or directory path to hash.
**Returns:** `STRING`
**Examples:**
**Example: hash**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$map` (`MAP<ANY>`): Map to probe.
- `$key` (`STRING`): Key to look up.
**Returns:** `BOOL`
**Examples:**
**Example: probe**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$val` (`INT|FLOAT|STRING|BOOL`): Value to convert to `INT`.
**Returns:** `INT`
**Examples:**
**Example: convert**
```oxdock
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`](#context-ast) only
**Returns:** `STRING`
**Examples:**
**Example: self**
```oxdock
# 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**
```oxdock
# 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`](#context-ast) only
**Parameters:**
- `$path` (`STRING|PATH`): Workspace path to probe.
**Returns:** `BOOL`
**Examples:**
**Example: probe**
```oxdock
# 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`](#context-ast) only
**Parameters:**
- `$name` (`STRING|PATH`): Command name or file path to probe.
**Returns:** `BOOL`
**Examples:**
**Example: probe**
```oxdock
# 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`](#context-ast) only
**Parameters:**
- `$path` (`STRING|PATH`): Workspace path to probe.
**Returns:** `BOOL`
**Examples:**
**Example: probe**
```oxdock
# 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`](#context-ast) only
**Returns:** `BOOL`
**Examples:**
**Example: main**
```oxdock
# Entry top level runs as main.
IMPORT [STD]
LET $m: BOOL = IS_MAIN()
ASSERT_EQ $m true
```
**Example: library doubles as demo**
```oxdock roots:unified
# 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`](#context-ast) only
**Parameters:**
- `$stream_name` (`STRING = "stdin" | "stdout" | "stderr"`): Stream name: `stdin`, `stdout`, or `stderr` (exact match).
**Returns:** `BOOL`
**Examples:**
**Example: null stdin**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$value` (`STRING|LIST|MAP`): Value to measure.
**Returns:** `INT`
**Examples:**
**Example: length**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$path` (`STRING|PATH`): Workspace file path to load and parse as JSON.
**Returns:** `ANY`
**Examples:**
**Example: load**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$path` (`STRING|PATH`): Workspace file path to load and parse as TOML.
**Returns:** `MAP<ANY>`
**Examples:**
**Example: load**
```oxdock
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`](#context-ast), [`RPN`](#context-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**
```oxdock
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`](#context-ast), [`RPN`](#context-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**
```oxdock
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`](#context-ast), [`RPN`](#context-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**
```oxdock
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**
```oxdock
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**
```oxdock
IMPORT [STD]
# Empty positionals are omitted, so declare the slot
# optional to bind a flags-only run clean.
TYPE FLAGS = MAP<model: STRING>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $parsed: PARSED = PARSE_ARGS(["--model=x"])
LET $flags: FLAGS = $parsed.flags
ASSERT_EQ $flags.model "x"
```
**Example: literal defaults**
```oxdock
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 POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
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**
```oxdock expect_error:"expected default literal"
IMPORT [STD]
# Defaults are literals: a variable in place
# of a literal fails instead of evaluating.
TYPE FLAGS = MAP<n: INT = $x>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $p: PARSED = PARSE_ARGS([])
```
**Expected error:** `expected default literal`
**Example: missing required**
```oxdock expect_error:"missing required flag"
IMPORT [STD]
# Absent required flags fail naming the flag.
TYPE FLAGS = MAP<model: STRING>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $parsed: PARSED = PARSE_ARGS([])
```
**Expected error:** `missing required flag`
**Example: unknown flag**
```oxdock expect_error:"unknown flag"
IMPORT [STD]
# Undeclared flags fail instead of passing through.
TYPE FLAGS = MAP<model: STRING>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $parsed: PARSED = PARSE_ARGS(["--model=x", "--nope=1"])
```
**Expected error:** `unknown flag`
**Example: alias accepted**
```oxdock
IMPORT [STD]
# One canonical key binds both spellings; the
# alias never appears as a separate key.
TYPE FLAGS = MAP<h: BOOL ALIAS help>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
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**
```oxdock expect_error:"duplicate flag"
IMPORT [STD]
# Canonical and alias together fail naming both.
TYPE FLAGS = MAP<h: BOOL ALIAS help>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
LET $p: PARSED = PARSE_ARGS(["--h", "--help"])
```
**Expected error:** `duplicate flag`
**Example: alias missing names both**
```oxdock expect_error:"--h/--help"
IMPORT [STD]
# Missing required flags name both spellings.
TYPE FLAGS = MAP<h: BOOL ALIAS help>
TYPE POSITIONS = LIST<STRING>
TYPE PARSED = MAP<flags: FLAGS, positionals?: POSITIONS>
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.
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`INT|FLOAT|STRING`): Byte-count token to parse, or bytes already.
**Returns:** `INT`
**Examples:**
**Example: parse**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Duration token to parse.
**Returns:** `INT`
**Examples:**
**Example: parse**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$args` (`LIST<STRING>`): Argv tail to parse, usually from `STD::ARGV()`.
**Returns:** `MAP`
**Examples:**
**Example: flags only**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): JSON text already held in memory.
**Returns:** `ANY`
**Examples:**
**Example: parse**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$args` (`LIST<STRING>`): Argv tail to parse, usually from `STD::ARGV()`.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: positionals only**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): TOML text already held in memory.
**Returns:** `MAP<ANY>`
**Examples:**
**Example: parse**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$path` (`STRING|PATH`): Path whose final segment to bind.
**Returns:** `STRING`
**Examples:**
**Example: base**
```oxdock
# 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`](#context-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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$base` (`STRING|PATH`): Base prefix segments must match.
- `$path` (`STRING|PATH`): Path below the base to relativize.
**Returns:** `STRING`
**Examples:**
**Example: relativize**
```oxdock
# 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`](#context-ast) only
**Parameters:**
- `$path` (`STRING|PATH`): Workspace path of the entry to describe.
**Returns:** `STRING`
**Examples:**
**Example: describe**
```oxdock
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`](#context-ast) only
**Parameters:**
- `$path` (`STRING|PATH`): Workspace path to probe for file creation.
**Returns:** `BOOL`
**Examples:**
**Example: probe**
```oxdock
# 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`](#context-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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$sem` (`SEMAPHORE`): Semaphore handle from `SEMAPHORE_NEW`.
**Returns:** `INT`
**Examples:**
**Example: readout**
```oxdock
# 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`](#context-ast) only
**Parameters:**
- `$max` (`INT`): Maximum concurrent holders; must be positive.
**Returns:** `SEMAPHORE`
**Examples:**
**Example: mint**
```oxdock
# 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`](#context-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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$words` (`LIST<STRING>`): Words to join into a shell command string.
**Returns:** `STRING`
**Examples:**
**Example: join args**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$command` (`STRING`): Shell command string to split into words.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: split args**
```oxdock
# 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`](#context-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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to search.
- `$needle` (`STRING`): Literal needle to count; empty fails closed.
**Returns:** `INT`
**Examples:**
**Example: count**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text whose lines to test.
- `$pattern` (`STRING`): Regex pattern tested per line.
**Returns:** `INT`
**Examples:**
**Example: count matches**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to test.
- `$suffix` (`STRING`): Literal suffix to look for.
**Returns:** `BOOL`
**Examples:**
**Example: ends with**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to search.
- `$pattern` (`STRING`): Regex pattern with capture groups.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: extract**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to split into fields.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: fields**
```oxdock
# 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`](#context-ast), [`RPN`](#context-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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$elements` (`LIST<STRING>`): List elements to join.
- `$delimiter` (`STRING`): Literal delimiter placed between elements.
**Returns:** `STRING`
**Examples:**
**Example: join**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to split into lines.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: lines**
```oxdock
# 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`](#context-ast), [`RPN`](#context-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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to test.
- `$pattern` (`STRING`): Regex pattern to match.
**Returns:** `BOOL`
**Examples:**
**Example: match**
```oxdock
# 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`](#context-ast), [`RPN`](#context-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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-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**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to split.
- `$delimiter` (`STRING`): Literal delimiter; empty splits into characters.
**Returns:** `LIST<STRING>`
**Examples:**
**Example: split**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING`): Text to test.
- `$prefix` (`STRING`): Literal prefix to look for.
**Returns:** `BOOL`
**Examples:**
**Example: starts with**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING|PIPE`): Text to lowercase.
**Returns:** `STRING|PIPE`
**Examples:**
**Example: lowercase**
```oxdock
# Text folds to lowercase.
IMPORT [STD]
LET $quiet: STRING = TEXT_TO_LOWER("HELLO")
ASSERT_EQ $quiet "hello"
```
**Example: lowercase pipe mirrors**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING|PIPE`): Text to uppercase.
**Returns:** `STRING|PIPE`
**Examples:**
**Example: uppercase**
```oxdock
# Text folds to uppercase.
IMPORT [STD]
LET $loud: STRING = TEXT_TO_UPPER("hello")
ASSERT_EQ $loud "HELLO"
```
**Example: uppercase pipe mirrors**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING|PIPE`): Text to trim.
**Returns:** `STRING|PIPE`
**Examples:**
**Example: trim**
```oxdock
# Leading and trailing whitespace falls away.
IMPORT [STD]
LET $clean: STRING = TEXT_TRIM(" hello ")
ASSERT_EQ $clean "hello"
```
**Example: trim pipe mirrors**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING|PIPE`): Text to strip.
- `$prefix` (`STRING`): Leading prefix to remove once.
**Returns:** `STRING|PIPE`
**Examples:**
**Example: strip prefix**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$text` (`STRING|PIPE`): Text to strip.
- `$suffix` (`STRING`): Trailing suffix to remove once.
**Returns:** `STRING|PIPE`
**Examples:**
**Example: strip suffix**
```oxdock
# 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**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$value` (`STRING|INT|FLOAT|BOOL|LIST|MAP`): Value to encode as JSON.
**Returns:** `STRING`
**Examples:**
**Example: encode**
```oxdock
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`](#context-ast) only
**Returns:** `LIST<STRING>`
**Examples:**
**Example: list**
```oxdock
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`](#context-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**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$value` (`ANY`): Value whose word to name.
**Returns:** `STRING`
**Examples:**
**Example: name the word**
```oxdock
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`](#context-ast), [`RPN`](#context-rpn)
**Parameters:**
- `$items` (`LIST<ANY>`): List to deduplicate.
**Returns:** `LIST`
**Examples:**
**Example: deduplicate**
```oxdock
# 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**
```oxdock
# 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`](#context-ast), [`RPN`](#context-rpn)
**Returns:** `STRING`
**Examples:**
**Example: report**
```oxdock
# The engine reports its own build version as a dotted string.
IMPORT [STD]
LET $v: STRING = VERSION()
ASSERT_CONTAINS $v "."
```
<!-- GENERATED by oxdock-render from function context metadata. Do not edit by hand. -->
## 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.