ral — specification

ral(1) — language specification

1. About this specification

This document defines the observable behaviour of ral programs and the ral shell. It is a reference. The tutorial teaches the language step by step.

The specification covers three surfaces:

  • the core language, which every ral host must provide;
  • the standard surface provided by the ral program;
  • features that depend on a host or an operating system.

A host can add builtins. Such a builtin is part of that host, not part of the portable core. A platform note changes only the rule that it names. All other rules still apply.

This document specifies results that a program can observe. It does not specify Rust modules, internal process layouts, or implementation algorithms. The code is the authority for the current implementation.

1.1. Normative terms

The words must and must not state requirements. May states a permitted choice. “Is an error” means that ral must reject the program or operation. A rule states the rejection phase when that phase is observable.

Examples show the rules but do not replace them. The formal definition is authoritative for grammar and types. The plain-language sections are authoritative for observable runtime behaviour.

1.2. Reading paths

Read the core model first. Then read the sections on values, bindings, commands, pipelines, and failure to write ordinary programs. Read the later sections when you need modules, concurrency, capabilities, the interactive shell, or platform integration. The final formal section is for implementers and readers who want the type and evaluation rules.

2. The core model

ral keeps data separate from work. This distinction explains most of the language.

  • A value is data. Strings, numbers, lists, records, and blocks are values.
  • A command is work. It can return a value, write bytes, change permitted shell state, or fail.

ral checks how values and commands fit together before it starts the program. Every type is inferred; the language has no syntax for writing one.

2.1. Values do not run by themselves

A quoted string, a number, or a collection is already a value:

'hello'
42
[host: 'example.net', port: 443]

let runs its right-hand side and binds the result:

let answer = 42
let host = hostname

The first line binds the integer 42. The second line runs hostname and binds its text result. Bindings are immutable. A later let can shadow an earlier binding for the rest of its scope.

Use $ when you want the value bound to a name:

echo $host

Without $, a word in argument position is text. For example, echo host passes the string "host" to echo.

2.2. Blocks make work into values

A block stores a command without running it:

let now = { date +%s }

Use ! to run stored work where a value is needed:

let timestamp = !$now
let inline = !{date +%s}

!$now runs a block held in a name. A command's value is its output, so let binds what date writes, whether the command is written inline, as in !{date +%s}, or reached through a name. | from-line and its siblings choose another decoding.

A block can take parameters:

let greet = { |name| "hello, $name" }
let message = greet 'world'

In command position, ral recognizes the bound name greet and applies the block. In other positions, use $greet to pass the block itself as data. Blocks remember the bindings that were visible when they were created.

2.3. Commands have two results

A command can produce two independent things:

  1. A return value for ral.
  2. A stream of bytes for a terminal, file, or pipeline.

An external command usually writes bytes. A command's value is its output: only on the right-hand side of a let, ral captures the command and decodes its output as UTF-8 text:

let branch = git branch --show-current

If the bytes are not UTF-8, decode them explicitly or keep them as Bytes. A command that returns another value binds that value directly.

The | connects a stage's standard output to the next stage's standard input. It carries bytes and nothing else: every stage but the last feeds the next by writing, and its own value is not used. The final stage's result is the pipeline's own and may be any value.

2.4. Pipelines carry bytes

A pipeline uses an operating-system byte channel at every |:

printf 'one\ntwo\n' | wc -l

Stage position is the whole of the connection, and neither side is obliged to use it: a stage may write nothing, and a stage may never read. A value never travels through |. Compose values by ordinary application, such as length [1, 2, 3], or by binding a result and applying a function to it. Each non-final stage must be a command that writes, so [1, 2, 3] | length is a type error: a value in stage position writes nothing to the pipe. Codecs such as from-json and to-json cross explicitly between bytes and values. A decoder ends the byte pipeline: from-json returns a value and writes nothing, so it may be the final stage, as in cat data.json | from-json, but never a non-final one.

2.5. Failure is not false

A command either succeeds or fails. An unhandled failure stops the remaining commands. ? runs a fallback only after failure:

cat 'optional.conf' ? echo 'default'

A Boolean is ordinary data. Returning false is still a successful command, so it does not select the right side of ?. Use if to branch on a Boolean, and use try when code must inspect or recover from a failure.

2.6. A session remembers; a block is contained

At the session level, completed changes remain available to the next run. This includes bindings and the shell's current directory. Changes made before a top-level failure remain too.

A block is a boundary for bindings: a let made inside it does not escape when it returns, and neither does anything else lexical — the block's value, output, failure, and recorded observations are what crosses. A directory change, a module load, or any other unbracketed shell-state write made inside a block persists past it exactly as it would outside one; a block is not a boundary for the shell's state.

within and grant are the scoped forms: within temporarily changes the directory, environment, or command handlers for its body's whole extent, and grant temporarily reduces authority the same way. Code called inside either scope sees that scope, even if the code was defined elsewhere, and the change is undone when the scope ends — under within [dir: …], together with any cd made inside it.

2.7. One complete example

let salutation = 'hello'
let greet = { |name| "$salutation, $name" }
let message = greet 'world'
echo $message | tr a-z A-Z

This program does the following:

  1. It binds a string value to salutation.
  2. It binds a parameterized block to greet. The block remembers salutation.
  3. It applies greet and binds the returned string to message.
  4. It reads $message, writes it as bytes with echo, and streams those bytes through the external command tr.

The output is:

HELLO, WORLD

The following sections define each of these rules precisely.

3. Source text and program structure

A ral program is a sequence of statements. A script can use a newline or a semicolon (;) to separate statements.

echo 'first'
echo 'second'; echo 'third'

An empty program does nothing and succeeds. Blank lines and extra semicolons between statements have no effect.

3.1. Source text

Source text must be valid UTF-8. When ral loads a script, a module, a -c program, or a program read from standard input, it converts Windows line endings (CRLF) and old-style CR line endings to LF. Source therefore has the same meaning on every platform, however it was supplied.

Spaces and tabs separate words. They do not separate statements. A newline usually ends the current statement. A semicolon always ends it.

There is no general backslash continuation. A backslash outside a double-quoted string is an ordinary character. Double-quoted strings have their own escape and line rules; see Strings.

3.2. Comments

# starts a comment when it occurs where a new word could start. The comment ends at the next newline or at the end of the source.

# A complete comment line.
echo 'ready'  # A comment after a command.
curl http://example.test/page#part

The last # is part of the URL. It does not start a comment because it occurs inside a word.

A run of # characters followed immediately by ' starts a raw string, not a comment. For example, #'can't'# is one string. See Strings for the full rule.

ral has no block comments. A comment does not cancel an open delimiter. In an interactive session, ral asks for more input when a comment follows an open { or [. In a complete script, an unclosed delimiter is an error.

A script can start with a conventional interpreter line:

#!/usr/bin/env ral

ral reads this line as a comment.

3.3. Newlines and continuation

A newline can continue a statement only in the cases in this section. A semicolon cannot continue a statement in any of these cases.

Pipelines

| can occur before or after a newline. Blank lines and comment lines are also allowed at that point.

generate
| transform |
  consume

These three lines form one pipeline. The following text is an error because a semicolon ends the first statement:

generate; | consume

Failure chains

? can occur before or after a newline, exactly as | can. Blank lines and comment lines are also allowed at that point.

read-primary
? read-backup

Bindings and control forms

The right-hand side of a let binding can start on a later line when the newline follows =.

let report =
  build-report

The condition and body of if and elsif can start on later lines. elsif and else can also start on the line after the preceding branch. A case's scrutinee and its arm list can be separated by newlines, and so can its arms.

if
  $ready
  { deploy }
else
  { explain-delay }

case
  $result
  [`ok: { |value| consume $value }, `err: { |error| raise $error }]

A newline after return ends that statement. It does not attach the value on the next line.

return
42          # a new statement

Command arguments do not continue onto the next line merely because the next line is indented. Bind a long argument list to a value and spread it when you need to split such a command across source lines.

3.4. Braces, brackets, and parentheses

Braces ({ ... }) contain a block. Newlines inside a block still separate statements.

Brackets ([ ... ]) contain a collection, pattern, index, or expression block. Newlines are whitespace while the bracket is the innermost open delimiter. Collection entries still need commas; a newline does not replace a comma.

let ports = [
  8080,
  8081,
]

let prompt = [render: {
  let mark = '>'
  return $mark
}]

The block in the second example is inside a map, but its own braces are the innermost delimiters. Its newline therefore separates the let and return statements.

Parentheses have three uses: () alone is the unit literal (§4.1), they group expressions inside $[...], and they delimit names in $(name). They are not a general command-grouping form.

Postfix indexing requires no space before [. Thus $item[key] is one indexed value, while $item [key] is two values in a command. A ! reaches over a dereference's keys, so !$item[key] forces the field; any other primary is forced first and indexed after, so !{cmd}[key] selects from the forced result.

ral reports mismatched or unclosed delimiters. It also rejects source with more than 64 nested forms. This limit prevents an implementation stack overflow.

3.5. Words and punctuation

A bare word is source text that needs no quotes. Most visible characters can occur in a bare word. Spaces, tabs, line endings, and these characters end a bare word or start another language form:

|  {  }  [  ]  $  ^  !  <  >  "  '  `  (  )  ;

Some characters depend on their position:

  • # starts a comment only at the start of a word. It remains literal inside a word.
  • ~ at the start of a word, standing alone or followed by a path separator (/, or \ on Windows; see below), abbreviates the current user's home directory, which home returns (§10.2): ~/src is "!{home}/src". Anywhere else ~ is an ordinary character, so neither foo~bar nor ~bob/x names a home directory.
  • , separates items while [...] is the innermost form. Outside brackets, it can be part of a word, as in --features=a,b.
  • : is punctuation before whitespace, a newline, ], or the end of input. It remains part of forms such as localhost:5432.
  • ? and & are punctuation where a new word can start. They can occur inside a longer bare word. ? is the failure chain; a lone & is always refused (§11.1), and so are the shell spellings && and ||, whose jobs here belong to ; and ?.
  • Inside $[...], and only there, <, >, <=, >=, !=, &&, and || are operators rather than redirects and punctuation, and the word characters +, -, *, /, %, and = end a word, so $[1+1] is a sum and needs no spaces (§17.1). A numeral is still read whole, its exponent's sign included and, where a value is expected, its own sign: $[1.5e+3] and $[-9223372036854775808] are numbers. Outside $[...] all of these are word characters or shell punctuation: 1+1 is a word and a >= b writes to a file named =.
  • ... is the spread marker where a new word can start. It can occur inside a longer word.

Quote a word when there is any doubt. Quoting prevents punctuation in its contents from changing the program structure.

Whitespace separates words, and nothing joins them. Two words written with nothing between them, such as --prefix=$d or 'a'"b", are an error, not two arguments and not one: write --prefix= $d for two, or "--prefix=$d" for one. Only the grammar's own attachments touch: an index after a $name or a forced block ($h[k], !{f}[k]), a spread before its list (...$xs), and a redirect before its target (>file). Except for redirects, these attachments must touch: ^ls, ...$xs, !$x, $h[k]. A space after ^, ..., or ! is an error. The rule holds in every position, not only in a command's arguments: if $c{a}, try{a}{b}, and [a'b'] are errors like --prefix=$d.

Backslash escapes nothing in a bare word. For example, C:\Users\name is one bare word. A dot is also ordinary, so .env and archive.tar are bare words.

A bare word containing a path separator is a path, and as a command head it runs that path directly (§6.2). / is a separator on every platform; \ is one on Windows only. So on Windows C:\Users\name and .\build are paths, while on Linux and macOS a\b is an ordinary word, which as a command head is a bare name searched on PATH.

3.6. Names and reserved words

A binding name starts with an ASCII letter or _. Later characters can be ASCII letters, digits, _, or -. Names are case-sensitive.

These words cannot be binding names or block parameters:

if  elsif  else  let  return  case
within  grant  try  guard  audit  spawn  gather  use
true  false

This restriction is contextual. For example, a quoted occurrence is always string data, and ^name uses an external command name rather than a binding.

3.7. Statements and stages

A statement is either a let binding or a command chain. A command chain can contain pipelines joined by ?. A pipeline contains one or more stages joined by |.

let is a statement form. It cannot occur after | or ?.

let result = produce | consume

produce | let result = consume   # error
produce ? let result = fallback  # error

The complete formal grammar is in §17.

4. Values and data

A value is data. ral does not split it into words or read it again as source text. For example, a string that contains spaces remains one value and one command argument.

ral has these kinds of value:

Kind Meaning
Unit One value that carries no information
Bool true or false
Int A signed 64-bit integer
Float A finite 64-bit floating-point number
String Unicode text
Bytes An arbitrary finite sequence of bytes
List An ordered sequence of values
record or map Values stored under string keys
variant A tag carrying one value; a bare tag carries ()
block or function A suspended command
handle A reference to concurrent work

Blocks, functions, and handles are values, but later sections define how to run or inspect them.

4.1. Scalar literals

The literals true and false produce Bool values. () is the unit literal, producing the one Unit value. It is punctuation rather than a word, exactly like [] and [:]; the bare word unit is ordinary text. A word shaped like a numeral produces a number:

numeral   ::= integer | float
integer   ::= sign? digit+
float     ::= sign? ( digit+ "." digit* | digit* "." digit+ ) exponent?
exponent  ::= ("e" | "E") sign? digit+
sign      ::= "+" | "-"
digit     ::= "0" … "9"

An integer produces an Int, a float produces a Float. A float must carry a decimal point, and digits on one side of it are enough, so .5 and 2. are both floats. An exponent alone is not: 1e6 has no decimal point, so it is a word. There are no digit separators and no other base — 1_000 and 0x10 are words. Leading zeros and a leading + are allowed and carry no meaning.

A numeral outside the range of its kind is a word instead. An Int must fit a signed 64-bit integer, so 9223372036854775808 is text. Every Float is finite, so a spelling that would overflow to infinity, such as 1.8e308, is text too. The float conversion likewise rejects NaN and positive or negative infinity, and floating-point arithmetic fails if its result would be non-finite.

return ()
return true
return 42
return -7
return 3.14
return 1.0e6

An unquoted word that is not a numeral is a String. Thus return hello returns the text hello.

Numerals denote numbers in every position

This reading does not depend on where the word stands. A numeral is its number as a command argument, as a bound value, as a redirect target — everywhere a word may appear, $[...] included, in which a sign touching a numeral is its sign wherever a value is expected (§17.1). 007 is the number 7 and 1.50 is the number 1.5, wherever they are written.

Each number in turn has exactly one printed spelling: the shortest decimal that reads back as the same number. A Float keeps its decimal point, so 3.0 prints as 3.0 rather than 3, and it takes exponent form where plain digits would run away, so the number ten to the three hundredth prints as 1.0e300 rather than as 301 characters. A canonical numeral therefore crosses the shell unchanged, and a non-canonical one is normalized on the way out:

Written Printed
007 7
+5 5
-0 0
.5 0.5
1.50 1.5
3.0 3.0
1.50e300 1.5e300

Every printed number is itself a numeral of the grammar above, and reading it back gives the number it came from. Printing and reading therefore compose to the identity on numbers, and a printed float never degrades into text. The grammar is unchanged by this: 1e6 still has no decimal point and is still a word — it is the printer that never produces such a spelling.

Quote a word to keep its bytes: '007' is three characters and '1.50' is four. Wherever ral renders a String back as source text — a completion, a quoted argument — it quotes a numeral-shaped one for the same reason. The edge worth knowing is a version-like token that is also a numeral: 3.10 is the number 3.1 and prints as 3.1; write '3.10' when the digits name something rather than count it.

4.2. Strings

A String contains valid UTF-8 text. chars $s is its Unicode scalar values, each a one-character String: slice counts in them, and length !{chars $s} counts them, never UTF-8 bytes.

Single quotes make literal text. They do not process escapes or interpolation:

return 'literal $name and \n'

Add matching # fences when the text contains a single quote. Add more # characters when the text contains a possible opening or closing fence:

return #'it's literal'#
return ##'body with '# and #' inside'##

In a raw string with n ≥ 1 fence hashes, a non-closing ' preceded by at least n body #s is a lexical error (L0007); use one more # on each side if that opener is literal text.

Literal strings may span lines. Their contents are exact after source-text normalization. A line ending written as CRLF or a lone CR in loaded source therefore appears as LF in the value.

Double quotes process escapes and interpolation:

return "hello $name"
return "field: $record[key]"
return "host: !{hostname | from-line}"
return "sum: $[2 + 3]"

$(name) marks the exact end of a name when the following text could be part of it. A splice is $name, $(name), $[...], !{...}, or !$name, and means what the same text means outside the string. A $ or ! that opens none of these is text.

$(name) takes nothing after it, inside a string or out: "$(red)[$host]" is a colour followed by a bracketed host, and $(red)[x] outside a string is two words that touch (§3.5). Every other splice is indexed by the [key] groups written immediately after it, exactly as outside a string: "$h[k]", "!{f}[k]", and "$[$xs][0]" select from the value.

A double-quoted string that begins with ~ followed by / or by the closing quote begins with the home directory, exactly as a bare word does (§3.5): "~/x" and "!{home}/x" mean the same. A ~ anywhere else in the string, and any ~ in a literal string, is text; "\~/x" begins with a literal ~.

The supported escapes are \n, \r, \t, \\, \0, \e, \", \$, \!, \~, \xNN, \u{X..}, and backslash followed by a line ending. \xNN accepts one ASCII byte from 00 to 7F. \u{X..} accepts one valid Unicode scalar value written with one to six hexadecimal digits. An unknown or malformed escape is an error.

Interpolation accepts Bool, Int, Float, and String, each in its normal text form. It rejects (), bytes, collections, variants, blocks, functions, and handles. () is nothing to print, so it is not a word either: write the text '()' if that is meant. Use an explicit conversion or select a field instead.

4.3. Bytes

Bytes can contain any byte, including NUL and invalid UTF-8. There is no byte literal. Codecs and input operations create byte values. to-bytes writes a Bytes value through unchanged; ints-to-bytes builds bytes from a list of integers from 0 through 255, which is how a program spells out bytes without a literal for them. Section 7 defines byte pipes and the codecs that cross between bytes and values.

Equality compares bytes exactly.

Displaying bytes decodes them with replacement characters for invalid UTF-8. This display is only for inspection; it can lose information. from-string performs a strict UTF-8 decode and fails on invalid input.

4.4. Lists

A list is ordered. Its elements must have compatible types. Use commas between elements. A trailing comma is allowed.

let names = ['Ada', 'Grace', 'Edsger']
let empty = []

... inserts the elements of another list at that position. It creates a new list and does not change the source list.

let middle = [2, 3]
return [1, ...$middle, 4]

Spreading a value that is not a list is an error. A literal's parts are evaluated left to right, and a failing spread fails where it is written.

4.5. Records and maps

Records and maps use the same runtime value: a string-keyed collection. They differ in what the checker knows.

  • A record has known fields. Its fields may hold different kinds of value.
  • A map's keys are data, not field names. Its values must have compatible types.
let server = [host: 'db.example', port: 5432]
let key = 'primary'
let ports = [$key: 5432]
let empty_map = [:]

A key is a label or data, and its form says which. A label is a bare name, a 'single-quoted' word, or a "double-quoted" string with no splice. true and false are labels too. A computed key, such as $key, "k$i", !{f} or $[…], is data and must have type String. Quotes never decide a collection's type. Keys are unique in the resulting value and iterate in sorted order. A literal's explicit entries, as opposed to those a spread brings, never repeat a key: a repeat among labels and strings that do not interpolate is a type error, and any other is a runtime error. A tag is not a key, in a literal or in a pattern (§4.6).

[:] is the empty map. [:, a: 1, b: 2] explicitly builds a map on written keys, and permits spreads, as in [:, ...$m, a: 1]; every non-spread entry must be keyed, and [:,] is refused: write [:] for the empty map. Otherwise a literal's keys decide: all written keys give a record, any computed key gives a map, and no keyed entry gives a list. One computed key makes every written key in that literal data. [a: 1, "b c": 2, 'd': 3] is a record.

There is no empty-record literal: [] is the empty list, not [a: 1] with its fields removed. A host file (§15.3) ends in its options written out; () means no options only where its table has no required keys.

let record = [host: 'db', port: 5432]
let by_data = [:, host: 'db', port: 'https']
let computed = [$key: 5432]

In a map literal every explicit entry wins over every spread entry, regardless of position, and if spread entries conflict with each other the first spread entry wins.

A record literal with a spread is an update of that one base: [...$r, k: v]. The ... comes first and there is only one; a spread after a field, and a second spread, are parse errors. The fields written after it replace fields the base already has, each at whatever type it is written, and the rest of the base keeps its place in the result. A spread never adds a field: naming one the base lacks is refused, with the three ways to carry a new field: give the record the field from the start, nest the record ([cfg: $cfg, total: 3]), or make $cfg a map ([:, ...$cfg, total: 3]). Nothing is appended after an unknown remainder, so defaults are not merged over an unknown record; absence over an unknown record travels as a variant.

Spreading a value that is not a record or map is an error. Spreading does not change the source value. A literal's parts are evaluated left to right, and a failing spread fails where it is written.

4.6. Variants

A variant records one named outcome. A bare tag carries (): `t and `t () are one value.

let absent = `none
let answer = `ok 42
let problem = `error [message: 'not found']

The tag takes the next value atom as its payload. So two tags in a row nest: `a `b is one value, `a carrying `b. To pass two tags as two arguments, bind the first: let a = `a and then f $a `b. A statement boundary, comma, closing bracket, pipe, ?, or redirect leaves it bare. Section 8 defines case, which chooses one arm by tag.

A tag says which of several alternatives, and a key says which part of one value, so the two alphabets belong to different type formers and never meet. A tag keys nothing: [`dev: 8080] is a parse error, in a literal and in a pattern alike. The one place a tag stands before a : is a case arm (§8.3), which is syntax rather than a record.

4.7. Indexing

Indexing is postfix syntax. The [ must immediately follow the value being indexed.

$items[0]
$server[host]
$config[database][port]

The written key picks one typing rule, applied immediately:

Key form Reads Type required
$r[host], $r['user name'], $r["user name"], $r[true] record field [label: α \| ρ]
$xs[0] list element [α]
$m[$k], $m["k$i"], $m[!{f}], $m[$[…]] map value Map α; key String

A constant double-quoted key is a label; a splice makes it computed. true and false name fields, not boolean keys. List positions are whole numbers from zero. Negative and fractional numerals are parse errors, with a hint to quote a numeric field name: $r['1.5']. Path and tilde words must likewise be quoted as field names, as in $r['a/b']; tags are not keys.

For a position computed at runtime, use nth : ∀α ν. Integer → [α] → Command[ν] α: nth $i $xs. It has the same bounds checks as a written list position. A helper { |m k| $m[$k] } is polymorphic over map element types; indexing neither defers a constraint nor makes a type variable weak. The prelude's get $m key default supplies a map fallback.

env : ∀α. Returns α is a checked boundary (§7.3). !{env}[HOME] uses a record field and checks its presence at that call; keys !{env} or has !{env} X uses a map. Each call is checked independently. Environment values are text: using HOME as a number fails at env, rather than converting it. A missing field or key, an out-of-range position, or an incompatible target is an error. A computed key on a list is refused with advice to use nth; a written key on a map needs a computed key or get instead.

4.8. Equality and ordering

== and != inside $[...] compare data structurally. The two operands have one type, and it is data (§17.3): no block, function or handle at any depth.

  • Unit, booleans, strings, and bytes compare by value.
  • Numbers compare numerically.
  • Lists compare their elements in order.
  • Records and maps compare their key-value pairs without regard to insertion order.
  • Variants compare their tag and payload.

Blocks, functions, and handles have no equality operation. Comparing one is a static error, including when it is nested in a collection, and so is comparing values of two different types: $[42 == hello] is refused, and $[3 == 3.0] too, since the checker keeps Int and Float apart.

Ordering is defined only for numbers and strings, and both operands have one type: <, >, <=, >=, lt and gt refuse a list, a record, a Bool, and a number against text. Integer-to-integer ordering keeps the full 64-bit integer precision. String ordering is lexicographic. + - * / take two numbers of one type (Int or Float) and % two Ints; "a" + "b" is refused, and joining text is interpolation.

4.9. Display

ral has a text conversion for command output and a value renderer for interactive hosts. They serve different purposes.

Text conversion writes strings without quotes and every other scalar value in its usual form. It shows lists, records, maps, and variants with brackets and tags. It shows bytes as lossy UTF-8, and a function, a block, or a handle in an abbreviated form such as <|x| block>. str and to-string expose it: it is total on data, every value having a text conversion. This form is readable but is not always valid ral source and is not a serialization format.

Only text, numbers and true/false go into an interpolated string ("n: $n"), and () is nothing to print: neither a word nor an interpolant. A list, a record or a map is rendered with !{to-json $x}, a list of text joined with !{intercalate ', ' $xs}, and the text () is written '()'.

The interactive value renderer quotes strings with a safe hash fence, writes () for Unit, and lays out collections to fit the available width. Maps display in sorted key order. A host may shorten deeply nested collections or a long string stored directly under a map key. It must mark any omitted content. Lists and top-level strings are not shortened by the standard ral renderer.

5. Bindings, patterns, blocks, and functions

let gives a name to the result of a command or to a value.

let branch = git branch --show-current
let port = 8080
let greeting = 'hello'

The first binding runs git and binds its result. The other two bind values without running an external command. Use $name to read a binding outside command-head position.

echo "$greeting from port $port"

A bare name in command-head position follows the lookup rules in Commands and name lookup. This is why let branch = git ... runs git, while let greeting = 'hello' binds a quoted value.

5.1. Immutable bindings and scope

A binding cannot be changed. A later let with the same name creates a new binding that hides the old one in the current scope.

let colour = 'blue'
let colour = 'green'
echo $colour                 # green

Bindings use lexical scope. Code uses the bindings that were visible where that code was defined.

let rate = 10
let add-rate = { |n| return $[$n + $rate] }
let rate = 20
add-rate 5                   # 15

The function keeps the first rate. A binding at its call site cannot change that captured value.

Every name is known before the program runs. Reading $name where no binding or builtin of that name is in scope is a static error, not a failure at run time, and ral suggests the nearest names that are in scope. Environment variables are not names: read them as !{env}[NAME].

echo $colur                  # error: undefined variable: $colur
                             # help: did you mean `$colour`?

A - inside a name continues it, so "$os-gnu" reads $os-gnu; "$(os)-gnu" ends it. (A trailing - does not: "$os-$arch" is $os, a -, and $arch.)

echo "$os-gnu"               # error: undefined variable: $os-gnu
                             # help: `$os` is defined, and `-` continues a name: write `$(os)` to end it there

A binding shadows a command of the same name, at every scope, whatever is on the current PATH: a program means the same on every host. ^name reaches the external command.

let dd = { echo mine }
dd                           # mine
^dd --version                # the binary on PATH

Prelude functions and builtins can be hidden the same way, although ral warns when a binding hides a prelude name.

A let is polymorphic: the type of a bound function generalises over every type variable that the rest of the program does not also mention, so let first = { |xs| return $xs[0] } can be applied to lists of any element type. The exception is a weak type variable: the type of a value whose shape the program did not decide, entering through a checked boundary such as a decoder or env. A weak variable has one type for the whole program, every use of it must agree, and a type that shows one prints as _α.

5.2. Patterns

The left-hand side of let is a pattern. Function parameters use the same patterns.

Pattern Meaning
name Bind the complete value.
_ Ignore the value.
[first, second] Bind a list of exactly that length.
[first, ...rest] Bind the first item and bind the remaining list to rest.
[host: h, port: p] Read named fields from a map or record.

Patterns can be nested.

let [first, ...rest] = [10, 20, 30]
let [name: user, address: [city: city]] = $account

One pattern cannot bind the same name twice. ral reports this as a parse error, including when the repeated name is nested or used as a list tail.

A list pattern without ...rest must match the complete list. It is an error if the list has too few or too many items. A record pattern requires every field it names. Extra map fields are allowed.

A pattern either binds every name or binds none of them. If any nested part does not match, ral reports an error and leaves the scope unchanged. try can catch this runtime error.

Patterns are structural. They cannot test for a literal value. Use if for a Boolean decision and case for a variant.

5.3. Plain blocks

A plain block stores commands as a value. Creating it does not run its body.

let announce = { echo 'ready' }

Force a block with ! to run it:

!$announce
!{echo 'run this anonymous block'}

! means force. It is not Boolean negation. Use not for Boolean negation inside $[...].

A bound plain block is also forced when its bare name is the command head. These two statements are equivalent:

announce
!$announce

A block captures lexical bindings when the block is created. Its body runs in a fresh local scope. Bindings created by the body do not escape. Shell state is not local: a cd or other unbracketed shell-state write persists (§2.6). The block's output, result, failure, and audit records remain observable.

let outside = 'outer'
let result = !{
  let outside = 'inner'
  let local = 42
  return $outside
}

echo $result                  # inner
echo $outside                 # outer
echo $local                   # error: no such binding

An empty block returns (). A non-empty block returns the result of its last statement. Earlier statement results are discarded.

5.4. Functions

A parameterised block is a function. Put one or more space-separated patterns between the two | characters.

let add = { |x y| return $[$x + $y] }
let describe-service = { |[name: name, port: port]| echo "$name:$port" }

Do not put commas between parameters. { || ... } is invalid; use a plain block { ... } when there are no parameters.

Each parameter is a separate pattern. A later parameter can therefore use the same name as an earlier parameter. The later binding hides the earlier one in the remaining function body.

let keep-second = { |item item| return $item }
keep-second 'first' 'second'  # second

Call a function by putting it in command-head position:

add 2 3                       # 5
describe-service [name: 'web', port: 443]

Use $function when passing a function as data.

let increment = { |n| return $[$n + 1] }
map $increment [1, 2, 3]

Without $, increment in argument position is the string "increment".

Each argument is applied from left to right. If a call supplies too few arguments, it returns a new function that waits for the remaining arguments.

let add = { |x y| return $[$x + $y] }
let add-five = add 5
add-five 3                    # 8

If arguments remain after the function returns, ral applies them to the returned value. This is valid when that value is another function. Otherwise, ral reports a type error or a runtime error.

A function call gets a fresh local binding scope. Its parameters and local let bindings do not escape. The function still acts in the caller's shell: for example, a successful cd in a function changes the caller's current directory, exactly as it does in a forced plain block.

5.5. return

return value produces value as the successful result of the current statement. return with no value produces (). It accepts at most one value.

Despite its name, return is not an early-exit statement. It does not skip later statements in a block, function, or file.

let example = {
  return 1
  return 2
}

!$example                     # 2

Use if, case, or a failure to choose which computation runs. ral has no non-local early return.

5.6. Top-level runs and local bodies

A top-level run is one complete script, one -c program, one submitted REPL entry, or one exarch tool call. When the host keeps the session open, successful top-level bindings are available to the next top-level run.

If a top-level run fails, effects completed before the failure still remain, and so do the bindings it established: a let that landed before the failing statement stays bound in the session. A binding after the failing statement is never evaluated.

let before = 1
failing-command
let after = 2

After this failed top-level run, before remains bound in the session and after does not exist.

Forced plain blocks are local bodies. The bodies used by within, grant, try, guard, audit, spawn, and gather follow the same local rule. guard's acquisition and release are local too: the resource reaches the body and release only through their parameters. None of these bindings become top-level session bindings.

5.7. Recursion and forward references

A simple named block binding can refer to itself.

let countdown = { |n|
  if $[$n == 0] { return () }
  else { countdown $[$n - 1] }
}

Consecutive named blocks in a statement list form a stretch, and the blocks of a stretch can refer to each other in any source order. This supports mutual recursion and helper functions written after their callers.

let even = { |n|
  if $[$n == 0] { return true }
  else { odd $[$n - 1] }
}

let odd = { |n|
  if $[$n == 0] { return false }
  else { even $[$n - 1] }
}

A stretch admits only simple named bindings whose right-hand side is a plain or parameterised block. Any other statement ends it, and so does a definition of a name that the same statement list has already bound, which begins the next stretch. Inside a stretch, every block sees every name the stretch defines, its own included, even where the name is already bound outside the list: by an enclosing block or parameter, by the prelude, or by an earlier top-level run. Every other reference sees only the bindings above it: no statement sees a binding below it, and a block sees one only within its own stretch. A block that names a block defined further down the same statement list, past its own stretch, is refused, unless a let above it in that list, or the parameter of the block whose body the list is, already binds the name. A binding from outside the body (the prelude's, an enclosing block's, or an earlier top-level run's) does not lift the refusal.

let limit = 10
let check = { return $limit }   # 10: rebinding `limit` begins a new stretch
let limit = { return 20 }

let main = { helper }           # refused: `echo 'ready'` ends `main`'s stretch,
echo 'ready'                    # so `main` cannot see `helper`
let helper = { echo 'help' }

Tail-recursive calls reuse the current evaluator frame. Non-tail recursion is limited by the configured recursion limit and fails with a clear error if it exceeds that limit.

The formal account of function application, recursion, and inferred types is in §17.

6. Commands and name resolution

A command starts with a head. The head decides whether ral applies a value, invokes a handler, or starts a program. Arguments do not use command lookup.

6.1. Command and value contexts

A statement and the right-hand side of let are command contexts:

hostname
let host = hostname

Both lines run hostname. The second line binds its result.

Arguments, return operands, collection elements, and interpolations are value contexts:

echo hostname
return hostname
let tools = [hostname, uname]

Here, hostname and uname are strings. Use $ to read a binding:

echo $host
return $host

A command written as a collection entry, [n: length $xs], is refused, and the diagnostic offers its spelling as a value, [n: !{length $xs}].

A value written alone in command context returns itself. This lets a literal or collection be the result of a block:

{ 'ready' }
{ [host: 'example.net', port: 443] }

6.2. Head forms

The spelling of the head selects one of four paths.

Form Examples Meaning
Bare head git status, map $f $xs Use the lookup order in §6.3.
Path head ./build, /usr/bin/env, ~/bin/tool, .\build (Windows) Run that path directly.
Explicit value head $f 3, !$factory 3 Apply the value. Never search for a program.
Caret head ^git status Skip value bindings and the whole handler stack; use program lookup.

A head is a path when it contains a path separator: /, or on Windows also \ (§3.5). A path head does not consult bindings, handlers, bundled commands, or PATH. ral expands ~ when it resolves the command. A relative path uses ral's current logical directory.

A literal word, a bare ~, and a $[...] block are value heads wherever they stand: let h = ~ binds the home directory, and 42 foo or ~ foo is a type error rather than a missing command.

An explicit value head stays in the value world. If ral cannot apply it, ral reports an error. It does not reinterpret the value as a command name.

A bare $f with no arguments is only a value:

let copy = $f       # store f
let result = f 3    # apply f
let same = $f 3     # apply f explicitly

^name is valid only at the start of a command. Its operand must be a plain name, not a path. The caret skips user bindings, prelude functions, builtins, and the entire handler stack — named handlers, base handlers, and catch-all handlers alike — and executes the external command of that name, subject to active capabilities. It is, in this respect, the same as a path head such as ./tool or /usr/bin/tool.

For example, ^echo is the operating system's echo, not ral's — a handler for echo, and ral's own base echo handler, are both skipped.

The bare names within, grant, try, guard, audit, spawn, and gather are reserved control forms. Each named form needs a machine frame or worker that intercepts or scopes something across an operand's whole dynamic extent: halts, observations, handlers, context, capabilities, or ownership of work. This is a runtime criterion, not a restriction of Hindley–Milner typing. Capture and redirection also scope frames, but are already syntax, not named forms. A caret form such as ^try uses caret lookup instead.

6.3. Bare-head lookup

ral resolves an ordinary bare head in this order. The first match wins.

  1. A value binding. ral searches the current lexical scopes, session bindings, and prelude. Builtins live here as values. A matching value must be one ral can apply — a function, a block, or a builtin. Otherwise, lookup fails without falling through: let date = 5; date +%s is a static error that says date is bound to an Int, and ^date runs the command.
  2. A named user handler. This includes persistent handlers installed by the host from the rc's or a plugin manifest's handlers: field, and scoped handlers installed by within [handlers: …]. The innermost handler for the name wins.
  3. A base handler. ral's own commands that take an argument list live here. echo is the standard example, and a host may install more. Every base handler has type [String] → Command by construction: an argv manifest row carries no type rule. It has no application arity and takes the whole argument list.
  4. A catch-all handler. within [handler: …] handles the call only if no binding, named handler, or base handler claimed it.
  5. A bundled or external command. A bundled command wins when the current build supplies that bare name. Otherwise, ral searches the effective PATH.

Prelude functions behave like user functions: use their bare name as a head, and $name when passing one as a value.

Builtins are functions held as values: each takes the arguments its entry declares, and supports partial application and higher-order use. A base handler is not a value. It is reached in command position only, so $echo is an error.

A named handler may share a name with a binding or builtin. The ordinary bare name still selects the binding. ^name is the external command name: it skips bindings, natives, and every handler, base frames included — ^echo is the operating system's echo, not ral's.

6.4. Command handlers

A named handler takes one parameter: the command's argument list. ral renders the arguments after the head and passes them as one List String:

within [handlers: [:, deploy: { |args| audit-deploy $args }]] {
    deploy 'prod' '--wait'
}

A catch-all handler takes the dispatched name and the argument list:

within [handler: { |name args| log-call $name $args }] {
    unknown-command 'arg'
}

An arm receives strings because a command receives strings. A handler stands in for a command, and it can only do that if it consumes what a call to that command would send; an arm that expected typed arguments would not be interchangeable with the command it replaces. So an arm cannot do arithmetic on $args[0]: it holds that argument's rendering, '1' rather than 1. Use int or float when the arm wants a number.

A head's type and argument gate depend only on Σ (the host's manifest and prelude) and lexical bindings, never on the handler stack. Every base frame has [String] → Command and the in-shell argument gate; every other command name has the same type and the external argument gate, even when handled. Thus ls [1, 2] is refused under a handler for ls too: spread the list or bind a function with let. Handled names inform diagnostics, not typing.

ral checks a handler's arity, which is its type and not its spelling, statically. Persistent handlers (rc, manifest) are checked again when installed; within needs no install-time check. A written within map entry is also checked as an arm standing in for the head it names (§9.4). A handler for echo, for example, stands in for a command, so its value is its output.

Handlers are self-masking. While a selected handler runs, its own frame is temporarily absent. A call to the same name from its body reaches an outer handler, a base handler, a catch-all handler, or an external command:

within [handlers: [:, git: { |args|
    warn 'running git'
    git ...$args
}]] {
    git status
}

Any named handler takes priority over any catch-all handler, even when the catch-all is in a more deeply nested scope. A base handler also takes priority over every catch-all handler.

6.5. Application and arity

ral passes arguments in two ways, and they share nothing. A value — a block, a lambda, or a builtin — is applied: it takes one argument at a time, at the arity its definition declares. A handler, a base handler, or an external or bundled command instead receives an argument list, and has no arity at all; see Arguments and spreading. This section is about application.

Parameterized blocks and builtins are curried:

let add = { |a b| $[$a + $b] }
let add-two = add 2
let five = add-two 3

A call to a parameterized block or builtin with too few arguments binds the parameters it was given and returns the residual function as a block; nothing of its body has run. add 2 returns a block of one parameter. An ordinary builtin of arity n displays as <native NAME>, or as <native NAME, k of n arguments> when 0 < k < n arguments are supplied. Its body runs only at saturation. Boundary builtins are η-expanded during inference into blocks carrying the call's checked site (§17.9).

If the callee's type returns a block before all arguments are used, the checker splits the call: the returned block is forced and given the rest. This is decided before the program runs; a value is never applied at run time.

ral checks known arity and argument-type errors before execution. An application's arity is always known, so the arguments written at a call site are exactly the arguments that arrive. Nothing in that position stands for an unknown number of them, because ... forms an argument list and a value takes none.

6.6. Arguments and spreading

Command arguments are values. Ordinary and quoted words produce strings. Numeric and Boolean literals keep their types. $name supplies a bound value, and !{…} supplies a forced block's result. What becomes of them next depends on which of the two mechanisms of Application and arity the head uses.

An argument list is the flat sequence of arguments that a base handler, a handler arm, or a bundled or external command receives. Its type is List String.

A handler arm receives rendered strings. In-shell argument rendering uses the text conversion of Display, the same conversion str exposes and echo writes. That conversion has a text form for every value; admission to an argument list is a separate rule. Bytes, collections, blocks and handles can be rendered at a base-frame call such as echo. Handling an external name does not grant it this wider gate. Nothing crosses a user handler's argument list as an unrendered ral value:

echo hello [a: 1]             # hello [a: 1]
let f = { |x| $x }
echo $f                       # <|x| block>

A bundled or external command receives operating-system arguments instead, and those are bytes. That is a second boundary, and a narrower one; its rule is below.

...value spreads a list into an argument list:

let flags = ['--all', '--long']
ls ...$flags '/tmp'

The spread value must be a list. Its elements are inserted in order at that position, and they are rendered like any other argument.

A value receives no argument list. It takes its arguments by application, one at a time, at the arity its definition declares, so a spread among them has nothing to spread into. ral reports a spread in the argument position of a value — a block, a builtin, or anything reached through a binding — before execution:

let numbers = [1, 2]
let add = { |a b| $[$a + $b] }
add ...$numbers               # error: a value takes no argument list
add 1 2                       # 3
echo ...$numbers              # 1 2

The same ... marker also builds a list ([1, ...$middle, 4]) and matches the tail of one ([first, ...rest]). Those are the forms of Lists and Patterns: they construct and destructure a list, and neither forms an argument list.

Unit is nothing, not a word: the checker refuses it at both the in-shell and operating-system argv boundaries. Write '()' for the text. Other shapes are admitted at base-frame calls. The external gate, also used for handled external names, is narrower: it admits strings, integers, floats, Booleans and tagged values, but refuses bytes, lists, maps, records, blocks, functions, builtins and handles as single arguments. Spread a list, and send bytes through a byte pipe or decode them first.

The checker judges a single argument's final type head after the unit has solved and defaulted (§17.3), not the head known when visiting the call. If that head is refused at the relevant boundary, the unit is rejected before execution, so nothing is started:

let r = [a: 1]
cat $r                        # error: cannot pass [a: Integer] as an argument to `cat`

A head still free at unit closure leaves the shape to runtime; being a parameter or a decoded value alone does not defer the check if the unit fixes its head. Spread elements are handled at the call, since how many arguments a spread contributes is known only then; an empty spread contributes none.

At runtime, an OS call checks each argument against the same refused shapes, and echo independently refuses Unit. Arbitrary handler arms currently render a Unit known only at runtime, including one supplied by a spread, rather than enforcing the checker's Unit refusal universally. The total display conversion must not be mistaken for uniform argv admission.

Arguments are never split, globbed, or parsed again. A string containing spaces remains one argument.

6.7. External commands

A bare external name uses the effective PATH. A within [env: [PATH: …]] scope changes that search for its body. ral resolves the command once, then starts that program with the current logical directory, environment, redirects, and capability restrictions.

When the build supplies a bundled command with the requested bare name, the bundled command wins over a same-named file on PATH. It still runs as a child command with the same byte-pipe, failure, audit, and sandbox behavior as an external program. Use a path head to select a particular system binary.

A missing bare command fails with status 127. A file found on PATH but not executable fails with status 126, as does a path naming a directory, and a path or PATH entry the operating system refuses to search; the diagnostic says which. Under a grant this is said only of a command the grant admits running (§12.3). A path head offers itself as text (#'…'#). A command that never became a process is not advised to attempt. A non-zero process result is a failure, except in a non-final byte-pipe stage that was still running when the stage reading it ended.

6.8. Returned values and emitted bytes

A command can return a ral value and emit bytes independently.

  • A let always runs its right-hand side.
  • In statement position, bytes go to the current output unless redirected. The returned value is discarded.
  • A command's value is its output: a let whose right-hand side is a command, whether written inline or reached through a block or function, binds what it writes. The capture is decoded as UTF-8 and loses one trailing newline.
  • In a pipeline, a stage's bytes go to the next stage's standard input. Every stage but the last feeds the next by writing, and its own value is unused; the pipeline's value is the final stage's.
  • Value-style composition is ordinary application or bind. The | operator does not apply a returned value as another stage's argument.
  • A redirect changes where emitted bytes go. It does not make those bytes the returned value.
let branch = git branch --show-current
let saved = echo 'hello' > greeting.txt

branch receives the captured branch name. The redirect sends echo's bytes to greeting.txt, so saved is ().

Captured text is data. ral does not re-lex it, split it, or expand wildcards in it. Use a decoder for structured bytes, and use from-bytes for data that is not UTF-8.

7. Pipelines and input/output

A pipeline connects computations with |. Every interior connection is an operating-system byte pipe, and stage position alone decides the wiring: the left stage's standard output becomes the right stage's standard input. The pipeline's own value is the final stage's, and may be an ordinary ral value. ral never inserts a codec and never turns a returned value into pipeline traffic.

7.1. Byte edges and value composition

The following is a byte pipeline. Its stages may be builtins, external commands, or ral code, but each interior handoff is bytes:

to-json $record | jq '.name' | from-line

An external command cannot receive a structured value by accident. The encoder takes its value as an ordinary argument, so the pipeline begins with bytes; the decoder ends it.

Neither side of a | promises traffic. A stage that writes nothing leaves the next stage an ordinary end of input, and a stage that never reads leaves the offered bytes unread; once that non-reader ends, ral ends the blocked producer itself (§7.6), so nothing hangs.

Each stage must be a command ready to run. A stage still waiting for an argument is a type error, reported before anything starts, and the diagnostic says to apply it rather than pipe into it:

cat notes.txt | fold-lines $step        # error
cat notes.txt | fold-lines $step 0      # runs

(pipe). A stage feeds the next by writing, so every stage but the last is a command: an external, a builtin that writes, or ral code that writes. A stage of any producer kind is accepted, but a decoder such as from-json returns a value and writes nothing, so it ends the byte pipeline, and a value is no stage. The pipeline's value is its final stage's. The checker refuses a stage that cannot feed the next before anything starts:

echo !{length $xs} | cat    # runs: the count is written, then piped
from-json | cat             # error: a decoder ends the byte pipeline; nothing reaches `cat`
[1, 2, 3] | cat             # error: a value in stage position writes nothing to the pipe

A block literal is a value, so a block literal as the final stage returns a thunk and runs nothing. cat f | { from-line } is accepted and does nothing; cat f | !{ from-line } runs the block as a stage.

In a multi-stage pipeline, a ral-written stage runs on its own thread and an external command runs as its own process; every | uses an operating-system byte pipe regardless. State changes made by a stage are private to it: its working directory, environment changes, handlers, loaded modules, and bindings do not alter the parent, since a stage thread evaluates over a cloned shell that is simply dropped at the stage's end. Only pipe contents, the final result, and recorded observations cross the boundary.

Value-style composition stays in the ordinary evaluator. There is no second kind of pipe; use application or bind:

let items = range 0 5
let squares = map { |n| return $[$n * $n] } $items

7.2. Output and results

Every computation produces two independent things:

  • the bytes it writes to standard output, which go wherever position and redirects send them: into the next stage inside a pipeline, and to the surrounding stream otherwise;
  • the value it returns to the evaluator.

Neither implies the other. Only a let captures a command's output and decodes it as a value. A computation that returns a value writes nothing of that value unless it explicitly encodes it. Only the final stage's value can become a pipeline's: every earlier stage feeds the next by writing (§7.1).

In statement position, byte output goes to standard output unless a redirect sends it elsewhere.

What let binds is decided by type (§6.8), not by what the checker knows when it first visits the binding. A command — an external, a builtin declared to write, or a handler arm standing in for one — has type Command. Only when it is a let's whole right-hand side does the checker wrap it in a capture frame. A right-hand side that runs out of arguments binds the block it returns; a value producer is run for its value.

If the right-hand side's type is unresolved, that choice waits for constraints in the region that owns the unknown. Only when that region closes does an undecided binding default to running for a value (§17.5). Thus a later constraint in the same region can establish that an earlier binding captures. Incompatible binding and application defaults are refused, not prioritized. A !{…} in a value position is hoisted into an ordinary let and follows the same rule. Arguments and control-flow arms are never implicitly captured.

The capture frame has three rules:

  1. On push, the standard-output sink becomes a fresh buffer and the previous sink is held.
  2. On return, the sink is restored and the buffer is yielded as Bytes. The body's value is ignored. A buffer that grows past the cap is an error.
  3. On halt, the sink is restored, the buffer is dropped, and the halt propagates: a capture that does not become its value writes nothing.

The bytes are then decoded:

  • decoding is strict UTF-8;
  • one final LF, or one final CRLF, is removed;
  • no other bytes are changed.

Invalid UTF-8 is an error. Use from-bytes when the byte payload is binary.

A command that writes nothing captures "". Capture wraps the whole computation: earlier statements write to its buffer too, unless an inner let captures them separately.

When the final stage returns a value, the value simply comes back from that stage's own thread: a ral-written final stage runs machine::evaluate over its own closure and returns the result directly, no serialisation and no separate channel involved.

let greeting = echo hello       # "hello"
let data = command | from-bytes # Bytes

Capture is of the whole computation: everything the block writes is its value.

let answer = !{ echo first; echo second }
# prints nothing; answer is "first\nsecond"

A stdout redirect gives the result a fresh grade at the same value type: M > f : F_ν A for M : F_ε A. It does not constrain ε. If no other constraint decides ν in its owning region, a binding defaults it to p, so let saved = to-json 1 > f binds ().

Captures nest. Output goes to the nearest enclosing sink, which inside a capture is that capture's buffer. A let inside a captured block captures its own command: let x = !{ let y = echo a; echo b } prints nothing and binds b. If a captured computation fails or escapes, the bytes it wrote are dropped with the value, so a try handler's value is all a failed capture leaves behind. A failure's report gives one summed, saturating count of discarded bytes across nested captures (§13.1); audit keeps a command's output.

An in-memory capture keeps at most 16 MiB. A capture that reaches the cap fails rather than bind a truncated value — the bytes captured are the value, so a prefix would be the wrong one. The failure is ordinary: nothing the capture held is kept, and try catches the error. Redirect output to a file when it may be larger.

7.3. Explicit codecs

Codecs make every conversion between values and bytes visible in the source. A decoder reads its byte input and returns a value:

Decoder Result Rules
from-bytes Bytes Preserves every byte.
from-string String Requires valid UTF-8.
from-line String Requires valid UTF-8 and removes one final LF or CRLF.
from-lines [String] Splits by the line rule below and replaces invalid UTF-8 in each line with the replacement character.
from-json a ral value, checked Requires valid UTF-8 and JSON. JSON null becomes Unit, a whole number an Int, a number with a fraction a Float.
from-jsonl a list of ral values, checked Splits by the line rule below and decodes each line as from-json does. A blank line, holding only spaces, tabs, and carriage returns, holds no value. An error names its line.
from-json-at tokens a ral value, checked Decodes as from-json does, then reads the value at the RFC 6901 reference tokens tokens, a list of String: an object member by exact key, an array element by canonical decimal. A token that does not resolve is an error naming the pointer prefix and the object's keys or the array's length.
from-csv a list of rows, checked ∀α. Returns [α]: the header names each row's keys. Label reads use records; computed reads use maps. Cells remain strings: a numeric use fails at the decode, naming the column and the line of use. A duplicate header or a ragged row is an error naming it.

Decoders are command forms. They read the preceding byte pipe, or standard input when there is no preceding stage; only from-json-at takes an argument.

Checked boundaries

The shape of a JSON/CSV value is the file's, not the program's, so a checked JSON/CSV decoder's result is a boundary: the checker gives it one type for the whole unit, _α, which every use of the value fixes (§5.1), and the decoder admits the value against that type before the program sees it. let n = $[$doc[size] + 1] over {"size": "12kB"} fails at the decode, naming where:

from-json: the value at `/size` is text (`'12kB'`), but this script uses it as an Int; line 3

A mismatch names an RFC 6901 pointer into the value, what was found, what the script uses it as, and the line of the use. An open record (the fields the script reads) admits extra fields; a closed record literal refuses them. Two decodes the program compares with < agree on numbers or on text, and are refused at the second decode otherwise. A JSON number keeps its kind: 3 is an Int and 2.5 a Float, so a position used as a Float refuses 3, and float at the use accepts both. A decoder never converts a value to fit its type.

The closed set of checked boundaries is from-json, from-jsonl, from-json-at, from-csv, env, exarch-agents, exarch-pins, exarch-transcript, and _ed-state. Each call admits its own result. from-csv : ∀α:data. Returns [α] checks rows against their use; env : ∀α:data. Returns α checks the environment as a record or a map. Neither converts text to numbers.

Every registered boundary returns first-order data. Its declared result constrains every type variable to data and every row variable to be deep, excluding functions and handles at every depth (§17.3). Using decoded data as a function or handle is therefore a kind error at the use, before execution, not a runtime admission refusal.

A decoder is a legal pipeline tail:

let document = cat data.json | from-json
length $document

The decoder consumes bytes and returns a value as the pipeline's result. A decoder writes nothing, so it cannot feed a further stage: cat data.json | from-json | wc -l is a type error, since a stage feeds the next by writing and from-json returns a value. Bind the decoded value and use ordinary application, or encode it again explicitly before another byte pipeline.

An encoder takes its value as an ordinary argument and writes bytes:

Encoder Accepted value Output
to-bytes Bytes Those bytes, unchanged.
ints-to-bytes a list of integers from 0 through 255 The bytes they number.
to-string any value Its ral textual form.
to-line any value Its textual form followed by a newline.
to-lines a list of values Each element's textual form followed by a newline.
to-json a JSON-representable value UTF-8 JSON. Bytes become an array of integers; variants become tagged objects.
to-jsonl a list of JSON-representable values Each element as to-json encodes it, followed by a newline.
to-csv a list of records or a list of maps, with scalar cells and the same keys ∀α:data. [α] → Command: UTF-8 CSV, keys in sorted order as the header, then one row per record or map. Cells are String, Int, Float or Bool, rendered as str renders them.

to-json rejects values with no faithful JSON representation, including blocks, lambdas, and handles. to-jsonl rejects a list holding one, names its index, and writes nothing. to-csv requires every row to use the string-keyed record/map carrier with exactly the first row's keys. It refuses missing or extra keys and zero-column rows. A non-scalar cell names its zero-based row index and key:

to-csv: the cell `k` of the row at index 2 is a list; a CSV cell is text, a number or a boolean

Every row is validated before any byte is written. Decoding the result with from-csv returns text cells, including cells encoded from numbers or booleans. To decode a value already held in memory, encode it into a byte pipe first:

to-string $json_text | from-json

Lines

One rule says where a line ends:

  • A line terminator is LF or CRLF. The CR of a CRLF belongs to the terminator, and only that one CR does.
  • A lone CR is ordinary text, never a terminator, whether mid-line or at the end of input.
  • The final line need not be terminated.
  • Each line strips its own terminator, so mixed endings are fine.
Input, as a ral string Lines
"" []
"a" ["a"]
"a\n" ["a"]
"\n" [""]
"a\n\n" ["a", ""]
"\n\na" ["", "", "a"]
"a\r\nb\nc\r\n" ["a", "b", "c"]
"a\r\n\r\nb" ["a", "", "b"]
"a\rb\n" ["a\rb"]
"a\r" ["a\r"]
"a\r\r\n" ["a\r"]

Every line reader splits by this rule — from-lines, from-jsonl, fold-lines, and the prelude's map-lines, filter-lines, each-line, and line-count — as does lines on a string. Capture (§7.2), from-line, and ask do not split: they remove at most one terminator from the end of what they read, so "a\r\n\r\n" becomes "a\r\n" and "a\r" stays "a\r".

ral writes LF alone: to-line, to-lines, to-jsonl, and echo never write CRLF. to-lines terminates every element, so to-lines [] writes nothing, to-lines [""] writes one LF, and from-lines inverts to-lines on every list of strings in which no element contains LF or ends with CR.

7.4. Redirects

Redirects attach input or output to one command or compound command:

Form Meaning
> path Replace a file atomically when possible.
>~ path Truncate the file and stream output into it.
>> path Append output.
2> path Stream standard error into a truncated file.
2>> path Append standard error to a file.
2>~ path Truncate the file and stream standard error into it.
2>&1 Send standard error wherever standard output goes.
< path Read standard input from a file.
<< value Read standard input from a string value.

Any stage takes trailing redirects, if and case included: if $ok { a } { b } > log. A command's redirects may also stand between its arguments: cmd a > f b.

A redirected stage must be ready to run, not a partial application waiting for arguments. This holds for every redirect, including stdin, stderr and 2>&1: to-json > f is refused; to-json $value > f is ready. Redirect operands are checked whether the redirects are fused into a command call or scope another computation.

A stdout redirect has a fresh result grade at the body's value type (§17.3). Stdin/stderr redirects and 2>&1 preserve the body's grade. This affects result typing, not which bytes are written or where they go.

Only the forms in the table are accepted: 1>, 02> and 2>&01 are errors. To pass a number as an argument before a redirect, leave a space: echo 1 > file.

Each standard stream may be redirected at most once; cmd > a > b is an error. Redirect order does not matter: cmd 2>&1 > f and cmd > f 2>&1 both send standard output and standard error to f.

All redirect operands are evaluated before any file is opened. Files are then opened in the order stdin, stdout, stderr. Relative paths are resolved against the scoped working directory.

ral has no numbered descriptors beyond these three streams. A redirect naming any other file descriptor — 3> path, 4< path, >&5 — is rejected outright, with a diagnostic naming standard input, output, and error as the only three that exist; there is no general facility for managing a spawned process's own inherited handles.

Descriptor duplication runs in that one direction only. 1>&2, and its short spelling >&2, are rejected: their only honest use is the shell idiom for writing a diagnostic, and a diagnostic is what warn is for. The message names warn, and names 2>&1 too, since a program holding the exchange backwards means that one.

A redirect on a stage overrides the wire the pipeline would otherwise use. In cmd > file | next, cmd writes to file and next sees end of input.

Across a | the same collision is refused rather than resolved. A stage after a pipe may not bind standard input at its own root: a | b < f and a | b << value are type errors, because the feed answers every read b makes for the stage's whole run and leaves a writing for nobody. Drop the pipe, run the producer as its own statement, or spawn it if the two were meant to run at once. A read redirected deeper inside the stage — within a block, or on one command among several — supplies that command alone and stays legal.

For a regular file, > writes a temporary file beside the destination, flushes it, then renames it over the destination. If the command fails, ral discards the temporary file and leaves the old destination unchanged. It preserves an existing file’s mode and follows a symbolic link to update its target rather than replacing the link.

This operation is failure-atomic, not a locking scheme: concurrent writers may still race. For non-regular destinations, > uses streaming behavior.

A file's own write permission guards it from > as from >~ and >>: an existing destination that is-writable reports unwritable, a read-only file among them, is refused before the command runs, although its directory would let the rename replace it. > also needs the directory, to make the temporary file and to rename it over the destination, which a sticky directory refuses over another user's file; a writable file whose directory refuses either takes >~.

Use >~ when readers should observe output as it is produced, or when writing a device, named pipe, or similar destination. 2> is also streaming so diagnostics are not delayed until a command finishes. A streaming write is committed byte by byte as it lands, so it is observed committed even if the body later fails; only an atomic > can be aborted.

7.5. Here strings

<< is a here string, not a heredoc delimiter:

from-json << '{"name":"Ada"}'

It feeds a string value to standard input. It does not add a newline. It removes exactly one leading LF, or one leading CRLF. This makes an indented multiline string convenient while preserving the rest of its contents, including any trailing newline.

Whitespace after << is required. There is no <<< form, and << can only redirect descriptor 0. A bare word after << is rejected because it is usually a mistaken heredoc; use a quoted, interpolated, raw, or dereferenced string value.

Large here strings are written concurrently with the reader, so filling an operating-system pipe cannot deadlock command launch.

7.6. Process completion and the terminal

ral runs a ral-written stage on its own thread and an external stage as a process; every external in the pipeline shares one process group the shell is not a member of. ral launches all stages and waits for all of them. A failure in any stage fails the whole pipeline. If several stages fail, the first failing stage in launch order supplies the reported failure. An escape outranks an ordinary stage failure, and a stop (§8.10) outranks an exit; two stops rank by cause; ties go to the earlier stage. A stage's own reader-gone stop, or an enclosing stage's, is no verdict at all: it ranks under everything. An exit in a stage, or a stop reaching a stage from outside the pipeline, ends the pipeline at once: the other stages are torn down, and what that teardown stops is the pipeline's own to forgive. A stage that cannot be launched ends the pipeline the same way, before any later stage starts, and the pipeline reports that failure, not what the stages already running did.

A downstream command often stops reading before an upstream producer is done writing, as in:

large-producer | head

An interior edge is dead once its reader stage has ended. A stage feels that death at exactly one place — its next write to that edge — and nowhere else. A ral-written stage's own write to a dead edge raises the break at that write; an external's write ral cannot see, so ral hears it instead: once the reader is gone, ral reads the edge itself, on the read-end duplicate it already holds, discards whatever bytes are pending at that moment (they were owed to a reader that left), treats the first byte written after them as the kill's cue — SIGKILL on Unix, a distinctive-code TerminateProcess on Windows — and discards whatever follows until the writer is reaped or joined, so no writer ever blocks on a reader that is gone. A write already blocked on a full pipe when the edge dies is completed into that same read and then judged dead: a write not complete when the edge dies does not complete.

That break — and only that break — is the pipeline's one forgiven death: a non-final stage ral cuts this way keeps no failure, because the rest of its output was owed to nobody. Everything a stage does before its first dead write is its own account and runs to completion: its stderr, its files, its children that never write the edge, its own exit status if it never writes again. Nothing after that write is promised. In the final stage the same condition is the closed-stdout stop: the pipeline's own output crosses the outer boundary, and a caller that stops reading it stops the run, status 141, an escape no try catches (§8.10). A reader-gone stage's guard release runs, shielded (§8.7): a release that halts on anything but its reader-gone stop is the pipeline's verdict; one that ends on it is forgiven; a release's own write to the dead edge is stopped, not masked, while a command the release runs is shielded with it (§8.7) and what that command writes there is discarded. A teardown cuts no stage at an edge: an edge whose reader has gone is still read and discarded, but a write to it is no break, so a guard release upstream runs within the remaining shared grace.

A stage whose own redirect statically sends every byte of its stdout to a file, never to the interior edge, never performs the write the cut watches for: cmd > file | next therefore runs cmd's redirect to completion regardless of when next settles, not because it is exempted but because it never reaches the operation the rule cuts.

ral holds a duplicate of each interior edge's read end until that edge's writer stage is reaped or joined, so no interior edge ever delivers a broken-pipe signal or a write error to the stage that writes it. For a ral-written stage the cut is exact — its own write is the operation that raises the break. For a process it lands within the kill's few-microsecond latency after the first dead write. An exit status, once recorded, is never overwritten: the kill precedes the wait, and a kill landing on an already-exited stage changes nothing. This is one rule, stated once, true on both platforms.

A producer that exits on its own account keeps that status, whatever the cause: sh -c 'exit 3' | true still fails with status 3, since it never writes to the dead edge and so is never cut, while yes | head -1 still succeeds, since its next write past the cut is the forgiven death — the same rule on both platforms rather than a broken-pipe signal on one and an exit-order reading on the other. A producer that never writes again is never cut and runs to completion: sleep 1000 | true waits for the sleep, as in every shell. One that must not be cut at all must not be a stage whose reader can leave — its own statement, or spawn.

On Unix, an interactive process-staged pipeline receives the foreground terminal as one process group only when the session owns a terminal lease and final standard output is attached to that terminal. A captured pipeline normally writes to a buffer, so the parent keeps terminal ownership. Ordinary application and bind do not create a pipeline process group.

A ral-written stage runs on a thread of the shell's own process, so it cannot itself read the controlling terminal while that terminal's foreground belongs to the pipeline's external process group: doing so would raise SIGTTIN against the whole shell. When the pipeline's group holds the terminal, a stage with no upstream pipe receives the terminal as its standard input, so that an external spawned inside the stage reads it as a member of the foreground group. A reading builtin never reads a terminal: it refuses with "no input (pipe bytes or pass a value as argument)", so !{ let l = from-line; echo $l } | cat at an interactive prompt fails at once rather than waiting for a line or reading EOF. Without the loan, when the group does not hold the terminal, the stage reads EOF. An external stage reading the terminal (cat | grep x) is unaffected, since it is a process inside the foreground group.

Windows has no POSIX foreground-terminal handoff. Pipeline members share the console and are supervised as one job.

8. Control flow and failure

ral separates successful values from failure. A computation may successfully return any value, including false, (), an empty collection, or an empty string. Failure is a separate control outcome carrying a cause and provenance, which a program reads as an error record (§8.6). This distinction is fundamental: if examines a Bool, while ? and try examine whether a computation succeeded.

Commands and control forms are checked before execution. Branches must agree on the value they return. A branch that is not selected is not evaluated.

8.1. Sequencing and return

A newline or semicolon sequences computations from left to right:

prepare
let result = calculate
publish $result

Execution stops at the first failure. If every computation succeeds, the sequence returns the value of its final computation; an empty sequence returns (). Bytes written by earlier computations remain observable even when a later computation fails or when the sequence is evaluated under capture, unless that capture itself fails (§7.2).

return value is the primitive successful computation. With no value, return returns ():

return 42
return

return is not a process exit and does not turn a false Boolean into failure. A successful run exits 0, whatever value it returned. There is no status register.

8.2. Conditional choice

The conditional form is:

if condition { then-body }
elsif other-condition { other-body }
else { fallback-body }

Conditions are evaluated in order and must return Bool. The body belonging to the first true condition runs. If none is true, the else body runs. The selected body has a fresh lexical scope, so bindings made inside it do not leak into the surrounding scope.

Each body is a thunk that if forces when it chooses it: a block written out, or a name holding one, so if $c $yes else $no runs the block $yes or $no. Any other atom would run before if chose, so it is a parse error: an arm is a block, or a name holding one. To compute the block first, bind it with let arm = $arms[a].

With else, the bodies must unify to one result type and grade. Commands join commands; value-returning bodies join values of the same type. No arm's output is captured. if $c { hostname } else { return 'none' } is refused: write { return !{hostname} } to return the command's output explicitly. A fresh unit producer, such as return (), can join either grade; a unit producer whose grade a let fixed to p cannot join a command. Without else, the form runs for effects and returns () at a fresh grade.

false chooses another branch; it does not cause ? to continue and does not invoke a try handler.

8.3. Variant elimination with case

case eliminates a variant. Its arms are syntax — one per tag, written out at the case itself:

let result = case $reply [
  `ok:  { |value| return $value },
  `err: { |error| raise $error },
]

The scrutinee must be a variant. case runs the arm whose tag matches it, applying it to the variant's payload; a nullary variant passes (). The arm has a fresh lexical scope for that binding, but it is a branch and not a function applied to the payload: it runs in the surrounding shell context, so the arm's own changes remain in place after the case, as an if body's do.

An arm is a thunk of one argument that case forces when it chooses it: a block with one binder writes the branch out, and a name holds one, so `ok: $handle runs exactly what `ok: { |p| $handle $p } runs. As for if, an arm is a block or a name; any other atom is a parse error.

Arm result types and grades must agree, exactly as for if branches and ? alternatives. Each arm is checked against a fresh result, then the results unify with the join in source order. No arm is captured or reordered; a disagreement blames the later arm. A fresh unit producer can join a command.

Because the alternatives are syntax, exhaustiveness is decided statically and always. The typechecker closes the scrutinee's variant row to exactly the arms' tags, and reports a tag with no arm before anything runs, listing the tags the case does match. What the grammar refuses is anything that hides the set of alternatives from that proof: a computed table in place of the arm list, a ... spread arm, a repeated tag, and an empty arm list are all parse errors (§17.1).

8.4. Fallback chains

The ? operator tries alternatives from left to right:

cached-value ? fetch-value ? fail 'no value available'

The first successful alternative supplies the chain's result. An ordinary failure continues with the next alternative. If every alternative fails, the chain propagates the final failure. Alternatives must return values of one type, and each runs in a fresh lexical scope. Alternatives join as the arms of if do: commands join commands, and returned values must agree. A command alternative is never implicitly captured; return an explicit capture to join it with text.

Control escapes are not alternatives. In particular, exit and internal tail-call control pass through a fallback chain rather than selecting its next arm. Cancellation is checked between arms.

8.5. Raising failure: fail and raise

fail takes one String and raises an ordinary, recoverable failure:

fail 'bad command line'

Its message is that text and its status is 1. In visible user code its failing frame is fail, located at that call. It does not choose an exit code: an unhandled raised failure exits 1. To choose a process code, handle the failure at top level and use exit n.

raise takes the closed error record (§8.6) and raises it as a failure:

try { risky-work } { |e| raise $e }

A record is plain data, whatever its origin: handed over by try, changed ([...$e, status: 2]), built by hand, or read back from data. raise always takes it as the program's own claim, as given, including its frame and site: a claimed [frame: f, message: m, status: 3, site: s] is reported as that claim and exits 3 if unhandled. The failure's original typed cause is not part of the record and is not restored. raise refuses a status of 0 (use return for success) and one above 255. Records decoded from data must also match the closed type; extra fields are not accepted.

The signatures are:

fail  : ∀ε α. String → F^ε α
raise : ∀ε α. ErrorRecord → F^ε α

A raised record is a claim: it has no typed cause, so it carries no intrinsic advice and no exit-hints entry. Its resolved site renders as script:line:col, without a caret. Stored hints, context prefixes and unwind facts are report-only and do not survive a handler. await propagates the live error instead, since no handler has intervened.

An external command that exits unsuccessfully and a runtime operation that cannot complete also produce ordinary failures. They participate in ? and try in the same way as fail.

8.6. Recovery with try

try evaluates a body and, only if that body fails, calls a one-argument handler:

let value = try {
  return !{read-config}
} { |error|
  warn $error[message]
  return default-config
}

On success, try returns the body's value. On recoverable failure, the handler receives this record:

[
  frame: String,
  message: String,
  status: Int,
  site: [script: String, line: Int, col: Int],
]

message is the failure's one human-readable description and status its process exit code, from 1 to 255. Both derive from the failure's typed cause, which the runtime keeps for the wire, logs and hosts and a program never reads. Only fail's text, or a claim a program raised, is authored; every other message is derived from typed subjects and causes, with opaque foreign detail only at foreign boundaries. Panic remains an ending, not a recoverable failure.

status derives from the cause. For fail it is 1, and for a raised claim the claimed status. For an external command:

The command status
exited with nonzero n n clamped into 1..=255
died of signal s, not by a cancellation (§8.10) 128 + s, clamped into 1..=255
does not exist 127
could not be started: not executable, a directory, permission denied, or a file whose #! interpreter or loader does not exist 126

For every other cause:

Cause status
a worker a cancel inside the session stopped, observed by await or poll 143
a worker reached by a timeout on an enclosing scope, observed likewise 124
a refused capability, an I/O or evaluation failure, an invalid input, unavailable state, a source that failed to load, a launch, protocol or host failure, a violated runtime invariant 1

This table is the shell tradition's code vocabulary; it may be revisited.

A command confined by a grant reports these exactly as an unconfined one does: one that cannot start is not-found (127) or not-runnable (126), never an exit status, and its own end is its own, a signal or an exit. A failure of the confinement itself, before the command could start, has status 1 and a message naming the failed step and its cause.

Status codes are not unique failure classes: status 1 also covers operational refusal, even when frame is grep. This handler diagnoses and then raises the failure rather than assuming it means no matches:

try { grep -q ERROR log.txt; echo found } { |e|
  warn "grep failed (status $e[status]): $e[message]"
  raise $e
}

The command name in a process failure's message is its head as dispatched (grep: exited with status 1, foo: command not found); it is not a provenance coordinate.

frame is provenance only: the name of the failing frame, not necessarily a command. An evaluator refusal names its operation (index, for example), and a visible fail names fail. frame and site come from one frame: the innermost operation whose span lies in a session source. The baked prelude is invisible, so last [] names and sites the user's last call. An initial _ is module privacy, not invisibility. Every run has a base: an unclaimed failure is sited at its run's start (script:1:1), or a hook's origin at 1:1. Sites are total, with one-based line and column. A worker completes its error before publication, so done, poll and try around await receive the same record.

The body and handler join as the arms of if do, without capture or coercion. In the example, the body's explicit return !{read-config} returns text, and the handler must return text too.

try covers what runs inside it. A block that leaves it unrun, returned or left by a call that ran out of arguments, runs outside it: in let g = try { add 1 } { |e| add 2 }, a failure inside g 3 is not this try's.

try is control flow, not output capture, and it observes nothing: it reads no audit trail, retains no bytes, and costs no more than its own frame. Bytes written to standard output or standard error continue through the surrounding byte pipes. $error[message] is the failure's description, not captured stderr. Use audit when command bytes and the full trail are required — its `err outcome carries this same record (§13.3).

A handler that succeeds recovers the failure and leaves status 0. exit, internal tail-call control, and a stop (§8.10) bypass the handler: a stop is not a failure, and try never sees one. The one stop a handler can meet is the error await or poll reports for a worker a cancel inside the session stopped or a timeout on an enclosing scope reached, which is the awaiting run's own failure.

8.7. Acquisition and release with guard

guard ACQUIRE BODY RELEASE runs in execution order. The acquisition returns a resource, the body receives it, and the release receives both the resource and how the body ended. The resource is bound as let binds it (§17.5): a command's output is captured as a String, so guard { mktemp -d } { |d| … } receives the path:

guard { temp-file } { |file|
  echo 'staged contents' > $file
  mv $file destination
} { |file end|
  case $end [
    `ok: { |_| () },
    `err: { |_| rm -f $file },
    `exited: { |_| rm -f $file },
    `stopped: { |_| rm -f $file }
  ]
}

The ending is the closed variant `ok | `err Error | `exited Int | `stopped CancelCause. Error is the record of §8.6; CancelCause is the structured cause of §8.10, represented by the Cause variant in §11.4. The nullary `ok carries (), not the body's value. There is no panic arm: a panic runs no release frame. An `err carries the same record as try; raise $e in its arm raises it as a claim (§8.5).

guard polls once before acquiring: a pending stop runs neither acquisition nor release. Acquisition is shielded, and its returned resource is placed in the release frame with no cancellation poll in between. If acquisition halts, no release runs. Otherwise the release runs after the body returns, fails, exits, or stops. Its value is discarded and the body's outcome is re-raised or returned unchanged: reading the ending cannot consume it. A release that itself fails, exits, or stops pre-empts that outcome.

Acquisition and release are shielded against ral's cooperative stops (§8.10) for the host's cleanup grace (five seconds by default). A root abort (Ctrl-\) passes the shield. The grace is counted from the instant the stop lands: acquisition and release, and every release in the same unwinding, share one budget; release gets no fresh grace. A stop during acquisition lets it finish within that grace, then pre-empts the body at its first poll and runs the release. An acquisition that outlasts the grace is stopped and runs no release, so anything it held leaks. One finishing late leaves little time for release: once the grace is spent, even the release's first command is stopped at its poll and the resource may leak.

The shield is cooperative, not an operating-system signal mask. A terminal's SIGINT still reaches an acquisition's or release's external children; a child that dies of it fails as a signalled command does (`signaled 2). If that halts acquisition, no release runs.

The shield follows ownership, not birthplace: it covers pipeline stages, external children, nested machines, and workers owned by a gather opened inside acquisition or release. A worker of an already enclosing gather, worker body, or session is not masked merely because it was spawned there. To delegate acquisition or release to a shielded worker, open its gather inside that operand, not around the guard:

guard {
  gather { let h = spawn { acquire-resource }; await $h }
} { |r| use-resource $r } { |r _| release-resource $r }

Past the remaining grace, even owned work is stopped at its next poll.

To ignore a release's ordinary failure, write guard $acquire $body { |r _| attempt { release-resource $r } }; try inside the release can instead report that failure and carry on. With no resource, write guard { () } { |_| … } { |_ end| … }; there is no two-operand form.

guard takes its value type and grade from the body alone; acquisition and release contribute neither. Output from all three operands goes to the current output, with no implicit capture by guard. Thus let x = guard { () } { |_| echo hi } { |_ _| () } captures hi by the normal binding rule. Bindings created in each block stay local to it.

For temporary paths, prefer the prelude's with-temp-dir and with-temp-file (§14.4), which acquire and remove the path with guard. A worker the body spawns to use the path belongs inside a gather, so it finishes before the body's extent ends and the path is removed.

8.8. Exiting the session

exit (also spelled quit) requests that the host end the current ral session:

exit
exit 7

The default status is 0. An explicit status must lie in 0..=255, one byte; anything else is refused. exit is a control escape, not an ordinary failure: ? and try do not catch it. await, race and poll re-raise a worker's exit: an exit in a worker ends the run that observes it, and no other. An exit in a loose worker that nothing observes changes nothing. A command-line host translates it to the platform's process exit status; an embedding host receives the structured exit request.

8.9. Diagnostics

Parse, type, and runtime errors identify their source and underline the relevant span. Type errors are reported before any part of the checked program runs. Runtime failures retain the innermost available source position while they unwind; code loaded from another file is diagnosed against that file, not against an unrelated caller.

When a failure has actionable context, ral may add hints beneath the primary message; §13.1 says which, and in what order. These diagnostics are presentation: recovery uses the record's status and the failing frame's name and site described above, never by parsing the rendered text.

8.10. Cancellation and signals

Cancellation is cooperative and scoped. The evaluator polls at stable boundaries, including between sequence elements and fallback arms, during collection loops and tail-call steps, and while launching or waiting for pipelines and external commands. A cancelled external process is terminated and reaped before control returns.

A stop is an escape, not a failure: it carries a cause, no error record, and no try catches it; the run it reaches ends stopped, with the cause's status. Two boundaries within a program own stops: a worker's boundary owns cancelled and timed out struck anywhere inside the session — on its own handle, on a worker that started it, or on the call that owns it (§11.1, §11.3) — which await and poll report as the awaiter's failure (§8.6); a pipeline owns the stops naming its own stages, the reader-gone stop of one whose reader left and the teardown it runs for a sibling's escape, and forgives them (§7.6). Every other stop is the host's and reaches the top of the run uninterpreted, as exit does. A stop in force is observed at the next step and, inside a blocked write, read or wait of ral's own, at the next ten-millisecond slice.

Cancellation causes form an escalation order and never downgrade:

Cause Message Status
reader gone its reader ended 141
foreground interrupt interrupted 130
explicit cancellation cancelled 143
deadline timed out 124
session termination terminated 143
root abort aborted 131

A cause a signal raises reports 128 plus that signal, as a POSIX shell does: an interrupt 128 + SIGINT, a root abort 128 + SIGQUIT, session termination 128 + SIGTERM. An explicit cancellation reports 128 + SIGTERM, what kill delivers, and a deadline 124, as timeout(1) does. A pipeline stage cut short because its reader ended is stopped with the reader-gone cause, which its pipeline forgives; no try inside the stage sees it. The shell's own write to its standard output after the reader left is the same stop at the run's own boundary, and ends the run with status 141 and no diagnostic, as a SIGPIPE death would. That stop lives in the lost stream itself: a cleanup after it runs unhurried, and only its own write to that stream ends it.

A stop reports the same cause, message and status whether it lands before a command starts or while the command runs. An external command that dies of the signal ral sends first to tear it down, or of the final kill, is reported as the cause in force, confined or not. An exit is never read as a signal: exit 130 is the command's choice, confined or not.

Only a terminal ral lent can make a command's failure a cancellation. While a command or pipeline holds the terminal, Ctrl-C, Ctrl-\ or a hangup comes back to ral when it takes the terminal back. A command that dies of the key is stopped with that key's cause, and the run it belongs to is stopped: try never sees it. A pipeline hears the key itself, whatever its stages do with it. A command that catches the key and carries on, or exits, has handled it. A signal from anywhere else is the command's own failure (`process [..., failure: `signaled s]), and so is any other death, such as SIGSEGV. Ctrl-\ on a lent terminal aborts the job it was lent to, and the session lives on. A command sharing ral's own process group, such as a capture, is signalled by the terminal and by ral at once, so its death may be read before ral's own interrupt lands and report the signal rather than the interrupt; the run stops regardless.

A foreground interrupt affects the work that was running when the interrupt arrived, including nested runs and the workers of a gather in flight, a par's among them (§11.3), but not a session worker and not a later prompt. Nothing a worker starts sits where the terminal reaches it: on Unix its external commands lead sessions of their own and its pipelines a group the terminal never holds, and on Windows its processes lead console groups ral never sends a console event. A terminal gesture reaches a worker only as the session termination or root abort ral itself raises. Explicit cancellation targets its handle. Deadlines affect their run scope. Session termination and root abort reach the durable session root and therefore its workers as well as foreground work.

On Unix, Ctrl-C is a foreground interrupt. At an idle interactive prompt it cancels the edited line instead. Ctrl-\ requests a root abort; SIGTERM and SIGHUP request session termination. The batch host escalates repeated termination signals and may force an immediate process exit when cooperative cleanup no longer completes. Interactive Ctrl-C itself does not use that force-exit ladder.

Other hosts translate their native gestures into the same structured causes. For example, an active exarch request treats Ctrl-C or Escape as a foreground interrupt, while an idle key may instead close its interface. Windows uses its console and process-group facilities rather than Unix signals, but preserves the observable cancellation messages and statuses: ral opens a teardown with Ctrl-Break and ends it with one fixed exit code, and a process that ends of either while a cause is in force is reported as that cause. A Ctrl-C exit reads as the interrupt only while the interrupt is in force.

9. Scoped execution and handlers

ral uses two kinds of scope for two different purposes:

  • Values are lexically scoped. A function or block sees the bindings that existed where it was written.
  • Execution context is dynamically scoped. The effective directory, environment overlay, handlers, and capability restrictions come from the call site and remain active through everything the body calls.
let place = 'definition'
let show = { echo $place }

within [env: [MODE: 'test']] {
    let place = 'call site'
    show                 # prints "definition"
    echo !{env}[MODE]    # prints "test"
}

let bindings are immutable. A binding in a deeper lexical scope shadows an outer binding without changing it. Closures retain their defining lexical environment, while commands run by those closures use the caller’s dynamic context.

9.1. within

within installs a dynamic execution context for one block:

within [
    dir: 'project',
    env: [MODE: 'test', RETRIES: 3],
    handlers: [:, deploy: { |args| to-json [mock: true, args: $args] }],
    handler: { |name args|
        fail "unexpected command: $name"
    },
] {
    deploy staging
}

The options are written in within's own bracket, and it accepts exactly four names:

  • dir — the effective working directory;
  • env — environment-variable overrides;
  • handlers — a map from command name to handler;
  • handler — one catch-all command handler.

Unknown names are errors, reported before the program runs. [] is the empty option set — the form's bracket is not a collection literal, so [] there is no more the empty list than [dir: 'p'] is a map, and [:] names no options at all.

The option names are syntax: each is written in the bracket, and its value may be computed.

let d = 'project'
within [dir: $d, env: [MODE: 'test']] { build }

A bundle built elsewhere (within $opts { … }), a spread into the bracket, and a repeated name are parse errors, each saying so. Whether an option is present is therefore a fact about the program's text, never about a value: to set dir only sometimes, lift the condition to the form — if $c { within [dir: $d] { … } } else { within [] { … } }.

handlers: is an ordinary map-valued option. Its keys are data, not option names: handlers: $table and handlers: [:, ...$table, ll: { |args| ls -lh ...$args }] are both valid. A record such as [ll: …] is refused; write [:, ll: { |args| … }]. The empty handler map is [:], not [].

A map is no options bundle either, and so a genuine one — off from-json, a plugin's configuration — is refused at the same place: its keys are data, a form's options are names.

All option values are evaluated left to right in written order, like ordinary record fields, and validated before the body begins. handlers: follows the same evaluation rule as every other option. The environment scope is installed outermost, then the directory scope, then the handler frame. This makes the environment visible while commands resolve beneath the directory and handler scopes.

Validation uses the incoming dynamic context. Options in the same bracket do not take effect one by one: for example, dir is resolved before the new env overlay is installed, so a HOME override beside it does not change how that dir value is resolved.

The frame remains active for the body’s whole dynamic extent, including functions defined elsewhere, nested blocks, command handlers, spawned work, and every landing of a tail-recursive call. Leaving normally, failing, or escaping restores the surrounding dynamic context.

9.2. Directory scope

dir is converted to a path string, resolved against the current effective directory, checked for filesystem-read authority, and required to name an existing directory.

within [dir: 'src'] {
    cat 'main.ral'
}

The scoped directory is used by ral path operations, relative executable lookup, redirects, and external children. It does not affect use, which is resolved before the body runs (§10.3). ral does not change the process-wide working directory; each child is launched in the effective logical directory. This avoids races between concurrent workers.

The working directory is one piece of shell state: cd sets it, and cwd and every relative path read it. dir makes within a local handler for that state. within saves the working directory, sets it to dir, runs the body, and restores what it saved when the body returns, fails, or escapes. A cd inside the body therefore moves only the scope's directory:

cd /usr
within [dir: /usr/share] {
    cd man
    echo !{cwd}      # prints "/usr/share/man"
}
echo !{cwd}          # prints "/usr"

Setting the directory on entry is not a cd, so a shell list without `chdir does not refuse it; a cd in the body still needs `chdir. A within without dir leaves the working directory alone, and a cd inside it persists.

An empty path, a missing path, a non-directory, or a path denied by the active filesystem grant is an error before the body runs.

9.3. Environment scope

env is a record or a map from variable names to values: [PATH: …] and [$name: …] both serve. Each value must be a string, integer, float, or Boolean; non-string scalars are converted to strings.

within [env: [PATH: 'tools:/usr/bin', DEBUG: true]] {
    build
}

An inner overlay shadows the same key in an outer overlay. Other keys remain inherited. The effective overlay is used by env, user, home, home and XDG resolution, PATH lookup, capability-path resolution, and external child environments.

PWD and OLDPWD cannot be set through within env. PWD is ral’s logical cwd, so use cd or within dir instead; ral keeps no previous directory, so there is no OLDPWD. Lists, maps, blocks, handles, and other non-scalar environment values are rejected.

The previous environment overlay is restored exactly when the scope ends. A spawned worker receives a snapshot of the overlay in force at birth; later changes in either shell do not cross back.

9.4. Named and catch-all handlers

A named handler reinterprets one command name:

within [handlers: [:,
    git: { |args|
        echo "git called with: $args"
    },
]] {
    git status
}

handlers: has type Map(U([String] → Command)): a map from command names to functions of one parameter, such as { |args| … }. Each receives the command's argument list: a List String holding every argument after the head, rendered as text. Use [:, git: { |args| … }] for one handler and [:] for none. A record ([git: …]) or a list ([]) is a static type error; there is no record-to-map conversion. The map may be computed or bound elsewhere:

let h = [:, git: { |args| echo "git called with: $args" }]
within [handlers: $h] { git status }

The singular handler field has type U(String → [String] → Command): its function takes two parameters, such as { |name args| … }, receiving the command name as a String and its argument list as a List String.

The number of parameters is the arm's type, not its spelling: with let forward = { |tool args| echo $tool ...$args }, { forward 'git' } is an arm, while { echo hi } and { |a b| … } are not. within checks its named handlers and catch-all statically and does not re-vet them at installation. Persistent handlers (rc, manifest) retain an install-time check: a refusal is one failure naming the block's role and every checker diagnostic with its code (the `git` handler does not typecheck: T0057 …).

A written handlers: map in within is checked entry by entry, each arm in its own region, so a diagnostic names the command and points at that handler. Any other value, including a bound map or a map with a spread or computed key, is checked by one equation against Map(U([String] → Command)). Written map labels inform diagnostics in the body; computed maps contribute no such names. Neither changes a head's type.

Every handler is a command. A named arm has type U([String] → Command), independent of its name, Σ, or other handlers; the catch-all has the same command result. Thus curl: { |args| echo '{"ok":1}' } is an arm, and curl: { |args| '{"ok":1}' } is refused, since it returns a String where it should write — write it with echo. The same rule holds for echo and every base frame. An arm returning () at a free grade unifies as a command and captures "" under a let; an arm whose grade is already fixed to p does not stand as a command. Handlers do not change a head's argument gate. An arm installed under a name held by a value binding, including a builtin, is accepted silently but never reached, because bindings resolve first (§9.5). A handler may change what a command writes, but not what kind of thing it is; use an explicit codec when conversion is intended.

detach is a first-class builtin, so handlers cannot intercept it. Its program is resolved as ^program would resolve one, bypassing bindings and the whole handler stack (§11.5). To stub detach, bind its name: let detach = { |desc program args| return [pid: 0, desc: $desc] }.

Handlers are command operations, not first-class names. They are invoked in command position and cannot be fetched with $name.

9.5. Command resolution and handler precedence

A bare command head is resolved in this order:

  1. the lexical value environment, including native commands;
  2. the innermost named handler for that spelling, searching all active run frames;
  3. a base command supplied by ral or the embedding host;
  4. the innermost catch-all handler;
  5. an external executable found through PATH.

Named handlers are searched in a complete innermost-first pass before catch-alls. Therefore any named handler, even in an outer frame, outranks every catch-all. Base commands likewise outrank catch-alls. A named handler can intercept a base command because named run frames are checked first.

A lexical binding still wins over every handler. Installing a handler under an already-bound name is allowed, but a normal bare call will not reach it. The explicit head ^name, like a path head such as ./tool or /usr/bin/tool, skips handlers entirely and executes the external of that name.

Persistent handlers are installed by the host between units from the rc's or manifest's handlers: field. Scoped frames are removed when their within ends. For an interactive helper, bind a function:

let ll = { |args| ls -lh ...$args }
ll ['--all']

The function takes its list by ordinary application; a handler instead receives the command's packed argv. The handler stack is fixed throughout a unit except for scoped within frames and self-masking during dispatch.

9.6. Deep, self-masking handlers

Handlers are deep: a frame remains installed after one interception, so every matching command in the rest of the body reaches it.

They are also self-masking. While a matched handler body runs, ral temporarily removes the entire matched frame. A same-name call in that body therefore reaches the next outer named handler, a base command, a catch-all in another frame, or the external command. It never immediately calls itself.

within [handlers: [:, git: { |args|
    echo 'before'
    git ...$args          # forwards past this frame
    echo 'after'
}]] {
    git status
}

Masking the frame rather than only one entry also means its sibling named handlers and its catch-all are unavailable while that handler body runs. Older and newly nested frames remain visible. ral restores the removed frame in its original order after success, failure, or escape.

There is no first-class resume. Returning from the handler supplies the intercepted command’s result and execution continues exactly once. A handler may instead fail or forward by calling the command again under self-masking.

Redirects apply to handler dispatch just as they do to other command calls. Bytes emitted by the handler or a command it forwards reach the active redirects and byte pipes.

9.7. State flow and containment

The body of within is a block. Its bindings stay local, and when the body ends within restores exactly what it scoped: the working directory under dir, which undoes any cd made inside (§9.2), the env overlay, and its handler frame. An unbracketed shell-state write such as cd persists, as in any block, unless the surrounding within scopes it with dir.

Boundary rules are deliberately specific:

  • A forced block and a function call keep their bindings private; a cd or other unbracketed shell-state write inside either persists to the caller. Inside a surrounding within [dir:], a cd persists only until that within exits.
  • Ordinary application and bind run sequentially in the evaluator, so they follow the ordinary function and block rules and do not create pipeline stages.
  • Each stage of a pipeline runs as a subshell with a snapshot of the active lexical and dynamic context — a ral-written stage on its own thread over a cloned shell, an external command as a process. Stage-local bindings, cwd changes, environment changes, and handlers do not return. If every stage succeeds, the pipeline's value is the final stage's. Otherwise the first stage failure observed in launch order is propagated; a control escape takes priority over an ordinary failure. Returned values and audit data cross only through their defined channels.
  • A spawned worker receives the closure’s lexical capture and a snapshot of the dynamic context, including directory, environment, handlers, arguments, and grants. Its body runs under that capture; explain reads the creator's session as of the birth, while use already carries its checked module (§10.3). Its cwd, bindings, and later dynamic changes remain private, while its result returns through the handle.
  • An external process receives the effective cwd and environment at launch. It cannot mutate ral’s shell state.

These containment rules are the same on every supported host. Host differences affect executable lookup, path syntax, and the implementation of process-staged pipelines and process control, not lexical scope, handler precedence, or dynamic restoration.

10. Programs, modules, and session state

A ral program may come from a file, command-line text, standard input, or an interactive session:

ral build.ral release     # run a file
ral -c 'echo hello'       # run command-line text
ral -s                     # read a program from standard input
ral                        # start the REPL when stdin is a terminal

A script and every module it names with use are read, parsed, and typechecked before the script starts.

10.1. Program arguments and identity

Arguments after a script path or -c program are returned by args as a list of strings:

ral deploy.ral staging eu-west
let [environment, region] = args

args does not include the ral executable, the script path, or the -c source text. It is empty in the REPL and for a program read from standard input.

$SCRIPT identifies the file containing the reference:

echo $SCRIPT

It is lexical: a reference inside a loaded module names that module, not the file that loaded it. ral fixes the value while compiling the file, so a later call from another file cannot change it. On Windows its path is /-separated (§14.4).

Only real script files have this identity. Using $SCRIPT in the REPL, -c, standard-input programs, preloaded sources, or other synthetic source is a compile-time error.

Without an explicit script or -c, ral starts the REPL when standard input is a terminal and reads a batch program otherwise. -i forces the REPL; -s forces a standard-input program and takes precedence over -i. An explicit script path takes precedence over both.

A successful batch program exits with status 0. exit n exits with n. Parse errors, type errors, runtime errors, and failed external commands produce a nonzero status and an explanatory diagnostic. Process exit statuses are reduced to the range 0 through 255.

10.2. Ambient reads

The live shell is read by six nullary builtins:

Name Type Value
env ∀α. Returns α Checked boundary: environment variables as the record or map the script uses; values remain text.
cwd Returns String The logical working directory, absolute, /-separated on Windows (§14.4).
home Returns String HOME, or USERPROFILE where appropriate, from the effective environment, /-separated on Windows; the directory ~ abbreviates.
user Returns String USER, or USERNAME where appropriate, from the effective environment.
nproc Returns Integer Available processor parallelism, never less than 1.
args Returns [String] The current program's argument strings.

Each is a computation: a let of one binds what it returns, and !{…} splices it. Each is also an ordinary native: a lexical binding of the same name shadows it, and ^env runs the program of that name.

The recorded command status is not among them: there is no status register a program can read. try hands over the failure's message, status and provenance where a program decides what to do about it. The process exit code is the failure's status, derived from its cause and not stored beside it.

env combines the host process environment with any active ral overrides. An inner override wins:

within [env: [MODE: 'test', USER: 'builder']] {
    echo !{env}[MODE]
    echo !{user}
}

Environment overrides are dynamically scoped. They affect env, user, home, home and command lookup, and child processes, then disappear when the within body ends. There is no general setenv operation in the language.

PWD and OLDPWD are deliberately absent from env. ral owns its working directory separately so concurrent computations never race over the process-wide current directory. Child commands receive PWD and their actual process working directory from this logical state, and no OLDPWD: ral keeps no previous directory.

cd path changes the session’s logical working directory. It resolves path as every path builtin does, path-prefix sigils included. Relative paths, file operations, command lookup, and child processes all use it. A module path without a containing file uses the cwd at check time, not an earlier cd in the same unit (§10.3). A top-level cd persists into later runs; one made inside within [dir: path] is undone when that within exits (§9.2).

A cd inside a function call or a forced block changes the caller's working directory, as at top level; only the body's bindings stay local.

10.3. Importing a module with use

use is a control operator taking one written path: a constant word or a quoted string without interpolation. The file is read and linked when the importer is checked, before any of its commands run. A computed path is an elaboration error; write the path relative to this file, or headed by ~ or xdg:.

let math = use 'lib/math.ral'
$math[mean] [1, 2, 3]

A module is checked against Σ (the host's natives and the prelude) and runs under Σ. It sees neither session bindings, rc helpers, nor the importer's lets. Shared helpers belong in another module. Bindings do not leak into the caller. Names beginning with _ are private and omitted from the returned record:

# lib/math.ral
let _sum = { |xs| fold add 0 $xs }
let mean = { |xs| return $[!{_sum $xs} / !{length $xs}] }

The module's final expression runs, but use returns its public bindings, not that expression's value. Each export has its checked scheme; use is not a checked boundary (§7.3). Missing exports and incompatible uses of an export are static type errors. The result is a closed record with one field per public binding, so a computed field key has no type to give. let m = use '…' generalises normally: an exported polymorphic function can be used at different types in the importer.

A module cannot export an undecided shape, even as data or nested inside a function or collection. After the module's constraints have been solved, every public definition is checked for remaining weak variables before its scheme is settled. A refusal names the definition and the boundary call that left its shape undecided. Use the decoded value at the intended type inside the module, or export text and decode it where it is used. Private bindings need not have decided shapes.

There is exactly one path to read. A ~ or xdg: head expands as in any written path; an absolute path is used as written. A path still relative is read against the containing file's directory, or the session's cwd at check time when there is no file. A shared library can be named explicitly, for example use 'xdg:config/ral/lib/json.ral'. There is no search list or implicit extension.

Resolution uses the session's environment, cwd, and filesystem grant at check time. A surrounding within or grant, or an earlier cd in the same unit, cannot change which file is read or authorise that read. The module's execution still uses the caller's dynamic environment, handlers, cwd, and grants: a lexical grant governs what its body does when it runs.

10.4. Module freshness, cycles, and errors

ral has no module cache. Each check reads and compiles its modules afresh. Separate REPL submissions therefore see intervening edits; two uses in one script are both linked before the script starts. A unit cannot write a module and then load the new file with use.

Each evaluation of use runs its already checked module again. A use inside a function is linked when that function's unit is checked, not at each call, but the module body runs on every call. Bind the returned record once when repeated evaluation is unwanted.

During checking, nested relative imports use the innermost file's directory. The check carries a load chain and refuses any file already in that chain, reporting the circular dependency. The load depth is limited to 100 files; exceeding it is a compile error, not runtime recursion.

Filesystem read authority is checked before the module is read. A path that is not UTF-8 is refused before reading it. Missing or unreadable files, denied reads, parse or type errors, undecided exports, cycles, and depth overflow are compile errors of the importer. They cannot be caught by try: no phrase of that unit runs. A module's compile errors are reported against its own text, with the importer's use marking the load that caused them. A denied read names only the path, since the module was never read. A check-time filesystem refusal remains in the dispatch's audit trail, stamped at that use, even when compilation fails (§13.4).

A failure raised while the checked module body executes is still a runtime failure and can be caught by try around the use.

10.5. Persistent sessions

A batch invocation owns one fresh shell and ends with the process. A REPL or embedding host may submit many top-level runs to one session.

Successful top-level changes persist between those runs, including:

  • let bindings and their inferred types;
  • loaded definitions;
  • the logical working directory.

Changes completed before a later command fails also persist:

let ready = true
failing-command

A later REPL run can still read $ready; statements after the failure never ran.

A nested block's bindings stay local, but its shell-state writes, such as cd, persist into the session like any other (§2.6). Use within for a temporary directory, environment, or handler change.

Interactive sessions load their rc file unless --norc (or its --noprofile alias) is given. Login sessions additionally load the system and user login profiles. Each login profile must return Unit. The rc ends in its options written out (§15.3), checked before it runs. Their evaluation is not transactional, so bindings and effects completed before a runtime failure or exit remain part of the session. Applied RC bindings, handlers, environment configuration, hooks, and startup behavior likewise belong to that session.

11. Concurrency and process lifetime

ral distinguishes concurrent work by who owns it. Every concurrent block has exactly one owner, fixed at birth:

  • a gather: a gather { … } form (§11.3), or a worker's body, which is a gather of its own. A spawn or watch inside a gather is the gather's: its worker hangs under the scope that was current when the gather was entered, and the gather ends it at its own exit;
  • the session: a spawn or watch with no gather around it, in a run, creates a worker that ends by completing, by cancel, or with the session;
  • nobody: detach gives an operating-system process away, so the session no longer owns or controls it.

There is no fourth owner. An ordinary command is not concurrent: it belongs to the current run.

This distinction is visible in the result type. A spawned or watched worker, whichever its owner, returns a Handle. Surrendered work returns only a receipt.

11.1. Spawning work

spawn [TITLE] BODY starts a block concurrently and returns its handle at once:

let build = spawn 'build' {
    cargo build
    return 'built'
}

echo 'the build is running'
let result = await $build
echo $result

await writes what cargo build printed, then binds 'built' (§11.2).

spawn is a control form, not a function (§3.6). BODY is a block; TITLE, written before it, is a String naming the work to people: it is the name the worker is born under, reported in the audit trail (§13.3), in the host's notices, and in the worker registry (§11.4). It must be non-empty and on one line. The title may be left out, spawn { cargo build }, and the worker is then named by its source location, block at <script>, line N. Whether a title is required is the host's policy, checked when the form runs, before any worker is born: the ral hosts accept an untitled spawn, and the exarch agent host refuses one, naming the fix. A spawn with no operand or with three is a parse error.

A pipeline is spawned by naming it in the block:

let filtered = spawn 'errors' { cat large.log | grep error }

ral has no backgrounding operator. A trailing & is a parse error naming spawn, because the two are not the same operation: a POSIX & makes a process-group job that fg, bg, and disown address, while spawn makes a worker addressed by its Handle. Borrowing the spelling would promise the former and deliver the latter.

The worker receives the lexical environment captured by its block. Values are immutable, so concurrent workers do not share mutable lexical bindings. Each worker has its own shell state: cd and environment overrides in the worker do not mutate the spawning thread's shell state.

A nested spawn or watch is owned by the enclosing gather: a gather form (§11.3), or else the worker it was started inside, whose body is a gather of its own. Cancelling a worker cancels its tree, and a worker finishes only after its children have, by the exit rules of §11.3: when the worker's block returns, every child still unclaimed is awaited in birth order, the first failure being the worker's; when the block fails, exits, or is stopped, every child is cancelled and drained within the host's cleanup grace (§8.7). A spawn inside a pipeline stage belongs to the gather the stage runs in. A spawn in a run, outside any gather, is owned by the session.

A gather's child is not announced: no birth notice and no completion notice of its own reach the host, since its result and its completion reach the session through its owner. It is registered (§11.4), so the host's worker cap bounds it and workers lists it, and its bytes are buffered and written when it is claimed, as any worker's are. A session worker's birth reaches the host as a worker observation (§13.3). Its ending is announced at most once, by a host that announces at all, and only while its result is still unclaimed when the host reads it: at the REPL's next prompt or at exarch's batch admission. A result already claimed by await, race or cancel is not announced; a later claim does not retract an earlier announcement. Batch, -c and stdin scripts announce nothing.

A session worker is not part of the foreground run. Interrupting or timing out the run that created it does not cancel the worker. A gather's child is part of it: its worker hangs under the gather's entry scope, so an interrupt or a timeout on the run reaches it (§11.3). A worker's standard input is empty rather than inherited from the terminal, so a worker cannot steal interactive input.

Lifetime and failure are independent:

Work Does its failure count? Lifetime
A gather's child, including a worker's child yes (§11.3) its owner joins it
A loose session spawn or watch only when explicitly observed a returning batch script waits; a halt takes it down
An external started with detach no outlives the session

A loose worker's ending never fails the run or the session; only await, race or poll observes it. A script that returns waits for its still-unclaimed loose workers in birth order, claims each and writes its stdout then stderr, and drops every ending, keeping the script's own value and status. A script that halts — exit, an uncaught failure, a stop or a panic — takes them down at session end instead; Ctrl-C during the wait halts it too. In batch, a failing unclaimed worker leaves no failure notice or diagnostic and does not change the exit status; any bytes it wrote are still replayed on return.

A forgotten spawn { serve } can therefore keep a returning script alive. A worker no longer needed is cancelled; an exit takes every loose worker down; an external command meant to outlive the session is started with detach (§11, Unix). There is no outlive form for a ral block.

Pipelines inside a worker still use byte pipes between stages. Value-style composition remains ordinary application and bind. Concurrency changes lifetime, not the typing of a pipeline.

Buffered output

Each ordinary worker has independent stdout and stderr byte buffers. Its bytes do not appear on the spawning run's output while it executes. await writes the bytes to the awaiter's streams (§11.2); poll returns them as data, as Bytes: those written so far while the worker is `running, all of them once it is `ready. When a worker is `stopping or `consumed, its result has been claimed and no buffered output is retained or exposed.

Each buffer is capped at 16 MiB. Past the cap ral keeps the exact prefix, continues draining the writer, and counts and discards later bytes; no marker is written into the stream. Draining continues so a chatty child cannot deadlock on a full kernel pipe, while memory remains bounded. poll returns the kept prefix. A replay (await, or a loose worker's at the end) writes it, then one note per cut stream to stderr, naming the worker, the bytes written and the bytes kept. Redirect high-volume output inside the spawned block when the full stream matters:

let server = spawn 'docs server' {
    python -m http.server > server.log 2> server.err
}

Explicit redirects bypass the corresponding handle buffer. A watched worker also has empty completion buffers because its bytes were streamed live, so await of it writes nothing.

11.2. Handles and eliminators

A live handle is a shell-local capability for one worker. Typed handles are the only capabilities for retrieving a result, observing a handle directly, or cancelling an individual worker: await, race, and cancel are the core eliminators, and poll, is-done, and first-settled are the observations.

When a host bequeaths shell state to a child, every inherited handle becomes withheld, including inside collections, block captures and handler arms. Its binding, data position, type Handle and title remain. All six operations above refuse a withheld handle with withheld-handle, naming its title and advising the caller to await it where it was spawned and pass its result instead. This rule holds for both in-process and serialized bequests; no live capability crosses.

Every worker moves monotonically through a four-state public lifecycle that separates execution liveness from result availability and claim state:

State Execution Result ownership Counts against admission Listed by workers
`running Not ended Unclaimed Yes Yes
`stopping Not ended Claimed through cancellation Yes Yes
`ready Ended Unclaimed No Yes, until claimed or reaped
`consumed Ended Claimed No No; observable through an existing handle

Here execution ended means the worker's computation, its child gather exit (§11.3), and its final stream flushes have completed. `stopping means the worker itself was claimed by cancellation (running -> stopping -> consumed), not merely that an enclosing scope was cancelled: a worker reached by its parent's cancellation, but not itself claimed, remains `running until it publishes its cancellation error as `ready.

A worker's result is claimed at most once: by await, by race, by cancel, or by the gather that owns the worker as it exits (§11.3). Claiming is atomic, so of two callers trying at once on copies of a handle, at most one claims the `ready result. poll, is-done, and first-settled observe without claiming: they return data, never write, and never claim. Whether a handle has been claimed is checked at run time; its type does not record it.

await

await handle behaves as if the handle's block had run at the await. It:

  1. waits while the worker is `running, then atomically claims its `ready result (moving the handle to `consumed);
  2. writes the bytes the worker wrote to its stdout to the awaiter's current stdout, then the bytes it wrote to its stderr to the awaiter's current stderr;
  3. ends as the block ended: it returns the block's value, raises its failure as it stands (cause, provenance and report decoration included), re-raises its exit or its stop, and resumes its panic.

The sinks are the awaiter's at the await: inside a capture, let out = await $h captures the bytes; under 2> f, the worker's stderr goes to f; inside another worker, they land in that worker's own buffers. A failure is the awaiting run's, so try recovers it:

try { await $build } { |error|
    echo "build failed: $error[message]"
}

A handle carries its block's type, grade included (§17.3): spawn of a block of type F_ε A returns a Handle_ε A, printed Handle (Returns A), Handle Command, or, with a visible grade variable, Handle (Command[ν] A); and await : Handle_ε A -> F_ε A. So await of spawn { echo hi } is a command, and let x = await $h binds "hi" as let x = !{ echo hi } would; await of spawn { echo pre; return 5 } writes pre and returns 5, as the block would inline. Replaying bytes changes nothing about the grade, which says how a result is produced, not whether anything is written.

The equation holds for the value or failure and for the bytes on the two standard streams; the block's effects happened earlier, concurrently, in the worker's own shell. It does not hold for:

  • shell state: cd and environment overrides inside the block do not reach the awaiter (§11.1);
  • the interleaving of the two streams: all of the worker's stdout is written, then all of its stderr, so a block that alternates echo and warn replays as its stdout followed by its stderr;
  • a block that spawns: run inline in a run, its inner spawn would be a session worker, while as a worker it awaits that child before it settles (§11.3), so the awaiter sees the child's output and failure too;
  • a cancelled or timed-out worker, which ends with cancelled or timed out (below), an ending the block run inline could not have;
  • exit: an exit in the block ends the run that awaits it, which may be a later run than the one that spawned it.

A result is claimed once. await of a handle in `stopping or `consumed — claimed by an earlier await, by race, by cancel, or by an enclosing gather — writes nothing and fails with await: this worker's result was already claimed, an ordinary failure that try recovers; the block is not run again. await polls for caller cancellation at the start of each availability sweep before inspecting the handle, so a foreground cancellation already pending at the sweep boundary unwinds the wait without claiming an already-`ready result. An interrupted await interrupts the wait, not the worker, and claims nothing; the handle may be awaited later.

poll and is-done

poll handle (forall ε ν A. Handle_ε A -> F_ν …) never waits, never writes, and never claims. It samples the handle's lifecycle, elapsed time, and available result under one lock and returns one of four variants:

`running  [stdout: Bytes, stderr: Bytes, elapsed: Float]

`stopping [elapsed: Float]

`ready    [
    stdout: Bytes,
    stderr: Bytes,
    elapsed: Float,
    outcome: <`ok A | `err ErrorRecord>,
]

`consumed [elapsed: Float]

ErrorRecord is exactly [frame, message, status, site] (§8.6). The worker completes its provenance before publication, so this record agrees with done and try around await, regardless of the observer's source context.

elapsed is in seconds on a monotonic clock: how long the worker has run so far while `running or `stopping, or, once execution has ended (`ready or `consumed), how long it ran, frozen at its single completion stamp.

The `running bytes are a cumulative, non-destructive snapshot sampled from the worker's stream buffers. Polling does not consume them, so a later poll or await still sees the complete buffered output. Repeated `running polls may therefore return progressively longer byte sequences.

poll claims nothing on any arm, and never errors merely because a result was claimed: a handle claimed by cancel, await, race, or a gather returns `stopping [elapsed: …] while still executing and `consumed [elapsed: …] once execution has ended, with no output or outcome fields. A `ready poll leaves the handle unclaimed and its entry in the registry (§11.4), so a script may poll until the worker is `ready and then await it, its bytes written once.

poll is total over ordinary worker failures and claimed states. The `ready arm reports an ordinary worker failure, including a block stopped by its scope through a parent cancel or a timeout, as outcome:err ...; it does not raise that failure, and leaves status zero. Special non-value endings in ``ready preserve the `await` rule: a worker's `exit`, a foreign stop, or a worker panic is re-raised when polled in `ready ``.

is-done handle (forall ε ν A. Handle_ε A -> F_ν Bool) is a core builtin that tests only whether the worker's execution has ended: it returns false for `running and `stopping and true for `ready and `consumed. Unlike poll, is-done never copies stream buffers, never constructs an outcome record, and never re-raises a completed exit, foreign stop, or panic.

first-settled

first-settled handles waits until it observes a `ready handle and returns its 0-based index in the list, an Int. It is the availability observation of several handles: it writes nothing and claims nothing, so the handle it names remains `ready for a subsequent await or poll (though an observation does not reserve the claim against concurrent callers).

let mirrors = [$a, $b]
let k = first-settled $mirrors
let first = await $mirrors[$k]

Each availability sweep polls for caller cancellation first, then scans the list in order:

  • the first `ready handle wins (list order breaks ties);
  • `stopping and `consumed handles are skipped;
  • if no handle is `ready and at least one is `running, first-settled waits and sweeps again;
  • if every handle is `stopping or `consumed so none can ever provide a result, first-settled fails with first-settled: this worker's result was already claimed.

An empty list is an error.

race

race handles uses the same cancel-aware availability sweep as first-settled to claim the first `ready handle: it skips `stopping and `consumed handles, waits while at least one handle is `running, and fails with race: this worker's result was already claimed if no handle can provide a result. Once it atomically claims a `ready winner, it claims and cancels every remaining unclaimed handle and drains all non-terminal losers — including arguments that were already `stopping — within a single host cleanup-grace deadline (§11.3), then writes the winner's bytes and ends as the winner's block ended. Losers' bytes are never written.

let a = spawn 'mirror a' { fetch 'https://a.example/data' }
let b = spawn 'mirror b' { fetch 'https://b.example/data' }
let first = race [$a, $b]

If several handles are `ready when inspected, list order breaks the tie; a pending caller cancellation at the start of the sweep unwinds before any `ready handle is claimed. A worker stopped by an enclosing scope (without being directly claimed by cancel) publishes `ready with the cancelled or timed out ending and can win the race. An empty list is an error.

cancel

cancel handle claims the worker's result and ensures the worker stops:

  • on `running, it atomically signals cancellation and transitions the handle to `stopping under the state lock; when the worker's execution later ends, its output buffers and ending are drained and discarded as it transitions to `consumed;
  • on `ready, it transitions the handle to `consumed at once and discards the buffered output and outcome outside the lock;
  • on `stopping or `consumed, it is a no-op.

Cancellation is cooperative for ral computation and is propagated to external child process groups by the process runtime. A `stopping worker remains live — listed by workers and counted against the host's admission cap — until its execution actually ends (§11.4).

Cancellation returns (). Since cancel claims the handle, a later await or race of it fails as already claimed, while poll observes `stopping or `consumed and is-done returns false then true.

A worker stopped by anything but its own cancel ends as its own `ready failure: cancelling a worker cancels every worker it started (§11.1), each of which ends with cancelled, status 143, and a worker reached by a timeout on an enclosing scope ends with timed out, status 124. An await that claims such a worker raises that ending as the awaiting run's own failure, which try can recover (§8.6), and poll reports it as that error record in `ready. A cancelled worker's halt claims the workers it started (§11.3), so an await of one of them from outside meets that ending only if it claimed the worker first; otherwise it fails as already claimed.

11.3. Structured fan-out: gather, par, race

Fan-out that must leave nothing behind is a gather, not a set of loose spawns. gather BODY runs BODY as a block that owns the workers spawned inside it: nothing it started outlives it.

gather {
    let b = spawn 'build' { cargo build }
    let l = spawn 'lint'  { cargo clippy }
    return [build: !{await $b}, lint: !{await $l}]
}

gather is a control form (§3.6). BODY is a block, and the form has the body's type, grade included (§17.7): joining the workers is a run-time effect that changes no type. Inside the body, every spawn and watch is the gather's (§11.1), and its worker hangs under the scope that was current when the gather was entered, so an interrupt or a timeout on the run reaches it. A within inside the body does not move it. A worker's body is a gather of its own, and the rules below are the rules a worker applies to its children.

Each gather has a unique scope owner that survives frame pops and unwinding:

  • Close. As soon as the body finishes (whether normally, by failure or escape, or by panic), enrolment in the gather is closed monotonically. Any late spawn or watch that attempts to enrol in the closed gather (for example from a concurrent pipeline stage) is rejected and cancelled before enrolment returns, failing with spawn: the enclosing gather has ended; the new worker was cancelled (or watch: …).
  • Return. When the body returns, each accepted child still `running or `ready is claimed and awaited in birth order, as await would (§11.2): its output joins the gather's own, and the first failure, escape, or panic among them is the gather's, the rest being claimed, cancelled, and drained. If a child join resumes a panic after the gather frame has popped, the scope owner's drop still closes and stops every remaining child. A child already `stopping or `consumed is skipped for result retrieval. A normal return joins its unclaimed children; it never cancels them.
  • Halt. When the body fails, exits, or is stopped, every child not yet claimed is claimed and cancelled, and the gather drains all accepted children before it propagates the halt.
  • Drain. On every non-unwinding exit (both Return and Halt), the gather waits under a single cleanup-grace deadline for every accepted child to reach a terminal state (`ready or `consumed), including children that were already `stopping because of an earlier cancel inside or outside the body.

Draining is bounded by the host's cleanup grace (§8.7): a gather waits at most one grace interval across its child set for non-terminal children to finish. Cancellation is cooperative (§8.10), so a non-cooperative worker that ignores cancellation past the grace remains in `stopping after the gather returns: it stays listed in workers and continues to occupy a seat under the host's admission cap until its execution actually ends (§11.4).

A handle may leave its gather as a value, but the gather claims its worker at exit, so a later await of it fails as already claimed while poll and is-done still observe its lifecycle (§11.2). A spawn or watch meant to outlive the expression goes outside any gather, where the session owns it (§11.1). A gather is synchronous: it ends before the run that entered it does.

Three standard-prelude functions are written over gather:

let converted = par { |path| convert-one $path } $paths 4
let checks = both { return !{cargo build -q} } { return !{cargo clippy -q} }
let data = first-of [{ fetch 'https://a.example/data' }, { fetch 'https://b.example/data' }]
  • par function items jobs is the standard parallel map. At most jobs workers run at once; a non-positive limit permits one worker per item. A new item starts as soon as any running worker settles. The first failure observed is raised at once, and the other workers are cancelled and drained. The items are awaited in input order, so each item's output is written in input order and the result is the list of their values in input order, whatever order the workers finished in. A command callback's value is (): par { |u| curl $u } $urls 4 replays output and returns unit elements; use { |u| return !{curl $u} } to collect text instead.
  • both first second runs two value-returning blocks at once and returns the record of their values, [fst: …, snd: …], the fixed-arity form of fan-out into a record. It awaits fst, then snd, so it does not fail fast: a failure in either is the call's, and the other is cancelled and drained at the gather's exit.
  • first-of blocks is race over a fresh spawn of each block, inside a gather: it ends as the first to settle, with its output and value, or its failure, and the others are cancelled and drained before it returns. An empty list is an error.

Each worker these start is titled: par #i for item i of a par, both.fst and both.snd, and first-of for each of its blocks.

race handles (§11.2) is the form for handles already held, which no gather of the caller's owns: it claims the winner and cancels and drains every loser (including any argument already `stopping) however the winner ended. first-of is the form for fresh blocks.

11.4. Registry and shutdown

Every worker birth — by spawn or watch — is registered at once in the owning shell. A registry entry holds the worker's id, its title, its owner (the session, the worker whose body it was born in, or a gather), its birth stamps (one on a monotonic clock and one on the wall clock), and the handle (whose state carries the single completion stamp once execution ends). Nested workers share the owning shell's registry.

The id is a read-only identifier for observation in workers, audit trails, and host notices; the title is for people. A worker id is not a capability and cannot reconstruct a Handle: there is no lookup builtin from an id back to a handle, and nothing looks a worker up by title. Callers must retain the typed Handle returned by spawn or watch in a binding or data structure if they need to await, poll, is-done, race, or cancel that worker.

workers lists the non-consumed entries in the registry as data: one record per `running, `stopping, or unclaimed `ready worker, in ascending id order:

[
    id: Int,
    title: String,
    owner: <`session | `worker Int | `gather>,
    state: <`running | `stopping | `ready Ending>,
    started: Int,
    elapsed: Float,
    settled: <`some Int | `none>,
]

where

Ending = `ok | `err ErrorRecord | `exited Int | `stopped Cause | `panic String
Cause = `reader-gone | `interrupted | `cancelled | `timed-out
      | `terminated | `aborted

poll's and audit's outcome is this ending's `ok/`err half; await, race and poll re-raise the rest (resuming an unwind for panic).

Field Meaning
id the worker's numeric identifier in the registry
title the spawn's title or block at name, or a watch's label (a par titles the worker for item i par #i, §11.3)
owner `session for a worker born in a run outside any gather, `worker n for one born in the body of worker n, `gather for one a gather form owns
state `running while executing unclaimed, `stopping while executing after cancel claimed it, or `ready with how the block ended: it returned, failed with an error record (§8.6), ran exit with a status, was stopped with a cause (§8.10), or panicked
started when the worker was born, in Unix seconds
elapsed seconds on a monotonic clock: how long it has run so far (`running or `stopping), or how long it ran (`ready)
settled `some the Unix second its execution ended when `ready, `none while `running or `stopping

Each row's state, elapsed, settled, and retention eligibility are derived from a single lifecycle snapshot so a concurrent transition cannot produce contradictory fields. A listing claims no result and holds no handle, so a workers result crosses every boundary a value does (§11.7).

An entry stays in the registry while `running, `stopping, or unclaimed `ready, and leaves when:

  • it reaches `consumed — either when an unclaimed `ready result is claimed by await, race, cancel, or its owning gather, or when a `stopping worker finishes execution (consumed entries are pruned eagerly on directory scans and lazily on amortized admission sweeps, without reap notices); or
  • a host retention policy expires an unclaimed `ready entry.

poll and is-done leave the entry in place.

A worker lives as long as its owner: nothing but cancel, its own completion, its owner's end — a gather's exit, a parent worker's included — or the session's end stops it. Retention applies only to unclaimed `ready entries whose parent owner is no longer live (neither `running nor `stopping); no policy reaps a `running or `stopping worker.

Hosts may cap live workers. Admission reserves a seat before the thread is created, so concurrent births cannot overshoot the cap. The admission count is running + stopping + reserved births: a cancel request transitions a live worker to `stopping and does not free its seat until execution actually ends, while `ready and `consumed workers occupy no seat. A refused birth reports that workers are still executing or stopping, suggests waiting for one to end or cancelling work no longer needed, and points at workers to list them.

These bounds are host policy, not core constants. The ral interactive and batch hosts arm no retention bound or worker cap. The exarch agent host currently caps live workers (running + stopping) at 64 and retains unclaimed `ready entries for 256 ral calls.

A returning batch script first waits for its still-unclaimed loose workers and replays their bytes, discarding their endings (§11.1). A halting script, REPL quit and exarch session end do not wait for normal completion: every remaining session worker is cancelled when its session is destroyed. Teardown claims and stops remaining workers and waits briefly and boundedly for live worker threads (both `running and `stopping) to finish execution and tear down their children. The interactive shell first warns once with the ids and titles of workers still live (`running or `stopping). Batch says nothing. Workers do not survive process exit; use detach for an external command when survival is the requirement.

11.5. Host-installed worker forms

The core language provides the spawn and gather forms and the builtins await, poll, is-done, first-settled, race, cancel, and workers; the standard prelude adds par, both, and first-of over them. watch and detach are optional host builtins, both first-class values. If a host does not install one, its name is absent from that shell's base scope and is checked and resolved like any other unknown command.

Live output with watch

watch label block creates an ordinary worker, owned as a spawn in its place would be (§11.1), whose output is streamed instead of buffered:

let build = watch 'build' { cargo build }
await $build

Each stdout line is prefixed [build] and each stderr line [build:err]. Sibling watchers serialize complete framed lines, though their lines may interleave. A partial final line is flushed when the worker finishes execution.

The returned value is an ordinary handle, so await, poll, is-done, race, and cancel apply. Its stdout and stderr buffers remain empty because those bytes have already been sent to the durable output sink. Programs run through the ral executable, in interactive and batch modes, install watch. A host whose output capture ends with each run, including exarch, omits it because a worker cannot safely retain that run's sink.

Work that survives with detach

detach description program args starts an operating-system process that the session deliberately stops owning. It is an ordinary first-class builtin with type String → String → [String] → F [pid: Int, desc: String]: a task description, a program name, and one list of its arguments.

let receipt = detach 'local documentation server' python3 ['-m', 'http.server', '8000']
echo $receipt[pid]

The program is resolved as ^program would resolve one: bindings and the whole handler stack, including base frames such as echo, are bypassed, since they run inside the session. ^detach likewise names an external program, not this builtin.

Handlers cannot intercept detach itself. To stub it, bind its name:

let detach = { |desc program args| return [pid: 0, desc: $desc] }

Like other functions, it supports higher-order use ($detach) and partial application (let bg = detach 'docs'). Its last argument is a list, not an argv at the call site: write detach 'nap' sleep [...$xs], not detach 'nap' sleep ...$xs. Every list element must be a String; it is not rendered from another type.

The description must be a non-empty, single-line String, and the program name must be non-empty; an empty program is refused before lookup. The result is:

[pid: Int, desc: String]

This record is a receipt, not a handle. await, poll, is-done, race, and cancel do not apply. The pid is the process's number at birth, not an enduring capability; operating systems may later recycle it.

The surviving process has standard input, standard output, and standard error connected to the null device. It has no buffered result and its exit status is unrecoverable. A successful return says that the program was launched; it does not prove that it remained alive or initialized successfully. A detached program must arrange its own logs, and callers must probe the resource it is supposed to provide.

On Unix the implementation double-forks, reparents the grandchild, and creates a new session. It preserves the logical working directory, environment, and the sandbox projection active at birth. Later grants cannot widen it. Inside a synod guest every survivor joins one shared ral-exec/detached cgroup: together they have one command's allowance (6 GiB memory, 1024 tasks, 400% CPU). Each runs under the guest's one command uid/gid and outlives the engine that birthed it; machine halt kills them all. An active grant may refuse the operation by omitting `detach from shell before any process is born.

detach is Unix-only and present where the host installs it, with no call budget. Neither interactive nor batch ral installs detach; Windows has no such command.

11.6. Stop signals

ral does not suspend. There is no job table, no fg/bg/jobs/disown, and no Ctrl-Z gate: a stopped child — by SIGTSTP, SIGTTIN, SIGTTOU, or an external kill -STOP — is resumed at once by whoever waits on it, the same rule for every role and every platform that has stops. Ctrl-Z in an interactive command such as vim therefore does nothing visible: the program stops and is resumed before the terminal can register the gap. Work meant to run in the background is spawn, whose handle already carries await for foreground waiting and cancel for termination; Ctrl-C ends what Ctrl-Z used to park.

11.7. Availability summary

Facility Core / portable ral interactive ral batch exarch agent host
spawn, gather (forms) yes yes yes yes
await, poll, is-done, first-settled, race, cancel, workers yes yes yes yes
par, both, first-of from the standard prelude when that prelude is installed yes yes yes
watch optional yes yes no
detach optional, Unix only no no Unix sessions that enable it

Handles may be stored, passed to functions, and returned through locally evaluated blocks. Child-shell bequests retain them only as withheld handles (§11.2), not opaque data placeholders. First-order host results do not carry handles at all: returning one fails rather than transferring its capability. Await it where it was spawned and pass its result instead.

12. Capabilities and sandboxing

grant temporarily reduces the authority available to its body and to work started by that body.

grant [
    exec: [
        allow: [`name git, `name rg, `dir `system],
        deny:  [`name sh],
    ],
    fs: [
        read:  [`cwd ., `absolute /usr/share],
        write: [`cwd build],
        deny:  [`cwd .git],
    ],
    net:   `offline,
    shell: [`chdir],
] {
    git status
}

The values are ordinary records, lists and variants; the checker types them like any other value (§12.1). Each dimension is independent. Omitting net, for example, says nothing about network access; it inherits the surrounding authority. A written dimension restricts. An empty grant changes nothing:

grant [] {
    # ambient authority
}

A grant can never restore authority withheld by an outer grant or a session profile. Nested grants intersect:

grant [exec: [allow: [`name git, `name rg]]] {
    grant [exec: [allow: [`name git]]] {
        git status   # allowed
        rg foo       # denied
    }
}

A denial at any layer remains a denial: an exclusion (a deny entry) beats every allowance, in exec and in fs, however specific the allowance and in whichever layer it sits. Neither a narrower directory nor an exact file reopens an excluded region, and nor do a carrier (an interpreter a script's #! names), the dynamic linker or ral's own binary. A refusal that cites an exclusion says that an allowance cannot override it.

Authority is a ceiling, extended once and then only restricted. A host that composes profiles (exarch's --extend) may extend a base once; within ral there is no extension. In an extension an allowance never removes authority and only an exclusion does, on every axis, including one the base leaves unrestricted.

An exclusion names programs by path and name: it is a guardrail, not a wall. A copy of a program, a program newly written to a folder that is both writable and runnable, or a script fed to an admitted interpreter is a different request that no exclusion sees.

Every list in a grant denotes a set. An entry written twice, in one list or through spreads of two computed lists, adds nothing; no rule refuses a repeat. A target that is both allowed and denied is denied, and a place may be both read and written. An allowance names what it named when it was granted: it keeps the real path it was frozen to, while an exclusion names the object it reached then (§12.2).

12.1. Capability fields

A capability record accepts exactly these names:

  • exec
  • fs
  • net
  • gpu
  • editor
  • shell

Unknown names are errors, reported before the program runs. exec and fs are nested tables with the fields below; net takes `offline and gpu takes `withheld; editor and shell take lists of verbs.

grant's bracket is the form's own, as within's is: [] is the empty grant, each field is written out with a value that may be computed, and a bundle or a map in its place is a parse error. Nested tables follow §15.3, at forms and in files alike. Write an empty list under a table's key to allow nothing: exec: [allow: []], fs: [read: []].

The tags are types, not strings. A bare string where a place or an exec target belongs, a misspelled tag, a tag with the wrong payload, and net: true are refused statically, before the program runs, with the tags on offer and the nearest one named. Unresolved field values retain runtime shape checks; grants received as data also retain runtime keyset checks.

Omitting a whole field inherits that dimension. Within fs, an omitted read or write adds no allowances of its own (reads still follow from write and from what the grant runs, §12.4); a present exec table admits only what its allow list names (§12.3).

Thus:

grant [fs: [read: [`cwd .]]] { … }

allows reads beneath the frozen working directory, denies all writes, and leaves every non-filesystem dimension unchanged.

Similarly:

grant [editor: [`read]] { … }

allows editor reads, denies editor writes and TUI access, and leaves non-editor dimensions unchanged.

12.2. Places and selectors

A place names one path. It is resolved when the grant is frozen, against the anchor its tag names:

Place Denotes
`absolute P the absolute path P
`cwd S S against the working directory at decode time
`home S S against the effective home
`tempdir S S against the platform temporary directory at decode time
`scratch S S against the session's scratch directory, the one its host made for it and carries as a spelling; refused, as an error naming the place, where the host made none
`gitdir S S against the current repository's real Git directory, or the working directory outside a repository
`xdg-config S, `xdg-data S, `xdg-cache S, `xdg-state S, `xdg-bin S S against that XDG base

A selector names a set of directories that the environment chooses, not a path the author wrote. It is valid only as the payload of dir in an exec list (§12.3):

Selector Denotes
`path every absolute directory in the host process's $PATH at decode time; an error if there are none, if an entry is a filesystem root, the home or an ancestor of the home, or if an entry is one `absolute would refuse under the host's rules (a malformed or mixed two-separator head) or is not valid Unicode
`system ral's platform-defined system tool directories, without Homebrew
a package manager, such as `rustup or `homebrew the directories that manager runs programs from, where they exist; nothing if the manager is absent (§12.3)

Selectors never appear in fs lists: their expansion is held under no anchor, and a $PATH entry can be $HOME or /, so a write grant on one would let a child plant programs where the user's own shell looks.

The payload P is absolute under the host's rules; the one spelling read under neither host's rules is /, the filesystem root, which names everywhere on every host as an allowance and is refused as an exclusion. The payload S is a relative subpath of components separated by / (and \ on Windows): . is the anchor itself, and .. folds at decode and may leave the anchor, as in `cwd ../sibling (the XDG escape guard still judges the result). The empty string, a leading / or \, and a drive prefix X: are refused in S on every platform, so a profile fails alike everywhere.

A payload headed by ~ or xdg:NAME is refused under every tag: those prefixes are expanded when a path is used, not when a grant is read, so `absolute ~/x would name a relative path. The error names the place meant, `home x or `xdg-config x.

At run time, a path headed xdg:NAME followed by a separator (/, and \ on Windows) and a subpath expands to that XDG base with the subpath joined beneath it. The subpath is everything after that one separator. A root of the current volume is dropped, so xdg:config//etc names etc under the config base, never /etc. .. is joined as written and folds with the rest of the path, so it is not confined to the base: xdg:config/../x names x beside the config base. On Windows a subpath that names a volume of its own would replace the base: one with a drive component (C:, C:x), or one opening with two separators, as a share or a namespace head does (\\srv\share, \\?\UNC\srv\share, \\.\pipe\x, and so xdg:config///x). Such a path cannot be answered and is used literally, as an unknown NAME is. Elsewhere every root is the one root, so nothing is refused.

`absolute classifies its payload on the raw string, before any folding, host first: it is live if absolute under the host's rules, dead if absolute only under the other platform's, and refused if under neither.

Raw P POSIX Windows
/x, / absolute dead
//server/share/x (well-formed UNC) absolute absolute
C:\x, C:/x, \\server\share\x dead absolute
\\?\C:\x, //?/C:/x, //?/UNC/server/share/x (verbatim) dead absolute
\x (root-relative) refused refused: it names no drive
\??\C:\x (NT object-manager path) refused refused: no grant can name one
C:x (drive-relative), anything relative refused refused
\\ or // with no server and share, or with . or .. for either (malformed UNC) refused refused
/\x, /\srv\share, \/srv/share (two mixed separators) refused refused

Absoluteness is the kernel's: under POSIX a path is absolute when it opens with /, under Windows when it opens with a drive root or two separators. Two grant rules stand beside it. A root opening with two separators that is no well-formed UNC or verbatim path, or that names the device namespace, is refused under both rules, though Windows would read it as absolute. So is one opening with two separators of different spellings, /\ or \/, outside a verbatim head: Windows reads it as a UNC or device head, while POSIX reads /\x as rooted at / and \/x as relative, so the one spelling would grant different paths on the two platforms. A verbatim root is a Windows grant and is dead under POSIX, though POSIX reads //?/C:/x as the rooted /?/C:/x: its author named a Windows path, and a profile must not grant a different path on another host.

A dead grant names no path on this host, so one profile can contain host-specific entries and load on both platforms; it matches nothing and, in a deny list, denies nothing.

A read, write or run allowance by path names the real path it was frozen to and is never re-resolved: a symlink put in its place afterwards redirects nothing, and the allowance grants nothing there. Creating a granted directory after the grant, or rm -rf dir && mkdir dir, keeps working, since these are path grants, not inode pins; a symlink spelling that existed at the grant and is retargeted later keeps showing its old target; replacing a granted directory, or an ancestor of it, with a symlink refuses every launch that shows it on Linux and Windows, naming it, and reaches nothing on macOS; macOS firmlinks keep working as twins of the real path. An exclusion names the object its spelling reached when the grant was decoded — the link and its target, where it was a link — under every name it has or gets, the position its spelling names, whatever is put there, and that name under any folder on the way that is renamed. That is ral's own reading; the OS sandbox a program runs under knows the positions ral holds at launch: where a denied object was named, and where it is now. Linux and macOS obtain the current position from a live hold and verify its identity; Windows holds nothing. A second hard link is not necessarily named by that hold, a copy is a new object, and a stack received over a wire reacquires holds only at its recorded positions. An exclusion follows the object it names, not what is moved out of it: a file renamed or hard-linked out of a denied folder by a process allowed to write that folder is a new name, judged on its own. A link retargeted after the grant is still the denied link, and its new target is judged on its own. A bare program name is resolved to the program it names when the grant is decoded. A grant whose real path is not valid Unicode is refused when it is frozen.

Places, anchors, .., environment-derived bases and symlink identities are frozen when the inline grant or profile is decoded. Later cd, HOME, TMPDIR, XDG, or repository changes do not retarget the grant. An anchored place that freezes relative (a relative HOME or TMPDIR) is refused. Ordinary relative paths and bare strings are rejected: write `cwd relative/path when that is intended.

An XDG place must resolve beneath the effective home directory. ral rejects an unset home needed by `home or an xdg-* tag, an XDG environment override that would escape the home directory, and a .git pointer file that no Git directory claims. Where .git is a file naming the Git directory, `gitdir follows it only if that directory names the working tree back, as a linked worktree's gitdir file does and as a --separate-git-dir repository's core.worktree setting does, since the file itself lies inside the tree the grant confines.

12.3. exec

exec has two lists of targets, allow and deny:

exec: [
    allow: [`name git, `name rg, `absolute /opt/tools/lint, `cwd tools/build, `dir `system],
    deny:  [`name bash, `absolute /usr/bin/curl],
]

A target is one of:

  • `name N — the bare command N: the file the PATH in force where the grant is decoded finds for it (its absolute entries; a relative entry is the environment's, not a grant's), and the bundled tool of that name; a PATH scoped inside the grant's body does not change what it names. N must be a bare command name; a path-shaped payload is refused with a hint to use a place. Path shape is judged under Windows rules on every host, so a\b and a drive-headed C:x are refused alike everywhere;
  • a place (§12.2) — the one executable at that path, frozen to its real path when the grant is decoded. A place that is a directory is refused, with a hint to use dir;
  • `dir D — every executable beneath each directory D names, recursively, frozen to its real path, where D is a place or a selector. Directory scope is spelled, never inferred from a stat: `cwd tools/build names one executable, `dir `cwd tools names everything beneath tools.

Bare strings are not targets. Authority over a command does not depend on its arguments: an allowed target is admitted with any arguments, or none, and a denied target is refused. ral has no first-argument or subcommand policy.

Every rule judges the file that will run: its real path, with symbolic links followed.

A link inside a granted directory to a file outside it admits nothing: the grant covers the files beneath the directory, not the names listed in it, as a read place reads what lies beneath it (§12.4). Where a distribution installs its commands elsewhere and links them from /usr/bin, as Ubuntu's coreutils-from-uutils links into /usr/lib/cargo/bin, grant the directory the links reach; `system names that root where it exists.

A bare name is resolved against the host PATH afresh at each run (one submitted line, one script or one dispatch), so the program launched is the program judged, with one residual: the program is started by its real name, and a file put at that name between the judgment and the start runs unjudged. So `name git also admits /usr/bin/git spelled `absolute /usr/bin/git, because it is the same file. A deny of a name also vetoes the command by file name wherever it lives, so deny: [`name bash] cannot be avoided through a link or another directory. A denial holds every spelling some filesystem takes for its name, in any case or Unicode form, so it also refuses BASH or a file under a differently cased denied directory; an allowance holds its name only as stored. An excluded program is, as in §12.2, the object its spelling reached when the grant was decoded: a hard link to it is the same program, and a copy of it is another.

There is no specificity. A target is permitted when some allowance covers it and no exclusion does: an exclusion of a directory refuses the exact file or deeper directory an allowance names inside it, a target in both lists is denied, and the refusal names an exclusion that applies. A command is judged before anything about it is looked at. A path that names nothing, a directory or a link loop fails with status 127 or 126 only where the grant admits running that path; elsewhere it is refused as a program there would be. A bare name runs the first PATH candidate the grant admits that is a program, passing over candidates it refuses. Failing every candidate, the first that was refused, was a file lacking execute permission, or could not be searched says why, and otherwise the status is 127.

Once an exec table is present, commands not admitted by it are denied: exec: [allow: []] admits no executable (ral's own binary included), and omitting exec inherits. Nested exec tables intersect, and every denial remains effective.

An omitted exec is every program, and a host that extends a base that omits it with a fragment that has exclusions (exarch's --extend) yields every program, less those exclusions. Such a policy restricts only through its exclusions: a layer that denotes no restriction, such as every program with no exclusion or an fs that writes the root and excludes nothing, activates no launch hardening (§12.10). On Linux, a program created during a launch on the spine of an excluded path does not run until the next launch, and under a restricted fs the sandbox's private /tmp runs nothing.

Running reads. Whatever a grant lets run by path, directory or name, and whatever it lets be written, may be read: a layer reads its own read and write places and the programs that it and the grants enclosing it let run. An fs-only restriction therefore does not hide the tools an enclosing grant runs; to hide one, exclude it in fs, and an fs exclusion of a run place refuses running it. A nested grant never makes anything readable by naming it in exec. A program that runs only through an omitted exec must be readable under fs, and is refused otherwise: '/opt/x/foo' may run, but it is not readable under the active grant. A trusted interpreter outside the reads and the floor starts its scripts under a restriction that supplies fs alone, as under a restricted exec.

ral's own binary is an ordinary file: ral runs exactly where a grant admits it, by path, directory or name, in the in-process guard and the kernel alike, so under an allow-list that omits it ral -c, a #! ral script and sh -c 'ral …' are refused. A grant that admits the folder holding ral admits ral (reasonable admits ~/.cargo/bin/); a nested ral there is bound by the kernel alone, so bundled-tool rules and verbs do not bind it. A bundled tool runs inside the confined child and reads ral's image: an fs exclusion over ral's binary refuses every bundled tool, on every platform, and an exec exclusion of ral leaves bundled tools alone.

A selector may be the payload of dir:

  • `path — every absolute directory in the current $PATH; an entry that is a filesystem root, the home or an ancestor of the home is a freeze error, as for any selected directory below, and so is one `absolute would refuse under the host's rules, or one that is not valid Unicode;
  • `system — ral's platform-defined system tool directories, without Homebrew;
  • a package manager, such as `rustup, `cargo, `go, `pyenv, `homebrew or `scoop. The implementation holds them as one table, and the checker's refusal of an unknown selector lists every name.

A package manager's selector is a set of locations: the directories it installs programs into and those its shims dispatch into. Each location has an ordered list of overrides, each a host environment variable with an optional subpath ($CARGO_HOME/bin), and its defaults, each anchored at an absolute path, the home, or an XDG base. A location is expanded in two steps:

  1. Choose. The first override with a usable value chooses, and is all the location has. A value is usable when it is non-empty and absolute under the host's rules; an empty or relative value is skipped, as path skips a relative entry. Where no override is usable, every default is chosen. For a variable that holds a path list (GOPATH) the override is its first entry.
  2. Keep what exists. Only the directories that exist when the grant is frozen are kept. An override that chose a missing directory yields nothing and does not fall back to the defaults: the environment said where the manager is, so a default it disowned is not granted.

A selector is the union of its locations, and a manager that is absent expands to nothing, never to an error. Overrides are read from the host process environment, as path reads $PATH, and never from the variables of a running shell or from a tool's own configuration files; a user who relies on such a file names the directory with `dir `absolute. A home default with no bound home is absent, and a default rooted on the other platform is skipped. A location is read by running (see Running reads above), so it is the narrowest subtree that holds what runs, and holds no credential.

Every kept directory of a named selector, default or override, is judged on its already-walked position before becoming an allowance or exclusion. A filesystem root (a drive or share root on Windows), the home, or an ancestor of the home is a freeze error: running reads would make the selector a read of everything. An override error names the variable and asks whether it is set correctly. A default error names the selector, default spelling and walked position when different, and points at the default directory or symlink and its HOME/XDG base. The test is on the directory, not its base, and follows symbolic links, so GOPATH=~, which chooses ~/bin, is accepted. An ordinary tool directory outside HOME remains valid; this is not the tagged-XDG home-containment rule (§12.2). A Windows root is refused independently of whether it denotes universal authority over all drives. A chosen directory that `absolute would refuse under the host's rules (a malformed or mixed two-separator head) is a freeze error too, as for `path: the error names the variable or default, the selector and the reason, and says what to change.

Four selectors, `homebrew, `macports, `nix and `pkgsrc, name system-wide package prefixes outside any home, and the read floor (§12.4) includes them wherever they exist, less any chosen directory inside the home: that is the user's, and is readable only where the grant says so. Nor does it include one that is a filesystem root or an ancestor of the home: the floor drops such a directory without error. A floor directory the environment chose (one of these prefixes, or on Windows %SystemRoot%, %ProgramFiles% or %ProgramFiles(x86)%) that `absolute would refuse, or whose walk fails, keeps ral from starting: the error names the variable and says what to change.

12.4. fs

fs has three lists of places:

fs: [
    read:  [`cwd ., `xdg-data .],
    write: [`cwd build, `tempdir .],
    deny:  [`cwd .secrets],
]
  • read permits reads under the listed places.
  • write permits writes under the listed places.
  • deny forbids both reads and writes under the listed places.

name, dir and selectors are refused in these lists. Writing reads: a write allowance also allows reading what it names, in the layer that states it, so the in-process guard reads every write prefix as the kernels do. A present fs table with no read or no write entry grants nothing for that operation, for read nothing beyond the floor; fs: [read: []] keeps only the floor. Deny regions are carve-outs and accumulate across nested grants.

The floor is the platform's fixed set of read-only system paths that any program needs to start (§12.11). Every restricted read admits it, whether or not the grant names it, and the in-process check and the host sandbox agree on it. No nested grant narrows it; only a deny removes a floor path. It admits reads alone: never writes, never execution.

ral resolves the accessed path, including symlinks, before testing prefix membership. Every prefix is resolved when the policy is decoded and keeps that resolution; an exclusion also holds the object it reached (§12.2). Composition never flattens nested policies into one: each active layer keeps its own frozen prefixes, and a check folds the whole stack afresh — the allow region for a read or write is the intersection of every opining layer's admitted prefixes, the deny region is the union of every layer's carve-outs, and a denial at any layer wins over an allow admitted elsewhere in the stack. Point-of-use checks resolve the live path again. The discard device is always permitted: /dev/null on Unix, \\.\NUL on Windows. On Windows a path whose last component is a reserved DOS device name (NUL, CON, PRN, AUX, COM1–COM9, LPT1–LPT9, and COM¹–COM³ and LPT¹–LPT³ with a superscript digit, in any case and with any extension) is refused; \\.\NUL is the one device name ral accepts. A path opening with two separators that is no well-formed share or verbatim path is resolved as written, .. included: no lexical fold can tell where such a root ends, and folding across it could assemble a share or a drive the path never named. So is a verbatim path spelled \\?\ with backslashes alone: Windows hands its rest to the kernel uninterpreted, / a character of a name and . and .. names. One spelled with a / in its head, such as //?/C:/x, is normalised by Windows like any other path, and . and .. fold past its drive or share. On Windows a file operation on one whose head names neither a share nor a namespace (\\x, \\\srv\share, /\x) fails, rather than reaching a path on the current drive, and so does one that reaches such a path, or one relative to a drive's current directory (C:x), through a symlink's target.

ral checks filesystem operations that it performs itself. A spawned program’s own filesystem access is instead confined by the host sandbox where supported.

A deny may name a path that does not exist yet. On macOS the kernel refuses spawned programs both reads and creation at that name, including reads of a file the host creates during the launch. On Windows nothing is granted that could reach it: the allowance is carved around it, and a name made in a carved directory during a run is unreadable to that run (§12.11). On Linux a name absent when the envelope is rendered gets no mask: making a mountpoint would touch the host. Even under a read-only grant, the host can create the name during the launch and that launch reads it; the next launch masks it. Under a writable grant a spawned program can also create the name, use what it created, and leave it on disk. Each launch whose render finds the name absent keeps that gap for its lifetime, including every process it starts; overlapping launches can therefore share it. The risk includes leaked host-created secrets and planted files. ral's own check refuses reads and creation throughout, before and after the name appears. A symbolic link created at the path is not the denied object; what it reaches is judged on its own.

A deny also pins every directory above the denied path that lies within a write place, that place itself included: no confined program can rename or remove one, or it could carry the denied object to a name no later grant denies. On Linux and macOS the entries of a pinned directory stay writable; on Windows it is carved (§12.11). The price holds on every platform: a grant that writes a repository and denies .git/config refuses mv .git .git.bak, rmdir .git and moving the repository itself. ral's own mv, rm and rmdir run as confined programs and are held alike. On Linux a pinned directory that has become a symbolic link since the grant was read refuses the launch, naming it.

One write no grant admits: onto a binary the sandbox pinned at startup — bubblewrap on Linux, ral’s own executable where it re-execs itself — judged by inode, so a hard link or a rename since startup names it too. The refusal names the binary and is not a grant denial. Replacing the file by rename is permitted; the session keeps running the copy it pinned.

12.5. net and gpu

net takes the one value `offline, and gpu the one value `withheld:

grant [net: `offline, gpu: `withheld] { … }

`offline disables network access for spawned children through the OS sandbox. A grant only narrows, so there is no value that grants network access: omit net to inherit, and an outer `offline cannot be lifted. net: true and net: false are refused statically. ral has no in-process network primitive, so there is no separate ral-level network check.

`withheld keeps the GPU from spawned children through the OS sandbox, as `offline keeps the network. There is no value that grants the GPU: omit gpu to inherit, and an outer `withheld cannot be lifted, an extension included. On macOS a child left the GPU may open Metal's device and IOSurfaces, reach its shader compiler, and read and write Metal's per-user caches (so it can alter shader caches other programs read); withheld, it can do none of these. On Linux the envelope shows the GPU's device nodes (DRM render nodes, never the card nodes; NVIDIA's; AMD's kfd; WSL's dxg) and the sysfs a driver discovers them by; withheld, it shows none, and over an unrestricted filesystem it masks them. Windows cannot withhold the GPU: an AppContainer reaches Direct3D with no capability to withhold. There `withheld refuses nothing and confines nothing; the launch proceeds with the GPU in reach, and the grant exarch shows its agent says the GPU is in reach because this platform cannot withhold it.

If the host cannot enforce `offline, ral refuses the confined launch rather than silently running it online.

12.6. detach

detach is a verb of shell (§12.8): it controls whether the body may create a process that the session stops owning.

grant [shell: [`chdir]] {
    # detach is refused; spawn remains the session-owned alternative
}

A layer that supplies shell and omits detach denies the birth, anywhere in the active stack; a layer cannot override an outer one's omission. Writing shell: [`chdir] therefore withholds detach, the safe direction, since detach is the authority that outlives the session.

When detachment is allowed, the child is created under the effective filesystem and network projection and, on hosts that support it, the effective executable-path projection. That projection remains attached to the survivor for its lifetime. On Linux the survivor also keeps its envelope's process namespaces: the receipt's pid names the envelope, not the program; the survivor's own getpid() is local to its namespace; and from inside any later grant the survivor is invisible, reachable only through what it serves. detach itself is not part of the OS profile; it decides whether the survivor may be born.

The detach command is present only when the host installs it.

12.7. Recorded decisions

A grant has no dimension for recording. Whether a capability decision is recorded is decided by the decision, not by the grant that made it: whenever an audit trail is open — from the language-level audit { ... } form or from batch --audit — every exec and ral-owned fs denial is recorded as a `check observation (§13.3), and no allowed check ever is. There is nothing to ask for and nothing to switch off, so no grant can hide a denial from a trail its caller opened.

An exec check identifies the command by the name shown, never the program it resolves to or its arguments. A filesystem check identifies the operation and the path as requested: a refusal discloses no link's target. A denied exec also reaches the surface rail, whether or not a trail is open.

grant is transparent to the audit model: it contributes no observation of its own. Its body's checks, command calls, and redirect reads and writes land directly in the trail that lexically owns them, and nested grants add no levels.

Entering a newly composed capability frame can also record a deputy / flagged check when an executable directory prefix is writable, since the body could replace or create a program there — one observation per flagged prefix, naming it in fields[prefix]. This finding reports the confused-deputy shape; it does not deny it.

The checks on net and gpu and on the editor and shell verbs record no individual observations.

12.8. editor and shell

editor and shell are lists of verbs, each a tag:

editor: [`read, `write, `tui]
shell:  [`chdir, `detach]

editor controls the private line-editor interface:

  • `read — inspect editor text, cursor, history, keymaps, parse state, and related state;
  • `write — change editor text or state and accept input;
  • `tui — open the editor TUI facility.

An _ed-* builtin needs the verb of every operation it performs, checked before its first effect; _ed-state needs both `read and `write.

shell controls what the body may do to the session itself:

  • `chdir — change the working directory with cd; within [dir: …] scopes a directory and is judged by fs alone;
  • `detach — create a process that the session stops owning (§12.6).

A verb is permitted only where every layer that supplies its list names it, so nested grants intersect. A list naming every verb is neutral, like omitting the field; an empty list withholds every verb, and an unknown verb is an error listing the verbs on offer. Under an extension, as exarch's --extend, the base's verbs are joined by union with the extension's: a verb list has no spelling for an exclusion, so an extension can add a verb its base lacks, a base cannot withhold a verb (detach included) against it, and a base that omits the field keeps every verb.

12.9. Concurrency and inheritance

A spawned worker receives a snapshot of the complete dynamic context, including the active grant stack. It cannot observe a later widening in its creator. Pipeline-stage children likewise inherit the active capabilities through their process boundary.

Authority does not flow back from a worker. A worker may narrow its own authority further, but finishing that inner grant does not change its creator’s stack.

On hosts, external and bundled commands receive an OS-sandbox projection folded from the effective fs, net, gpu, and, where supported, exec policies at the moment of launch. Linux guest engines use the guest jail instead (§12.11).

12.10. The two enforcement layers

ral uses two complementary enforcement layers:

  1. The in-process guard checks command admission, ral-owned filesystem operations, editor operations, cd, and detached-process birth.
  2. On hosts, the OS sandbox confines filesystem, network and GPU actions performed directly by a spawned program, subject to §12.11's platform limits. On macOS and Linux hosts it also confines executable paths. It enforces the same rules as the guard, an exclusion at the positions ral holds at launch: where a denied object was named, and where it is now (§12.2): an exclusion beats every allowance there too, and no backend makes an exception for a carrier, the dynamic linker or ral's own binary.

The in-process command guard applies on every host, including when no OS sandbox is needed. It cannot see a command that an admitted child launches internally. Conversely, an OS sandbox cannot protect operations ral performs in its own process.

A directory that exec admits is also a place a child could author a program the grant never named. ral does not freeze such a directory against a broader write prefix that covers it: an allowance never withdraws write authority. A broad write over a run-admitted folder therefore lets a child write programs there, including ones the user later runs from their own PATH outside any sandbox, and a name exclusion beneath a writable directory, or beneath an omitted exec, is advisory to descendants. exarch's edit-only launched from the home directory can write ~/.local/bin. The deputy findings name every folder a grant leaves both writable and runnable, each writable island under a runnable folder and none that is wholly excluded on either side; they are recorded only into an open audit trail (§13), by pushing the profile as a session layer under an open trail, for example ral --audit --capabilities exarch/data/edit-only.exarch.ral -c true, which from the home directory records a deputy check for ~/.local/bin.

Dynamic loader injection variables such as LD_PRELOAD, LD_AUDIT, LD_LIBRARY_PATH, and DYLD_* are removed from child environments while a restriction is active. Every other variable reaches the child as it stands: a grant does not filter the environment. A stack is restricting when some layer denotes something other than no restriction: an exec that is not every program less nothing, an fs that does not write the root with no exclusion, net: `offline, gpu: `withheld, or a verb list that omits a verb; a layer that restricts nothing ([], a policy that denotes everything, or full editor and shell lists) leaves ral ambient, and added to a restricting stack it changes neither the judgments nor the protections. Confined Unix children also receive resource limits; Windows confines process trees with a Job Object.

12.11. Host differences and limits

macOS. ral launches confined children under Seatbelt. Filesystem, offline-network, withheld-GPU, and executable-path restrictions are kernel-enforced. Network access means IP sockets, loopback included, and the system resolver's Unix socket. Other pathname Unix sockets bound outside the sandbox require a stated fs.write prefix covering their path; an fs exclusion wins. An unrestricted filesystem projection admits no outside socket through fs. Binding and accepting connections at a pathname socket likewise require a stated write. Admitting a socket (ssh-agent's, say) admits a daemon acting with the user's authority outside the sandbox. The executable allow-list also constrains programs launched internally by an admitted child. Since Seatbelt logs filesystem, executable, network, and Mach/IPC denials through one stream, a denial's diagnostic hint (§13.2) is classed by what was actually refused, never assumed to be a filesystem read merely because a hint has to say something. The read floor is /bin, /usr, /lib, /System, /dev, the Command Line Tools and Xcode developer directories, the system-wide package prefixes of §12.3 (`homebrew, `macports, `nix, `pkgsrc) that exist, the dyld cache directory, /etc wholesale, and the xcode-select and runtime-socket directories under /var; Rosetta's runtime is likewise runnable by every confined child.

Linux hosts. ral uses bubblewrap for filesystem restrictions, net: `offline and gpu: `withheld; on x86-64 and aarch64 every confined child also runs under a seccomp deny-set: kernel attack surface (ptrace, bpf, module loading, kexec/reboot/swap, keyrings, userfaultfd, open_by_handle_at, the mount family) is killed with SIGSYS, and user-namespace creation, setns, clone3, ioctl(TIOCSTI) and ioctl(TIOCLINUX) are refused with an errno: no mounting and no containers inside a grant. The deny-set also refuses socket outside Unix, IPv4, IPv6 and AF_NETLINK/NETLINK_ROUTE, socketpair outside Unix, and all three io_uring syscalls with EPERM, independently of net; io_uring can create and connect sockets without a syscall this filter sees. Routing netlink remains available for interface discovery; Unix sockets remain admitted by this deny-set. ral opens each path the envelope shows itself, never through a symbolic link, and has bubblewrap mount that open file rather than a name, so a path replaced by a link after the grant was read shows nothing the grant did not name, and one whose components became a link refuses the launch, as does a mount destination turned into a link after the open, rather than moving the mount; this needs bubblewrap 0.10.0 or later, and under an older one no confined command runs. A grant that limits which programs may run is refused on a kernel without Landlock, and every confined command is refused on a kernel older than 5.9, which cannot close every descriptor above stderr before its program starts. A directory the exec grant admits is readable inside, as on macOS. The read floor is /bin, /usr, /lib, /lib64, the files under /etc that dynamic linking, name resolution, user lookup and toolchain resolution need, the system-wide package prefixes of §12.3 (`homebrew, `macports, `nix, `pkgsrc) that exist, and of /sys only what sizes a program (/sys/devices/system/cpu, /sys/kernel/mm/transparent_hugepage); the envelope binds it read-only. The rest of /sys describes the host — its class/net lists the host's interfaces whatever net says — and a grant that wants it lists /sys under read. Every confined child runs in its own ipc and uts namespaces and, wherever the host can mount a fresh procfs, its own pid namespace with its own /proc: on every projection it sees and can signal no host process. Wherever the kernel builds a cgroup namespace the child has one, and on every projection /sys/fs/cgroup is the tree its own /proc/self/cgroup names — ral's cgroup, so a runtime reads its real limits; where the kernel cannot, the child sees the host's tree. A container runtime that masks /proc prevents the pid namespace; the launch still runs, and the table is the container's own. Each other invariant the host cannot build is likewise absent while the launch still runs. A confined command has no controlling terminal. A confined command whose working directory lies at or beneath a directory the grant denies is refused. Bubblewrap has no path-based executable filter, so the confined child enters a Landlock domain of its own inside the envelope: executable-path restrictions are kernel-enforced on kernels with Landlock (Linux 5.13 and later), constraining programs launched internally by an admitted child as on macOS, and on Landlock 6 kernels (Linux 6.12 and later) the child can signal no process outside the envelope even where no pid namespace could be built, nor connect to an abstract Unix socket bound outside it. On Landlock ABI >= 9 (Linux 7.1), connecting to a pathname Unix socket bound outside the envelope requires a stated fs.write prefix covering its path; an fs exclusion hides it. An unrestricted filesystem projection admits no outside pathname socket. No Linux resolver socket is admitted: name resolution falls back to DNS over IP. Below ABI 9, every pathname socket the envelope shows remains reachable, even under net: `offline. What the kernel gates is the path passed to execve. Landlock is allow-list only, so a denied path inside an admitted directory is held by admitting that directory's other entries, as they stand when the command launches: a program added there afterwards is refused until the next launch, and a bare-name deny under an admitted directory that a write reaches is held by ral's own check alone, since a child could author a renamed copy there. Landlock lists a directory where an exclusion's recorded position lies inside it or the directory is on that exclusion's recorded spine by identity. It judges enumerated entries and exact-file allowances by identity as well as position. A program denied from running but not reading, moved into an allowed directory on no exclusion's recorded spine and holding no recorded position, runs. Within a listed directory the walk refuses an excluded inode under every name. An excluded path that is a hard link to an admitted file runs only when the admitted name lies beneath a directory admitted whole, since Landlock admits inodes. A symbolic link inside an admitted directory to a file outside it does not run unless the target is independently admitted. Under every program with exclusions, a program created during a launch on the spine of an excluded path waits for the next launch, and the sandbox's private /tmp runs nothing. Neither ral's own check nor the kernel reads a command's arguments: an admitted dynamic loader or interpreter runs any file it can read, whether ral starts it or a child does. An attenuated exec alone is enough to build the envelope, so a grant that narrows only which programs run is still kernel-enforced.

Under a restricted filesystem no host terminal is reachable by name. Where bubblewrap can create a fresh devpts the child gets a private one; where it cannot (a container whose mount policy refuses devpts, as SELinux's container_t does), the envelope has no devpts at all: the child keeps the terminals it inherits and allocates none, so a program that needs a pty (tmux, script, ssh -t) fails there. Running the container --privileged lifts it.

Guest engines. On Linux x86-64 and aarch64, --guest-engine requires root and one absolute cgroup root. Every command runs under one shared unprivileged uid/gid, with resource-limited cgroup membership, NO_NEW_PRIVS, the host envelope's seccomp deny-set, and close-on-exec marking above stderr. Kept commands own transient engine-<pid>/exec-<seq> cgroups whose teardown kills their members and removes them, including on setup or launch failure. Detached commands share the detached leaf and one command's allowance (§11.5); preparing, failing or abandoning a launch never tears down that shared membership. This needs Linux 5.11; any setup failure refuses launch. The guest sets Yama ptrace_scope to 3, so no command can attach to or open the memory of another; sharing a uid, any command may still signal another command and read its other /proc entries (environ, fd/*). socket(AF_VSOCK) is refused with EPERM; debuggers and strace die of SIGSYS. An offline command gets its own network namespace with loopback up: local IP works within the command, IP egress and outside abstract Unix sockets are out of reach, and pathname Unix sockets remain reachable through the shared filesystem and can relay for it. The evaluator still checks ral-owned filesystem operations and direct command admission. The admitted utility's own file operations and internal execs, as well as its descendants', have no per-grant filesystem or executable-path projection: the jail replaces bubblewrap and Landlock. Guest-visible topology, read-only mounts and Unix ownership/modes remain the filesystem perimeter; the host-side NetPolicy remains the destination gate for guest egress. The protocol version covers confinement and frames; every attach refuses a mismatch, including media without the guest deny-set.

Windows. A launch whose filesystem region holds every path (exarch's dangerous with an exclusion from --extend, or a restrict file that only excludes) is refused before anything is stamped, since an AppContainer reaches only stamped folders and ral will not stamp every drive; the in-process guard still judges. A Windows sandbox cannot have access taken away beneath a folder it is granted, so an allowance holding an exclusion is carved at each launch: it is granted as its entries as they exist then, less entries excluded by position or identity, down to each exclusion, and each directory on the way is granted only the listing of its own names. The entries and listed directories are pinned and stamped through the handles carving examined. An entry made in a carved directory during a run is unreadable to that run, the excluded name included; nothing can be created or renamed into a carved directory; a link among its entries is not granted or followed; and its entries' names and listed metadata are visible. A launch is refused whose exclusion lies on or around an allowance, the program it runs included, since nothing can be carved there. Every exclusion is then checked at each launch against the sandbox's own access, and the launch is refused, naming the object, if anything beneath the exclusion is open to it: an entry granted to every sandbox (ALL APPLICATION PACKAGES), or a hard link to a granted file. ral uses a projection-specific AppContainer token, filesystem capability SIDs, and a Job Object. AppContainer is deny-by-default: a child confined only to obtain net: `offline does not automatically retain ordinary access to the user’s working tree. Windows has no path-based executable filter, so an admitted program may execute another visible program internally. Network and UNC grant paths are unsupported. The read floor is %SystemRoot%, %ProgramFiles% and %ProgramFiles(x86)%, which AppContainer already reads. A host's ambient ALL APPLICATION PACKAGES grants may reach beyond the floor: the kernel is then wider than ral's own check, never narrower, and only a less-privileged AppContainer could close it. Filesystem capability entries are attached to NTFS objects; same-volume renames and hard links can therefore preserve or omit authority differently from a purely path-based rule. An AppContainer reaches the GPU through Direct3D with no capability to withhold, so gpu: `withheld is not enforced there: the launch proceeds with the GPU in reach, and the grant exarch shows its agent says so (§12.5).

On another host, a filesystem restriction fails when no per-command sandbox backend can be built, and net: `offline is explicitly rejected if kernel network enforcement is unavailable.

12.12. Capability profiles

A capability profile is an ordinary .ral script that writes grant's options under the host-file rule (§15.3):

# read-only.ral
return [
    exec: [
        allow: [`name git, `name rg],
    ],
    fs: [
        read: [`cwd .],
    ],
    net:   `offline,
    shell: [`chdir],
]

Load one or more session-wide profiles with:

ral --capabilities read-only.ral script.ral
ral --capabilities base.ral,offline.ral script.ral

The loader parses, elaborates, type-checks, and evaluates each profile, then decodes its options. Like a module, a profile is checked against Σ (natives and the prelude) and runs under Σ. It sees no rc or session bindings; its helper lets stay private, and its value is its tail, not its bindings. A profile may use modules. Every profile key is optional: an omitted axis states nothing, and return () is the lattice top. Nested tables follow §15.3 too. Unknown keys and incompatible field types are refused before the profile runs; unresolved field values and domains retain runtime checks. Either kind of failure refuses the whole profile — the session never starts under it.

All listed profiles use the same load-time home and working directory. They are decoded by the same strict decoder as inline grants. Each decoded profile already contains frozen paths; the profiles are then pushed onto the session's capability stack in listed order, each its own permanent layer above the ambient root, rather than flattened into one composite policy — the ceiling they form is whatever the ordinary per-check fold of that stack decides. Later inline grants may narrow that ceiling but cannot widen it.

Profile field values may be computed, as at inline grants: grant [fs: [read: $paths], net: `offline] { … }. A bound bundle in place of grant's bracket, grant $p[policy] { … }, does not parse.

Compilation or runtime failure in a profile, an unwritten options tail (§15.3), a map or () where a nested table belongs, unknown fields at any depth, a bare string where a place or exec target belongs, an unknown tag, verb, or net or gpu value, a tag with the wrong payload, an obsolete argument restriction (only, or a list of subcommands), a selector in an fs list, an unwrapped selector or a directory place in an exec list, a path-shaped name, a place whose payload is not absolute (`absolute) or not a relative subpath (every other tag), a ~ or xdg: payload, and an anchor that cannot be frozen are reported as configuration errors. Inline-record decode errors occur before the grant body runs; session-profile errors prevent the requested session or batch program from starting.

13. Audit, diagnostics, and testing

ral keeps three kinds of evidence distinct:

  • a runtime error is a value-like description of failed computation;
  • a diagnostic explains that failure to a person, usually against source text;
  • an audit trail records what ran, how it settled, and which bytes crossed its file descriptors.

The distinctions matter. A command may write arbitrary bytes to fd 2 without failing. A command may fail without writing any bytes to fd 2. ral's explanation of a failure is therefore not inserted into the command's captured stderr; it lives in an error record, a diagnostic, or an observation's separate error field.

Byte pipelines preserve the same separation: their edges transport bytes between stages, while diagnostics and audit data use their own channels. A pipeline edge is never an implicit diagnostic or audit channel.

13.1. Runtime errors

A runtime error carries a typed cause and provenance. It aborts the current computation until a construct such as try handles it. A program reads it as the closed record [frame: String, message: String, status: Int, site: [script: String, line: Int, col: Int]] (§8.6), whose message and status are derived from the cause and never stored beside it, and which carries no output bytes. The cause is not language data: it stays typed through try, poll, audit, hosts and the wire, and raising a record raises a claim, not that cause (§8.5); none is reconstructed from diagnostic text. A runtime load's compile summary is intrinsic, while its source-labelled compiler rejection remains report-only. A source rejected before evaluation is a static diagnostic, not a runtime failure.

fail creates a fresh raised failure; raise raises a record as a claim; $error[message] is its description (§8.5):

try {
    refresh-index
} { |error|
    warn $error[message]
    raise $error
}

The failed command's raw fd 1 and fd 2 bytes have already followed their ordinary destinations; use audit when those bytes must also be retained as evidence. audit's `err outcome and poll's `ready `err outcome carry the same record as try.

Hints, context prefixes, compile rejections and unwind facts stay on the live error, outside its record. A hint is advice a site attaches to the error as it unwinds; the error keeps its hints in attachment order. The failure's intrinsic advice is the ordered advice its typed cause determines, including signal advice and remedies for operational refusals. A process that exited also receives the session's matching exit-hints entry. Advice is recomputed at each render and is never stored in the record. Some host operations add situational advice from the cause and report-only context; that advice does not survive a handler's raise.

Hint composition. A refused capability's intrinsic advice precedes its stored hints. Other causes show stored hints, then any report-context advice, then intrinsic advice and the exit-hints entry. Stored hints retain attachment order. None displaces another; hint text never determines failure identity or control flow. The compact form (§13.2) composes them identically. After them come one counted discard note, then an abandoned-tail note. Failed captures add their discarded byte counts, saturating at u32::MAX; written sequences and binds record whether later steps were abandoned. The abandoned-tail note is omitted for spawn failures and whenever any hint or advice is shown. Escapes carry no unwind facts. Raising a record drops these report-only facts.

Errors raised by the evaluator use the same path as explicit failures. For example, a map is indexed by a key computed at runtime, so a key the map does not carry can only be discovered there; the miss is an ordinary runtime error naming the absent key. It is catchable by try and recordable by audit; it is not an implicit Unit, sentinel, or process crash.

13.2. Human diagnostics

The ral executable reports parse, type, and runtime failures on standard error. A diagnostic normally includes:

  • a stable category code;
  • the source name and a highlighted source range;
  • a concise message and label;
  • a secondary range or help text where it clarifies the repair.

Lexer diagnostics use L codes, parser diagnostics use P codes, type diagnostics use T codes, and runtime diagnostics use R codes. When a span cannot be resolved safely, ral prints the code, message, and optional help without inventing a caret in the wrong file. Source spans count bytes internally; diagnostics convert them to character positions before rendering.

For a one-command interactive input, a compact runtime diagnostic is often more useful than pointing back at the line just entered. It has this general shape:

error: MESSAGE (exit status N)
hint: REPAIR

The status suffix appears only for worker timed-out and cancelled reasons; the hint line appears only when a hint or advice exists (§13.1). Errors in scripts, startup files, handlers, and other stored sources use the source-aware form instead.

A failure the OS sandbox reports for a spawned program is diagnosed from the kernel's own denial log over that call's window (§12.11), and the hint answers once for each class of denial the log actually contains, rather than assuming every denial is the same kind. On macOS, a denied filesystem read or write names the fully-resolved path — so a symlink inside a granted directory does not make the link's own directory sufficient — and the grant's matching read or write set; a denied executable names the path and the grant's exec allow-list, the only layer a re-exec such as sh -c or find -exec reaches; a denied socket names the net: `offline grant as the whole of the remedy, unless it is a Unix socket other than the resolver's, which no grant opens; a denied Metal device, IOSurface or shader compiler names the gpu: `withheld grant as the whole of the remedy; and a denied Mach or IPC lookup names the service itself, quoting the base profile's own recorded reason for withholding it where one exists — an unexplained service is still named, since it is usually a harmless probe rather than the failure's real cause. On Linux, the kernel log carries only the seccomp deny-set: a denied syscall is described by that deny-set's own reason where it has one, and otherwise named by number alone.

Colour is presentation, not meaning. It is disabled when the terminal cannot support it or the usual no-colour conditions apply.

Batch-mode exit status distinguishes static phases:

Failure Exit status
lexing, parsing, or elaboration 2
type checking 1
runtime error or explicit exit the resulting byte status (§16.3)

Successful execution exits 0. Diagnostics go to standard error; they are never a payload and never pipeline traffic.

13.3. The audit trail

audit { body } evaluates body with a fresh lexical trail active and returns a report:

let report = audit {
    echo 'checking'
    verify-index
}

case $report[outcome] [
    `ok:  { |value| return $value },
    `err: { |error| echo $error[message] },
]

Auditing is observational. Captured output is teed into the trail while the same bytes continue to their ordinary fd 1 and fd 2 destinations. audit does not change where bytes go or turn a returned value into pipeline traffic. Process-staged pipeline fragments are transported back and merged into the surrounding trail; crossing a process boundary does not make a stage disappear from the trail that lexically owns it.

The report is not itself an observation. It has two fields:

[
    outcome: <`ok A | `err [frame: String, message: String, status: Int,
                            site: [script: String, line: Int, col: Int]]>,
    trail:   [Observation],
]

outcome is the `ok/`err half of the body's ending. `ok carries the body's value. `err carries exactly the error record try hands its handler (§8.6), so one outcome vocabulary serves try, poll (§11.2), and audit: a reader who can read one can read all three. Its message is the failure's description; hints and advice are for a person and never enter that data (§13.1).

audit therefore handles an ordinary runtime error as data: evaluating the audit expression succeeds, with the failure in outcome. Control escapes are different — exit propagates out of audit rather than being converted into a returned report.

Two prelude functions read a report without a case:

Call Result
commands $report the `command payloads of $report[trail], in order
succeeded $report Bool, true exactly when $report[outcome] is `ok
let r = audit { grep -c ERROR app.log }
if !{succeeded $r} {
    echo !{bytes-to-string !{commands $r}[0][stdout]}
} else {
    echo 'search failed'
}

Settlement order

trail is the flat list of every observation the body's dynamic extent produced. It is not a tree: an observation carries no children of its own.

Observations appear in settlement order — each is appended when the fact it records becomes true, not when the construct that produced it began. So a command's observation lands after any observations produced within its extent, and a redirect's write lands when the write settles rather than when the redirect was parsed. The trail is a post-order traversal of observed facts.

Nesting is recovered from the timestamps, by containment: one observation's start–end interval contains another's exactly when the first's extent contained the second's. Containment is the only nesting the trail carries, and it needs no parent pointers, so a fragment transported back across a process boundary stays as readable as one recorded in place.

Observations

Every observation shares this common shape:

Field Type Meaning
site [script: String, line: Int, col: Int] total one-based source position; a run root starts at 1:1
start Int microseconds since the Unix epoch
end Int microseconds since the Unix epoch
principal `some String \| `none shell principal when the observation was recorded; `none where nothing named one
what Variant which kind of fact this is, together with its own fields

There is no kind field. The tag of what is the kind, so a reader dispatches with case and the checker decides exhaustiveness (§8.3):

what: `command [argv: [String], status: Int, origin: <`external | `detached>,
                stdout: Bytes, stdout-total: Int,
                stderr: Bytes, stderr-total: Int,
                error: <`some String | `none>]
    | `write   [path: String, mode: <`write | `append | `stream>,
                outcome: <`committed | `aborted | `failed>,
                new-bytes: <`some Bytes | `none>,
                old-bytes: <`some Bytes | `none>]
    | `read    [path: String]
    | `grep    [scope: String, pattern: String]
    | `check   [resource: <`exec | `fs | `deputy>, decision: <`denied | `flagged>,
                fields: Map String]
    | `worker  [id: Int, title: String]
    | `act     [verb: String, subject: <`some String | `none>,
                payload: String, refused: Bool]

grep and act are raised by host-side code — exarch's grep-files and its committed harness acts — not by core itself.

A `command observation records one ral-dispatched external or bundled invocation, or a detach birth, not a census of process images or syscalls. For example, env /bin/echo hello records env, not a separate /bin/echo; rg --hostname-bin helper pattern file records rg, not its supplied helper. Ordinary rg uses the platform hostname without starting a hostname helper; a helper may also be configured through RIPGREP_CONFIG_PATH. The outer invocation's status and captured stdio remain observed, including descendant bytes reaching those streams. Descendant image names, configuration reads, private output and individual statuses need not appear independently.

Its fields are:

Field Type Meaning
argv [String] the shown name first, then its evaluated arguments
status Int the outcome's status: 0 for a command that returned, otherwise its error's exit code
origin `external \| `detached the way the command was launched
stdout Bytes retained prefix of fd 1, at most 1 MiB
stdout-total Int bytes written to fd 1, 0 without byte capture
stderr Bytes retained prefix of fd 2, at most 1 MiB
stderr-total Int bytes written to fd 2, 0 without byte capture
error optional String ral's runtime error message, `none when the outcome was not a runtime error

A command's returned value is not among them. argv, the status, and the bytes are the evidence a later reader can act on; a process-local or executable value has no honest projection, and an external command has no value to project.

A `write observation records a > / >> / >~ redirect settling:

Field Type Meaning
path String the redirect's resolved target
mode `write \| `append \| `stream how the redirect opened its target
outcome `committed \| `aborted \| `failed how the write settled
new-bytes optional Bytes the target's whole content after the write
old-bytes optional Bytes the target's whole content before it, empty for a new file

An optional field is a variant, `some of the value or `none. Both byte fields are always present: an absent image is `none, never a missing key, so a reader eliminates it with case rather than testing for a key, and "there was no before-image" stays a fact the trail states rather than one the reader infers from silence.

A write is observed when its body settles — or, one whose target never opened, as failed there — carrying its target before and after: each image whole, or `none when it cannot be read whole, being past 64 KiB, not a regular file, or not readable under the live grant. A write that did not land carries neither. A streaming write (>>, >~, 2>) is committed whatever the body did, since its bytes landed as they were written; only an atomic > can be aborted.

A `read observation — a < file redirect opening — carries only path. A `grep observation carries the scope searched and the pattern searched for. A `check observation records a capability decision and is described below.

A `worker observation records a session worker's birth; a gather's child is not announced (§11.1), so its birth records none:

Field Type Meaning
id Int the worker's registry identifier
title String the title it was born under

An `act observation records an act the host committed:

Field Type Meaning
verb String the act performed
subject optional String what it acted on, where the act names one
payload String the act's rendered argument
refused Bool true when the host refused the act

When an atomic > commit fails after the command itself exited cleanly, the `command observation reports the failed commit, not the child's own status: status is nonzero and error names the commit failure.

A `command's error field is present even on success, where it is `none. It is `some only from ral's runtime-error path; it is not copied from stderr, and a nonzero status need not imply a `some error. Conversely, stderr contains only bytes observed on fd 2. It never contains synthetic runtime prose merely because a command failed.

stdout and stderr each retain an exact prefix of at most 1 MiB; no synthetic marker is inserted. stdout-total and stderr-total count every byte observed at the tee, so a stream is complete exactly when its total is at most 1 MiB and truncated when the total exceeds that cap. A detach birth, a direct-spawn pipeline stage, or a command running without byte capture (CapturePolicy::Off) has empty bytes and total 0. Neither stream is privileged. These are retention rules, not I/O limits: every byte still streams to its ordinary destination. Ordinary value capture (§7) and worker buffers (§11.1) retain their separate 16 MiB limit.

Command observations cover external commands, bundled commands, pipeline stages, and detach births. A command observation's status is one byte (0..=255), presented as an Int. Arguments are recorded after evaluation and rendered to strings as part of argv.

A builtin application is not an observation. The language's own value fragment — builtins, prelude functions, lexical bindings — performs no effect, and a builtin that reaches the world does so through an operation the trail already watches: a redirect, an atomic write, a worker's birth, a capability check. The operation records the effect there, as the `write, `read, `worker or `check it is, so == evaluated a million times inside audit { } adds nothing to the trail and a file edit lands once, as the write it made.

User-function application is transparent. Control forms and scopes, including if, case, within, grant, guard, and try, are transparent too. A guard adds no observation for acquisition, body, or release; their operations remain visible directly. Collection iteration manufactures no wrapper observation, and the builtin that performs it records none of its own.

Commands, reads, and writes performed inside a transparent function, form, scope, or iteration remain visible. They land in the trail that lexically owns them rather than under a synthetic wrapper. A function that only computes and returns a value adds no observation at all. A nested audit returns its own report, while its own observations also merge into an enclosing trail.

try does not consult the trail. The failing frame's name and site are located together at the innermost visible operation (§8.6). try therefore costs nothing beyond its own frame: it forces no collection, requests no byte retention, and adds no observation. Inside an enclosing audit, byte capture remains enabled — an inner try cannot silence an outer audit.

Capability checks

Capability decisions are recorded as `check observations whenever a trail is open. grant has no dimension for asking and none for withholding: the decision itself settles whether it is recorded.

  • A denial is always recorded. It is a fact about authority that nothing else in the trail attests.
  • An allowed check is never recorded. Everything it would attest is already attested by the command, read, or write it let through.

A denied exec also reaches the surface rail, whether or not a trail is open. An fs denial reaches the trail alone; the command it refused still surfaces in its own right, as a failed `command observation carrying the denial message.

A check's fields are:

Field Type Meaning
resource `exec \| `fs \| `deputy the resource class judged
decision `denied \| `flagged `denied, or the advisory `flagged; the resource's own, so a `deputy is never denied
fields Map String the resource-specific detail

A check is a leaf: no arguments, no I/O, and equal start and end timestamps. A denial is never encoded as a status, and it manufactures no raw stderr bytes.

The confused-deputy advisory (§12.7) records one `check per flagged prefix, with resource: `deputy, decision: `flagged, and fields: [prefix: …] naming the writable executable-directory prefix. It reports that shape; it does not deny it.

13.4. Batch audit JSON

For a script or -c program, --audit records the entire run and emits its report as JSON after the dispatch settles:

ral --audit script.ral
ral --audit --pretty -c 'echo hello'

--pretty requires --audit. These flags are batch options for an explicit script or -c; they are not interactive or stdin-script options.

The top-level JSON object has the same two fields as the language-level audit report — outcome and trail — but describes the whole CLI dispatch, not one body's ending. trail is the dispatch's flat list of observations, in settlement order. outcome is one of:

  • `ok value or `err record for an evaluated program;
  • `exited n for an exit, `stopped cause, or `panic text;
  • `static [rendered: String, status: Int] for a compile refusal;
  • payloadless `checked for a successful --check.

The runtime audit report's outcome remains only `ok or `err (§13.3). The CLI report has no separate top-level process status: the host derives it from the dispatch outcome (§16.3), and --audit does not change it.

The JSON projection favours legibility over round-trip fidelity:

  • Bytes become strings using lossy UTF-8 conversion;
  • Unit becomes null;
  • variants become objects with tag and, where present, payload;
  • a non-data final result (a block, function or handle) becomes an `err ending, status 1, rather than crossing the result boundary (§11.7).

The variant rule is what shapes the report: outcome reads as {"tag": "ok", "payload": …}, {"tag": "err", "payload": {…}}, {"tag": "exited", "payload": 3}, and the other outcome tags likewise; a Unit payload is absent, so a unit result reads {"tag": "ok"}. A successful check reads {"tag": "checked"}; a static refusal reads {"tag": "static", "payload": {"rendered": …, "status": …}}. Each observation's what reads as {"tag": "command", "payload": {…}} and its kin.

Compact mode writes one JSON document followed by a newline. Pretty mode writes the same data with indentation. Both write to fd 2. Program output is not suppressed: fd 1 remains ordinary stdout and raw program fd 2 bytes remain ordinary stderr. Consequently the JSON shares stderr with any bytes the program writes there, and with optional RAL_TIMING lines. fd 2 is not promised to be a standalone JSON stream.

For evaluated programs, static refusals, and successful checks, --audit emits only the report envelope, not a separate ordinary diagnostic. Runtime errors carry ral's explanation in `err; parse, elaboration, and type errors carry the rendered diagnostic and status in `static. A static refusal retains the check-time trail: a module read denial is stamped at the use that caused it, even though no phrase ran. Raw program stderr is not suppressed. The dispatch's real exit status is preserved; --audit does not turn a failed run into a successful one.

13.5. Testing ral programs

The language does not reserve a privileged assertion form. Tests can build small assertions from ==, fail, and ordinary functions:

let assert-equal = { |name expected actual|
    if $[$expected != $actual] {
        fail "assertion failed: $name"
    }
}

assert-equal 'answer' 42 !{compute-answer}

Expected failures remain explicit. For a parse-config that raises 'invalid configuration' on this input:

try {
    parse-config 'broken input'
    fail 'parse unexpectedly succeeded'
} { |error|
    assert-equal 'parse message' 'invalid configuration' $error[message]
}

within [handlers: ...] supplies deterministic command doubles without changing global process state:

within [handlers: [:, fetch-clock: { |args| echo '12:00' }]] {
    assert-equal 'clock' '12:00' !{fetch-clock}
}

The handler receives the command's argument list, a List String. Per-name handlers follow the ordinary command-dispatch rules, including inside byte pipelines. A handler stands in for a command, and a command's value is its output, so a mock must be a faithful one: it writes what the real command would write, and the test decodes it the same way a real caller would — !{fetch-clock} captures the mock's line, and a decoder such as from-json reads a mock that emits structured output.

audit is the execution-observation testing surface. It can assert the observation sequence, statuses, raw output, capability denials, and source locations without scraping a human diagnostic, and succeeded and commands cover the common assertions without a case. Transparent language forms do not supply nesting assertions; their nested calls appear directly in the trail that owns them. Tests that compare output bytes should inspect a `command's stdout or stderr; tests that compare ral's explanation should inspect its error, or read message from the report's `err payload.

For executable-level checks:

  • ral --check boots the engine as for a run, applies capability profiles and the recursion limit, then parses, elaborates (linking modules), and type-checks the script without evaluating it (§16.2);
  • ral --audit exercises the real program and exposes its audit trail.

The repository's corpus harness runs each script under tests/run/ through the real ral executable and compares its stdout with a sibling .out file after ignoring carriage returns; leading # directives state any expected exit status and stderr fragments (tests/README.md). just bless rewrites those goldens.

Those harness conventions test this implementation; they are not additional language semantics.

14. Standard environment

Every normal ral program starts with two layers of public names:

  • core builtins, implemented by the runtime for primitive value operations, shell state, structured operating-system queries, codecs, and concurrency;
  • the prelude, an ordinary ral module loaded before user code and built from those primitives.

An embedding host may add a third layer. The ral REPL adds interactive commands; exarch adds agent tools and a small helper library. Host additions are not part of the portable core environment.

The standard environment is typed. A builtin that writes to standard output, rather than returning a value, says so in its type, Command, and the typechecker records that before execution.

14.1. Discovering the live environment

The running shell is the authority on the names it actually provides:

help
explain map
explain from-json

help prints sorted Language:, Builtins:, and Prelude: sections. The language section covers every reserved form and Boolean literal. The other sections use the builtin registry and the prelude's ## documentation, the same sources used to build the shell. When a host has installed documentation for a sourced library, help also prints a Library: section.

explain name prints the name's full documentation, inferred type or command signature where one exists, and where the name comes from. It understands language forms and literals, core and host builtins, prelude entries, documented host libraries, session bindings, handlers, and external commands. Language entries are short standalone usage guides. The renderer heads the entry with the name and its source, prints the prose, then labels the facts it has as usage, type, path, and shadows; a missing fact is omitted. The source is language syntax, session, prelude, handler, builtin, bundled for a bundled tool, or the file a command would run. Where the active grant refuses a command it reads denied by grant, and path names the refused candidate. Every other place that holds the name is listed under shadows. If no exact documented name exists, it searches documented names case-insensitively. Regex search is used when regex support is compiled in; otherwise the search is a substring match.

Producer types print as Command[g] A: Command abbreviates stdout grade w, and Returns A abbreviates value grade p. A free grade also prints Returns A when its paired type excludes Unit; otherwise it prints Command[ν] A, using ν ξ ο π. Scheme quantifiers list only visible grades. For example:

cd     : ∀ν. String → Command[ν] Unit
length : ∀α. [α] → Returns Integer
map    : ∀α β ν. {α → Command[ν] β} → [α] → Returns [β]
both   : ∀α β. {Returns α} → {Returns β} → Returns [fst: α, snd: β]
await  : ∀α ν. Handle (Command[ν] α) → Command[ν] α

Returns means a value, never a command; Command[ν] permits either producer kind, as ν is chosen. Unit values are written () in programs.

help is the canonical catalogue of documented standard and host-library entries, not a list of every command that might be reachable. Arbitrary handlers, plugin bindings, and programs found on PATH are dynamic. Use explain name to inspect one of those.

Names beginning with _ are implementation interfaces. They are hidden from help and are not part of the public scripting contract. Prelude code and plugins may use the particular private interfaces supplied for them; ordinary programs should not.

14.2. Values, collections, and comparison

The collection family includes:

  • each, map, and filter for applying a function to list elements;
  • fold for a left-to-right reduction;
  • sort-list and sort-list-by;
  • range start end, whose end is exclusive;
  • length, is-empty, keys, and has;
  • lt and gt.
let items = range 0 5
let squares = map { |n| return $[$n * $n] } $items
let names = keys $record

These are value operations: ordinary composition uses application and bind. Higher-order operations stop and propagate an error if their callback fails. Lists remain homogeneous, and the typechecker rejects a callback or accumulator with an incompatible type.

lt and gt compare numbers numerically and strings lexicographically, both of one type; unsupported or incompatible shapes are type errors. length and is-empty take a list, and sort-list a list of numbers or of text; text is measured as length !{chars $s} and a map as length !{keys $m}. The predicate family returns Bool. A result of false is a successful computation; there is no status register, and a returning run exits 0.

The prelude builds the familiar derived operations from these primitives: for, reduce, reverse, last, take, drop, take-while, drop-while, first-where, option-or, elem, contains, nub, zip, flat-map, enumerate, concat, sum, max, min, maximum, minimum, cross, group-by, median, and median-by.

map accepts a block of either grade. map { |f| echo $f } [1, 2] writes 1 and 2 and returns [(), ()]. To collect output, return it: map { |f| return !{echo $f} } [1, 2]. A let around map binds its list; it does not capture individual callbacks. cross and par also accept command callbacks. flat-map never implicitly captures either, but requires list-valued callbacks: it maps, then concatenates the returned lists. filter demands a returned Bool, and sort-list-by a returned comparable key; command blocks are refused there.

14.3. Strings, numbers, and shell text

The string family includes upper, lower, dedent, slice, and intercalate. string-replace performs one literal replacement and fails unless there is exactly one match. Regex operations use the explicit re- prefix: re-match, re-split, re-find-match, re-find-matches, re-replace, and re-replace-all.

ral-quote renders a string as one ral word that reads back as that string: bare where it can be, quoted where a bare word would read differently, so '007' stays text. posix-quote and posix-split are the same pair for POSIX shell words, for sh and for tools such as fzf that split their options that way. All three are explicit conversions, not an invitation for ral values to be re-lexed automatically.

int, float, and str convert scalar values. round x places returns a Float, rounds halves away from zero, and accepts 0 through 308 decimal places. floor, ceil, and trunc accept a finite, in-range Float and return an Int; an Int is already integral and is rejected at the type level.

lines splits a string by the line rule of §7.3, and chars into its Unicode scalar values. The prelude adds words, from-words, indent, repeat, pad-left, and pad-right. It also supplies styled, ral's whole public ANSI surface: styled style text wraps text in the escape code named by style — reset, bold, dim, or one of red green yellow blue magenta cyan — and resets after; black, white, underline, reverse, and bold-colour variants are not supported styles. styled returns text unchanged when NO_COLOR is active, stdout is not a terminal, the selected interactive mode is minimal, or stdout does not support ANSI colour.

Regex names remain present in builds without regex support so source-level name resolution stays stable, but calling one then fails with a clear feature error.

14.4. Paths and filesystem queries

ral provides structured queries rather than requiring programs to parse the text output of ls or stat:

  • cwd, absolute-path, resolve-path, and abbreviate-home;
  • list-dir, file-info, and glob;
  • exists, is-file, is-dir, is-link, is-readable, and is-writable;
  • temp-dir and temp-file.

absolute-path is lexical: it resolves ~, ., and .. against the logical working directory without requiring the result to exist. resolve-path canonicalises through the filesystem, follows symbolic links, and requires an existing path. resolve-path reads .. as the filesystem does, after the symbolic links before it; a path ending in a separator names a directory, and a file or a link to a file under that name is refused, as the operating system refuses it; / is a directory every query may ask about. abbreviate-home is for display: it folds a leading home directory to ~. Filesystem reads and creations are checked against the active filesystem grant. temp-dir and temp-file return the path they create as a string, so they refuse a temp directory whose real path is not valid UTF-8, before creating anything in it.

The prelude's with-temp-dir { |path| … } and with-temp-file { |path| … } are the default for lexical lifetimes. They use guard to acquire the path and release it with rm -rf or rm -f, even when the body fails, exits, or stops (§8.7). The path is removed when the body's extent ends, so a worker the body spawns to use it belongs inside a gather. Bare temp-dir and temp-file leave the path yours to remove, and make it only if rm could remove it; prefer with-temp-*. Bare paths suit lifetimes beyond a block, such as a scratch directory across tool calls or a path handed to detach.

Before creating anything, temp-dir and temp-file require that the bare command rm would launch there: bundled when available, otherwise found on PATH, and admitted by the grants in force. The check uses the same lookup and admission as that command, launches nothing, and records a refusal where a refused rm would be recorded. It raises the lookup's own error (including status 127 when rm is not found) or the grant's denial, with a hint saying why the temp operation needs rm. An exec allow-list can admit it with `name rm. The existing write check on the parent supplies filesystem authority; no separate removal check is added.

For with-temp-*, acquisition and release have the same dynamic grants and PATH: scopes inside the body end before release. An enclosing within handler for rm receives the release's command as intended. For bare temp-*, this is a check at creation only; later context changes and removal are the caller's responsibility.

A relative path is read against the working directory, which is always an absolute path, and on Windows one on a drive or a share: cd and within [dir: …] refuse any other, and ral does not start in a process that has none. On Windows two more spellings are relative, and read as Windows reads them. \x and /x name x at the root of the working directory's drive or share. C:x names x in the working directory when that is on C:, and otherwise in the current directory Windows keeps for C: in the ral process, or at C:\ when it keeps none.

xdg: reads the XDG_*_HOME of the effective environment, within [env: …] included. For use, that environment is the session's at check time (§10.3).

On Windows, every path ral returns or prints is /-separated, never \-separated: cwd, home, ~, $SCRIPT, absolute-path, resolve-path, list-dir and file-info names, glob matches, temp-dir and temp-file, and the paths named in error messages. There are two exceptions. A command written as a path is named in its error as the user wrote it, so a failed .\missing reports .\missing. A path that only the operating system can read literally, such as \\?\UNC\server\share\x or \\.\pipe\name, keeps its backslashes, because / is not a separator there; a \\?\ prefix that can be dropped without changing the path's meaning is dropped, and the rest is shown with /.

list-dir returns records rather than formatted columns. file-info uses link metadata and reports fields including name, type, size, timestamps, readonly state, and symbolic-link target. type is a tag, `file, `dir, `symlink, or `other; target is `some the link's contents for a symlink and `none otherwise. An unavailable timestamp is 0.

glob matches ?, *, […], [!…] and {a,b} within one name and ** across names. A wildcard never matches a name starting with .: a dotfile is matched only by a component that names it literally, and a wildcard component that could match only such names, such as .h*, [.]env or {.env,.git}, is refused.

exists, is-link, and file-info judge a symbolic link at the link itself, never at the name it points to: a dangling link is judged and reported there, not as absent. exists and is-link both answer true for a dangling link, and file-info reports its own symlink type and target rather than failing as though nothing were there. is-file, is-dir, is-readable, and is-writable instead resolve through the link, so a dangling link answers false to each of them.

A lookup whose symbolic-link budget is exhausted discloses that diagnosis only if the grant admits the requested operation at the link where resolution stopped. Otherwise it reports and records a filesystem denial. An admitted loop remains an error, including for probes; it is not reported as absent. This diagnostic check grants no access through the unresolved name.

The prelude adds file-empty, line-count, and extension, the Option-valued extension of a path's last /-separated component: what follows its last dot when a character other than a dot precedes that dot, so a.tar.gz has gz, foo. the empty extension, and Makefile, .bashrc, ..hidden and .. none. line-count counts a file's lines by the line rule of §7.3, in bounded memory. from-lines < $path reads a file's lines as a list; for bounded-memory processing, redirect the file into fold-lines, map-lines, filter-lines, or each-line.

Filesystem mutations deliberately use command-shaped tools such as cp, mv, rm, mkdir, and ln. They are effects with byte-oriented command interfaces, not duplicate structured builtins.

14.5. Bytes, text, and lines

The codec families are the named boundary between values and bytes:

cat data.json | from-json
to-json $record > data.json

The core environment provides from-bytes, from-string, from-line, from-lines, from-json, from-jsonl, and from-csv, with corresponding to- encoders, and ints-to-bytes beside them for bytes given as numbers. Codecs do not silently reinterpret arbitrary values or output. Their exact UTF-8, newline, JSON, CSV, and capture rules are specified with pipelines and input/output.

fold-lines is the bounded-memory primitive for a byte pipe of UTF-8 lines. It splits by the line rule of §7.3, calls fn accumulator line, and returns the final accumulator. It does not first build a list, though the accumulator and callback may of course retain data themselves.

The prelude builds three bounded-memory filters on that primitive:

  • map-lines f calls f for each line and echoes the returned value as one output line;
  • filter-lines predicate echoes the original line when the predicate returns true;
  • each-line f calls f and discards its returned value, while any bytes the callback itself writes continue through the active byte pipe.

Use them with a byte pipe or redirect, for example map-lines $clean < input.txt. Calling a line reader with terminal stdin and no pipe or redirect is an error rather than an interactive prompt.

from-lines and from-jsonl are decoders like the rest: they read to end of input and return a list, of the lines and of each non-blank line decoded as JSON respectively. to-jsonl writes each element of a list as to-json encodes it, one per line.

14.6. Failure, session control, and concurrency

The core session family includes fail, raise, exit and quit, cd, use, ask, echo, warn, surface, clear, reset, help, and explain. use is a control operator (§10.3); the others are builtins except echo, which is a base handler: it takes an argument list, writes each argument's text conversion separated by single spaces, and ends with one newline.

fail raises a recoverable failure from exactly one String:

fail 'unavailable'

raise $err raises the closed [frame, message, status, site] record supplied by try as the program's claim (§8.5). $err[message] is its derived description (§8.6). exit and quit leave the current program rather than producing a recoverable failure.

warn message takes one String and writes it, followed by one newline, to standard error. It returns Unit and puts nothing on the byte channel, so a let binding the computation gets () and never captures the message. This is the whole of ral's diagnostic surface: there is no redirect that sends standard output to standard error.

surface value sends a first-order structured event to a host that installed a surface sink; without one, it safely produces no visible event. ask reads from the controlling terminal rather than redirected standard input and fails on end-of-file.

Concurrency primitives are the spawn and gather forms and await, poll, is-done, first-settled, race, cancel, and workers. The prelude adds par, both, first-of, attempt, and succeeds. Exact ownership, cancellation, output capture, and lifetime rules are specified with concurrency.

14.7. Host and build additions

The portable contract is the core registry plus the prelude. A host may install more names before user code is typechecked; those names then appear in that shell's help and explain output.

The ral command-line host provides watch. Its interactive form also supplies private editor builtins. Plugins load only from rc during startup and may install validated handlers, hooks, and keybindings; those are session extensions, not portable standard names.

Exarch installs its agent operations and a documented ral helper library. It does not provide watch. On supported Unix hosts it may also provide detach, whose process deliberately outlives ral and cannot be awaited or cancelled through a handle. These host-owned names must not be assumed in a portable ral script.

Builds may bundle external-style utilities. The coreutils feature provides a curated cross-platform set including ls, cat, wc, head, tail, cp, mv, rm, mkdir, sort, and related tools. Unix builds may add id, kill, stat, tac, test, and timeout; separate features add cmp, diff, or rg. A bundled bare name wins over a program of the same name on PATH, but it still runs as a child executable image with the current cwd, environment, byte pipes, redirects, status, and capability restrictions.

The standalone ral build does not guarantee bundled coreutils; ordinary external lookup remains available. Exarch enables its bundled tool set for a more self-contained environment. Platform-gated tools are absent rather than registered as commands that can never run.

15. Interactive use and extensions

Interactive editing is a service of the ral program, not part of the core language. A portable ral program may rely on values, commands, byte pipelines, types, and the core builtin surface. It must not assume that its host has a prompt, history, completion, plugins, or editor builtins.

The ral executable adds those facilities when it creates an interactive session. It installs their builtin signatures before checking startup files or prompt input, so the type checker sees the exact surface that the session can execute. Another host may install a different surface or none at all.

15.1. Entering the interactive shell

With no script or -c argument, ral starts an interactive session when standard input is a terminal. Otherwise it reads standard input to end of file and runs it as a batch script.

ral                         # interactive when stdin is a terminal
ral -i                      # force an interactive session
ral -s                      # read a batch script from stdin
ral --surface minimal       # choose the canonical-input frontend
ral --surface readline      # choose the full line editor
ral --norc                  # skip every startup file

-s takes precedence over -i. A positional script takes precedence over both. --surface overrides the RC setting of the same name.

The shell collects lines while the parser reports incomplete syntax. It joins continuation lines with newline characters and evaluates the result as one top-level run. Abandoning a continuation discards the whole partial input. A parse error, type error, or runtime error is reported and the next prompt is shown; exit ends the session.

The interactive evaluator is the ordinary language evaluator. In particular, a byte pipeline still transports bytes at every interior edge, while ordinary application and bind compose values. The frontend does not reinterpret the pipeline operator.

After a successful run, Unit prints nothing and Bytes are written without a prefix. Other values are displayed with the REPL renderer. Lists and maps use the bounded pretty-printer; other values use their ordinary display form. A list of two or more records sharing one field sequence prints one record per line, each field padded to its column's width, so a workers result reads as a table and still pastes back as the same list. The default prefix is => and the default value colour is yellow where colour is supported.

15.2. Frontends

The ral executable provides two interactive frontends:

Surface Contract
minimal Canonical standard-input reads and a > continuation prompt; no raw mode, completion, editor keybindings, ghost text, or highlighting.
readline The default full editor, with history, completion, vi or Emacs editing, plugin keybindings, ghost text, and highlighting.

Terminal capability is stronger than preference. A dumb terminal, or RAL_INTERACTIVE_MODE=minimal, forces the minimal surface even when another surface was requested.

The full frontends complete variables, command-position names, and paths. Variable candidates come from live non-private bindings. Command candidates also include installed builtins, handlers, and executables on PATH, and the working directory's subdirectories, offered with a trailing /. Relative paths are resolved from ral's logical working directory. Matching is by prefix, ignoring case unless the typed text has a capital; candidates extending the typed text are listed alphabetically; only when none does in the whole request does matching fall back to fuzzy, best first. A new binding is visible at the next prompt.

History is persisted in ral's state directory, $XDG_STATE_HOME/ral/history, normally ~/.local/state/ral/history; a host with no such directory keeps none. Consecutive duplicate entries are omitted. Saving appends the current session's new entries instead of replacing the file, so concurrent sessions do not erase each other's history.

Ctrl-C at the prompt abandons the whole current input, including continuation lines, and presents a fresh prompt without waiting for Enter (also on the Unix minimal surface). In a full frontend, Ctrl-D on an empty prompt exits cleanly. Ctrl-D within non-empty input performs the editor's ordinary delete operation. Ctrl-C while a command is running interrupts that foreground run. Unix Ctrl-Z is specified with concurrency (§11.6): a stopped process is resumed at once, so Ctrl-Z has no visible effect; ordinary application and bind have no process group to stop at all. Windows has no such signal.

15.3. Startup files and RC configuration

A login session first adopts the POSIX login environment (§16.4).

Every interactive session then reads the first existing RC file:

  1. $XDG_CONFIG_HOME/ral/rc, normally ~/.config/ral/rc
  2. ~/.ralrc

If neither exists, ral attempts to create a documented skeleton at the first available location. --norc, also accepted as --noprofile, skips both login environment adoption and the RC file.

Host files write their options. An rc file, a plugin manifest (§15.5), or a capability profile (§12.12) is checked against its declared table during constraint generation, key by key, exactly as within and grant options are. This is a syntactic rule on the elaborated tail, not a check of an inferred return row.

The tail is the last phrase. For a Run(M), descend through Bind.rest and Seq.rest to its terminal computation, preserving the environment of hoisted binds. The accepted tails are:

  • Return(Val::Record(fields)): a record literal, with return or bare. Every key is written; values may be arbitrary expressions.
  • Return(Val::Unit): (), read as empty options.
  • Only for a manifest, Return(Val::Thunk(b)) where b is a Lam with exactly one parameter and its body is not another Lam: a written { |options| … }. Its body's tail follows the first two cases, not this one. Factories are one level deep.

An empty file reads as (). A top-level let as the last phrase is T0077: it is not the file's options. Bare return means () too. Inside a factory, an empty body or one ending in let elaborates to return () and follows that case; it therefore lacks the manifest's required name (T0081).

Every other tail is T0077 (OptionsNotWritten), at the tail: a bound record (return $cfg), a computed result, a spread, a map, a list, or a block not admitted above. A hoist of a computed tail does not make it written. Advice distinguishes the file's tail from a factory body's tail, and names an actual returned variable when showing how to write its fields explicitly. For example:

let extra = [surfase: 'minimal', env: [:]]
return [...$extra, env: [:]]        # T0077 — a spread hides its keys

At every depth, a nested table must itself be a record literal, at forms and in files alike. A bound table, spread, computed table, map, or () is T0079 (TableNotWritten). Write the keys and compute only the values: grant [exec: [allow: $targets]], not grant [exec: $table]. The keys of collections — handlers:, env:, and plugins: — are data, not nested-table keys, and are outside this restriction.

Generator::check_options checks each written key with check_option. Unknown keys are T0076, refused keys T0026, duplicate keys T0022. Missing required keys produce one T0081 (OptionsMissing) per table listing only the missing required keys, without claiming that optional keys are required: “form is missing required keys: …”. It points at the record, or at the tail for () and an empty file. When every missing key has an empty value, its hint supplies those values for pasting. This includes missing limits: and theme: keys, whose empty value is `inherit. All these checks precede execution. Field types are ordinary uses during generation: they may constrain a let mode or call split and reach decoder admission sites before readback freezes them (§17.5). The rc and manifest decoders retain value-shape and domain checks, not redundant checks of the host result's shape or keyset. Grant's decoder also handles grants received as data and keeps its runtime shape and keyset checks.

The rc is total. It writes all twelve keys below. limits: and theme: are total nested tables: every one of their keys is required too. An empty rc or return () is T0081, not an rc with hidden defaults. The skeleton writes every key at its empty value.

Setting(T) is the closed variant [`inherit, `set T]. `inherit keeps what ral or the system already has; `set v overrides it. The empty values are exactly:

Key Empty value Meaning
umask `inherit Setting(String): keep the process umask, or set 1–4 octal digits at most 0777, e.g. `set '0022'. Applies to ral's own creates and every child.
limits [open-files: `inherit, core-bytes: `inherit, stack-bytes: `inherit] Each key is Setting(Int): keep ral's limit for children, or set a non-negative soft limit no greater than ral's hard limit. ral's own limits stay unchanged; a grant's limits win.
env [:] Set environment entries. PWD and OLDPWD are ignored: ral derives PWD from its logical working directory and keeps no OLDPWD.
prompt `inherit Keep ral's built-in prompt, or `set { … } to install a zero-argument base-prompt body.
handlers [:] Map(U([String] → Command)): install command handlers (§9.4); use let above the return for lexical values and functions.
edit-mode emacs String: emacs or vi.
bell false Bool: enable or disable the audible line-editor bell.
surface readline String: minimal or readline.
recursion-limit `inherit Setting(Int): keep --recursion-limit, else DEFAULT_STACK_LIMIT (100000), or set a positive function-call recursion limit.
plugins [:] Names each plugin and its options; loaded before the first prompt (§15.5).
startup `inherit No startup block, or `set { … } to run a zero-argument block once after the configuration is applied.
theme [value-prefix: `inherit, value-color: `inherit] Both keys are Setting(String): keep "=> " and yellow respectively, or set a prefix and a colour (black, red, green, yellow, blue, magenta, cyan, white, or none).

The rc decoder validates prompt:, startup:, and collection value shapes; setting domains such as octal masks, positive recursion limits, limit bounds, and colour names remain runtime checks. prompt: and startup: and a manifest's hooks: and keybindings: have no static hook-type obligation; installation still infers closure types and checks hook arity. The built-in base prompt is itself a host-made thunk, not a declared native. Windows accepts umask: `inherit and an all-`inherit limits:, refusing only actual settings. Top-level lets above the return install session bindings with their checked, generalised schemes. For example, a complete rc can choose:

let work = '/srv/work'
return [
    umask: `inherit,
    limits: [open-files: `inherit, core-bytes: `inherit, stack-bytes: `inherit],
    env: [EDITOR: 'vim', PAGER: 'less'],
    prompt: `set { return "!{abbreviate-home !{cwd}} ❯ " },
    handlers: [:, ll: { |args| ls -lh ...$args }],
    edit-mode: vi,
    bell: false,
    surface: readline,
    recursion-limit: `set 1024,
    plugins: [:],
    startup: `set { echo 'ready' },
    theme: [value-prefix: `set '⇒ ', value-color: `set cyan],
]

A written handlers: map is checked arm by arm, each in its own region, with duplicates refused, in the rc, manifest, and within alike. A bound or computed map is constrained as a whole to Map(U([String] → Command)). Write [:, ll: { |args| ls -lh ...$args }], or [:] for none; a record such as [ll: …] is refused with the map spelling. These uses reach decoder admission sites inside locally checked handlers. Persistent handlers are still vetted against the same constant type at installation; names supply diagnostic wording only.

The prompt body may return a value, whose display form becomes the prompt. If it returns Unit, its captured standard output is decoded lossily after removing exactly one trailing LF or CRLF; a lone CR and any preceding terminator remain. A returned String is unchanged. Prompt failures are reported and fall back to ❯. Plugin prompt hooks then transform the base prompt in plugin load order.

Parse, type, read, and runtime failures in a startup file are reported without preventing the interactive shell from starting. exit ends the session with its status.

RC evaluation is trusted session bootstrap. Command-line --recursion-limit, --surface, and capability profiles are applied afterward, so the command line wins and the session capability ceiling narrows the resulting shell.

15.4. Discovering the installed surface

help lists language forms and literals, installed public builtins, documented prelude bindings, and any library documentation supplied by the host. Names beginning with _ are hidden. The lists are sorted.

explain name shows the entry's full documentation, inferred or declared type where one exists, and where it comes from. For a language entry the full documentation is a standalone usage guide. The source heads the entry, as in §14.1; the other facts are labelled usage, type, path, and shadows. When no exact entry resolves, explain performs a case-insensitive search and prints matching public entries. These commands are informational: a missing query prints a message and leaves status zero.

Because help is assembled from the live shell, it describes host additions such as watch and _ed-* only where they are actually installed.

15.5. Plugins

A plugin is an ordinary ral file following the host-file rule (§15.3): its manifest is a written record, directly or as the tail of a written one-parameter factory. The runtime passes the factory its options as a Map.

let change = { |_old|
    let text = !{_ed-get}[text]
    if $[$text != ''] { _ed-ghost ' …' } else { _ed-ghost '' }
}

return { |options|
    let key = get $options key 'ctrl-g'
    return [
        name: 'example',
        hooks: [buffer-change: $change],
        keybindings: [[
            key: $key,
            handler: { |_event| _ed-insert 'hello' },
        ]],
        handlers: [:, hi: { |args| echo 'hello' ...$args }],
    ]
}

The manifest schema is:

[
    name: String,
    hooks?: Map<String, Block>,
    keybindings?: List<[key: String, handler: Block, guard?: String]>,
    handlers?: Map(U([String] → Command)),
]

name is required; the other fields are optional and default to empty collections. These four are the manifest's whole keyset. Unknown keys are T0076, and a missing name, including return (), is T0081. Both are refused before the file runs. return { [name: 'example'] } and return { |a b| [name: 'example'] } are T0077, as is a factory made by application (return $factory); see §15.3.

The name: field can constrain a decoder's type during generation. The handlers: map follows §15.3's arm-by-arm rule. A record such as [hi: …] is refused with the map spelling [:, hi: { |args| … }]; [:] is the empty map. A handler returning 5 is refused statically; one returning decoded data is held to Command, so incompatible data is refused at its decode, naming the field use. Persistent handlers are vetted against the same constant type again at installation; names supply diagnostic wording only. Unresolved field and member shapes, domains, and install-time checks remain runtime questions; the result's shape and keyset do not. Each declared field is checked exactly: ral does not stringify a value of the wrong type or silently drop a malformed handler. Hook and keybinding handlers each take exactly one argument. Unknown hook names, wrong handler arity, invalid key notation, invalid guard regexes, and handler conflicts are load errors. Validation and registration are atomic; a rejected load leaves no hooks, keybindings, or handlers installed.

Plugins run with the authority of the live session and current grant stack. A manifest capabilities: field is rejected because it would not enforce confinement. Use grant around an invocation that needs narrower authority. Plugin options are maps forwarded to the factory without checking their contents against its parameter type; they may contain blocks.

Plugins load only from the RC's plugins: map at startup and remain installed for the session. A new plugin requires a new session. Each key names exactly one file:

  • without a path separator, NAME names <config>/ral/plugins/NAME.ral, where <config> is the user configuration directory;
  • any other key is a written path, resolved exactly as use resolves one (§10.3).

There is no search list, literal-path fallback, or extension added to a written path. A denied read refuses that file; no alternative is tried. A plugin is checked against Σ (natives and the prelude) and runs under Σ, like a module. It sees no rc or session bindings, and its own helper lets never enter the session. Its value is its manifest or factory tail. A helper shared with the rc belongs in a module, which either file may use.

A direct manifest rejects non-empty options. In a complete rc (§15.3), set its plugins: field to:

[
    autosuggestion: [:],
    fzf-files:      [key: 'ctrl-t'],
]

Each key in plugins: is a plugin name or a path to a plugin file; a bare hyphenated name needs no quoting, but a path must be quoted. Each value is that plugin's options map, forwarded verbatim to the plugin's top-level block as its single argument; [:] is the empty map, for a plugin taking no options. A plugin whose value is not a map is reported by name and skipped; the other plugins still load. Loading a duplicate plugin name is an error.

Plugin handlers occupy the handler namespace. A collision with an existing handler is a load error. A lexical or native command with the same name is permitted, but the handler underneath it is then unreachable: a bare head hits the lexical binding or native first, and ^name is the external of that spelling, not the handler. explain name still reports it, under shadows:.

15.6. Hook and keybinding events

Every plugin hook takes exactly one argument, and registration checks this arity. In particular, lifecycle fields are not passed as separate positional arguments: pre-exec, post-exec, and chpwd each receive one event record. The recognized hooks are:

Hook Argument and result Time
buffer-change [old: String]; returns Unit After the text or cursor changes.
complete [words: [String], current: Int, offset: Int]; returns [String] or [[replacement: String, display: String]] When completions are requested, before the editor's own.
pre-exec [src: String]; returns the line to run (String), or Unit Before one complete prompt input is evaluated.
post-exec [src: String, status: Int]; returns Unit After evaluation settles.
chpwd [old: String, new: String]; returns Unit After an input line that leaves the session working directory changed.
prompt The current prompt String; returns a String Before each prompt render.

The value of a buffer-change, post-exec, or chpwd hook is ignored. The prompt hook is deliberately different: it is a string transformer, read like the session prompt (a returned value, else the captured standard output), so each successful result becomes the next plugin's input.

Hooks run in plugin load order. A failed lifecycle hook is reported but does not prevent later plugins' hooks from running or replace the command's status. A fault is attributed plugin 'name' hook 'event'. Prompt transformers compose: each successful result becomes the next hook's input, while a failed hook leaves the current prompt unchanged. The faults of one render print together, once while they repeat.

pre-exec hooks fold over the input line: each receives the line the previous one returned, and the last line is the one evaluated. A String result replaces the line and Unit leaves it. A failed hook is reported and a result of any other type is reported with a warning; both leave the line as it was, so no hook can stop every line. A line is refused by rewriting it to a failing one, such as "fail 'refused'"; its exit code reaches post-exec through the ordinary evaluation. post-exec's src is the line that ran.

complete runs when completions are requested for a buffer that lexes, with the record _ed-parse returns. Each candidate is a String, standing for itself, or a [replacement, display] record. The first plugin in load order whose hook returns a non-empty list claims the word: its candidates replace the text from character offset to the cursor, unfiltered, and no later hook runs. An empty list or () passes to the next plugin and finally to the editor's own completion, and so does a result of any other shape, with a warning. The hook runs aside: its writes to the buffer, ghost text, and highlights are discarded.

buffer-change and complete run on the editing path, so ral protects the session from a persistently bad handler, braked separately for each plugin and hook. A single invocation that exceeds its budget (100 milliseconds for buffer-change, 500 for complete), or three consecutive failures, disables that plugin's hook for the rest of the session and prints a notice.

A keybinding handler receives [key: String, mode: String]: the binding's key notation, and the editor's input mode at the press, insert, command, or replace (insert throughout emacs). A hook reads the editor only through the _ed-* builtins.

A key notation is one or more chords separated by spaces:

notation := chord (' '+ chord)*
chord    := (modifier '-')* key        each modifier at most once, any order
modifier := ctrl | alt | shift
key      := one character | f1…f12 | tab | enter | escape | up | down
          | left | right | home | end | delete | backspace

A modifier is a modifier only while something follows its dash, so ctrl-- is ctrl with -. shift applies to the keys that are not characters; for a character the shifted character is itself the key, so A and not shift-a. ctrl with an uppercase letter is refused, being the same key to a terminal as the lowercase one; so are ctrl-h, ctrl-i, ctrl-m, and ctrl-[, which a terminal sends as backspace, tab, enter, and escape, and a control character written as the key. Each refusal names the spelling to use. A sequence of several chords must begin with ctrl-x, the prefix the line editor leaves free for sequences. Ctrl-C and Ctrl-D, with no other modifier, are reserved and cannot be bound, alone or in a sequence.

Keybindings form one ordered table: plugin load order, then manifest order, then the frontend's built-in action. A guard is a regular expression matched against the text left of the cursor. A binding claims its keys only when the guard matches. Every unmodified key except F1 through F12 already has an editor action and therefore requires a guard. Modified chords and function keys may be unguarded. A binding that can never fire loads with a warning naming the binding that claims its keys first: an earlier unguarded binding on the same keys, or an unguarded binding on a proper prefix of its sequence.

The minimal frontend does not dispatch buffer-change or complete hooks or editor keybindings and cannot display ghost text or highlights. Plugin handlers and the pre-exec, post-exec, chpwd, and prompt hooks remain session facilities and do not depend on raw-mode editing.

15.7. The editor plugin interface

The _ed-* builtins are installed only by the interactive ral host and are hidden from help. Except for the pure _ed-hyperlink formatter, they require the corresponding editor.read, editor.write, or editor.tui authority. They also require an editor context, which only a buffer-change hook, a complete hook, or a keybinding handler carries; calling one from any other hook (pre-exec, post-exec, chpwd, prompt), at an ordinary prompt, or from a batch host is an error.

Cursor and span offsets count Unicode characters, not UTF-8 bytes.

Builtin Contract
_ed-get Return [text, cursor, keymap]; keymap is emacs or vi, the configured keymap. The text left of the cursor is slice $st[text] 0 $st[cursor].
_ed-set [text:keep|set Str, cursor:keep|set Int] Replace text and/or cursor; `keep leaves a field unchanged and an out-of-range cursor is clamped.
_ed-set-lbuffer text Replace text left of the cursor, preserving the right side.
_ed-insert text Insert at the cursor and advance past the insertion.
_ed-push Save the current buffer on a stack and clear it for another command.
_ed-accept Execute the resulting buffer immediately when the handler returns.
_ed-history prefix limit Return matching history, most recent first; zero means no limit.
_ed-parse Return [words, current, offset] for the simple command at the cursor, admitting open strings and blocks: words[current] is the word the cursor touches, or a spliced-in '' when it sits in whitespace, and offset is that word's start. words is empty when the buffer does not lex.
_ed-ghost text Set suggestion text; an empty string clears it.
_ed-highlight spans Replace highlight spans of shape [start, end, style]; an empty list clears them.
_ed-state default updater Read, transform, store, and return one persistent cell belonging to the plugin.
_ed-tui block Suspend the editor, run the block, and return [output: String, status: Int].
_ed-clipboard text Copy text to the system clipboard, natively when local, else by OSC 52; return whether all of it landed.
_ed-hyperlink uri text Return an OSC 8 hyperlink where supported, otherwise return plain text.

_ed-push and _ed-accept may be combined to preserve the current input while running a generated command. Ghost text and highlights are display state; they do not become part of the input buffer.

_ed-tui : ∀α ν. {Command[ν] α} -> Returns [output: String, status: Integer] runs the body with its standard output captured while allowing an interactive child to use the terminal. The body's value is ignored; the captured bytes are decoded as text, lossily after removing exactly one trailing LF or CRLF, and supply output. A lone CR and any preceding terminator remain. A body failure is returned as data in output and status rather than raised. _ed-tui opens only from a keybinding handler, the run that holds the terminal; from any other hook, and nested inside another _ed-tui, it is reported as status 1.

Terminal presentation remains capability-dependent. Clipboard emission may return false; hyperlink formatting may return plain text; colour, ghost text, and highlights may be suppressed by the selected surface or terminal. These fallbacks do not change language evaluation.

15.8. Host and platform limits

The following are promises of the ral executable, not requirements on every ral host:

  • persisted history, completion, terminal titles, and the three frontends;
  • startup profiles and RC discovery;
  • startup plugins and _ed-*;
  • terminal signal handling and crash-time terminal restoration.

Foreground terminal ownership depends on Unix process groups and a controlling terminal; Windows has no such handoff and supervises pipeline members as one console job instead. The minimal frontend uses canonical input and offers no raw editor surface. Batch execution and embedded hosts may omit all these facilities; portable code must discover optional installed commands rather than assuming them.

16. Invocation, interoperability, and platforms

The ral language and the ral executable are separate contracts. The language defines ral source, values, byte pipelines, and effects. The executable chooses where source comes from, prepares a session, reports diagnostics, and maps the result to an operating-system exit status.

Direct invocations always parse ral syntax:

ral
ral build.ral release --clean
ral -c 'echo $[2 + 2]'
ral -s < build.ral

ral -c does not accept POSIX shell syntax. Use ral-sh (§16.7), ral invoked by that name, as the registered login shell when programs may call $SHELL -c with POSIX source.

16.1. Invocation modes

ral selects one of four modes:

  • ral starts an interactive session when stdin is a terminal.
  • ral SCRIPT [ARG …] reads and runs a script file.
  • ral -c CODE [ARG …] runs inline ral source.
  • ral -s reads ral source from stdin to EOF and runs it as a batch.

On Unix, a bare invocation with non-terminal stdin also selects stdin-script mode:

generate-ral-source | ral

Reading source from stdin consumes that byte stream to EOF before execution. It is therefore already exhausted if the resulting program later tries to read its runtime stdin. File and -c modes do not consume stdin; the program may use it as a byte pipe.

-i forces the interactive session even when stdin is not a terminal. -s forces stdin-script mode and takes precedence over -i. A script positional takes precedence over both.

After SCRIPT, every remaining token is a script argument, even if it begins with -. A lone - names a script file literally; it is not stdin shorthand. In -c CODE [ARG …], CODE is the complete source string and every later token is an argument, including literal --. Shell options must precede -c. In short-option clusters, put c last (-ec, -lc): text attached after c is its source value, so -ce means source e, not a combination of flags. For example:

ral task.ral --force
ral -- task.ral --force
ral -c '--version'

Script arguments are returned by args. Arguments are text: one that is not UTF-8 is refused with status 2 rather than altered. $SCRIPT is a lexical string containing the source file’s path. That path is text too: a script, module, startup file, or plugin whose path is not UTF-8 is refused, naming it, before it is read. It is available in script files, including sourced modules under their own names, but is rejected in the REPL, -c, and synthetic preloaded source.

16.2. Batch processing

A batch run parses, elaborates, typechecks, and only then evaluates. Typechecking is always performed: inference builds the checked IR beside its types, inserting capture/decode at bindings and explicit forces for returned-thunk application. After inference succeeds, the unit's sites are frozen and its binding schemes settled. A pipeline carries no per-stage type annotations.

The batch-only checking and reporting flags are:

  • --check — boot as for a run, then parse, elaborate (linking modules), and typecheck without evaluating the requested program;
  • --audit — execute and print the run's audit report as JSON on stderr;
  • --pretty — pretty-print that JSON; it requires --audit.

These flags require a script path or -c; they are not accepted for a bare interactive or stdin-script invocation.

--check runs in the same engine and follows the same compile path as a run. Boot evaluates the capability profiles and applies --recursion-limit before checking; --check is not an effect-free check of the source alone. Module resolution and read authority are therefore the same as for a run, including refusals imposed by --capabilities. The requested program and its linked module bodies are not evaluated. The checker and evaluator also receive the same batch builtin surface.

The emitted JSON is one report for the whole batch run, its trail a flat list in settlement order. `command observations exist only for external or bundled command executions and detach births; a builtin application records nothing of its own, its effects landing through the write, read, and worker observations (§13.3). Function application, control forms such as if, case, try, guard, within, grant, audit, spawn, and gather, and loop iterations record nothing of their own either (a session spawn's birth lands through the worker observation); the commands executed inside them land in the open trail directly, including all three operands of guard. Each observation carries its evaluated arguments, status, source location, timing, and principal, plus the bytes it captured.

Batch stdout and stderr remain ordinary byte streams. A program's final ral value is not an operating-system pipe protocol: interior pipeline stages exchange bytes, while final values are reported through the ral result boundary. Explicit adapters perform any conversion between values and bytes.

16.3. Results, diagnostics, and exit status

Parse and elaboration failures print source-labelled diagnostics and exit 2. Type errors exit 1. Failure to read the script file exits 1. A malformed or unreadable --capabilities profile exits 2.

At runtime:

  • a normal completion exits 0;
  • exit N returns N;
  • a runtime error prints a source-labelled diagnostic and exits with the code that is the status of its record (§8.6);
  • a stop returns its cause's status (§8.10), with no diagnostic for a closed stdout;
  • a panic of ral itself prints its message and returns 101.

A returning script waits for its still-unclaimed loose workers and writes their bytes; a halting script takes them down. Loose workers' endings never change the status (§11.1).

An external's raw status stays in its typed cause until the failure code is computed, where it is clamped into 1..=255. exit refuses arguments outside 0..=255; fail takes text and yields code 1. A negative Windows NTSTATUS therefore cannot turn a failed external into success. --audit does not change the process status and adds no top-level status field: it represents the dispatch outcome in outcome (§13.4) and suppresses the duplicate ordinary diagnostic.

A foreground batch launched from a terminal may lend that terminal to an interactive child. A backgrounded or non-terminal batch has no such authority.

16.4. Interactive startup

-l or --login requests a login session. On Unix, an executable name whose basename starts with - does the same. Login affects only an interactive session: ral -l -c CODE and ral -l SCRIPT remain ordinary batch runs and do not source interactive startup files.

On Unix, an interactive login session first runs /bin/sh -l, which reads /etc/profile and ~/.profile. ral adopts the environment the helper reports: new and changed variables are set, removed variables are unset, and SHLVL, PWD, OLDPWD, and _ are ignored as the helper's bookkeeping. On any failure ral warns and keeps the environment it started with. A broken profile therefore leaves the user a shell. Installers that write only to ~/.zprofile or ~/.bashrc are not seen. A profile's umask and resource limits are not adopted; use the rc's umask: and limits: instead. Windows adopts nothing.

Every interactive session then reads $XDG_CONFIG_HOME/ral/rc or ~/.ralrc. The rc writes all its options under §15.3, checked before it runs. If neither file exists, ral may create a complete default rc skeleton and reports the created path. Read, parse, type, runtime, and configuration-value errors are reported; no invalid configuration is applied, and the user still receives a shell. An exit in the rc ends the session with its status.

Startup evaluation is not transactional. A read, parse, or type error prevents that file from running, and invalid RC values prevent configuration application, but bindings and effects produced before a runtime failure, exit, or value validation are not rolled back. Boot continues after errors; exit ends the session.

--norc, also accepted as --noprofile, skips POSIX login environment adoption and the rc file. Command-line --recursion-limit and --surface values are applied after the rc and therefore override it. Session --capabilities profiles are also applied after startup files: startup is operator-trusted setup, and the capability profile becomes the ceiling for subsequent work. A relative profile path names a file in the directory ral was started in, even when a startup file or an earlier profile changes directory.

16.5. Interactive surfaces

--surface minimal or --surface readline selects the frontend. Without the flag, the rc setting is used, then readline by default.

RAL_INTERACTIVE_MODE=minimal forces the canonical-stdin frontend regardless of the selected surface. An unknown value warns interactively and falls back to automatic probing.

16.6. Compatibility flags and environment

For tools that pass traditional shell flags blindly, ral accepts:

  • -e — accepted with no effect;
  • -u — accepted with no effect;
  • -i, -s, and -l — with the meanings above.

These flags and --norc/--noprofile may repeat.

ral seeds a stable dynamic environment at boot. Inherited values win; a variable the host does not bind at all takes a default for PATH, TERM, and LANG. ral reads the environment as text: a variable whose value is not UTF-8 is absent from env and from ral's own lookups, and reaches children with its bytes untouched. HOME, USER, LOGNAME, and SHELL are seeded from the host alone: where the host binds none, the variable stays unbound rather than taking an invented value, and ~ is then an error naming HOME rather than a directory. It increments SHLVL and supplies OS_NAME, OS_ARCH, and OS_FAMILY. Recognised terminal and multiplexer variables are retained when present. At startup, ral warns when PATH or HOME is set but not UTF-8: command search or ~ respectively cannot use it, while child programs still receive its original bytes.

PWD and OLDPWD are not exposed through env. ral owns the working directory as shell state so parallel work cannot race through the process-wide current directory. Each external child receives the correct PWD and actual launch directory; an inherited OLDPWD is removed, since ral keeps no previous directory.

RAL_TIMING, when present, prints batch phase timings to stderr.

On Unix, ral refuses a setuid invocation (effective and real user id differ) before it does anything else — before argument parsing, and before any of the four modes above is selected. The refusal is therefore unconditional: it does not depend on which mode the arguments would otherwise name.

16.7. ral-sh: the POSIX bridge

ral is intentionally not POSIX-compatible. Registering ral itself as $SHELL can break ssh host command, scp, rsync, Git-over-SSH, editors, multiplexers, and other programs that expect $SHELL -c to parse POSIX syntax.

On Unix, install ral-sh as the login shell instead. ral-sh is ral invoked by that name, a symlink installed beside it: the name in argv[0] is the one bit a login shell's caller preserves. Under that name ral reads no source before choosing a target; the first matching rule over the arguments after argv[0] applies:

  • any short-option cluster containing c, or any argument that is neither such a cluster nor --login (a positional, --, -, an opaque --long option), goes to /bin/sh, so -lc … and -l script.sh both do;
  • otherwise a short-option cluster containing l or i, or --login, goes to ral;
  • otherwise no arguments with both stdin and stdout attached to terminals goes to ral;
  • every other invocation goes to /bin/sh.
/usr/local/bin/ral-sh -lc 'printf "%s\n" ok'  # /bin/sh
/usr/local/bin/ral-sh -l                       # ral

The /bin/sh branch forwards arguments without requiring UTF-8, and replaces the process with the literal path /bin/sh: no PATH lookup. If the invoked name begins with -, it preserves that login-shell convention as -sh. The ral branch does not exec: the same process continues as ral, which sees the leading - itself. Failure to replace the process exits 127. The setuid refusal applies first, under either name.

The bridge's ral branch is an ordinary ral process, so a login through it adopts the POSIX environment per §16.4; the bridge itself is unchanged.

16.8. Platform distinctions and limits

Unix. Terminal detection selects a bare REPL or stdin-script mode. Login-shell argv[0], process-group foreground ownership, immediate resume-on-stop (§11.6), and ral-sh are Unix facilities. Signals are translated into cancellation and conventional process statuses; the shell restores terminal ownership after foreground children, and on exit hands the terminal back to the process group it started in.

Windows. A bare invocation defaults to the interactive mode because the CLI does not infer stdin-script mode from Windows terminal state; use -s for source redirected on stdin. ral enables virtual-terminal processing where available. Unix process groups and stop signals do not exist. Direct execution refuses .bat and .cmd images, named so once Windows drops trailing dots and blanks (run.bat., run.bat), because their additional cmd.exe quoting pass has no safe general argument encoding; invoke cmd.exe explicitly only if that risk is acceptable. ral-sh is a Unix login-shell bridge and is not a usable Windows shell dispatcher.

On every host, external commands communicate through operating-system byte pipes. A pipeline has no typed-value wire format: values cross only through the final ral result boundary or ordinary application/bind, and explicit adapters perform conversions between values and bytes. Paths, executable lookup, path-list separators, default system paths, and sandbox enforcement otherwise follow the host rules described in their respective sections.

17. Formal language definition

This section collects the implemented core language in a compact notation. It is descriptive, not a claim of soundness, completeness, progress, or preservation. The parser, typechecker, annotated IR, and evaluator remain the authorities when this presentation is ambiguous.

Metavariables used below are:

  • x for an identifier, w for a word, s for a string, and n for an integer;
  • p for a binding pattern, v for a value term, and M, N for computations;
  • A, B for value types, C, D for computation types, and ρ for a row;
  • T, E, H for values that are thunks, which a branching form forces.

17.1. Concrete grammar

The lexer supplies words, quoted strings, interpolation segments, tags, redirect tokens, newlines, and punctuation. Its mode is set by the innermost open delimiter: inside [...] and $[...] newlines are whitespace and commas punctuate, and inside $[...] alone the spellings <, >, <=, >=, !=, &&, ||, +, -, *, /, %, =, and == are operator tokens of their own, ending the word before them, a numeral being read whole. A newline or ; separates statements. The shared stage parser requires every stage to end at a statement boundary, |, ?, a closing delimiter, or end of input; juxtaposed same-line statements are not admitted.

The following EBNF omits lexical escape details and source-span bookkeeping. NL denotes a newline and sep denotes NL or ;.

program       ::= sep* (statement sep+)* statement? sep*
statement     ::= binding | chain

binding       ::= "let" pattern "=" NL* chain
chain         ::= pipeline ((NL* "?" NL*) pipeline)*
pipeline      ::= stage ((NL* "|" NL*) stage)*

stage         ::= (return | conditional | case | scope-form | module-use | command)
                  redirects

return        ::= "return" atom?
conditional   ::= "if" NL* atom NL* atom
                  (NL* "elsif" NL* atom NL* atom)*
                  (NL* "else" NL* atom)?
case          ::= "case" NL* atom NL* "[" case-arm ("," case-arm)* ","? "]"
case-arm      ::= tag-key ":" atom
tag-key       ::= "`" identifier

scope-form    ::= "try" atom atom
                | "guard" atom atom atom
                | "within" options atom
                | "grant" options atom
                | "audit" atom
                | "spawn" atom? atom
                | "gather" atom
options       ::= "[" "]"
                | "[" option ("," option)* ","? "]"
option        ::= static-key ":" atom
module-use    ::= "use" written-path
written-path  ::= constant-word | quoted-string | constant-double-quoted-string

command       ::= head (argument | redirect)*
head          ::= "^" bare-name | atom
argument      ::= atom | "..." atom

atom          ::= primary index*
primary       ::= word-value | block | collection | unit-literal
word-value    ::= lexical-word
                | quoted-string
                | interpolated-string
                | variable
                | expr-block
                | force
                | tag
index         ::= "[" index-key "]"         /* adjacent to a target other than $(name) */
index-key     ::= static-key | position | computed-key
position      ::= nonnegative-integer
computed-key  ::= variable | spliced-double-quoted-string | expr-block | force
force         ::= "!" variable index* | "!" primary
variable      ::= "$" identifier | "$(" identifier ")"
expr-block    ::= "$[" expression "]"
expression    ::= operand (infix-op operand)*    /* by the precedence below */
operand       ::= "(" expression ")" | "-" operand | "not" operand | atom    /* a sign touching a numeral is the numeral's, §4.1 */
tag           ::= "`" identifier atom?

block         ::= "{" program "}"
                | "{" "|" pattern+ "|" program "}"

collection    ::= list | record | map
list          ::= "[" list-items? "]"
list-items    ::= list-item ("," list-item)* ","?
list-item     ::= atom | "..." atom
record        ::= "[" record-entry ("," record-entry)* ","? "]"
record-entry  ::= static-key ":" atom | "..." atom
map           ::= "[:]"
                | "[:," map-entry ("," map-entry)* ","? "]"
                | "[" map-entry ("," map-entry)* ","? "]"
map-entry     ::= map-key ":" atom | "..." atom
map-key       ::= static-key | computed-key

unit-literal  ::= "(" ")"

pattern       ::= "_" | identifier | list-pattern | record-pattern
list-pattern  ::= "[" pattern-list? "]"
pattern-list  ::= pattern ("," pattern)* ("," "..." identifier)?
                | "..." identifier
record-pattern ::= "[" record-pattern-entry
                   ("," record-pattern-entry)* ","? "]"
record-pattern-entry ::= static-key ":" pattern
static-key    ::= identifier | quoted-string | constant-double-quoted-string

redirects     ::= redirect*
redirect      ::= fd? ">" word-value
                | fd? ">>" word-value
                | fd? ">~" word-value
                | fd? ">&" fd
                | fd? "<" word-value
                | fd? "<<" word-value

A redirect list binds each stream at most once (§7.4); the parser refuses a second binding. For <<, an explicit descriptor, if present, must be 0. For >&, the source descriptor must not be 1 when the target is 2: 1>&2 and its short spelling >&2 are rejected in favour of warn (§7.4). [] is the empty list and [:] the empty map; [:, …] explicitly opens a map on written keys. Otherwise a collection's entries decide: any computed key makes it a map, written keys alone a record, and no keyed entry a list (§4.5). A constant double-quoted string is a written key; a spliced one contains at least one interpolation splice. A pattern's keys are written out in the same alphabet: let ["user name": u] = $r is a record pattern; a spliced key is refused because a pattern cannot bind through data. within and grant likewise admit constant quoted option names but refuse computed ones. A tag is no key at all: tag-key occurs only in a case arm.

A case's arm list is a production of its own, and no expression may stand in its place: a spread among the arms and a repeated tag are both rejected, and the list may not be empty. This is what makes the set of alternatives a fact the parser establishes (§8.3).

The atom after an if condition, after else, and after a case tag is an arm, and an arm is a block or a name: a literal { … } or { |p| … }, or a $name. Any other atom would be hoisted and run before the form chose, so it is refused, with the advice to bind the block first (let arm = $arms[a]).

Which lexical words are literals rather than names is the numeral grammar of §4.1, and the expression grammar inside $[...] reads numbers by that same rule.

A plain identifier in head position enters ordinary name dispatch. A word containing a path separator (§3.5) or a ~/ path is a direct path head. ^name requests external-name lookup. A literal word, a bare ~, a $[...] block, and every other atom are value heads. With no arguments or redirects, a value head is simply its value.

The parser curries a multi-parameter block:

{|p q| M}  =  {|p| {|q| M}}

Each pattern binds all its names simultaneously and may not bind one name more than once. A list rest pattern is terminal.

? and | admit newlines on either side.

An operator spelling inside $[...] is a token of its own, not a word, with one exception: where a value is expected, as an operand or a tag's payload, a + or - touching a numeral is that numeral's sign (§4.1). So $[-9223372036854775808] is the smallest Int, $[+5] is 5, and $[2*-3] is -6. After a complete operand, + and - are binary however they are spaced: $[5 -1], $[5 - 1] and $[5-1] are all 4. A tag is greedy, as everywhere: $[`a -1] is `a carrying -1, as `a -1 is outside $[...], while $[`a - 1] subtracts from the nullary `a. A - that touches no numeral is unary minus, as in $[- 5] and $[-$x]; there is no unary +.

Inside $[...], expressions have the following precedence, from low to high:

||
&&
== != < > <= >=
+ -
* / %
unary - and not

Binary operators associate left. && and || short-circuit. An operand is any atom of the value grammar — a numeral, a quoted string, a variable, an indexed value, a forced block, a collection — or a parenthesized expression; () is the unit atom, not an empty group. $[...] therefore adds no node of its own to the tree: it is the lexical mode in which the operators can be written, and which values each operator accepts is the type system's question (§4.8 for ==; arithmetic and ordering want numbers). One case is settled earlier: a bare word that is not a numeral is a string here as everywhere, so under -, arithmetic, or ordering it can never typecheck, and ral refuses it at parse time, asking whether $name was meant.

17.2. Core terms

Surface syntax elaborates into a call-by-push-value IR. Its essential value and computation forms are:

v ::= x | unit | true | false | n | f | s | bytes
    | [v1, ..., vn] | {l1 = v1, ..., ln = vn}
    | `l v | thunk M | builtin b | handle h

M ::= return v
    | force v
    | lambda x . M
    | M v
    | M to p . N
    | exec h [v1, ..., vn]
    | M1 | ... | Mn
    | M1 ? ... ? Mn
    | if v T E
    | case v of {`l1 H1, ..., `ln Hn}
    | M1 ; ... ; Mn
    | letrec {xi = vi}
    | scope op
    | capture M
    | prim o [v1, ..., vn]
    | δ(b; a1, ..., an)

op ::= try v1 v2 | guard v1 v2 v3 | within v1 v2 | grant v1 v2 | audit v
     | spawn [v1] v2 | gather v
     | redirect M redirects

T, E and each Hi are values, thunks the form forces when it chooses one. Every scope op but the last takes its body as a thunk, because a scope installs an effect before the body runs, spawn runs its own on a worker, and a value is what can be held unrun. redirect takes the computation itself: its body is an application or a nested scope, neither of which can fuse its own redirects the way exec does. guard's three values are acquisition, body, and release, in that order; the last two are thunks accepting one and two arguments respectively.

Byte, builtin and handle constants share this value syntax but are written only by the runtime. The runtime also writes δ: it reads its builtin and arguments by name from the lexical environment (§17.8).

capture is a checker-written control form (§17.5). decode v abbreviates prim decode [v], a primitive on a byte value. Other primitives include arithmetic, rendering, concatenation, indexing, record update, and list/map assembly; all operands are values. Operand computations elaborate to surrounding binds. A bare tag supplies unit as its payload. A lambda binds one name; destructuring parameters elaborate to binds after the whole lambda chain.

Command calls elaborate either to exec, which enters command dispatch, or to application when the head resolves to a bound value. A trailing redirect on an application or scope form becomes a redirect scope; redirects on exec remain part of the atomic command launch.

An if arm is a thunk of the computation it runs, forced in place. A case arm is a thunk of one argument: case applies the chosen arm to the variant's payload. A literal { |p| M } and a name holding one are the same value, so both spellings reach the same arm.

Blocks elaborate to thunks. A parameterized block elaborates to a thunk whose computation is a function. Within a stretch of block definitions (§5.7), each largest set of definitions that refer to one another, directly or through others, elaborates to one simultaneous letrec group, as does a single definition that refers to itself; every other definition is an ordinary binding. Each comes after the definitions it refers to, and none leaves its stretch.

17.3. Types and rows

Value and computation types are:

A, B ::= Unit | Bool | Int | Float | String | Bytes
       | List A | Map A | Record ρ | Variant ρ
       | U C | Handle_ε A | α

ρ ::= · | l : A, ρ | r

C, D ::= F_ε A | A -> C | β       ε ::= p | w | ε̂

Map A is a homogeneous string-keyed map. Record ρ is a row-typed record; Variant ρ is a tagged sum over the same row machinery. Bare record labels and tag labels occupy distinct alphabets and do not unify. A nullary variant has payload type Unit.

U C classifies a suspended computation. F_ε A pairs a grade with the value type it produces: p produces a value, w produces output and has value type Unit. A command is F_w Unit: an external, a base frame such as echo, a builtin declared Command, or an arm standing in for one.

The inferred invariant is F_w A ⇒ A = Unit. Every introduction of w is at unit, and every copied grade keeps its paired value type. When meeting two returners or two handles, if either grade resolves to w, the other value type must resolve to unit or a variable whose kind admits unit. Otherwise unification fails before binding either grade. After this guard, when neither grade is p and either a value-type variable admits unit or the two value types differ in unit capability, it validates the fallible payload equation before joining grades. Other pairs unify grades before value types. Thus a failed payload equation leaves no hazardous grade alias. Grades are atomic and never weak.

Only commands, boundaries and value demands fix a grade.

  • Commands introduce w.
  • A binding defaults an undecided grade to p only at the close of its owning region (§17.5). A non-unit payload can entail p before then. A builtin parameter demanding a value, such as filter's block, requires p.
  • Boundary results are p: checked-boundary JSON/CSV decoders and other checked doors supply data. A free boundary grade would let a command join type that data Unit and admit a program whose supplied value then fails admission.
  • Other producers get fresh grades: return, primitives, ~, capture, spawn, audit, ordinary builtin results and stdout redirects. Command declarations, boundary results and already graded builtin results such as fail and await are exceptions. The ordinary decoders from-bytes, from-string, from-line and from-lines have fresh result grades; their non-unit payloads hide those grades when printed as Returns.

The grade says how the result is produced, not whether anything is written: { echo pre; return 5 } prints pre and returns an integer. A free unit producer can unify with w without conversion. Once a let fixes it to p, it cannot stand as a command. return () and return $u for u : Unit obey the same rule.

Printing (§14.1) uses Command for w, Returns A for p, and Command[ν] A for an unresolved grade. A free grade whose paired type excludes unit prints Returns A too: a concrete non-unit type, or a quantified variable whose kind excludes unit. Only visible grades appear in ∀, named from ν ξ ο π. Thus { |x| return $x } has type ∀α ν. {α → Command[ν] α}. Handle_ε A keeps a suspended producer's grade; await : Handle_ε A -> F_ε A, printed with the same producer notation.

The checker is Hindley-Milner with unknowns in four sorts: value types, computation types, rows and grades. Let-bound names are generalized by rank (§17.5) and their quantified variables are instantiated freshly at use sites. There is no value restriction.

Ranks express ownership. The unit has rank zero. Entering a region raises the rank in force by one; a fresh unknown takes that rank. Every root, bound or free, retains a rank. Unification keeps the lower rank, and binding an unknown to a structure lowers all reachable unknowns to at most its rank. A suspended match likewise lowers everything it mentions to the rank of its scrutinee. In a region of rank r, an unknown of rank r is young; one of lower rank is old. A let right-hand side and its pattern form a region; so do a within arm and a recursive group. A lambda's lexical scope alone is not a region.

Weak means rank zero, not a propagated mark. A boundary — a place where a value of a shape the program did not decide enters typed code: the checked JSON/CSV decoders, env, the exarch host's answers, _ed-state — puts its result's unknowns at rank zero and records the result type on the call. No let generalizes rank zero, and unification lowers whatever meets it to zero. The result therefore has one type per unit. WeakSource retains provenance for mismatch notes; a scheme's weak roles list the value-, computation- and row-level rank-zero residuals it carries into another unit. Grades also have ranks, but a scheme has no weak grade: residual grades are settled before export, and what remains of them is quantified.

Once the unit is solved, the boundary's type is frozen as a site on the call, which admits the value against each position's head, each free variable's kind, and, for one comparable variable, number or text agreed across the unit. A session data binding with weak residuals is admitted once per unit, before its first phrase, against its solved type there; every use shares that type. A loaded file is a unit too, whether loaded by use or a host. Admission checks the environment supplied to that unit, not necessarily the session environment. A refusal runs no phrase and names the use that imposed the type, in the loaded file when that is where it was written. Residuals are re-seeded at rank zero in the next unit, preserving their kinds and sharing. A stored name cannot be used in a later unit if its scheme reaches a weak residual beneath a thunk or a handle. This includes a function's argument and result types, a handle's payload, and weak type, computation or row variables. The refusal is static, even if that unit would decide the shape. Define and use a decoder helper in one unit, or return text and decode it where its shape is used.

The rule follows recursive μ-equations from the scheme's body, retaining whether the path has entered a thunk or handle. A shared recursive type must be considered in both data and delayed contexts: [data: α, later: U(F α)] is refused if α reaches a weak residual, even though [data: α] alone can be readmitted. Unreachable μ-equations impose no delayed-use restriction. A decided function beside undecided data is allowed: [x: _α, f: U(F Int)] can be readmitted because its only weak residual is in existing data. Universally quantified parameters are not weak residuals and remain fresh at each instantiation. Only weak comparable identities acquire session-wide number-or-text fixings.

A recursive group is inferred once, at its first projection, in a region of its own: against monomorphic self-bindings, each member then generalized as the region closes. Every projection, the first included, instantiates its member's scheme, so no member's unknowns reach a sibling region and regions form a stack. Runtime-created top-level bindings carry closed schemes into later units.

A row variable carries a deep bit and a value-type variable a kind. The kinds form a chain under inclusion of the heads they admit: number ⊂ comparable ⊂ scalar ⊂ data ⊂ any. The unconstrained kind any admits every head and is not printed; the other four print as ∀α:number. …:

number       Int, Float                          + - * /, unary -
comparable   Int, Float, String                  < > <= >=, lt, gt, sort-list, int, float
scalar       Bool, Int, Float, String            each interpolation part
data (deep)  every head but U and Handle         == !=, str, the encoders

% is Int -> Int -> Int. Two variables unite at the smaller of their kinds, so no meet is empty, and since every kind admits at least two heads, none forces a type. Binding a kinded variable to a structure requires the structure's head to be admitted, and a deep kind imposes data on every component: a list or map element, the fields of a record and the payloads of a variant, and, through the tail row variable's deep bit, every field later added. A kinded variable still free at the end of a unit needs no default, since every admissible type supports the operation. Every read instead has one immediate unification rule (§4.7): a written label requires [label: α | ρ], a written position requires [α], and a computed key requires Map α with a String key. These are the core's proj, index and lookup, respectively. There is no deferred read constraint, shape default or index-made weak variable. nth : ∀α ν. Integer → [α] → Command[ν] α reads a computed list position without sacrificing polymorphism.

A stored scheme is closed over its whole graph: body and recursive equations. All variables are quantified, recursive roots, or listed weak residuals. A scheme leaves its unit only as Closed, constructed only by settlement, a builtin's own binder supply, or checked deserialization. Each sort has its own roles: a row has no recursive equation, since every cycle is rooted at a value or computation type, and a grade is only ever quantified. Cross-unit reseeding alpha-renames local binders and weak residuals simultaneously, without capture; settlement substitutes live weak-variable images and resolves residual grades through the whole graph, even with no weak variables, without interpreting local ∀/μ binder names as unifier slots. It quantifies remaining free grades. No environment free-variable scan or cached environment free-variable set participates in generalization.

The principal judgments are:

Γ ⊢v v : A                         value inference
Γ ⊢c M : C                         computation inference
Γ ⊢p p : A ⇒ Γ'                    pattern binding
Γ ⊢ M ⇝ C ; K                      inference with constraints K
K ⊢ C1 ~ C2                        unification

Generation, solving and readback are separate. Generation writes equations, instantiations, regions, the suspended matches of §17.5, weak τ (rank-zero lowering), and gate τ obligations. It builds a pending tree without resolving an unknown. Instantiation and the two matches return unknowns, not their solved heads; only syntax and declarations supply known structure. Stored schemes are inspected for cross-unit admissibility, not to select elaboration. An equation may report whether it held, solely to suppress a second complaint after the unit has already been refused.

The solver settles equations and matches while the unit is open. Holes are annotations of the IR's inferring phase: every let RHS carries a binding hole, and every application, a bare binding call included, a call hole. In the checked phase these annotations are empty, and a bare binding call cannot occur, so no hole survives in a checked tree. Discharging or defaulting a match records its decision on its hole (§17.5). Closure produces a read-only solution only when the unit has no errors and every hole is decided; readback applies those decisions, freezes sites and settles schemes. A refused unit exports neither a checked tree nor a stored scheme.

Types are regular trees, and every cycle crosses a data edge: a list element, a map element, a record field, or a variant payload. The edges U, ->, F and Handle are not data, so binding a variable to a structure that reaches it along those edges alone is refused, as in w $w, or a function that returns itself. A cyclic type prints as μβ. Map β.

A failed constraint records both the source span at which it was introduced and a provenance reason, such as argument application, pipeline stage shape, conditional branches, fallback branches, try arms, scope body, handler shape, or the handler a case arm names. Diagnostics render the structural mismatch together with that provenance; provenance does not change the unification relation. A match's branch failure is blamed at its binding or application, under Reason::Binding or Reason::Call. A default also retains the span at which it was chosen (defaulted_at) and explains which head nothing in the enclosing definition established. Errors are stably sorted by source span at unit closure; their discovery order is not their report order. Diagnostic wording and blame need not be independent of constraint order.

Representative rules are:

Γ ⊢v v : A
---------------------------- Return
Γ ⊢c return v : F_ν A       ν fresh

Γ ⊢v v : U C
---------------------------- Force
Γ ⊢c force v : C

Γ, p:A ⊢c M : C
---------------------------- Lambda
Γ ⊢c lambda p.M : A -> C

Γ ⊢c M : A -> C    Γ ⊢v v : A
-------------------------------- App
Γ ⊢c M v : C

App is the rule for an explicit core application. Source application also allows returned thunks; generation uses apply C A D (§17.5), and readback inserts the explicit forces and binds needed to reach this rule. Checking a lambda against an expected computation writes expected ≐ A -> D with fresh A and D before checking its body under the monomorphic parameter A. Other computations are generated, then equated with the expectation; no rule reads a solved head to decide how to check.

Pattern inference recursively constrains list elements to one element type, record fields to their labelled types, and a list rest name to List A. A binding generalizes its bound value as §17.5's Let says.

Heads and commands. A bare head c has one static class, decided by Σ and lexical bindings alone. Runtime dispatch (§6.3, §9.5) may select a handler without changing that class:

class(c) = binding(σ)     c is a lexical or session binding, of scheme σ
         | row(σ)         c is a builtin value row, of scheme σ
         | base-frame     Σ declares c as an argv row
         | external       otherwise, and always for ^c, ./p and ~/p

A row's scheme says what it produces. The rows that write — the encoders (to-json, to-string, to-line, to-lines, to-jsonl, to-csv, to-bytes, ints-to-bytes), help, explain, clear and reset — end in Command, and a row writes only when applied at its full arity: to-json alone is a function, and to-json $x is a command. The rest end in freshly graded returners, with warn among them: stderr is not the byte channel. Boundary results remain p. map, each, fold, fold-lines and audit run a body of either grade, stream its output and keep its value; filter and sort-list-by demand value-returning callbacks. watch, like the spawn form, keeps the body's grade in the Handle_ε A it returns, and await and race give it back (§11.2); fail, raise, exit and diverges inhabit every grade. Every base frame, including echo, is [String] → Command by construction. A handler does not change the answer: every handler has the constant command type of §17.7. An arm for the name of a value row is never reached, because builtins resolve first.

A command takes an argv and produces output:

class(c) = external    Γ ⊢ ā : argv
------------------------------------- Ext
Γ ⊢c c ā : Command

class(c) = base-frame    Γ ⊢ ā : argv_in-shell
-------------------------------------------- Base-frame
Γ ⊢c c ā : Command

class(c) = row(σ)    σ ⊑ A1 -> ... -> An -> C    Γ ⊢v ai : Ai
--------------------------------------------------------------- Row
Γ ⊢c c a1 ... an : C

Γ ⊢ ā : argv and Γ ⊢ ā : argv_in-shell require text rendering and list-valued spreads, with the external and in-shell gates of §6.6 respectively. For a single argv argument, generation records gate τ rather than deciding from the head known at that visit. After rank-zero defaults at unit closure, the gate judges the final head: Unit is refused for all argv calls; bytes, lists, records, maps, thunks and handles are additionally refused at the OS boundary. A head still free leaves the question to the runtime check (§6.6). The gate imposes no kind and does not constrain a parameter at every later instantiation. Thus { |x| echo $x; return [$x, ()] } is refused statically, as is its statement transposition: both solve x to Unit before the gate.

Every nonempty redirect list requires Γ ⊢c M : F_ε A at the outermost computation: a function still awaiting arguments is refused, rather than redirecting its eventual result. Redirect operands are checked in both fused calls and redirect scopes. Generation writes C ≐ F_ε A with fresh ε and A rather than inspecting C's current head. A redirect of standard output has type F_ν A for a fresh ν: its bytes go to the file, and the payload type is preserved. This does not constrain ε; other uses of M retain its original grade. Stdin and stderr redirects, and 2>&1, leave the grade alone.

17.4. Pipe composition and sequences

A | is an operating-system byte wire fixed by stage position. A stage feeds the next by writing, so every stage but the last has type F_ε Unit for some grade ε, and is not a decoder; the pipeline's value is the final stage's. A stage after a pipe binds no standard input at its own root.

Γ ⊢c Mi : F_εi Unit    Mi is no decoder    (1 ≤ i < n)    Γ ⊢c Mn : F_ε A
Mi binds no stdin at its root, for 1 < i ≤ n
------------------------------------------------------------------------------ Pipe
Γ ⊢c M1 | ... | Mn : F_ε A

A decoder (from-bytes, from-string, from-line, from-lines, from-json, from-jsonl, from-csv, from-json-at) returns a value and writes nothing, so it ends the byte pipeline. It is refused as a non-final stage by its own mark, before its type is read: for a boundary ∀α. Returns α unification would otherwise set α := Unit and let cat data.json | from-json | wc -l through to fail at the decode. '3' | cat and [1, 2, 3] | f are refused because a value in stage position writes nothing to the pipe; each { |x| echo $x } $xs | cat is accepted, since each streams what its body writes. A stage whose type is A -> C is still waiting for an argument and is rejected as well, and the diagnostic says to apply it rather than pipe into it. Generation requires each stage C to satisfy C ≐ F_ε A with fresh ε and A; the non-final payload additionally satisfies A ≐ Unit. These are equations, not decisions made from a partially solved type. A stage whose root carries < f or << value is rejected: the feed answers that stage's reads for its whole run, so the producer before it writes for nobody (§7.4). Each premise reads one stage, never a pair.

Operationally, M | N:

  1. connects stdout(M) to stdin(N) with an operating-system byte pipe;
  2. runs both stages under the process discipline of §7.1;
  3. takes its value from N.

Neither side promises traffic. A producer that writes nothing yields an ordinary end of input; a consumer that never reads leaves the bytes unread, and once it ends, ral ends the blocked producer itself (§7.6). No returned value is ever placed on a wire, and no implicit codec is inserted at an edge. Value-style composition uses the ordinary application and bind rules instead.

The final stage is not held to Unit, so a block literal there is well typed: it is a value, and the stage returns a thunk and writes nothing.

cat f | { from-line }    # accepted: f's bytes go unread, the thunk is returned
cat f | !{ from-line }   # accepted: the block runs as a stage and decodes them

The first does nothing and is not diagnosed; no rule in ral inspects how a stage was spelled to decide whether a pipeline is well formed.

A sequence is its tail:

Γ ⊢c M : F_ε A    Γ ⊢c N : C
----------------------------- Seq
Γ ⊢c M ; N : C

Every earlier element runs for its effects. Its value is discarded, it is never captured, and what it writes goes to the current standard output, which inside a capture is the capture's buffer and inside a non-final pipeline stage is that stage's pipe. A sequence whose final element is a function is that function.

The diverging forms are fail, raise and exit/quit. None returns, so each takes whatever type and grade its context asks of it: in if c { exit 1 } else { return 'hello' } the conditional is F_ν String for a fresh ν, printed Returns String. Divergence is a typing fact only; exit remains a control escape that ? and try do not catch (§8.8).

17.5. Capture at a binding boundary

Only a binding implicitly turns output into a value. Binding and application are suspended matches: they wait for the head of a computation type, then add the equations of that branch. Generation cannot choose from a partially solved type. Here τ ranges over value types, β is a computation unknown, ν a grade, and ≐ is an equation in the appropriate sort.

bound τ C = match C {
    A -> D  => τ ≐ U (A -> D)                     -- to-box: run
  | F_ν A   => match ν {
                   p => τ ≐ A                    -- run
                 | w => τ ≐ String               -- capture
               }
}

apply C A D = match C {
    A' -> D' => A ≐ A', D ≐ D'                    -- no split
  | F_ν B    => B ≐ U β; apply β A D              -- one split, β fresh
}

The value-producing binding rules are CBPV's to and its boxing case:

Γ ⊢c M : F_p A    Γ, x : A ⊢c N : D
------------------------------------- to
Γ ⊢c M to x. N : D

Γ ⊢c M : A -> C    Γ, x : U (A -> C) ⊢c N : D
----------------------------------------------- to-box
Γ ⊢c M to x. N : D

Both run M; to-box binds the residual function as a block. Output-producing bindings use capture below. A guard's acquisition is the one other binding boundary: its resource is bound τ C without the to-box branch, so the checked Guard rule (§17.7) only ever sees F_p R.

bound τ C relates the type C of a right-hand side to the type τ of its bound value. It never reads τ to decide a branch. For F_ν A with ν free, there is one entailed improvement: if A excludes Unit, set ν ≐ p and run for A. A excludes Unit when it has another head, or is an unknown whose kind does not admit Unit. This follows from F_w A ⇒ A = Unit, not from a default. Otherwise the match waits for ν. In particular, τ ≐ String beside bound τ (F_ν Unit) does not select capture: the branch may not justify its own scrutinee.

apply C A D relates a head C, an argument A and a result D. An arrow consumes the argument directly. A producer cannot consume it: its payload must be a thunk U β, and application continues at β. If the payload is not a thunk, that equation fails. Readback inserts M to h. force h v before this argument, a split; several returned thunks can require several splits before one argument. Peeling terminates because cycles through F and U alone are refused (§17.3). An n-argument call generates n matches in a left-to-right chain, each result becoming the next head. Builtins within their declared arity have a known arrow spine and need only equations.

A match discharges at a known head only when its scrutinee has that head in every solution of its owning region's constraints, with suspended matches set aside. There is no backward reading of a branch and no propagation from an instance back into its definition. The solver repeatedly discharges known heads and lowers everything mentioned by each remaining match to its scrutinee's rank. At rest, every suspended scrutinee is an unknown: β, or the grade ν of a binding. A binding mentions its right-hand side and binder; an application mentions its head, argument and result.

Defaults are simultaneous at region closure. First settle the region. Collect all still-suspended matches on young scrutinees (rank r in a closing region of rank r), identifying scrutinees by their canonical roots. Compute the following defaults before adding any of their equations:

suspended match default equations elaboration
apply β A D β ≐ A -> D no split
bound τ β β ≐ F_p α, τ ≐ α, with α fresh run
bound τ (F_ν A) ν ≐ p, τ ≐ A run

Add that one set of equations together, then settle again. No default creates a new match; any match awakened into further suspension has an old scrutinee, so one round suffices. A successful region leaves no young match suspended. A match on an old scrutinee remains for the region of that scrutinee's rank, even if its binding is inside a region that has already closed. Lowering its binder, argument and result prevents premature generalization. Nothing outside a successfully closed region can later choose an elaboration for one of its quantified unknowns: instantiation copies them.

If a canonical scrutinee has both bound and apply waiting on it, their defaults disagree. Neither is prioritized: the region is refused with ConflictingDefaults (T0080), citing both uses and both explicit readings, named by the variable the binding forces or the call applies when there is one. For example, this is refused in either statement order:

{ |f| let a = !$f; let b = f 1; return $b }

Choose the intended reading explicitly:

{ |f| let a = $f; let b = f 1; return $b }  # f : {Integer -> Returns α}
{ |f| let h = !$f; let b = h 1; return $b } # f : {Returns {Integer -> Returns α}}

Those type comments show the defaulted readings. A failed default equation is also an error. Recovery retires rejected or otherwise unresolved young matches without selecting branches and restores the enclosing rank; this supplies no typing or elaboration result, and a refused unit is never read back.

Generalization is by rank. At an enclosing rank r, let q = M; N first opens rank r+1 around inference of M : C, bound τ C with τ fresh, and the pattern q at τ, collecting the pattern's binder types. It closes that region before generalizing any binder. Schematically, the first line is generated inside that region; the rest follows its successful closure:

Γ ⊢c M : C    bound τ C    Γ ⊢p q : τ ⇒ Δ
σx = Gen_Γ(Δ(x))  (x ∈ names(q))    Γ, {x:σx | x ∈ names(q)} ⊢c N : D
-------------------------------------------------------------------- Let
Γ ⊢c let q = M ; N : D

For each collected type A, Gen_Γ(A) means:

Gen_Γ(A) = ∀ { a ∈ FV(A) | rank(a) > r }. A

Here FV follows the solved type graph, in all four sorts; kinds and recursive equations are retained in the scheme (§17.3). This is not subtraction of FV(Γ): the subscript records the enclosing context at rank r, not an environment scan. The quantified unknowns are those still owned by the just-closed region. Rank-zero unknowns and unknowns lowered to an enclosing region are not quantified. All pattern types are constrained before any binder is generalized. N is then inferred with those schemes, freshly instantiated at each use.

For example, let k = { |g| g 1 } defaults g's unknown computation head to an arrow without choosing the result computation's head or grade. let v = g 1 also creates a binding match on the result: it waits for the owning region and, if still undecided there, defaults to a value producer. A grade disagreement elsewhere remains a mismatch of Command against Returns A.

A unit closes rank zero. A unit is one typecheck session, or one of the one-shot sessions arm_stands_in and binding_value_scheme. A top-level Run opens no region: its unknowns are rank zero, all its remaining matches default at unit closure, and its report is never captured. A REPL phrase is a unit whose predecessors are closed schemes; a script can therefore refuse shared boundary uses that separate REPL units admit (§17.3).

A one-shot session seeds its environment at rank zero and enters a region before inferring or checking its body. It exits that region, generalizes any scheme to be stored at enclosing rank zero, then closes the unit. Only success settles and exports the scheme; arm_stands_in stores none. Opening a region around an already inferred type is too late. The unit's phases have this order:

  1. Generate equations and the pending tree on Solver, checking any host-file options as ordinary uses (§15.3).
  2. Close the unit (Solver → Solution): close rank zero, deciding every remaining binding mode and call split, then check gates (§17.3) and errors, attaching () notes. No suspended elaboration match remains, and only an error-free unit yields a solution.
  3. Freeze sites, schemes and readmissions by readback from that solution.

Table checks finish during generation, not in a deferred or scratch walk. The declared table itself is never unified as a record type.

Readback makes the chosen branch explicit. A match records its decision on its hole when it is discharged or defaulted: a binding its mode (run, capture), an argument each split it performs. Readback elaborates from these decisions alone; it never re-reads a head. The binding modes elaborate M respectively to M (Let) or ⌈M⌉ (Let-cap). The arrow branch of bound is a typing case only; no hole chooses thunking. The checker inserts these terms, which no program can name:

Γ ⊢c M : F_w Unit                      Γ ⊢v v : Bytes
------------------------- Cap          -------------------------------- Decode
Γ ⊢c capture M : F_ν Bytes             Γ ⊢c decode v : F_ξ String
                  ν fresh                                ξ fresh

⌈M⌉ = capture M to d . decode d        the capture and decoding of a command

capture M returns the exact bytes written by M, ignoring its unit value. decode drops one trailing LF or CRLF and strictly decodes UTF-8, as from-line does; invalid UTF-8 is an error naming from-bytes as the way to keep binary data. These internal producer grades are fresh; they do not choose the binding branch.

This is the sole coercion: let x = M captures the whole RHS exactly when it resolves to F_w Unit. Arguments, control-flow arms and handler arms only unify with their demands. They are not wrapped or implicitly captured. A value-position !{…} is a hoisted let, so it follows the binding rule too. The user-facing rule is §6.8's: a command's value is its output; a let binds it. The elaborator's hoists are ordinary binds, so let x = cat f | grep "a$p" captures the pipeline, and "today: !{date +%F}" interpolates the date. let _ = cmd captures and drops: a surface _ is a fresh name, not a discard.

The intended independence property is that constraint traversal or solving order does not change acceptance or a successful checked tree. Defaults are choices, so no principal-elaboration claim follows. This account is not a mechanized soundness or independence proof.

With let add = { |a b| return $[$a + $b] }, the binding let g = try { echo body-ran; fail boom; add 1 } { |e| add 2 } prints body-ran at the let; g 3 later returns 5, outside that try. The binding let g = if true { fail boom; add 1 } else { add 2 } fails at the let with boom; a following statement does not run. A right-hand side of type A -> C runs like any other; running stops at the first λ that finds no argument, which is bound as a block (§17.8, Box).

A discarded statement is never captured on its own. The whole captured computation is one buffer, so let x = !{ echo a; echo b } prints nothing and binds "a\nb", while let x = !{ let y = echo a; echo b } prints nothing and binds b, the inner let capturing a. A stand-in dispatched for the captured command runs whole under the capture: under let x = curl, the arm curl: { |a| echo note; echo body } binds "note\nbody".

audit absorbs its body: audit { grep -c ERROR app.log } has type F_ν Report(Unit) for a fresh ν and outcome `ok (), while the bytes its body wrote sit in the trail's observations. map, each, fold and fold-lines absorb a command body likewise: they run it, stream its output, and keep its value, which for a command is (). spawn and watch do not absorb: the handle keeps the body's grade, so let x = await $h binds what a command block wrote, as let x = !{ … } would.

17.6. Branch and variant rules

Every form that takes a suspended command takes a thunk, and forces the one it chooses. A literal { … } is that thunk, so if $c { echo hi } else { () } and if $c $yes else $no are one rule; an arm is a block or a name, and any other atom is refused at elaboration (§17.1). The arms are joined by the rule below:

Γ ⊢v v : Bool    Γ ⊢v T : U C    Γ ⊢v E : U C
---------------------------------------------- If
Γ ⊢c if v T E : C

Γ ⊢v v : Variant(`l1 : A1, ..., `ln : An)    Γ ⊢v Hi : U (Ai -> C)    (1 ≤ i ≤ n)
--------------------------------------------------------------------------------- Case
Γ ⊢c case v of {`l1 H1, ..., `ln Hn} : C

Γ ⊢v T : U C    Γ ⊢v H : U (Error -> C)
---------------------------------------- Try
Γ ⊢c try T H : C

Here C is the join of arm result types R1 ... Rn, after the arm's parameters. Each arm is checked against its own fresh result, then each result is equated with C. A case first equates its scrutinee with Variant ρ and ρ with the closed row of arm labels at fresh payload types. Those equations supply the payloads to the arms before their bodies are checked; they do not require a read of the scrutinee's current type.

Ordinary generation checks and joins arms in source order for diagnostic blame; a failed join blames the later arm. That traversal order does not select a coercion or a verdict. An unresolved binding or application inside an arm follows §17.5: a match on an old scrutinee can remain pending across an inner let and be decided by equations elsewhere in the owning region.

if $c { hostname } else { echo b } is one Command, captured once by an enclosing let. A command and a returned value do not join, even if that value is text: try { fetch } { |e| return 'none' } is refused. Write try { return !{fetch} } { |e| return 'none' } to return text in both outcomes. For Bool, use succeeds { … }; for other data, decode or return the required value, or write values out with echo so all arms are commands.

A fresh unit producer can join either grade. Thus if $c { echo hi } else { return () } is a command. A unit producer whose grade has already been fixed to p in a closed definition cannot join the command: let twice = { |f| let _ = !$f; !$f } defaults its callback to p when twice's right-hand-side region closes, so if $c { twice { return () } } else { echo a } is refused. End the first arm with return () to give it a fresh unit producer.

That is distinct from an inner binding waiting on an enclosing parameter:

let g = { |f| let y = !$f; if true { !$f } else { echo a } }

The match for y is old at the inner binding's close. The join establishes f's computation as a command in g's region, so y captures. Moving that join before the binding does not change the choice. Uses of y do not choose its branch: { |f| if true { !$f } else { return () }; let y = !$f; upper $y } is refused, not made into a capture by upper's demand for text.

guard, within and grant preserve their body's type and grade (§17.7). For guard, this is the computation obtained by applying the body to the acquired resource, not the acquisition's or release's result. Additional elsif arms nest, each else holding the next if as a thunk. A conditional without else wraps its arm as { body; () }, returning unit at a fresh grade; the body's output goes to the current sink. M ? N is try M { |_| N } and follows the same join rule. In let x = if $c { echo hi } else { () }, the else arm unifies as a command and the enclosing binding captures "" when it runs.

The Case rule closes the scrutinee's row to exactly the arms' tags, which the syntax fixes: coverage is therefore decided wherever the rule fires, and both a tag the arms miss and an arm for a tag the scrutinee cannot carry are static errors. An open scrutinee row instead absorbs an arm label it has not been seen to construct — that is principal row inference (§17.3), not a gap in the coverage proof. case applies the chosen arm to the payload, () for a nullary tag.

17.7. Scope signatures and stand-in arms

Let Error be the closed error record {frame:String, message:String, status:Int, site:S}, where S = {script:String, line:Int, col:Int} — the one vocabulary try, poll, and audit all report failure in (§8.6). The scope forms take their bodies as thunks and are typed by them. Let ExitCase = <`ok Unit | `err Error | `exited Int | `stopped CancelCause>; CancelCause is §11.4's Cause. Unlike a worker's Ending there, ExitCase has no panic arm.

body : U (F_ε A)
------------------------------ Within / Grant
within opts body : F_ε A
grant  caps body : F_ε A

acquire : U (F_p R)    body : U (R -> F_ε A)
release : U (R -> ExitCase -> F_μ B)
------------------------------------------------ Guard
guard acquire body release : F_ε A

body : U (F_ε A)
------------------------------ Audit
audit body : F_ν {outcome : <`ok A | `err Error>, trail : List Observation}

title : String    body : U (F_ε A)
------------------------------ Spawn
spawn [title] body : F_ν (Handle_ε A)

body : U (F_ε A)
------------------------------ Gather
gather body : F_ε A

audit and spawn have fresh result grades ν, independent of the body's ε. spawn's title is optional; the handle keeps the body's grade (§11.2). gather passes its body's type through, grade included: joining its workers is a run-time effect that changes no type (§11.3).

try is §17.6's rule. within, grant and guard have their body's type, grade included. guard's acquisition must produce the resource type R. Its body accepts R; its release accepts R and the closed ExitCase, and must produce a value of any type B. The release runs for its effects and halts alone: its value is discarded, what it writes goes to the current output, and its type and grade are not joined with the body's. The scope-body, handler-shape, and arm-result constraints are equations against fresh shape unknowns and retain ordinary diagnostic provenance and source spans. Scope bodies preserve types without reading a partial solution.

within checks its options as one spread-free record node, as grant does. Option names must be written; their values are ordinary computed values. Unknown, repeated, spread, or dynamic option keys are refused before execution. handlers: is a map: a written map is checked entry by entry, each arm inside its own region, closed without generalizing or storing a scheme. A match on an old scrutinee still belongs to the enclosing region (§17.5). Written map labels are imported while checking the body for diagnostics alone; a computed map imports none. The catch-all is likewise checked in a region. Other handlers: values take one equation against Map(U([String] → Command)). Rc and manifest maps use the same arm-by-arm or whole-map check (§15.3). grant checks known capability fields.

Every named handler has one type, independent of its name and Σ. The catch-all adds the command name as its first parameter. Command is F_w Unit:

Γ ⊢v M : Map (U ([String] -> Command))          Γ ⊢v V : U (String -> [String] -> Command)
-------------------------------------- Handlers  ------------------------------------------ Catch-all
Γ ⊢ [handlers : M] ok                            Γ ⊢ [handler : V] ok

Σ declares c as a base frame  ⟹  Σ(c) = [String] -> Command

A written map [:, c : V, …] is checked entry by entry: Γ ⊢v V : U ([String] -> Command) for each entry. This is the same judgement with a diagnostic per handler. Every argv manifest row has this type by construction: it carries no type rule, so a host cannot declare a base frame with another result.

A handler's value is its output: curl: { |args| echo '{"ok":1}' } is an arm, and curl: { |args| '{"ok":1}' } is refused, since it returns a String where it should write. An arm returning () at a free grade unifies as a command, and under let x = curl captures "". A unit producer already fixed to p is refused; handler arms do not coerce. The rule is identical for echo and all other names. detach is a first-class builtin: an arm named detach must be a command, not return a receipt, and is never reached because the value binding wins. Stub detach by binding its name (§11.5). A call through an arm types as its head does. The catch-all has the same command result, so { |name args| cd $name } is valid. A host-installed persistent arm is checked by the same rule when it is installed. Generation first equates the arm with a thunk taking the slot's parameters and producing a fresh result, then equates that result with Command. The name affects diagnostics only. Generation does not coerce the arm or inspect a partial solution. An equation's success flag only suppresses a second complaint when the slot shape has already failed. The constraint is on the arm's type, never its spelling: { forward 'git' } is an arm when forward 'git' is a function of the argv, and { echo hi }, whose type takes no parameter, is not. For persistent handlers only (rc, manifest), the install-time one-shot check must close successfully before installation (§17.5); it returns only a verdict, never a stored handler scheme. within's static check is total and needs no install-time re-vet. Session checking imports handled names for diagnostics alone.

17.8. Operational outcomes

Evaluation is a small-step machine over a computation closure and a stack of frames, or a break over that stack:

⟨M, Γ⟩ / κ, Σ  ⟶  ⟨N, Γ'⟩ / κ', Σ'
X / κ, Σ                          (climbs to the first frame whose rule catches it)
v ⇓ κ, Σ                          (a value handed to its frame within the transition)
  • A runtime value is a value closure ⟨v, Γ⟩ whose root is not a variable. Every direct name — one outside a thunk — is bound in Γ. Forming a value restricts Γ to the names it mentions and captures any missing direct name from the signature. Reading a component shares that Γ; it does not restrict it again. Scalar, builtin and handle constructors use empty captures.
  • The machine stores only ⟨M, Γ⟩ or a break X. A rule producing a value hands it to the frame below in the same transition, through any restoring frames, until a computation resumes or the stack empties. The ⇓ notation denotes this handoff, not a stored value state; no runtime return v is constructed for it.
  • κ holds pending binds, sequences, arguments and scopes. Bind and sequence frames carry their resumption environment, so a binder's extent is structural. Application pushes one Arg per argument, right to left, before evaluating its computation head. Forcing a thunk enters its computation and pushes nothing: force(thunk M) = M. A lambda consumes one argument frame and enters its body in tail position. Depth counts computational frames, not provenance-only restoration frames. Pushing n arguments needs n free frames at entry.
  • Σ supplies the host signature and dynamic shell state: current directory, environment overrides, handlers, capabilities and audit state. Lexical bindings live in Γ; the signature supplies fallback names.
  • A lambda is a computation, not a value (§17.2). An Arg consumes it by β. Restoring frames preserve its computation closure; a value-demanding frame or the empty stack boxes it as ⟨thunk (λx.M), Γ|occ(λx.M)⟩. No rule applies a returned value or forces implicitly; the checker writes application through a returned thunk as M to h. force h v.
  • X is error e or escape q, where q is exit n or a stop (§8.10). A break climbs κ past frames whose rules do not catch it, each closing what it opened. try and ? catch ordinary errors; escapes reach their owning boundary.

Box is the rule for a lambda that finds no argument:

λx.M ; V :: K                 ⟶ M[V/x] ; K                       β
λx.M ; ([·] to y. N) :: K     ⟶ N[thunk (λx.M) / y] ; K          Box
λx.M ; ε                     final: thunk (λx.M)                 Box at run end

With environments, the box is ⟨thunk (λx.M), Γ|occ(λx.M)⟩: it retains the arguments supplied so far and only the names its code mentions. A tail call still consumes its caller's remaining arguments.

Forcing a builtin c of arity n enters its η-expansion, binding the builtin itself rather than looking its name up in the host signature:

force (builtin c)  ⟶  ⟨λa₀.…λaₙ₋₁. δ(b; a⃗), {b ↦ c}⟩
⟨δ(b; a⃗), Γ⟩ / κ, Σ  ⟶  run Γ(b) [Γ(a₀), …, Γ(aₙ₋₁)] ⇓ κ, Σ

Application is ordinary β. An under-applied builtin is a residual lambda, boxed by the same rule as any other lambda. Its runtime type_name is Lambda; its display retains the native name and supplied-argument count (§6.5). A call holding exactly the builtin's arity runs its body directly; forcing an arity-zero builtin runs it without arguments.

A partial builtin crosses the child-shell wire as a thunk, with its supplied arguments captured in Γ and its builtin entry encoded by name. Boundary builtins remain inference-built λ-closures over Exec with their per-use checked site; that site crosses as IR.

The central continuation rules are:

⟨return v, Γ⟩ / κ, Σ  ⟶  close(v, Γ, Σ) ⇓ κ, Σ

⟨M to p.N, Γ⟩ / κ, Σ  ⟶  ⟨M, Γ⟩ / (to p.N, Γ) :: κ, Σ      To-push
v ⇓ (to p.N, Γ) :: κ, Σ  ⟶  ⟨N, Γ[p ↦ v]⟩ / κ, Σ            To-return
error e / (to p.N, Γ) :: κ, Σ  ⟶  error e / κ, Σ             Propagate

M to p.N pushes its frame before M runs, carrying the environment N resumes under; p ↦ v is built from that frame's own Γ when M returns, so p scopes over N alone. A sequence M;N pushes its own frame, discards M's returned value and continues with N under the saved environment. It evaluates left to right, stops on the first error or escape, and its value is its last statement's. A written let _ is a pattern bind. if evaluates its Boolean condition and forces only the chosen arm, in place and over the same Γ: a literal thunk runs with the current environment and closes nothing. case evaluates the scrutinee, selects the arm carrying its tag, pushes an Arg frame holding the payload, () for a nullary tag, and forces the arm. The arm is a branch and not an ordinary function call: it runs in the ambient shell context, so the arm's own effects on the shell outlive the case.

Recursion is one n-ary computation, Rec: letrec {xi = vi} binds every group member's name to the thunk of its own projection and enters the chosen member; a recursive reference forces its name, which re-enters Rec and re-extends from the outer Γ. No body is ever rewritten; a group of one is Levy's rec f. M.

A Define at the top level — let x = v outside any block — extends the session environment, not a frame's: it is installed as it is reached, so a later top-level phrase sees it, and a run that halts has installed exactly the Defines that ran before the halt.

Before its first phrase, a unit readmits imported residual data at the type that unit solved (§17.3). It does not force a thunk or consume a handle to do so. A weak residual beneath either is a static refusal, not an obligation postponed to a call or an await. Admission of a thunk checks only that it is a function value: the defining unit checked its body, and no undecided shape beneath it can be imported. Boundaries return first-order data (§7.3), never functions or handles. No continuation frame checks a returned value against a type contract.

The stack is capped: a rule that would push a frame first checks |κ| < stack_limit (session.stack_limit, default 100 000, the --recursion-limit / rc recursion-limit: knob) and raises rather than pushing, before any effect the frame would hold undo for — a sink swap, a redirect's file open, a capability push — so a refused push commits nothing.

A ral-written pipeline stage starts this machine fresh, over the empty stack, on a worker thread; an external stage is a process. The parent's Pipeline rule launches the group, joins its outcomes and returns the final stage's value to its own κ. No frame stands for the running group or crosses a stage boundary. Bytes cross by the wiring of §7.1; lexical bindings travel as a persistent environment, not as continuation frames.

For try body handler, a body value is returned unchanged. A body error is converted to E and passed to the handler. An escape bypasses the handler. Standard output and standard error remain live; try does not capture them.

M ? N elaborates to try M { |_| N } (§8.4), so a value from M wins, an ordinary error from M runs N, and an escape from M propagates. A longer chain M1 ? ... ? Mn nests the same way, right-associated, so it reports the last error when every arm fails.

For guard acquire body release, entry reserves room for three frames before any effect, then polls once for a pending stop. It shields and forces acquire under an Acquire frame. An acquisition halt restores the previous scope and propagates without release. On a value r, it restores the scope, pushes Guard holding release and r, and applies body to r: no poll can occur before that frame is installed. The entry reservation makes every later guard-frame or argument-frame push infallible.

A body value, error, exit, or stop pops Guard, raises the shield, and pushes Cleanup holding the body's outcome and previous scope. It applies release to r and the outcome's ExitCase (§17.7). A release value restores the scope and resumes the saved outcome unchanged; a release error or escape restores the scope and takes priority. Acquire and Cleanup also restore their scopes when abandoned during panic unwinding, but no release runs for a panic. Both shields share the same strike-based grace (§8.7), not fresh budgets.

audit body opens a trail and evaluates body with it active, then returns the report: the body's outcome, `ok of its value or `err of E, beside the trail. An ordinary body error settles into `err; an escape propagates past the report. Within the trail, `command observations are recorded only for external or bundled commands and detach births; a builtin application is not an observation, and its effects are recorded at the sites they pass through (§13.3). User-function application, control scopes, and iteration machinery are transparent: they record no observation of their own, while the commands, reads, and writes reached inside them remain visible.

Observations are appended in settlement order, so a command's observation lands after any observations produced within its extent; the start–end intervals, not the list structure, recover which extent contained which.

A `check observation is a distinct tag from a `command. The in-process guards record every filesystem and execution denial while a trail is open, and no allowed check ever; entering a capability layer may also record a flagged confused-deputy prefix. With no trail open, capability checks add no observations.

fail m requires a String and raises a failure of message m and status 1 at the innermost visible operation frame, including its own. raise e requires the closed error record, raised as the program's claim as given, whatever its origin (§8.5). exit n raises an exit escape and is not caught by ? or try.

Cancellation is polled at evaluator and process boundaries. A poll of a cancelled scope raises a stop escape carrying the strongest cause. The run boundary polls again after evaluation, so recovery inside a final try cannot settle a cancelled run successfully. External children are torn down and reaped before their cancelled computation returns.

17.9. Grounding and execution

Each inference rule builds its pending node beside its type. A binding or call node carries its hole (§17.3); boundary calls are saturated or η-expanded at their inference rule and carry their result type. A stored name whose scheme delays a weak residual is refused at its use in a later unit (§17.3). An admitted residual occurrence remains a plain variable.

Once generation and closure (including gates) succeed, one fold reads the tree back in the checked phase. A binding hole becomes Let or capture/decode (§17.5); a call hole becomes returned-thunk bind/force segments before the recorded arguments. Boundary types become site snapshots. Frozen sites may retain free weak variables; they need not be ground. A readmission site may also contain a decided function beside undecided data. One unit identity serves all site snapshots and the first-use readmissions in Toplevel.admits. Re-checking a checked tree accepts it and inserts no further elaboration; raw variable ids are not canonical, so the re-checked tree need not be equal to it. Readmissions precede execution and are distinct from diagnostics for names bound to unit-valued calls. The runtime builds no IR for a contract.

Readback applies settle_weak to the schemes carried by each Phrase::Define, producing closed schemes. It makes no capture or type-inference decisions of its own. Inference and readback each memoise recursive groups by Arc identity, so their projections share one group. A unit with errors is refused whole and its pending IR discarded; one-shot inference sessions also discard their pending IR. Pipelines carry no per-stage type annotations.

The machine decides nothing about capture: it runs the capture the checker wrote. The capture frame has three rules, with buf a fresh buffer and prev the standard-output sink it replaces:

⟨capture M, Γ⟩ / κ, Σ   ⟶  ⟨M, Γ⟩ / (cap prev) :: κ, Σ[stdout ↦ buf]            Cap-push
v ⇓ (cap prev) :: κ, Σ       ⟶  bytes(buf) ⇓ κ, Σ[stdout ↦ prev]               Cap-return
X / (cap prev) :: κ, Σ        ⟶  X / κ, Σ[stdout ↦ prev]                          Cap-halt

Cap-return ignores v. Cap-halt drops buf: a capture that does not become its value commits nothing, and an error halting through it records the number of bytes dropped. A buffer that grows past 16 MiB is an error, and it halts by Cap-halt. Everything the body writes goes to the buffer — a command's output, a stand-in's every statement, a pipeline's final stage — because everything the body writes is the command's output. A discarded statement writes to the current standard output, which inside a capture is the buffer. A captured final pipeline stage is a capture node, so it runs as a thread stage: its standard input is the pipe and its buffer takes what the command writes.

A handler arm dispatched under a capture runs where the command would have run, so its writes land in the buffer.

Evaluation begins only from this finalized checked IR. A type mismatch is therefore a static error, not a request for the runtime to guess a codec. Runtime checks remain for genuinely dynamic facts: missing record keys, bounds, dynamic option maps, operating-system failures, cancellation, and external exit statuses. A case is not among them: its alternatives are syntax, so its coverage is settled here.