# Margeux Documentation

The single reference for learning, writing, checking, running, packaging, embedding, and deploying Margeux applications. It also documents every maintained language contract and bundled standard-library module.

## Learn: Welcome to Margeux


Margeux is an indentation-native, Lisp-shaped language for applications,
tools, games, servers, and terminal interfaces. Calls use prefix notation,
indentation supplies structure, ordinary local types are inferred, and one
bytecode VM runs the same programs natively and in browsers.

This guide is the practical, sequential manual for Margeux 0.1. It brings the
ordinary language, application model, standard facilities, tools, and runtime
together in one place. The focused specifications remain authoritative where a
host or wire-level detail matters.

## Learn: 1. Getting started

### Install the SDK

Download the SDK for your platform, extract it, and run its installer. You can
also use `bin/margeux` directly from the extracted directory.

Verify the command:

```console
$ margeux version
```

Create a project:

```console
$ margeux new hello
$ cd hello
$ margeux check main.mgx
$ margeux run main.mgx
```

`margeux check` performs parsing, name resolution, type checking, module
resolution, and application validation without running the program. `run`
compiles to Margeux bytecode and executes that bytecode on the canonical VM.

### Your first program

```margeux
def greeting [name]
  "Hello, {name}!"

def view []
  main
    h1 (greeting "Margeux")
    p "Change the source, then run it again."

app Hello
```

The final `app` declaration makes the zero-argument `view` function the GUI
application's view. The explicit long form is useful when an application has
state or events; you will use it later in this guide.

### The core idea

Margeux expressions are shaped like Lisp expressions but use Python-like
indentation for larger forms:

```margeux
# Lisp: (+ (* base 2) bonus)
+ (* base 2) bonus

# A larger nested expression uses indentation.
reduce
  fn [total value]
    + total value
  0
  values
```

Parentheses group a nested expression on one physical line. Each indented child
form is one argument expression. Parsing never needs to know the called
function's arity.

## Learn: 2. Source files and syntax

### Files, indentation, and comments

Margeux source files use UTF-8 and normally end in `.mgx`. Indentation uses
spaces; tabs in indentation are errors. Two spaces per level are recommended.
Siblings must align, and dedentation returns to an established outer level.

Comments begin with `#` outside a string:

```margeux
# A comment occupies the rest of the line.
def doubled [value]
  * value 2
```

Blank lines and comments do not open or close blocks.

### Names

Names may contain letters, digits, underscores, and hyphens. Predicate names
often end in `?`:

```margeux
player-x
round-even
valid?
```

A name cannot begin with a digit. Dots identify module members and record
fields: `math.sqrt` and `model.name`.

### Literals

```margeux
42
-4.5
1e3
true
false
nil
"hello"
[1 2 3]
dict :name "Ada" :score 42
```

Strings are single-line and support escaped quotes, backslashes, control
escapes, and interpolation:

```margeux
"Score: {model.score}"
"Six times seven is {* 6 7}."
```

An interpolation expression uses the normal expression parser and lexical
scope.

### Calls and evaluation

Function application is prefix notation:

```margeux
fahrenheit -4.5
+ left right
append values item
```

Ordinary arguments evaluate eagerly from left to right. `if`, `and`, `or`,
`match`, and other special forms control evaluation explicitly. Inline and
indented arguments may be combined:

```margeux
move-to model level
  key-x model.player-x key
  key-y model.player-y key
```

Use `call` to invoke a zero-argument function:

```margeux
let model
  call initial
```

A bare function name is a first-class function value rather than an implicit
zero-argument call.

## Learn: 3. Values and types

### Core types

The common built-in types are:

- `Int`, `Float`, and the shared numeric boundary `Number`
- `Bool`, `String`, and `Nil`
- `Vector[T]` and `Dict[T]`
- `Result[T, E]` and user-defined records and variants
- `Function`, `Task[T]`, `View`, `Views`, and `Terminal`

Dictionary keys are strings. `View` is one GUI node, while `Views` is an
ordered sequence of nodes with no wrapper.

### Inference first, annotations when useful

Margeux infers obvious local parameter and result types:

```margeux
def doubled [value]
  * value 2
```

Write an explicit contract at public boundaries, for domain schemas, or when
you want a particular abstract type:

```margeux
def doubled [value: Int] -> Int
  * value 2
```

Omitted types do not mean `Any`. Constraints from the body and call sites are
retained. Truly unresolved values are checked dynamically at the boundary.
Write `Any` deliberately when an API is meant to accept unrestricted values.

### Generic declarations

Reusable functions and nominal data types declare uppercase type parameters:

```margeux
def identity [T] [value: T] -> T
  value

record Box [T]
  value: T
```

Callers do not write type arguments; they are inferred from values.

### Numeric behavior

Integers and floats are distinct. `Number` accepts either. Mixed numeric
operations promote according to the numeric contract, while checked machine
arithmetic reports overflow rather than silently wrapping. Division,
rounding, non-finite floats, and conversion behavior are explicit standard
library operations when ambiguity would be dangerous.

## Learn: 4. Functions and control flow

### Named and anonymous functions

`def` creates a named function. `fn` creates a lexical closure:

```margeux
def total [values]
  reduce
    fn [sum value]
      + sum value
    0
    values
```

Functions capture lexical bindings. Calls must supply the declared number of
arguments; Margeux does not perform implicit partial application.

### Immutable bindings

`let` creates an immutable local binding. Its initializer can be inline or one
indented expression:

```margeux
let radius 3.0

let area
  * math.pi (math.pow radius 2)
```

`const` creates an immutable module value:

```margeux
const answer 42
```

A function body contains local bindings followed by its result expression.

### Conditions

`if` is an expression and always has a true and false result. Use aligned
`elif` clauses for several cases:

```margeux
def grade [score]
  if (>= score 90)
    "A"
  elif (>= score 80)
    "B"
  elif (>= score 70)
    "C"
  else
    "F"
```

Only the selected branch runs. `and` and `or` short-circuit left to right;
`not` accepts one Boolean.

### Pipelines

`pipe` sends a value through a readable sequence of functions:

```margeux
let display-name
  pipe model.name
    trim
    upper
```

Use a normal call when it communicates the operation more clearly. Pipelines
are composition syntax, not a separate runtime mechanism.

## Learn: 5. Collections

### Vectors

Vector literals retain a common element type:

```margeux
let scores [10 20 30]
let first-score (get scores 0)
let more-scores (append scores 40)
```

Common operations include `length`, `get`, `first`, `rest`, `slice`, `append`,
`range`, `map`, `filter`, and `reduce`. Collection functions receive ordinary
function values:

```margeux
let doubled
  map
    fn [value]
      * value 2
    [1 2 3]
```

The `std/vectors` module adds safe lookup, searching, grouping, uniqueness, and
other reusable operations. Out-of-range access is an error; use its safe
operations where absence is normal.

### Dictionaries

Dictionary keys are strings and updates are immutable:

```margeux
let person
  dict
    :name "Ada"
    :score 42

let promoted
  assoc person "score" 43
```

Homogeneous dictionaries infer `Dict[T]`. Use bare `Dict` or `Dict[Any]` for a
deliberately heterogeneous boundary such as arbitrary JSON. `std/dicts`
provides deterministic key, merge, update, filter, and removal helpers.

### Iteration in views

`for` produces a sequence of child views:

```margeux
ul
  for item in model.items :key item.id
    li item.name
```

Keys must be unique within their loop during a render. They preserve event
identity when a list changes.

## Learn: 6. Records, variants, results, and matching

### Records

Records define immutable named data:

```margeux
record Player
  name: String
  score: Int

let player
  Player
    :name "Ada"
    :score 0
```

Construction rejects missing, duplicate, unknown, and incorrectly typed
fields. Read fields with dot notation. `with` returns an updated record and
never mutates the old value:

```margeux
with player
  :score (+ player.score 1)
```

### Variants and pattern matching

Variants describe a closed set of alternatives:

```margeux
variant Message
  Increment
  Rename value: String
  Failed problem: String
```

`match` destructures the selected case and introduces branch-local bindings:

```margeux
match message
  Increment
    with model
      :count (+ model.count 1)
  Rename value
    with model
      :name value
  Failed problem
    with model
      :error problem
```

Matches over a known closed variant are exhaustive.

### Results and error propagation

`Result[T, E]` has `Ok value` and `Error problem`. Use it when failure is an
expected part of an operation:

```margeux
def describe [result: Result[Int, String]] -> String
  match result
    Ok value
      "Value: {value}"
    Error problem
      "Problem: {problem}"
```

Inside a Result-returning function, `? expression` returns early when the
expression is an `Error`. `std/results` provides `map`, `map-error`,
`and-then`, `recover`, predicates, and fallback helpers.

`nil` exists for explicit absence at loose boundaries. Prefer a domain variant
or a Result when the alternatives carry meaning.

## Learn: 7. Modules and packages

### Imports and namespaces

Import a module with `use`:

```margeux
use "std/math"
use "lib/player"

math.sqrt 81
player.initial "Ada"
```

Imports are namespaced by default. A module may declare an `export` list;
unexported declarations remain private. Relative project imports resolve from
the importing source file. Standard modules resolve from the runtime's bundled
library.

### Syntax modules and macros

Margeux macros run during compilation and transform syntax rather than runtime
values. Import phase-only syntax explicitly:

```margeux
use syntax "std/control"
  cond
  unless
```

Macros are hygienic by default, retain source provenance, and cannot perform
host effects. Quoted syntax, unquoting, and procedural syntax functions make
Margeux Lisp-like without changing how ordinary programs are written. Inspect
an expansion with:

```console
$ margeux expand main.mgx --all
```

Use a function when values are sufficient. Use a macro when the construct must
control evaluation, introduce bindings, or remove repeated syntax that a
function cannot express.

### Project manifests and locks

`margeux.json` names a project, its entry file, version, and dependencies.
`margeux.lock` records exact content-addressed dependency snapshots. The CLI,
compiler, language server, and browser packaging use the same resolution rules.

```console
$ margeux package lock .
$ margeux package pack . -o package.tar.gz
```

## Learn: 8. Applications and state

### The application model

A stateful Margeux application is a small state machine:

```text
update : (Model, Message) -> Model | Command
view   : Model -> View | Terminal
```

The runtime holds the model, turns host events into messages, calls `update`,
stores the returned model, and renders `view`. Views and terminal buffers are
values; constructing them does not immediately draw or perform host I/O.

### A complete application

```margeux
record Model
  count: Int

variant Message
  Increment
  Reset

def initial []
  Model :count 0

def update [model: Model message: Message] -> Model
  match message
    Increment
      with model :count (+ model.count 1)
    Reset
      with model :count 0

def view [model]
  main
    h1 "Count: {model.count}"
    button :on-click Increment "Increment"
    button :on-click Reset "Reset"

app Counter
  gui
    init initial
    update update
    view view
```

For a literal initial model, use `model` inside the application declaration.
For computed state, use a zero-argument `init` function.

### Events and binding

Event properties receive message constructors or handler functions. They do
not execute during view construction:

```margeux
input
  :value model.name
  :on-input NameChanged
```

The runtime supplies the event payload when the event occurs. `:bind` is an
explicit writable model-field binding for supported controls; it is not merely
the field's current value.

### Journal, replay, and hot reload

Transitions are atomic. The runtime can retain a bounded undo/redo journal,
named checkpoints, and deterministic traces. Hot reload preserves compatible
state and falls back to the last working program when compilation fails.
These features follow from immutable state and effect isolation rather than
from special application code.

## Learn: 9. GUI views and styles

### View composition

GUI builders create ordinary values:

```margeux
def greeting [name] -> View
  p "Hello, {name}!"

def view [model]
  main :class "page"
    h1 "Welcome"
    greeting model.name
    when model.ready
      p "Ready."
```

Properties begin with `:` and precede ordered children. Functions returning
`View` or `Views` compose without registration. `views` constructs a flat view
sequence. `br` is a GUI line break; use `\n` in strings and terminal text.

### Readable style blocks

Margeux lowers checked style forms to CSS in browser hosts and equivalent
properties in native rendering:

```margeux
main
  styles
    style page
      max-width 48 rem
      margin 2 rem auto
      padding 1.5 rem
      background white
      foreground "#181818"
      font-family "system-ui, sans-serif"
    style actions
      layout row
      gap .75 rem
      wrap
      on-hover
        foreground blue
```

Use `:class "page"` to apply a named style. `styles` also supports focus and
disabled states, responsive width breakpoints, and print rules. A node-local
style can be written as a checked dictionary or raw CSS string when necessary,
but reusable style blocks are clearer and scoped to the application.

### Forms and accessibility

Use semantic builders such as `main`, `section`, `nav`, `form`, `label`,
`input`, `button`, and headings. Builders validate known properties. Canvas and
terminal surfaces accept labels so assistive hosts can describe them.

## Learn: 10. Terminal and graphics applications

### Terminal values

A TUI view returns a `Terminal` value. Drawing forms construct cells in that
value:

```margeux
use "std/tui"

def view [model]
  terminal 24 8
    tui.box-line 0 0 24 8 0 "cyan"
    text 2 1 "Margeux TUI" "white"
    glyph model.x 3 "@" "yellow"
    cursor model.x 3

app TerminalDemo
  tui
    model :x 4
    update update
    view view
```

Keyboard and pointer events flow through the same update model as GUI events.
The host applies changed terminal cells as deltas rather than redrawing every
unchanged cell. Workspaces can contain independently focused panes.

### Canvas graphics

`canvas` contains declarative drawing primitives:

```margeux
canvas :width 320 :height 200 :label "Demo"
  rect :x 0 :y 0 :width 320 :height 200 :fill "#101820"
  circle :cx model.x :cy model.y :radius 20 :fill "#ffd166"
  line :x1 0 :y1 100 :x2 320 :y2 100 :stroke "white"
  draw-text :x 16 :y 24 :fill "white" "Score: {model.score}"
```

Primitives include rectangles, circles, lines, text, pixel text, and batches.
Pointer coordinates use the canvas's logical coordinate space.

### Frame input and games

`std/input` normalizes held, pressed, and released keys, pointer capture,
action axes, and gamepads. `std/animation` supplies pure timing, easing,
damping, and bounded fixed-step helpers. `std/vec3` and `std/ray3d` support
3D vector operations and deterministic grid ray casting.

Keep game rules pure and separate from input and rendering. This makes the
rules testable and avoids tying simulation speed to frame rate.

## Learn: 11. Tasks, effects, and capabilities

### Lazy tasks

`async def` and `async fn` return lazy `Task` values. Calling an async function
does not run its effects:

```margeux
async def load-health []
  let response
    ? await http.get "/api/health"
  json.parse response.body
```

`await` is valid inside asynchronous code. Synchronous views stay pure.

### Commands

An update starts work by returning a command with the immediate next model and
messages for completion:

```margeux
command
  :model
    with model :loading true
  :run (call load-health)
  :ok Loaded
  :error Failed
```

The runtime performs the task after the transition commits, then routes its
`Result` back through `update`. This preserves replayable state transitions and
prevents render-time effects.

### Explicit capabilities

Applications declare host authority:

```margeux
app ServiceStatus
  capabilities [http time]
  gui
    init initial
    update update
    view view
```

Important capabilities include `http`, `source`, `storage`, `database`,
`process`, and `time`. A declaration requests authority; the host must still
grant and implement it. Source code cannot enlarge the host's capability
policy. Pure code, tests, documentation tools, and macros receive no ambient
host access.

## Learn: 12. Files, storage, databases, servers, and processes

### Source and storage

`std/source` provides capability-scoped text files. It is appropriate for
editors and user-managed documents. `std/storage` provides application-scoped
key/value persistence without exposing file layout. Both return explicit
results and use host-specific backends with the same Margeux API.

`std/workspace` manages session-scoped program files and can explicitly check a
workspace compilation. It is distinct from unrestricted filesystem access.

### PostgreSQL

`std/database` provides parameterized PostgreSQL queries, mutations, prepared
hot paths, exact-one and optional-row helpers, transactions, and
checksum-protected migrations:

```margeux
use "std/database"

database.query
  "select name, score from players where score >= $1"
  [minimum]
```

The native host reads credentials; Margeux source and browser clients never
receive them. Browser applications require an embedding-page proxy. Always use
parameters rather than constructing SQL with string interpolation.

### HTTP servers

`std/server` defines typed requests, responses, routes, middleware, cookies,
explicit sessions, streaming responses, and server-rendered GUI documents.
Native hosts listen on sockets; browser hosts can simulate requests for
development without claiming to be a server.

### Native processes

`std/process` runs an exact executable with a vector of arguments and returns
exit code, stdout, and stderr. It never invokes a shell implicitly. The
`process` capability is native-only and intentionally powerful.

### LLM operations

`std/llm` represents provider-neutral tasks and SHA-256-bound edit proposals.
Generated text cannot directly modify files or execute code. The host adapter
and user retain authority over applying and running a proposal.

## Learn: 13. Testing and tools

### Source tests

Test declarations are first-class:

```margeux
use "std/testing"

test "doubled returns twice the input"
  testing.equal (doubled 21) 42
```

Files ending in `_test.mgx` are discovered by directory runs. Tests are
isolated and deterministic, and assertions retain source locations.

```console
$ margeux test .
$ margeux test . --filter doubled
$ margeux test . --fail-fast
$ margeux test . --json
```

Tests have no host capabilities unless a specialized harness explicitly
provides them.

### Formatter, language server, and REPL

```console
$ margeux check main.mgx
$ margeux lsp
$ margeux repl
$ margeux expand main.mgx --all
```

The language server supplies diagnostics, completion, hover, definitions,
references, rename, symbols, semantic tokens, and formatting to editors that
support LSP. Compiler and editor locations use explicit UTF-8 byte to UTF-16
position conversion so non-ASCII source remains accurate.

### MCP for coding agents

The local MCP server gives an LLM version-matched documentation, project
inspection, language-service operations, revision-bound edits, tests, and
optional bounded execution:

```console
$ margeux mcp /absolute/path/to/project
$ margeux mcp --read-only /absolute/path/to/project
$ margeux mcp --allow-run /absolute/path/to/project
```

The server uses stdio, remains inside its project root, never invokes a shell,
and exposes mutation or execution only when its startup policy allows them.

## Learn: 14. Compilation, bytecode, and execution

### One canonical VM

Every public execution path compiles source into validated Margeux bytecode and
runs it on the Go register VM. Native programs use the Go executable directly.
Browser programs use the same VM compiled to WebAssembly. The immutable source
evaluator is an internal testing oracle, not a second production runtime.

```console
$ margeux compile main.mgx -o main.mgxc
$ margeux exec main.mgxc
$ margeux disassemble main.mgxc
```

Compiled artifacts carry format and compatibility metadata and are validated
before execution.

### Native surfaces

```console
$ margeux run main.mgx
$ margeux gui main.mgx
$ margeux serve main.mgx
$ margeux render main.mgx -o page.html
```

`run` chooses the declared application surface. `gui` opens the native GUI
renderer. `serve` starts a declared server application. `render` produces a
deterministic document without opening a window.

### Browser embedding

The browser SDK loads source or bytecode through a version-negotiated embedding
API. A page may retain Margeux source in a `script` element and compile it in
the browser, or load a precompiled release. Hosts provide rendering and
capability adapters; application semantics remain in Margeux.

### Releases

```console
$ margeux release create main.mgx -o release
$ margeux release verify release
```

A release binds bytecode, metadata, capabilities, sources when retained, and
content digests. Verification happens before execution.

## Learn: 15. Standard library map

The full generated signatures are in the Standard Library reference. This map
helps you choose a module:

- Collections and values: `std/vectors`, `std/dicts`, `std/strings`,
  `std/results`, `std/sort`, `std/grid`, `std/math`, `std/random`
- Interfaces and games: `std/ui`, `std/tui`, `std/input`, `std/animation`,
  `std/fonts`, `std/vec3`, `std/ray3d`
- Application data: `std/source`, `std/workspace`, `std/storage`,
  `std/archive`
- Host integration: `std/time`, `std/process`, `std/database`, `std/server`,
  `std/cli`, `std/llm`
- Language composition: `std/control`, `std/infix`, `std/testing`
- Music tools: `std/instrument`, `std/arrangement`, `std/audio`, and the
  `std/music_*` modules

Import only the modules an application needs. Capabilities are separate from
imports: importing a host module does not grant its authority.

## Learn: 16. Where to go next

Read and run these maintained examples in order:

1. `examples/hello.mgx` for the smallest GUI application.
2. `examples/language-tour.mgx` for functions, types, collections, state, and
   views in one program.
3. `examples/testing/` for source tests.
4. `examples/tui-basics.mgx` and `examples/graphics.mgx` for alternate
   interfaces.
5. `examples/snake/` and `examples/canvas-game/` for modular games.
6. `examples/database.mgx` and `examples/server.mgx` for host capabilities.

For exact contracts, consult the core, runtime, async, macro, testing, package,
TUI, graphics, server, database, embedding, and host-support specifications
included beside this guide. They define edge cases and host obligations; this
manual teaches the stable ordinary path through them.

## Language: Complete language reference


This reference unifies every maintained, implemented Margeux language and host contract. The practical guide teaches the language; this book defines the complete behavior and records the status of versioned or evidence-only surfaces.

Each chapter names its authoritative repository source. Generated standard-module signatures are maintained separately in the Standard Library Reference.

## Language: Compiler-owned language surface

Authoritative source: `docs/LANGUAGE_SURFACE_REFERENCE.md`. Classification: **generated**.

**Status:** generated from `phase0.EditorSyntaxMetadata`; do not edit by hand.

This inventory lists every compiler-owned declaration, keyword, type, built-in name, view tag, view property, and indentation-aware block head. The normative specifications define their behavior, and the standard-library reference defines qualified module members.

### Declarations

- `app`
- `const`
- `def`
- `intrinsic`
- `macro`
- `protocol`
- `record`
- `syntax`
- `test`
- `variant`

### Keywords

- `app`
- `async`
- `await`
- `call`
- `capabilities`
- `case`
- `command`
- `const`
- `def`
- `elif`
- `else`
- `expand`
- `export`
- `fn`
- `for`
- `gui`
- `if`
- `implement`
- `in`
- `init`
- `intrinsic`
- `let`
- `macro`
- `match`
- `model`
- `otherwise`
- `pane`
- `pipe`
- `protocol`
- `record`
- `rule`
- `rules`
- `server`
- `splice-syntax`
- `split`
- `start`
- `syntax`
- `terminal`
- `test`
- `tui`
- `unsyntax`
- `update`
- `use`
- `variant`
- `view`
- `views`
- `when`
- `with`
- `workspace`

### Structural application keywords

- `capabilities`
- `gui`
- `init`
- `model`
- `pane`
- `server`
- `split`
- `start`
- `tui`
- `update`
- `view`
- `workspace`

### Types

- `Any`
- `Bool`
- `Dict`
- `Float`
- `Function`
- `Int`
- `Number`
- `Result`
- `String`
- `Syntax`
- `Terminal`
- `Vector`
- `View`
- `Views`

### Core built-in signatures

These names are available without importing a standard module. Checked failure behavior is defined by the numeric, macro, TUI, async, and host-contract chapters.

- `+ [Number Number] -> Number` — Checked numeric addition; promotes to Float when either operand is Float.
- `- [Number Number] -> Number` — Checked numeric subtraction.
- `* [Number Number] -> Number` — Checked numeric multiplication.
- `/ [Number Number] -> Number` — Checked division; division by zero is an error.
- `% [Int Int] -> Int` — Integer remainder; a zero divisor is an error.
- `= [Any Any] -> Bool` — Structural value equality.
- `!= [Any Any] -> Bool` — Negated structural equality.
- `< [Number Number] -> Bool` — Numeric less-than comparison.
- `<= [Number Number] -> Bool` — Numeric less-than-or-equal comparison.
- `> [Number Number] -> Bool` — Numeric greater-than comparison.
- `>= [Number Number] -> Bool` — Numeric greater-than-or-equal comparison.
- `and [Bool Bool] -> Bool` — Left-to-right short-circuit conjunction.
- `or [Bool Bool] -> Bool` — Left-to-right short-circuit disjunction.
- `not [Bool] -> Bool` — Boolean negation.
- `vector [...Any] -> Vector[Any]` — Construct an immutable vector from its arguments.
- `dict [:key Any ...] -> Dict[Any]` — Construct an immutable dictionary from named fields.
- `length [String|Vector|Dict] -> Int` — Return the number of Unicode code points, elements, or entries.
- `empty? [String|Vector|Dict|nil] -> Bool` — Test whether a supported value contains no items; nil is empty.
- `nil? [Any] -> Bool` — Test whether a value is nil.
- `contains? [String String] -> Bool` — Test whether a string contains a substring.
- `first [Vector[T]] -> T` — Return the first vector element; an empty vector is an error.
- `rest [Vector[T]] -> Vector[T]` — Return all elements after the first.
- `append [Vector[T] T] -> Vector[T]` — Return a vector with one value appended.
- `get [Vector|Dict Int|String] -> Any` — Read a vector index or dictionary key with bounds/key validation.
- `assoc [Dict[T] String T] -> Dict[T]` — Return a dictionary with one key associated to a value.
- `map [Function Vector[T]] -> Vector[U]` — Apply a function to every element in order.
- `filter [Function Vector[T]] -> Vector[T]` — Retain elements for which the predicate returns true.
- `reduce [Function U Vector[T]] -> U` — Fold a vector left-to-right from an initial accumulator.
- `range [Int Int] -> Vector[Int]` — Construct the half-open integer range from start through end.
- `slice [String|Vector Int Int] -> String|Vector` — Return a checked half-open slice.
- `concat [...Any] -> String` — Convert and concatenate every argument into one string.
- `join [Vector[String] String] -> String` — Join strings with a separator.
- `split [String String] -> Vector[String]` — Split a string on a separator.
- `trim [String] -> String` — Remove leading and trailing Unicode whitespace.
- `upper [String] -> String` — Convert a string to Unicode upper case.
- `lower [String] -> String` — Convert a string to Unicode lower case.
- `replace [String String String] -> String` — Replace every occurrence of a substring.
- `str [Any] -> String` — Return the ordinary string representation of a value.
- `string [Any] -> String` — Alias of str.
- `int [Any] -> Int` — Convert to Int or raise a bounded conversion error.
- `float [Any] -> Float` — Convert to Float or raise a bounded conversion error.
- `int.try [Any] -> Result[Int, String]` — Attempt Int conversion without raising an error.
- `float.try [Any] -> Result[Float, String]` — Attempt Float conversion without raising an error.
- `Ok [T] -> Result[T, E]` — Construct a successful Result.
- `Error [E] -> Result[T, E]` — Construct a failed Result.
- `json.parse [String] -> Result[Any, String]` — Parse one JSON value without losing integer precision.
- `json.stringify [Any] -> Result[String, String]` — Encode portable Margeux data as JSON.
- `text [Int Int String String] -> TerminalDraw` — Construct terminal text drawing data.
- `glyph [Int Int String String] -> TerminalDraw` — Construct one terminal glyph drawing operation.
- `cursor [Int Int] -> TerminalDraw` — Construct a terminal cursor position.
- `syntax.kind [Syntax] -> String` — Return the syntax node kind.
- `syntax.head [Syntax] -> String` — Return a form head or an empty string.
- `syntax.text [Syntax] -> String` — Return the source text represented by a syntax atom.
- `syntax.terms [Syntax] -> Vector[Syntax]` — Return a form's inline terms.
- `syntax.children [Syntax] -> Vector[Syntax]` — Return a form's indented child forms.
- `syntax.items [Syntax] -> Vector[Syntax]` — Return the items of a syntax sequence.
- `syntax.sequence [Syntax] -> Vector[Syntax]` — Return a normalized syntax sequence.
- `syntax.sequence-of [Vector[Syntax]] -> Syntax` — Construct a syntax sequence.
- `syntax.span [Syntax] -> Dict` — Return the original source span.
- `syntax.identifier? [Syntax] -> Bool` — Test whether a syntax value is an identifier.
- `syntax.identifier [Syntax String] -> Syntax` — Construct an identifier with lexical context.
- `syntax.literal [Syntax Any] -> Syntax` — Construct a literal with source context.
- `syntax.form-of [Syntax Vector[Syntax] Any] -> Syntax` — Construct a form with explicit terms and children.
- `syntax.same-binding? [Syntax Syntax] -> Bool` — Compare lexical binding identity.
- `syntax.introduce-at-call-site [Syntax Syntax] -> Syntax` — Intentionally introduce an identifier in caller scope.
- `syntax.error [Syntax String] -> Never` — Emit a source-located expansion diagnostic.
- `http.get [String] -> Task[Result[String, String]]` — Create a capability-gated HTTP GET task.
- `http.request [String String String String] -> Task[Result[String, String]]` — Create a capability-gated HTTP request task.

### Built-ins and standard exported names

- `Error`
- `Ok`
- `and`
- `animation.FixedStep`
- `animation.advance`
- `animation.approach`
- `animation.damp`
- `animation.ease-in`
- `animation.ease-in-out`
- `animation.ease-out`
- `animation.fixed-step`
- `animation.fixed-step-unchecked`
- `animation.lerp`
- `animation.loop-progress`
- `animation.ping-pong-progress`
- `animation.progress`
- `animation.smoothstep`
- `append`
- `archive.epub-book`
- `archive.zip-entries`
- `arrangement.compact-grid`
- `arrangement.copy-range`
- `arrangement.expanded-length`
- `arrangement.grid-cell-for-item`
- `arrangement.grid-item-at`
- `arrangement.insert-copy-after`
- `arrangement.last-occupied-cell`
- `arrangement.paste-at`
- `arrangement.remove-range`
- `arrangement.repeat-active`
- `arrangement.replace-at`
- `arrangement.swap-at`
- `assoc`
- `audio.AudioSource`
- `audio.Envelope`
- `audio.Filter`
- `audio.LFO`
- `audio.SynthPatch`
- `audio.default-patch`
- `audio.envelope`
- `audio.lfo`
- `audio.low-pass`
- `audio.patch`
- `audio.sample`
- `audio.source`
- `audio.synth`
- `cli.Option`
- `cli.Parsed`
- `cli.Response`
- `cli.arguments`
- `cli.failure`
- `cli.flag`
- `cli.flag?`
- `cli.help-option`
- `cli.option`
- `cli.parse`
- `cli.parse-failure`
- `cli.required-option`
- `cli.response`
- `cli.success`
- `cli.usage`
- `cli.value`
- `concat`
- `contains?`
- `cursor`
- `database.OptionalRow`
- `database.QueryResult`
- `database.execute`
- `database.execute-one`
- `database.execute-one-prepared`
- `database.execute-prepared`
- `database.execute-statement`
- `database.expect-affected`
- `database.migrate`
- `database.migration`
- `database.one-row`
- `database.optional-row`
- `database.query`
- `database.query-one`
- `database.query-one-prepared`
- `database.query-optional`
- `database.query-optional-prepared`
- `database.query-prepared`
- `database.query-statement`
- `database.statement`
- `database.transaction`
- `dict`
- `empty?`
- `filter`
- `first`
- `float`
- `float.try`
- `fonts.list`
- `fonts.load`
- `fonts.remove`
- `fonts.remove-named`
- `fonts.restore`
- `fonts.select`
- `get`
- `glyph`
- `grid.centered-subset`
- `grid.column`
- `grid.distance`
- `grid.index`
- `grid.matching-component`
- `grid.neighbors`
- `grid.placement-indices`
- `grid.row`
- `grid.valid-index?`
- `grid.valid-indices?`
- `http.get`
- `http.request`
- `infix.expression`
- `infix.infix`
- `input.action-pressed?`
- `input.action-released?`
- `input.action?`
- `input.axis`
- `input.gamepad-axis`
- `input.gamepad-button`
- `input.held?`
- `input.normalize-key`
- `input.pointer-held?`
- `input.pressed?`
- `input.released?`
- `instrument.InstrumentAdapter`
- `instrument.all-pitches`
- `instrument.instrument-id`
- `instrument.lane-count`
- `instrument.pitch-at`
- `instrument.step-count`
- `int`
- `int.try`
- `join`
- `json.parse`
- `json.stringify`
- `length`
- `llm.Completion`
- `llm.Identity`
- `llm.Request`
- `llm.Selection`
- `llm.SourceCreate`
- `llm.SourceDelete`
- `llm.SourceEdit`
- `llm.SourceFile`
- `llm.apply`
- `llm.digest`
- `llm.file`
- `llm.identity`
- `llm.no-selection`
- `llm.request`
- `llm.request-value`
- `llm.selected-request`
- `llm.selection`
- `lower`
- `map`
- `math.abs`
- `math.acos`
- `math.approx?`
- `math.asin`
- `math.atan`
- `math.atan2`
- `math.ceil`
- `math.clamp`
- `math.combinations`
- `math.cos`
- `math.degrees`
- `math.distance`
- `math.dot`
- `math.e`
- `math.exp`
- `math.factorial`
- `math.finite?`
- `math.floor`
- `math.gcd`
- `math.hypot`
- `math.infinite?`
- `math.inverse-lerp`
- `math.lcm`
- `math.lerp`
- `math.log`
- `math.log10`
- `math.log2`
- `math.magnitude`
- `math.max`
- `math.mean`
- `math.median`
- `math.min`
- `math.nan?`
- `math.normalize`
- `math.permutations`
- `math.pi`
- `math.pow`
- `math.product`
- `math.radians`
- `math.remap`
- `math.round`
- `math.round-even`
- `math.sign`
- `math.sin`
- `math.sqrt`
- `math.standard-deviation`
- `math.sum`
- `math.tan`
- `math.tau`
- `math.truncate`
- `math.variance`
- `math.vector-add`
- `math.vector-scale`
- `math.vector-subtract`
- `music_builder.Builder`
- `music_builder.add-at-cell`
- `music_builder.beats`
- `music_builder.can-move-selection?`
- `music_builder.capacity`
- `music_builder.compact`
- `music_builder.copy-selection`
- `music_builder.duplicate-loop`
- `music_builder.duplicate-selection`
- `music_builder.editable-cell?`
- `music_builder.extend-selection`
- `music_builder.grid-cell-for-item`
- `music_builder.grid-item-at`
- `music_builder.grid-span`
- `music_builder.initial`
- `music_builder.insert-selected-copy`
- `music_builder.item-selected?`
- `music_builder.move-selected-one`
- `music_builder.move-selection`
- `music_builder.paste-count`
- `music_builder.paste-selection`
- `music_builder.playback-beats`
- `music_builder.playback-position-at`
- `music_builder.playback-span`
- `music_builder.position-at`
- `music_builder.remove-selection`
- `music_builder.reorder-selected`
- `music_builder.replace-beats`
- `music_builder.replace-position`
- `music_builder.replace-quality`
- `music_builder.replace-root`
- `music_builder.replace-scale`
- `music_builder.replace-voicing`
- `music_builder.select`
- `music_builder.selection-finish`
- `music_builder.selection-length`
- `music_builder.selection-start`
- `music_builder.set-columns`
- `music_builder.set-key`
- `music_builder.set-name`
- `music_builder.set-roots-locked`
- `music_builder.with-positions`
- `music_catalog.Quality`
- `music_catalog.Scale`
- `music_catalog.quality`
- `music_catalog.quality-count`
- `music_catalog.quality-intervals`
- `music_catalog.scale`
- `music_catalog.scale-count`
- `music_catalog.valid-quality?`
- `music_catalog.valid-scale?`
- `music_export.position-detail`
- `music_export.position-notes`
- `music_export.position-title`
- `music_export.progression-svg`
- `music_export.progression-url`
- `music_export.svg-data-url`
- `music_export.title`
- `music_finder.chord-compatible-codes`
- `music_finder.chord-compatible?`
- `music_finder.chord-containing-codes`
- `music_finder.chord-exact-codes`
- `music_finder.chord-exact?`
- `music_finder.scale-compatible-codes`
- `music_finder.scale-compatible?`
- `music_practice.beat-offset`
- `music_practice.item-limit`
- `music_practice.parsed-beats`
- `music_practice.parsed-bpm`
- `music_practice.parsed-count-in`
- `music_practice.timelines`
- `music_practice.total-beats`
- `music_program.Position`
- `music_program.beats`
- `music_program.chord`
- `music_program.chord-item`
- `music_program.chord?`
- `music_program.copy-range`
- `music_program.custom`
- `music_program.custom-item`
- `music_program.custom?`
- `music_program.insert-copy-after`
- `music_program.note-set`
- `music_program.note-set-item`
- `music_program.note-set?`
- `music_program.paste-at`
- `music_program.remove-range`
- `music_program.repeat-active`
- `music_program.replace-at`
- `music_program.rest`
- `music_program.rest-item`
- `music_program.rest?`
- `music_program.scale`
- `music_program.scale-item`
- `music_program.scale?`
- `music_program.swap-at`
- `music_program.transpose-roots`
- `music_program.with-beats`
- `music_program.with-custom`
- `music_program.with-note-set`
- `music_program.with-quality`
- `music_program.with-root`
- `music_program.with-scale`
- `music_program.with-voicing`
- `music_progressions.ChordSuggestion`
- `music_progressions.ProgressionTemplate`
- `music_progressions.make-chord-suggestion`
- `music_progressions.next-chord-suggestion`
- `music_progressions.progression-category-count`
- `music_progressions.progression-category-first-template`
- `music_progressions.progression-category-name`
- `music_progressions.progression-category-template-index`
- `music_progressions.progression-template`
- `music_progressions.progression-template-count`
- `music_progressions.progression-templates-per-category`
- `music_theory.compatible-scale?`
- `music_theory.contains-pitches?`
- `music_theory.exact-pitches?`
- `music_theory.interval-name`
- `music_theory.normalize`
- `music_theory.pitch-class-count`
- `music_theory.pitch-name`
- `music_theory.pitches`
- `music_theory.relative`
- `music_theory.transpose`
- `nil?`
- `not`
- `or`
- `process.ProcessResult`
- `process.run`
- `process.run-program`
- `process.success?`
- `random.Sample`
- `random.at`
- `random.bool`
- `random.chance`
- `random.float`
- `random.int`
- `random.int-at`
- `random.next`
- `random.pick`
- `random.seed`
- `range`
- `ray3d.cast-frame`
- `ray3d.cast-view`
- `ray3d.frame-hits-cell?`
- `ray3d.frame-width`
- `reduce`
- `replace`
- `rest`
- `server.ClientRequest`
- `server.Cookie`
- `server.Request`
- `server.Response`
- `server.Route`
- `server.RouteMatch`
- `server.Session`
- `server.Stream`
- `server.StreamChunk`
- `server.StreamResponse`
- `server.StreamStep`
- `server.async-header-middleware`
- `server.async-request-middleware`
- `server.async-response-middleware`
- `server.bool-param`
- `server.client`
- `server.cookie`
- `server.cookie-value`
- `server.delete-session`
- `server.emit`
- `server.encode-path`
- `server.end`
- `server.expired-cookie`
- `server.float-param`
- `server.header-middleware`
- `server.html`
- `server.int-param`
- `server.json`
- `server.json-client`
- `server.load-session`
- `server.match-route`
- `server.new-session`
- `server.param`
- `server.redirect`
- `server.response`
- `server.response-middleware`
- `server.route`
- `server.route-path`
- `server.save-session`
- `server.secure-cookie`
- `server.send`
- `server.stream`
- `server.stream-response`
- `server.text`
- `server.validate-route`
- `server.validate-routes`
- `server.with-cookie`
- `server.with-header`
- `slice`
- `sort.ascending`
- `sort.descending`
- `sort.using`
- `source.delete`
- `source.list`
- `source.load`
- `source.paths`
- `source.read`
- `source.save`
- `source.tokens`
- `split`
- `storage.delete`
- `storage.get`
- `storage.keys`
- `storage.set`
- `str`
- `string`
- `syntax.children`
- `syntax.error`
- `syntax.form-of`
- `syntax.head`
- `syntax.identifier`
- `syntax.identifier?`
- `syntax.introduce-at-call-site`
- `syntax.items`
- `syntax.kind`
- `syntax.literal`
- `syntax.same-binding?`
- `syntax.sequence`
- `syntax.sequence-of`
- `syntax.span`
- `syntax.terms`
- `syntax.text`
- `testing.approx`
- `testing.check`
- `testing.equal`
- `testing.fail`
- `testing.is-false`
- `testing.is-true`
- `testing.not-equal`
- `text`
- `time.after`
- `time.day`
- `time.days`
- `time.deadline`
- `time.elapsed`
- `time.expired?`
- `time.hour`
- `time.hours`
- `time.millisecond`
- `time.milliseconds`
- `time.minute`
- `time.minutes`
- `time.now`
- `time.remaining`
- `time.second`
- `time.seconds`
- `time.sleep`
- `trim`
- `tui.box-line`
- `tui.clamp-index`
- `tui.horizontal-line`
- `tui.repeat-character`
- `tui.scroll-start`
- `tui.wrap-index`
- `ui.activate?`
- `ui.focus-index`
- `ui.hit`
- `ui.horizontal-index`
- `ui.inside?`
- `ui.key-event`
- `ui.normalize-event`
- `ui.pointer-event`
- `ui.vertical-index`
- `upper`
- `vec3.Vec3`
- `vec3.add`
- `vec3.cross`
- `vec3.distance`
- `vec3.dot`
- `vec3.length`
- `vec3.normalize`
- `vec3.scale`
- `vec3.subtract`
- `vec3.vec3`
- `vector`
- `vectors.all?`
- `vectors.any?`
- `vectors.at`
- `vectors.concat`
- `vectors.contains?`
- `vectors.count`
- `vectors.drop`
- `vectors.find`
- `vectors.find-index`
- `vectors.first`
- `vectors.index-of`
- `vectors.last`
- `vectors.matches`
- `vectors.maximum`
- `vectors.minimum`
- `vectors.replace-at`
- `vectors.reverse`
- `vectors.take`
- `vectors.unique`
- `workspace.create`
- `workspace.delete`
- `workspace.paths`
- `workspace.read`
- `workspace.run`
- `workspace.write`

### View tags

- `a`
- `br`
- `button`
- `canvas`
- `circle`
- `code-diff`
- `code-editor`
- `div`
- `draw-text`
- `footer`
- `form`
- `h1`
- `h2`
- `header`
- `iframe`
- `input`
- `label`
- `li`
- `line`
- `main`
- `media-rule`
- `nav`
- `ol`
- `option`
- `p`
- `pixel-text`
- `pre`
- `process-view`
- `ray-columns`
- `rect`
- `runtime-preview`
- `sample-engine`
- `section`
- `select`
- `span`
- `strong`
- `style-rule`
- `stylesheet`
- `textarea`
- `tile-map`
- `ui-column`
- `ui-row`
- `ui-spacer`
- `ui-stack`
- `ul`

### View properties

- `align`
- `allow`
- `baseline`
- `bind`
- `blink`
- `bpm`
- `buffered-keys`
- `button`
- `changes`
- `class`
- `columns`
- `continuous`
- `cx`
- `cy`
- `disabled`
- `document`
- `entry`
- `files`
- `fill`
- `font`
- `frame-rate`
- `height`
- `href`
- `key`
- `label`
- `language`
- `line-width`
- `loading`
- `master-volume`
- `mute`
- `on-click`
- `on-drag`
- `on-files`
- `on-frame`
- `on-input`
- `on-key`
- `on-navigate`
- `on-pointer`
- `on-run`
- `on-shift-click`
- `on-submit`
- `original`
- `path`
- `playing`
- `projection`
- `proposed`
- `radius`
- `read-only`
- `referrerpolicy`
- `revision`
- `sandbox`
- `scale`
- `selected`
- `source`
- `src`
- `stroke`
- `style`
- `swing`
- `target`
- `timelines`
- `title`
- `type`
- `value`
- `volume`
- `width`
- `x`
- `x1`
- `x2`
- `y`
- `y1`
- `y2`

### Indentation-aware block heads

- `app`
- `command`
- `def`
- `elif`
- `else`
- `expand`
- `export`
- `for`
- `gui`
- `if`
- `implement`
- `init`
- `macro`
- `match`
- `model`
- `on-focus`
- `on-focus-visible`
- `on-hover`
- `pane`
- `protocol`
- `record`
- `rule`
- `rules`
- `server`
- `split`
- `style`
- `styles`
- `syntax`
- `terminal`
- `test`
- `tui`
- `variant`
- `views`
- `when`
- `when-disabled`
- `when-printing`
- `when-width-above`
- `when-width-below`
- `with`
- `workspace`

### Leaf view tags

- `br`
- `input`
- `textarea`

### Multiline call arities

These known call heads use the listed arity for editor indentation. User macros and imported syntax extend this table per workspace.

- `Error`: 1
- `Ok`: 1
- `and`: 2
- `concat`: 2
- `filter`: 2
- `infix.expression`: 1
- `infix.infix`: 1
- `map`: 2
- `not`: 1
- `or`: 2
- `reduce`: 3

## Language: Core language syntax and composition

Authoritative source: `MARGEUX_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented and test-backed, version 0.1  
**Scope:** Core expression syntax, functions, records, types, and application composition.

This document is the normative core-language contract. Its portable execution
matrix and the focused parser, semantic, application, module, macro, and tooling
tests named in `IMPLEMENTATION_CHECKLIST.md` provide implementation evidence.
Companion specifications govern the runtime, embedding, packages, servers,
graphics, and other surfaces layered on this core.

### 1. Design principles

Margeux uses prefix expressions and indentation for computation and
composition. It MUST provide predictable grouping independent of arity,
consistent application for builtins and user functions, explicit function
values and invocation, immutable bindings and record updates, ordinary-function
view composition, and source locations preserved through expansion.

The ordinary path MUST remain small. Local helpers MAY rely on inference when
their intent is clear. Explicit annotations SHOULD be used at public module
boundaries, for domain schemas, where inference is ambiguous, or where a
concrete numeric or collection contract enables better generated code.
Annotations MUST guide checking and optimization rather than becoming mandatory
ceremony for every binding. Advanced facilities MUST compose with this core
without becoming ceremony for simple programs.

Ease is not permission to make the language incomplete. Ordinary Margeux MUST
be sufficient for complete applications; Go, JavaScript, WebAssembly, and host
adapters provide capabilities and execution targets, not a second application
language that users must escape into. Complexity needed by servers, databases,
graphics, terminals, packages, asynchronous I/O, and tooling SHOULD live behind
consistent libraries and explicit boundaries instead of complicating basic
functions and values.

MUST, SHOULD, and MAY express requirements, recommendations, and optional
behavior.

### 2. Source structure

Source files use UTF-8. Indentation MUST use spaces; indentation tabs are
errors. Two spaces per level are RECOMMENDED. Siblings have equal indentation,
and dedentation returns to an established enclosing level. Blank lines and
comments do not change block structure. Comments begin with `#` outside strings.

```margeux
def doubled [value]
  * value 2
```

### 3. Names and literals

Names may contain letters, digits, underscores, hyphens, and trailing
predicate or mutation-style punctuation, but cannot begin with a digit.
Qualified names and fields use dots (`math.sqrt`, `model.name`); binding MUST
distinguish module members from record fields.

Core literals are integers, floats, booleans, `nil`, strings, and vectors.
Literal recognition consumes complete tokens: `true-value` is one name.

### 4. Expression grouping

Application is prefix notation. Inline arguments are terms; parentheses group
compound expressions; each indented child form is one additional argument.
Inline and child arguments may be mixed. Parsing MUST NOT depend on function
arity. Ordinary calls evaluate eagerly from left to right; special forms define
their own evaluation. Parenthesized groups remain on one physical line in 0.1.

```margeux
+ (* base 2) bonus

reduce
  fn [total value]
    + total value
  0
  values
```

### 5. Function values and invocation

A bare function name denotes its value. Supplying arguments invokes it.
Zero-argument invocation uses `call initial`. Calls supply the declared arity;
implicit partial application is not specified.

A homogeneous vector of functions retains their shared parameter and result
signature. Selecting a function with `get` therefore produces a directly
callable value without a cast or wrapper:

```margeux
const transforms
  vector
    double
    triple

let transform
  get transforms 1
transform 7
```

Functions with different signatures do not form a precisely callable vector.
Calling a value selected from such a mixed collection is a compile-time error.

### 6. Functions and bindings

`def` declares functions and `fn` creates lexical closures. `async def` and
`async fn` are their lazy Task-producing counterparts. Parameter and return
annotations may be omitted where inference succeeds. `let name value` and a
one-child multiline `let` are equivalent. Bindings are immutable and lexical.
A function body contains zero or more bindings followed by a result expression.
`const` declares immutable module values. For an unannotated function, an
unambiguous body type MUST flow to callers transitively across ordinary
function chains regardless of declaration order. This applies to synchronous and asynchronous bodies; invoking
an asynchronous function still produces a lazy `Task` carrying that result.
Inference MUST retain primitive, collection,
`Result`, nominal record or variant, and rendering types when known; it MUST
leave genuinely unresolved values unrestricted rather than inventing a type.
An unannotated local parameter MAY infer an exact requirement imposed by its
body, such as `Int` for remainder, `String` for `upper`, or `Bool` for Boolean
operators. Using an unannotated value as an `if` or `when` condition likewise
infers `Bool`. A `Number` requirement alone MUST remain unresolved rather than
silently choosing `Int` or `Float`; its numeric operation retains the runtime
check unless another constraint determines an exact static type.

Reusable functions MAY declare type parameters between their name and ordinary
parameters. Calls infer those arguments; callers never write them explicitly:

```margeux
def identity [T] [value: T] -> T
  value

identity 42
```

Type parameters are scoped to the declaration and MUST be uppercase, unique,
and distinct from built-in type names. The same syntax is available to standard
library intrinsics so their public type relationships remain declared in
Margeux rather than encoded as compiler knowledge. Homogeneous `Vector[T]` and
`Dict[T]` values retain their concrete element type. Mixed and empty collection
literals use an erased element representation, reported as `Vector[Any]` or
`Dict[Any]` when a diagnostic must name it. That representation MUST NOT satisfy
or weaken a concrete `Vector[T]` or `Dict[T]` boundary. A deliberately gradual
API MUST write `Any`, `Vector[Any]`, `Dict[Any]`, or the compatibility shorthand
`Vector` or `Dict` in its annotation.

Annotations are required where the programmer wants a stable contract that
cannot be inferred from the body: a deliberately gradual boundary, an abstract
`Number` rather than a concrete numeric type, a nominal type chosen among
otherwise compatible shapes, or an unresolved higher-order relationship.
Annotations remain optional when body constraints determine a unique type.
An unresolved omitted parameter remains dynamically checked; it MUST NOT be
silently rewritten to `Any` in source diagnostics or used as evidence that a
concrete contract has been met.

After linking a complete program, an implementation MAY specialize an omitted
parameter internally when every reference is a direct call and every argument
at that position has the same concrete type. This is an optimization, not an
implicit source annotation: a function that escapes as a value, receives mixed
numeric types, or explicitly declares `Number` MUST retain its polymorphic
contract. The specialized and unspecialized programs MUST have the same
observable result and checked arithmetic behavior.

At a higher-order collection call, inference MUST specialize an unannotated
callback from the actual element and accumulator types when its result retains
their structure. This includes identity results, nested Vector construction,
element projection through `first` or integer `get`, Vector preservation through
`rest`, `slice`, and `append`, and composition through `map`, `filter`, and
`reduce`. Identical structural results from every `if` or exhaustive `match`
branch MUST be retained. If branches disagree or a relationship remains
ambiguous, inference MUST leave it unrestricted rather than guess a type.
`map`, `filter`, and `reduce` callbacks MUST be synchronous. A known async
callback is a compile error; an async callable crossing an unresolved dynamic
boundary is rejected by the VM before the callback runs, including for an empty
collection.
An `append` through an unannotated helper MUST retain the relationship between
the Vector element and appended value, including when either value is captured
by a returned closure or when the helper composes `append` through `reduce`
across a module boundary. An unknown argument MUST NOT allow a callee-local
inference placeholder to escape and bind to an unrelated caller parameter.
`slice` retains its complete input type for both `String` and `Vector[T]`,
including during contextual semantic checking.
Returned closures retain the same relationships. A captured argument remains
bound to the factory invocation that supplied it, including through nested
returned closures; parameters introduced by an inner closure remain scoped to
that closure and MUST NOT be confused with an outer capture.

### 7. Conditionals

`if` has one Boolean condition and exactly two branches, evaluating only the
selected branch. Aligned `elif` clauses provide additional conditions, and an
`elif` chain MUST end with `else`:

```margeux
def grade [score]
  if (>= score 90)
    "A"
  elif (>= score 80)
    "B"
  elif (>= score 70)
    "C"
  else
    "F"
```

`elif` and `else` MUST align with their originating `if`, and each clause body
contains exactly one expression. The reader lowers the chain into nested `if`
expressions while retaining the original clause locations for diagnostics and
formatting. Consequently, only the selected condition and branch are evaluated
and the syntax adds no VM operation or runtime overhead.

`and` and `or` short-circuit left-to-right; `not` is unary. `when` contributes
view children only when its condition is true.

The phase-only `std/control` module exports derived `when`, `unless`, and
`cond` macros. They expand before type checking and add no runtime module or
bytecode dependency:

```margeux
use syntax "std/control"
  unless
  cond

def describe [value: Int] -> String
  cond
    case (< value 0)
      "negative"
    case (= value 0)
      "zero"
    otherwise
      "positive"
```

`unless` is the lazy inverse of view-producing `when`. A `cond` contains one or
more `case condition` clauses followed by exactly one final `otherwise` clause.
Every clause contains exactly one result expression. Conditions are evaluated
from top to bottom; only the selected result is evaluated. The expansion is an
ordinary nested `if`, so branch typing and diagnostics follow the same rules as
handwritten conditionals.

### 8. Records

Records declare named typed fields. Constructors reject missing, duplicate,
unknown, or incorrectly typed fields. Dot syntax reads fields. `with` creates a
value of the same record type and cannot add undeclared fields. Field values may
be inline or one indented expression.

Generic records declare their type parameters in the same bracket form used by
function parameter lists:

```margeux
record Box [T]
  value: T
```

### 9. Types

Core types include `Int`, `Float`, `Bool`, `String`, `Function`, `View`, `Views`,
and `Dict`.
`Number` means `Int | Float`; its numeric rules are specified separately.
Parameterized annotations use square brackets. Annotations remain optional
where inference succeeds:

```margeux
def minimum [values: Vector[Int]] -> Result[Int, String]
  ...
```

`Function` is the simple checked type for a first-class callable value. It is
useful at storage and public API boundaries where the exact signature remains
dynamic. Calling it still performs the callable's ordinary runtime arity and
argument checks. Exact function-type syntax is intentionally not part of 0.1;
ordinary named and anonymous functions retain their inferred signatures without
requiring users to spell them.

Dictionary keys are always Strings. `Dict[T]` states that every stored value is
`T`; homogeneous dictionary literals infer that parameter, while bare `Dict`
remains available for heterogeneous JSON and boundary data. Typed `get`, dotted
access, `assoc`, and immutable standard-library deletion preserve and check `T`.

User-defined records and variants may also be parameterized. Constructors infer
their concrete arguments from field or payload values, and the arguments remain
part of the static nominal identity. A constructor outside a generic function
retains those concrete arguments in its runtime nominal descriptor. Portable
generic functions have one shared body rather than one bytecode clone per call;
free declaration parameters in descriptors created by that body are therefore
erased to `Any` at the runtime boundary. Call sites still retain and check the
concrete substitution, including field access and exhaustive matching:

```margeux
variant Option [T]
  Some value: T
  None

def value-or [value: Option[Int] fallback: Int] -> Int
  match value
    Some item
      item
    None
      fallback
```

The older angle-bracket spelling is accepted as source compatibility input, but
the formatter emits square brackets. The parser recognizes type applications
only in annotation contexts, so they do not conflict with vector expressions or
comparison operators. `Any` explicitly means unrestricted; errors MUST NOT
silently introduce it. Generic parameters are lexically scoped to their record
or variant declaration and do not create module-level types.

[`TYPE_SYSTEM_BOUNDARIES.md`](TYPE_SYSTEM_BOUNDARIES.md) gives the concise,
non-normative guide to which checks occur during compilation and which remain
at explicit dynamic, artifact, or host boundaries.

### 10. Results and matching

`Result[T, E]` has `Ok value` and `Error problem`. Match bindings are local and
only the selected branch evaluates. Matches over closed variants MUST be
exhaustive.

The pure `std/results` module composes these values through `map`, `map-error`,
`and-then`, `recover`, `get-or`, `ok?`, and `error?`. These helpers MUST retain
the concrete success and error relationships inferred from their callbacks and
inputs; they do not introduce effects or a separate runtime representation.

When the matched value has no explicit type, a complete set of case names MAY
identify its closed variant. Implementations MUST require an explicit type if
those cases do not identify exactly one variant; pattern inference MUST NOT
silently select between ambiguous variants.

### 11. View composition

Functions may return `View` or `Views`. `View` is one node; `Views` is an ordered
sequence that introduces no wrapper node. The `views` form constructs and
flattens sequences. Builders accept typed colon properties and ordered text,
`View`, or `Views` children. `for` and `when` return `Views`. The two types are
not interchangeable in returns or conditional branches, and an application's
root rendering function returns `View`. Duplicate properties are errors unless
a builder documents another policy. Ordinary functions compose in views without
compiler registration. An unannotated synchronous function whose body
unambiguously produces `View`, `Views`, or `Terminal` MUST infer that return
type, including through other inferred rendering functions; composition MUST
NOT require a redundant return annotation.

`br` is the zero-argument line-break view. It emits one HTML-style break and
accepts no properties, events, text, or child views:

```margeux
p
  "First line"
  br
  "Second line"
```

String, CLI, and terminal line breaks continue to use `\n`; `br` exists only
in GUI view composition.

`iframe` embeds a browser document as an inert view element. It requires a
relative, HTTP, HTTPS, or `about:blank` `:src`; executable URL schemes and
inline `srcdoc` documents MUST be rejected by browser and server renderers.
Its content executes within a browser document boundary and is not part of the
parent Margeux application's model or view tree.

`process-view` launches an application as an isolated session in the same
canonical runtime as its parent. The application is described directly by
`:entry` and `:files`, or lazily by a same-origin `:document` whose
`application/margeux` script elements name the entry and source files. Loading
a process document MUST NOT execute that document's scripts or create another
VM. Its `:key` identifies the child session across parent renders. GUI and TUI
children render in place and keep their own model, event history, and undo
cursor. A process view does not expose the Studio preview debugger controls;
server rendering emits only a deterministic hydration shell and MUST NOT start
the child application.

The canonical VM's public GUI `View` tree MAY be serialized to HTML without
re-executing a view function. Server rendering MUST escape text and attribute
values, use deterministic attribute and event order, retain stable handler
metadata for hydration, and reject renderer-specific nodes it cannot represent
rather than silently changing them. Server rendering MUST NOT invoke handlers,
resume commands, or grant host capabilities.

`:style` accepts either a raw String for HTML compatibility or an immutable
Dict for locally scoped declarations. Dict keys use lowercase CSS kebab-case
(or `--custom-property` form); values are String, Int, or finite Float. The
runtime sorts keys and emits one deterministic declaration String on the public
View. Empty values, declaration delimiters, control characters, compound
values, non-finite numbers, and bounded-size violations are errors. A style
Dict affects only its owning node and introduces no global selector state.

For ordinary literal styles, a readable declaration block lowers to the same
checked Dict representation:

```margeux
div
  :style
    columns 3
    gap 1 rem
    margin-bottom 1.5 rem
    border-bottom 1 px solid black
```

Numeric unit tokens are joined (`1.5 rem` becomes `1.5rem`). `columns N` is a
checked grid shorthand that emits `display:grid` and `N` equal columns. Invalid
compound values and common border-style misspellings are compile errors. Raw
String and explicit Dict forms remain available for dynamic or advanced CSS.
`keep-together true` prevents an element from being divided across printed
pages; `false` restores normal page-breaking behavior.

A lone numeric value on a layout measurement uses Margeux's scalable spacing
unit, one quarter of a root em. Thus `gap 4` emits `gap:1rem`, `padding 2.5`
emits `padding:0.625rem`, and zero emits `0`. This default applies to gaps,
margins, padding, dimensions, inset positions, and border radius. It does not
apply to inherently unitless properties such as opacity, z-index, line height,
or font weight. Exact CSS measurements remain explicit with `px`, `rem`, `em`,
`percent`, `vh`, `vw`, `vmin`, `vmax`, and `fr`.

Reusable application styles use ordinary view composition:

```margeux
stylesheet
  style-rule ".card:hover"
    :background-color "navy"
    :color "white"
  media-rule "(max-width: 600px)"
    style-rule ".card"
      :padding "4px"
```

`stylesheet` accepts `style-rule` and `media-rule` children. A `style-rule`
has exactly one selector String and at least one declaration property. A
`media-rule` has one condition String and one or more `style-rule` children.
Declaration ordering and validation are identical to `:style` Dicts. Rule
order remains source order. Selector lists use separate `style-rule` children.
Nested media rules, events, keys, malformed selectors, CSS block delimiters,
and bounded-size violations are errors.

Before a public snapshot crosses a host boundary, the canonical runtime
compiles this tree to one deterministic CSS String and adds a stable
`data-margeux-scope` to the application's root view. Each selector matches
either that root or its descendants. Application CSS therefore supports
pseudo-selectors and media queries without escaping into Studio, an embedding
page, or another Margeux application. `:scope` explicitly selects the
application root.

### 12. Iteration

`for name in collection` produces `Views` and scopes its binding to the
body. Using an unannotated value as the collection infers `Vector`; when its
element type is known, the loop binding receives that type for checking and
inference. Keys are unique within the originating loop for that render; separate
loops have separate key scopes.

The ordinary-source `std/sort` module provides stable sorting without making
every `std/vectors` user compile its implementation. `sort.ascending values`
and `sort.descending values` provide numeric order. `sort.using less? values`
accepts a strict
two-argument comparator and preserves source order when neither value precedes
the other. Sorting is immutable and retains `Vector[T]`.

### 13. Events and bindings

Event properties receive functions and never run during view construction. The
framework invokes them with current model state and the event contract's value.
Inline handlers use explicit `fn`. Click and submit actions receive `[model]`;
input actions receive `[model value: String]`; pointer and key actions receive
`[model event: Dict]`. Handler arity, parameter types, synchronous execution,
and return model type are validated before execution. A returned model replaces
state.

`:on-drag` actions receive `[model event: Dict]`. The event contains `kind`,
`x`, `y`, `dx`, `dy`, and `button`; deltas describe movement since the previous
delivered drag position. Dragging is distinct from `:on-pointer`, which remains
a completed pointer action rather than a stream of movement events.

`:bind model.field` identifies a writable model field rather than merely reading
its value. Input changes immutably update state according to control conversion
rules.

### 14. Applications

An application names initialization and rendering functions. A stateful GUI or
TUI uses `model` or a zero-argument `init` function; `view` maps that model type
to `View` or `Terminal`. A stateless GUI may omit `model` and `init` and use a
zero-argument view. The runtime supplies an internal empty model in that case,
so the compiled lifecycle remains uniform. Stateless GUIs cannot declare
`update` or `start`. The framework validates compatible model types across
initialization, rendering, updates, and handlers.

An explicit `init` MAY return an empty `Dict`; reference and bytecode runtimes
MUST treat that value consistently.

CLI and server roles replace the state/view lifecycle with a validated `main`
function. CLI main accepts `Vector[String]` and returns `cli.Response`. Server
main accepts `server.Request` and returns `server.Response` or
`server.StreamResponse`, directly or inside an async `Result`. The normative
server adapter and security contract is specified in
`MARGEUX_SERVER_0_1_SPEC.md`.

An optional `start Message` entry dispatches one ordinary update message after
the initial model is created. If that update returns a command, hosts settle the
command before presenting the first interactive view. This is the explicit way
to load files or perform another capability-gated startup task without making
`init` or `view` effectful.

The declaration of a stateless GUI with the conventional zero-argument
function `view` may be shortened to:

```margeux
app Greeting
```

This is exactly equivalent to `app Greeting` with `gui` and `view view`
children. The explicit form is required for state, capabilities, TUI, CLI,
server, startup behavior, or a differently named rendering function.

### 15. Strings and interpolation

Quoted strings support escaped quotes, backslashes, and common control escapes.
Unescaped braces contain expressions in lexical scope; `\{` and `\}` are
literal braces. Interpolation uses the normal parser and preserves original
source spans.

A raw multiline string uses standalone triple-quote delimiters:

```margeux
let query
  """
  select id, title
  from posts
  where published = true
  """
```

The delimiter indentation is removed from every nonblank content line. The
result has no implicit leading or trailing newline; physical lines between the
delimiters are joined with `\n`. Quotes, backslashes, braces, and `#` are literal
content, so raw multiline strings do not interpolate or process escapes. Both
delimiters MUST be the only non-whitespace content on their lines and MUST use
the same indentation. Nonblank content MUST NOT be outdented past them.

`string value` and its alias `str value` produce Margeux's stable textual
representation rather than a host-language representation. A top-level String
is returned unchanged. Nil, Bool, Int, and Float use their source spelling.
Nested Strings are quoted and escaped; Vectors use `[item item]`; Dict fields
are sorted by Unicode key and use `{:key value}`; Records use
`Type{:field value}`; and Variants use `Case` or `Case(value)`. Functions,
tasks, views, and terminals use their documented opaque display forms. This
representation is deterministic across execution engines and is intended for
people and diagnostics, not data interchange; programs use `json.stringify`
for machine-readable serialization.

### 16. Modules and intrinsics

`use "std/math"` imports a module namespace. `export` explicitly lists public
names. `intrinsic name [parameters] -> Return` declares documented host-backed
behavior. Libraries SHOULD use ordinary Margeux definitions when practical.

An indented `use` suite selectively imports exported names into local scope
while preserving the module namespace:

```margeux
use "std/cli"
  Response
  success

def done [] -> Response
  success "Done\n"
```

Each selected name MUST be a simple exported name. Duplicate selections,
unknown or private names, and conflicts with local declarations are errors.
Qualified access such as `cli.failure` remains available after a selective
import.

Small programs and teaching examples SHOULD select the few names they use so
the computation remains visually direct. Larger modules MAY prefer qualified
access when it materially clarifies ownership or avoids collisions. These are
two uses of the same module system, not separate language modes.

Reproducible external source dependencies use strict `margeux.json` manifests
and verified `margeux.lock` snapshots. Package imports have the form
`use "pkg/owner/name"` and retain `name.member` as their explicit source
namespace. The normative resolution and artifact contract is
`MARGEUX_PACKAGES_0_1_SPEC.md`.

### 17. Extension requirements

Extensions preserve structural grouping unless selecting a different reader.
Macros preserve spans and lexical information and are hygienic by default; the
normative 0.1 expansion contract is in
`MARGEUX_MACRO_0_1_SPEC.md`.
Builtins and user constructs SHOULD lower to a documented core. Editor support
MUST NOT rely solely on a fixed list of block heads. Macro syntax is specified
separately.

### 18. Diagnostics and tooling

Compiler and editor agree on tokens, indentation, grouping, and qualified names.
Diagnostics identify the relevant source span and rule. Type-mismatch
diagnostics MUST name the expected and actual source-visible types, including
types inferred from omitted annotations. A qualified imported call MUST retain
that source-qualified callable name in its diagnostic. UTF-8 byte offsets are explicitly
converted for UTF-16 editors. Newline normalization preserves source mappings.
Recovery SHOULD retain malformed structure rather than discard unrelated forms.

The compiler exposes version-matched syntax metadata for editor highlighting and
indentation. Standard-library member metadata derives from parsed module exports;
editors SHOULD consume this contract instead of maintaining independent keyword,
type, view-tag, or block-head catalogues.

Tooling SHOULD treat generic type parameters as scoped symbols with definition,
reference, hover, rename, and semantic-token identity. Reusing a parameter name
in a different record or variant MUST NOT merge those identities.

Synchronous and asynchronous function declarations MUST participate in the same
navigation and signature-help model. For a semantically valid workspace, hover
and signature help SHOULD display checked inferred parameter and result types
when their source annotations are omitted; incomplete source retains a
syntax-only fallback. Displayed nominal types use the declaration's
source-visible module namespace rather than an internal canonical path.

Canvas graphics, TUI/workspace surfaces, server applications, asynchronous
commands, protocols, and macros are companion specifications layered on this
core.

The canonical formatter uses two-space structural indentation, one space
between terms, LF line endings, one final newline, preserved comments, and
square brackets for generic type applications. It is independent of Studio.
Formatting valid source MUST be idempotent and MUST preserve its canonical
syntax tree. Canonical invocation and data spellings are `function argument`,
`call function` for zero arguments, `value.field`, `module.member`, `with value`
for immutable updates, and `|>` for an explicitly staged pipeline.

## Language: Application runtime

Authoritative source: `MARGEUX_RUNTIME_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented contract  
**Scope:** GUI and TUI application state, rendering, transitions, effects, and time travel.

### 0. Canonical runtime identity

Margeux has one runtime contract. Bytecode execution, immutable values, numeric
behavior, application transitions, effects, capabilities, diagnostics, and
resource limits are defined once by the Margeux specifications and versioned
bytecode contract.

The Go register VM is the sole canonical execution engine and is used for
development, Studio, native applications, and browser hosts through Go/Wasm.
Direct WebAssembly is an optional, conformance-gated code-generation backend,
not another Margeux runtime or language edition. Its development is frozen
until the canonical VM and language are complete; it is not a 0.1 completion
requirement. The CLI MUST NOT expose that backend under the unqualified name
`wasm`, because browser Margeux uses this canonical Go VM compiled to Wasm.
Host adapters may differ by platform, but they MUST
implement the same capability contracts and expose the same observable Margeux
behavior.

The concrete 0.1 native/browser surface and capability matrix is maintained in
[`SUPPORTED_HOST_CONTRACTS.md`](SUPPORTED_HOST_CONTRACTS.md). Feature work is
governed by [`V0_1_STABILIZATION_POLICY.md`](V0_1_STABILIZATION_POLICY.md)
until the complete release evidence is current.

The public GUI View or TUI Terminal snapshot is also the sole input to native
HTML server rendering. Serialization does not re-run application code or
create an alternate view runtime; browser hydration must resume through the
same Wasm-hosted canonical VM and the handler or terminal-input contract
already present in the snapshot.

The source evaluator used by compiler analysis and differential tests is an
implementation oracle, not a user-selectable runtime. Public native, browser,
REPL, server, and embedding entry points MUST compile to validated Margeux
bytecode and execute the register VM unless an explicitly optimized artifact
has passed the same conformance contract. Repository tests scan production Go
code and reject calls into evaluator session constructors. Even the language
knowledge corpus verifies bundled examples through the compiler and register
VM rather than treating the evaluator as an executable product path.
Production code is additionally forbidden from naming the evaluator's
stateful `Session` and `REPL` types or dot-importing the frontend package. This
prevents constructor renames, wrappers, and struct literals from quietly
creating a second execution path while leaving the parser, diagnostics, and
source metadata available to tooling.

Every operation admitted by an optimizing backend MUST pass differential
conformance against the canonical VM, including successful values, traps,
source diagnostics, limits, and application transitions where applicable. An
operation not yet covered by that evidence MUST fail at build time; an engine
MUST NOT silently substitute different semantics or fall back to an undeclared
host implementation.

Bytecode 1.52 serializes whether each named function or closure is async.
Consequently indirect calls through unannotated higher-order parameters retain
the original callable's identity: only an async target constructs a lazy Task.
The compiler, native VM, Go/Wasm VM, server host, and embedding API all consume
that same metadata rather than reconstructing async behavior independently.
Function identity survives moves, lexical capture, collection storage,
serialization, host invocation, and opaque callable invocation. Synchronous
collection operators and application event/continuation slots inspect this
identity and reject async functions before executing them.

#### 0.1 Canonical dynamic values

Concrete typed paths remain unboxed. A value crossing into `Any`, abstract
`Number`, a heterogeneous collection, or another dynamically typed boundary
uses one canonical logical representation: a two-word immutable record whose
first word is a stable concrete tag and whose second word is the complete raw
payload. The initial tags, numbered from zero, are `Nil`, `Bool`, `Int`,
`Float`, `String`, `Vector`, `Dict`, `Record`, `Variant`, `Function`, `Task`,
`View`, and `Terminal`. Float payloads contain raw finite binary64 bits; heap
payloads contain the compact allocation address. The representation retains
the full 64 bits of Int and Float rather than stealing payload bits for tags.

Bytecode signatures identify function boundaries and `BOX_DYNAMIC` identifies
the concrete transition. The canonical Go VM may use its native tagged
value representation, but an optimizing engine MUST expose equivalent tags and
payloads internally and MUST preserve the same observable Margeux value.
Dynamic unboxing and dispatch MUST validate the tag before interpreting the
payload. Heterogeneous vectors store canonical dynamic values in every element
slot. A homogeneous vector remains unboxed until it crosses such a boundary;
`BOX_VECTOR_DYNAMIC` performs an immutable element-wise transition without
changing the source vector.
Dictionary keys retain the compact UTF-8 String representation. Every
dictionary value slot stores a canonical dynamic value, including homogeneous
source literals. Construction rejects duplicate keys, `DICT_GET` returns boxed
`nil` for a missing key, and `DICT_ASSOC` returns a fresh dictionary while
preserving the original value.
Record field slots and present Variant payload slots likewise store canonical
dynamic values. Known field access and pattern binding perform checked,
path-local unboxing according to the declared schema; dynamic access preserves
the canonical value. Record construction and immutable `with` updates, and
Variant construction, MUST establish this invariant before the value can cross
another boundary. This makes nested Records and Variants self-describing
without requiring an optimizing runtime to recover source schemas.
`UNBOX_DYNAMIC` is the inverse representation boundary for a concrete use. It
MUST validate the tag before extracting the payload and MUST leave its source
box unchanged. Compilers use path-local results so an `Any` value tested as one
type in a branch cannot corrupt its representation on another branch.
Operations that remain deliberately overloaded do not guess a payload layout.
`DYNAMIC_LENGTH` and `DYNAMIC_EMPTY` accept only boxed String, Vector, or Dict
values, dispatch on the stable tag, and then read the payload's logical length.
`DYNAMIC_IS_NIL` compares the canonical tag rather than the box address.
`DYNAMIC_GET` validates both the collection tag and the opcode's key mode before
performing an indexed Vector read or a UTF-8 Dict lookup. It returns the
canonical dynamic value stored in the selected slot; a missing Dict key returns
boxed `nil`, while an invalid Vector index fails. A homogeneous Vector crossing
an `Any` or Dict boundary MUST first canonicalize each known element, so a
subsequent dynamic read never has to infer an element type from payload bits.
For a nested homogeneous Vector this rule applies recursively from the leaf
Vector outward. A Vector whose leaf type is `Any` or `Number` preserves those
already canonical leaf slots rather than boxing their box addresses again.
`UNBOX_VECTOR_DYNAMIC` is the inverse immutable boundary for typed collection
callbacks. It validates every element tag and produces a fresh homogeneous
Vector of raw payloads, recursively reconstructing nested homogeneous Vectors
and leaving the canonical source unchanged. A mismatch at any depth fails
before the callback executes. Appending to a canonical dynamic Vector first
canonicalizes the appended value and preserves the representation invariant.
`DYNAMIC_EQUAL` implements language equality over canonical values. Nil, Bool,
Int, finite Float, and String use value semantics; mixed Int/Float comparison
is exact and never rounds the Int through Float. Vector, Dict, Record, and
Variant equality is recursive. Dict equality is independent of insertion order
and distinguishes a missing key from a present key whose value is `nil`.
Records require the same nominal type and schema-ordered fields; Variants
require the same nominal type, case, payload presence, and payload value.
Function values are never equal. Effectful Task, View, and Terminal equality is
not part of the direct scalar contract and MUST fail rather than compare host
pointers.
`DYNAMIC_SLICE` accepts only a canonical String or Vector plus two raw Int
bounds. It dispatches on the stable collection tag, applies the same immutable
checked-and-clamped slice contract as the statically typed operation, and
returns a fresh canonical box of the same concrete kind. String indexes count
Unicode code points. An invalid tag or invalid bound MUST fail before exposing
or reinterpreting a payload.
`DYNAMIC_STRINGIFY` dispatches on the canonical tag and produces the stable
human-readable representation specified by the core language. It recursively
formats canonical collection and nominal payloads, sorts Dict fields by Unicode
key, removes internal module qualification from public nominal names, and never
exposes allocation addresses or host-language formatting. Its result is an
ordinary String because the operation itself has a statically known result.

### 1. State machine

A running application owns one immutable model value. A stateless GUI uses an
internal empty Dict and may expose a zero-argument view; stateful GUI and TUI
applications expose the model normally. Their pure application functions have
these conceptual shapes:

```margeux
update : Model Message -> Model | Command<Model, Message>
view : Model -> View | Terminal
stateless-view : () -> View
```

The runtime stores the model returned by a successful update. Application code
cannot mutate the previous model. A view constructs an inspectable display
value; it does not draw, access files, perform HTTP requests, or otherwise run a
host effect.

TUI applications may accept a pane and normalized input event in addition to
the model. The same transition rules apply.

### 2. Atomic transitions

A deferred GUI event, TUI key, TUI pointer input, or command completion is one
transition. The runtime MUST:

1. retain the current checkpoint;
2. run the handler and update;
3. render the resulting model;
4. commit the transition only if all three operations succeed.

If handling, updating, or rendering fails, the runtime restores the model,
pending command, and TUI focus from the retained checkpoint. A failed command
completion therefore remains pending and may be inspected or retried.

### 3. Effects

Tasks are lazy values. Constructing a task or returning a `command` does not run
the task. The runtime runs it only at the explicit command-completion boundary,
then passes its `Result` to the declared continuation and feeds that message
through `update`.

Views remain pure even when an application has capabilities. Host effects are
not reversible: undo restores Margeux state but cannot undo an HTTP request,
file write, process, clock read, or other already completed host operation.

### 4. Transition journal

The canonical register VM retains the latest 256 committed transitions. Each public
journal entry contains:

- a monotonic sequence number;
- the transition kind and normalized input;
- public model snapshots before and after the transition; and
- whether a command was pending before and after it.

The journal cursor is the number of currently applied entries. Application
initialization and its optional startup message establish state zero.

`Undo` restores the private checkpoint before the preceding entry. `Redo`
restores the checkpoint after the following entry. Neither operation re-runs
application code or host effects. Dispatching new input after undo discards the
redo branch while sequence numbers remain monotonic.

Rendering after time travel regenerates handlers from the restored model, so
stale handler identifiers are never retained.

`Seek` restores any retained cursor directly, with the same no-execution
semantics as undo and redo.

#### 4.1 Named checkpoints and state comparison

A session may attach at most 64 unique UTF-8 names of at most 64 characters to
retained journal cursors. Saving an existing name deliberately moves it to the
current cursor. A named checkpoint is a bounded bookmark, not an independent
unbounded model copy: labels older than the retained journal are removed, their
cursors shift with eviction, and labels on a discarded redo branch are removed.

Restoring a named checkpoint has the same no-execution semantics as `Seek`.
Deleting a name does not alter application state. Comparing a checkpoint with
the current state produces deterministically ordered JSON-pointer paths and
tagged before/after values. Comparison includes the immutable model, whether a
command is pending, and TUI focus. It does not expose private handlers or task
continuations.

### 5. Portable traces

A version 1 trace is bound to the SHA-256 digest of the complete bytecode
module and records the application identity, state-zero model, normalized
inputs, expected state after every transition, and command completion Results.
Integers and floating-point values use tagged exact spellings rather than
untyped JSON numbers.

Replay MUST start the same module from state zero. It re-executes pure GUI and
TUI inputs, injects captured `Ok` or `Error` command results, and verifies the
model, pending-command state, and TUI focus after every step. It MUST NOT invoke
the host tasks represented by those captured results. A mismatched module,
malformed value, missing result, or divergent checkpoint terminates replay.

A trace cannot be exported after bounded-history eviction or compatible model
adoption because the retained journal no longer contains a reproducible
state-zero checkpoint.

### 6. Recompilation

A compatible live recompile may adopt the previous immutable model and TUI
focus. It MUST NOT adopt handlers, pending effects, or transition history,
because those values belong to the replaced program. The adopted model becomes
state zero of the replacement session.

### 7. Browser contract

The Wasm runtime exposes `history`, `undo`, `redo`, `seek`, `checkpoints`,
`saveCheckpoint`, `restoreCheckpoint`, `deleteCheckpoint`, `diffCheckpoint`,
`exportTrace`, and `replayTrace` requests for reference-engine sessions. Margeux
Studio presents a seekable transition list, named checkpoint controls,
structured state comparison, trace download/import, and undo/redo beside each
embedded runtime preview. They are distinct from source-editor undo and Studio
run-checkpoint undo.

## Language: Portable bytecode

Authoritative source: `MARGEUX_BYTECODE_0_1_SPEC.md`. Classification: **normative**.

This document specifies the first portable Margeux bytecode container. The
format, validator, disassembler, and initial bounded register VM are implemented
by `internal/bytecode`. Source lowering currently covers entry blocks, lexical
bindings, annotated named functions and calls, literals, checked mixed numeric
arithmetic and exact comparisons, short-circuit Boolean operators, and lazy
conditionals, and will expand toward the complete language.

Interpolated strings lower each embedded expression through the ordinary
compiler, cross the canonical tagged boundary, apply `DYNAMIC_STRINGIFY`, and
join all literal and computed segments with `CONCAT_STRING`. Each generated
instruction retains the segment or expression's original source location;
interpolation does not introduce a second offset coordinate system.

Portable user modules are statically linked before bytecode lowering. `use`
paths are normalized relative to the importing file, cycles and missing modules
are rejected, and imported members remain qualified. Explicit `export` lists
limit the names visible to importers; exporting a variant type also exposes its
constructors through that module namespace. Linked symbols receive a
path-qualified internal name, while function location tables retain their
originating source path. Exported and private module constants lower to hidden
zero-argument initializer functions. The compiler loads them in module order
before the entry expression. `LOAD_GLOBAL` evaluates each initializer at most
once per VM execution, caches its immutable result, and traps direct or
indirect initialization cycles. Bundled `std/*` modules remain excluded until
their operations are either ordinary portable Margeux or have explicit
intrinsic contracts; version 1.17 admits `std/math`, `std/vectors`, the
deterministic state-threaded `std/random` module, and the nominal-record
`std/vec3` and `std/animation` modules. Version 1.18 adds the bounded
deterministic intrinsic contract required by `std/grid` and admits the pure
`std/ui` and `std/input` modules. Dotted access on statically known records uses
`RECORD_GET`; dotted access on `Dict` values lowers to `COLLECTION_GET`.
Version 1.19 adds the bounded deterministic `ray3d.*` intrinsic contract.
Version 1.20 adds lazy user and host tasks, `await`, Result propagation,
deterministic JSON operations, and an embedded immutable source snapshot. This
admits the remaining `std/cli`, `std/time`, `std/process`, `std/storage`, and
`std/source` modules.

Version 1.21 encodes an optional application lifecycle table naming its `init`,
optional `start`, `update`, and `view` function indices, along with the app
name, surface, and sorted capability list. Those functions exchange immutable
VM values: the model is a Dict, a view is a Dict-backed declarative node, and
an update returns either a model or a reserved command envelope containing a
suspended Task and Result continuations. Event properties retain opaque VM
message or function values; the host never serializes or evaluates them
itself. Consequently a standalone `.mgxc` contains everything required to
initialize and run its application lifecycle.

Version 1.21 also adds the compact `MAKE_TERMINAL_DRAW` instruction. Portable
TUI applications construct immutable terminal values in `view`; the host
validates and rasterizes those values after evaluation. Keyboard and pointer
events enter the same immutable `update` lifecycle as GUI events, so rendering
does not perform terminal effects.

Workspace, split, and pane constructors lower to reserved immutable Dict
values and require no effectful opcode. The application host validates the
layout, rasterizes pane borders and clipped child terminals, retains ephemeral
focus, reserves focus-navigation keys, and translates pointer positions to
pane-local coordinates before invoking `update`.

Version 1.22 adds `MAKE_VIEW`, a compact declarative View constructor whose
metadata names the tag and ordered properties while registers hold immutable
property and child vectors. It prevents large canvas display lists from
exhausting the fixed register file. Canvas children may also lower into small
capture-aware helper functions; evaluation remains eager and ordered. The
portable application host validates canvas dimensions and primitives before a
browser or native renderer receives the display list.

Version 1.23 adds non-trapping `TRY_CONVERT_INT` and `TRY_CONVERT_FLOAT`
instructions, which return `Result` values, and `PROTOCOL_CALL`, whose closed
dispatch table selects an implementation from the runtime type of its first
argument. Protocol tables contain only validated functions linked into the
same artifact.

Version 1.24 adds an optional CLI `main` function index to application
metadata. A `cli` surface requires this index and the referenced function must
accept one argument. The host supplies a `Vector[String]`, resolves a returned
Task when necessary, and validates the resulting `cli.Response`. CLI artifacts
therefore execute without embedded source or the reference interpreter.

Version 1.25 permits a `server` application surface using the existing
validated one-argument `main` index. The host supplies a nominal
`std/server.Request`, optionally resolves a returned Task Result through the
capability boundary, and validates `std/server.Response`. Server artifacts may
be stripped and served without source.

Version 1.26 adds `INT_BINARY_CONST`, a general dispatch-reduction instruction
for checked integer arithmetic and comparisons whose right operand is a
constant. It preserves the ordinary operation's overflow, zero-divisor, type,
and source-location behavior. The fused operation consumes one instruction
budget unit; compilers may always emit the older `LOAD_CONST` plus binary
instruction sequence when fusion is unavailable.

Version 1.27 extends the deterministic intrinsic registry with `llm.digest`
and `llm.apply-json`. The former computes a lowercase SHA-256 source digest;
the latter validates a request/completion pair and returns an immutable,
canonically ordered candidate source snapshot. Neither operation performs
inference, writes files, or executes generated source.

Version 1.28 extends the validated host-task registry with `http.request` and
`agent.identity`. The former constructs a four-argument lazy task containing
method, URL, body, and content type. The latter constructs a zero-argument lazy
task that reports the configured LLM provider and model before inference.
Validation rejects either task in older artifacts; execution still requires
the application's explicit `http` or `llm` capability.

Version 1.29 adds `INT_COMPARE_JUMP_FALSE`. It compares two Int registers and
branches when the selected equality or ordering relation is false, without
materializing an intermediate Boolean. Compilers emit it only when the
ordinary comparison result has no other consumer. The fused instruction keeps
the comparison's source location and consumes one instruction-budget unit.

Version 1.30 adds `TAIL_CALL_DIRECT` for tail-position calls whose top-level
function target and arity are statically known. It carries the linked function
index, argument-window start, and argument count directly, avoiding a temporary
function register and dynamic target check. The VM preserves the ordinary tail
call's frame reuse, exact parameter rebinding, source location, instruction
budget, and error behavior. Calls through locals and closures continue to use
`TAIL_CALL`.

Version 1.31 adds `INT_MULTIPLY_REMAINDER_CONST` for a checked Int
multiplication whose sole result consumer is an immediately following
remainder by a nonzero Int constant. It retains the multiplication's source
location and overflow behavior, uses the prepared constant-remainder metadata,
and consumes one instruction-budget unit. Compilers do not fuse when another
instruction consumes the product or when control flow enters at the remainder.

Version 1.32 extends `INT_BINARY_CONST` with a `not-equal` selector. The
compiler uses it for `!=` when the left operand is known to be Int and the
right operand is an Int literal, replacing the prior equality plus Boolean
negation sequence. It preserves exact Int comparison semantics and consumes
one instruction-budget unit. The selector was appended so every operation
encoded by versions 1.26 through 1.31 retains its numeric identity; validators
reject `not-equal` in modules older than 1.32.

Version 1.33 adds `INT_REMAINDER_PREDICATE_CONST` for the common divisibility
forms `= (% value divisor) 0` and `!= (% value divisor) 0`, including the
equivalent comparison with zero on the left. Mode zero tests for a zero
remainder and mode one tests for a nonzero remainder. The operation uses the
same signed, zero-divisor, `MinInt64 / -1`, prepared-reciprocal, source-location,
and checked-Int behavior as ordinary remainder, produces Bool directly, and
consumes one instruction-budget unit.

Version 1.34 adds `INT_RETURN`, which combines a checked integer operation and
the immediately following return. With Imm equal to -1, A and B are register
operands. With a nonnegative Imm, A is the left register and Imm indexes the
right Int constant. C uses the stable integer-operation selectors 0 through 8,
or 9 and 10 for constant remainder-zero and remainder-nonzero predicates. The
compiler emits it only when the operation result is returned directly and no
branch enters at the removed `RETURN`. It retains the operation's source
location, checked arithmetic and type failures, prepared constant-remainder
behavior, and ordinary function-return semantics while consuming one
instruction-budget unit.

Version 1.35 adds `TAIL_CALL_DIRECT_3` for statically linked three-parameter
tail calls whose already-evaluated arguments do not occupy one contiguous
register window. A, B, and C name the three argument registers and Imm names
the linked target. The VM snapshots all three values before rebinding parameter
registers, so permutations and overlapping destination slots remain correct.
The compiler replaces only its canonical infallible argument shuffles, refuses
control-flow entry inside the removed sequence, preserves left-to-right
argument evaluation and the tail call's source location, and consumes one
instruction-budget unit.

Version 1.36 adds `INT_ADD_REMAINDER_CONST` for checked addition immediately
followed by signed remainder with a nonzero Int constant. B and C name the
addition operands, Imm indexes the divisor, and A receives the remainder. The
compiler emits it only when the sum has no other consumer and no branch enters
at the removed remainder instruction. It retains the addition's source
location, checked overflow, operand-type failures, signed `MinInt64 % -1`
behavior, prepared reciprocal fallback, and one instruction-budget unit.

Version 1.37 adds `INT_ADD_REMAINDER_TAIL_SELF_3` for an immediately adjacent
checked add/remainder and three-argument self tail call whose third argument is
the arithmetic result. A and B name the add operands; C names the first tail
argument. Imm packs a 20-bit nonzero Int divisor-constant index and the second
argument register in bits 20 through 27. The current function is the implicit
target and must have exactly three parameters. The VM computes the checked
result before snapshotting the already-evaluated first and second arguments,
then rebinds all three parameters and clears scratch registers. The compiler
requires the arithmetic result to have no other consumer, refuses aliasing that
would change argument values, and refuses branch entry at the removed call. The
instruction retains the arithmetic source location, left-to-right failure
order, signed remainder and prepared-reciprocal behavior, and consumes one
instruction-budget unit.

Version 1.38 extends the validated capability and host-task registries with
`database` and `db.query`, `db.execute`, and `db.transaction`. These tasks carry
only SQL text and portable values; connection credentials remain entirely in
the host. Validators reject the capability and tasks in older artifacts.

Version 1.39 adds `STRING_SLICE`, an append-only specialization of `SLICE` for
statically known `String` operands. A, B, and C name the destination, source,
and start registers, while Imm names the end register. Bounds retain the
existing non-negative, ordered, code-point-indexed, and clamped semantics.
Legacy `SLICE` remains valid for both vectors and strings in older artifacts;
new compilers emit `STRING_SLICE` when the source type is known so direct
backends never need to guess a heap value's representation.

Version 1.40 adds `EQUAL_STRING`, an append-only specialization of
`EQUAL_VALUE` for two statically known `String` operands. A receives whether
String B and String C contain exactly the same UTF-8 bytes. The portable VM
retains generic structural equality for legacy and dynamically typed code;
direct backends may use the specialized operation without runtime heap tags.

Version 1.41 adds homogeneous finite-Float arithmetic and comparison opcodes
plus `INT_TO_FLOAT`. These append-only operations let direct backends preserve
binary64 values as unboxed bits without confusing them with Int payloads.
Arithmetic rejects division by either signed zero and any result that is NaN
or infinite. Mixed arithmetic may explicitly convert its known Int operand;
mixed Int/Float comparison remains on the generic exact-number path so an Int
is never rounded through binary64 merely to compare it.

Version 1.42 adds `COMPARE_INT_FLOAT` and `COMPARE_FLOAT_INT`. Imm selects
equality, less-than, or less-than-or-equal as values 0 through 2. Operand order
is part of the opcode, so direct backends can implement the exact mixed numeric
contract without dynamic tags and without rounding the Int through binary64.

Version 1.43 adds a canonical function-signature table to every function
record: zero or one type name for each parameter followed by an optional result
type name. Current compilers always emit complete signatures. Empty tables are
accepted for hand-authored and compatibility-test modules, but an optimizing
engine MUST use an emitted signature as the representation boundary rather
than inventing a backend-specific type convention. It also adds `BOX_DYNAMIC`,
which explicitly changes a statically known raw representation into the
canonical two-word dynamic representation. Imm contains the stable concrete
tag and B contains the unboxed payload; A receives the boxed value. The
canonical Go VM treats this representation instruction as an identity because
its values already carry runtime tags. `BOX_VECTOR_DYNAMIC` performs the same
transition for every element of a homogeneous Vector and returns an immutable
Vector of canonical dynamic values; the source Vector remains unchanged.
Concrete typed paths remain unboxed;
`Any`, abstract `Number`, and heterogeneous container boundaries use the
canonical dynamic representation defined by the runtime contract. Signatures
and boxes do not change evaluation semantics or make explicit annotations
mandatory.

Version 1.44 adds `DICT_GET`, separating statically known dictionary lookup
from legacy overloaded collection lookup. Dictionary values are canonical
dynamic boxes while UTF-8 String keys remain compact String values.

Version 1.45 adds `UNBOX_DYNAMIC`. It validates a canonical dynamic tag and
extracts the untouched payload into a raw typed register. The source box is
not modified, so separate control-flow paths may safely consume the same value
under independently checked concrete expectations.

Version 1.46 adds `DYNAMIC_LENGTH` and `DYNAMIC_EMPTY` for operations that are
intentionally overloaded across String, Vector, and Dict. They validate one of
those three tags before reading the common first-word logical length from the
boxed payload. `DYNAMIC_IS_NIL` tests the tag itself, so boxed `nil` is not
mistaken for the nonzero address of its canonical allocation.
`DYNAMIC_GET` performs checked Vector indexing or Dict lookup when the
collection itself is dynamic; its key-mode immediate prevents a backend from
guessing the payload layout. `UNBOX_VECTOR_DYNAMIC` validates and immutably
copies canonical boxed elements into a homogeneous raw Vector for a concrete
typed callback. The Vector boxing opcodes encode the leaf tag in the low eight
bits of Imm and the nested Vector depth in the next eight bits. Leaf marker 255
means the slots are already canonical (`Any` or `Number`); depth is limited to
32. Boxing and unboxing recurse from the leaf outward without modifying any
source Vector.

Version 1.47 adds no opcode. It makes the existing canonical representation
recursive for nominal values: `MAKE_RECORD` and `RECORD_WITH` receive canonical
dynamic field values, `RECORD_GET` returns one, and a present `MAKE_VARIANT`
payload is canonical and returned unchanged by `VARIANT_PAYLOAD`. A compiler
uses the declared Record or Variant schema to insert checked `UNBOX_DYNAMIC`
operations at statically typed uses. The reference VM may retain its native
tagged values, where these transitions are identities.

Version 1.48 adds `DYNAMIC_EQUAL`. It compares two canonical values using the
runtime equality contract, including exact mixed numeric equality, recursive
Vector/Dict/Record/Variant content, nominal identity, and insertion-order-
independent dictionaries. It returns raw Bool and never exposes box or compact-
heap pointer identity.

Version 1.49 adds `DYNAMIC_SLICE`. It validates a canonical dynamic collection
as either a String or Vector, applies the ordinary immutable slicing contract,
and returns a newly boxed canonical value of the same concrete kind. String
bounds and results use Unicode code points. Invalid tags and invalid bounds
fail exactly as their statically typed counterparts.

Version 1.50 adds `DYNAMIC_STRINGIFY`. It converts one canonical dynamic value
to the deterministic Margeux human-readable String representation. The input
tag controls recursive formatting; implementations MUST NOT delegate compound
values to host-language formatting. The result is an ordinary compact String,
not a canonical dynamic box.

Version 1.51 adds the deterministic `server.encode-path` intrinsic. It converts
a decoded Unicode application path into its RFC 3986 wire spelling, preserving
slash separators and percent-encoding UTF-8 bytes, reserved characters, spaces,
and literal percent signs exactly once. This supports route-derived clients
without delegating URL semantics to a browser or native HTTP implementation.

Version 1.52 adds one serialized async marker to each function. `LOAD_FUNCTION`
and `MAKE_CLOSURE` retain that function identity, so an indirect `CALL` to an
async target constructs a lazy user Task instead of entering the body. This is
the same behavior as a statically known async call lowered with `MAKE_TASK` and
keeps higher-order async functions precise without a second runtime or an
effectful source-level wrapper. Calling a synchronous function still executes
it immediately; applying `AWAIT` to that result remains a runtime error when
the callable was too dynamic to reject statically.

Version 1.53 adds `FLOAT_TO_INT`. The source compiler emits it only when the
operand is statically `Float`, leaving String and dynamic conversions on the
general checked conversion path. It truncates toward zero, admits exactly the
half-open range [-2^63, 2^63), and rejects NaN, infinity, and out-of-range
values. This typed operation lets compact optimizing engines implement the
canonical conversion without guessing whether an untagged machine word is a
Float payload or a String address.

Version 1.54 adds `STRING_TO_INT`. The source compiler emits it only for a
statically known String. Implementations trim the canonical Unicode whitespace
set, accept one optional ASCII sign followed by ASCII decimal digits, detect
overflow before multiplication, and admit the complete signed 64-bit range.
Empty, sign-only, internally separated, non-decimal, and out-of-range inputs
fail conversion. The specialized operation prevents compact engines from
confusing a String heap address with an untagged numeric payload.

Version 1.55 adds the deterministic `dicts.keys` and immutable `dicts.remove`
intrinsics. `dicts.keys` accepts one Dict and returns every key exactly once in
ascending Unicode code-point order. `dicts.remove` accepts a Dict and String
key and returns a fresh Dict without that key; removing an absent key still
returns a distinct immutable value. Neither intrinsic mutates its input.

Version 1.56 adds `VECTOR_CONCAT`. It accepts two Vectors, allocates one flat
Vector containing the left elements followed by the right elements, and does
not mutate or alias either input. The source compiler uses it both for the
typed `std/vectors.concat` wrapper and for register-bounded construction of
large Vector literals.

Version 1.57 adds `DICT_MERGE`. It accepts two Dict values and returns an
immutable right-biased union: fields present in the right Dict replace fields
with the same String key from the left Dict. Neither input is mutated. The
source compiler uses it for the typed `std/dicts.merge` wrapper and for
register-bounded construction of large Dict literals.

Version 1.58 adds no opcode. It expands the validated deterministic intrinsic
registry with `testing.equal`, `testing.not-equal`, `testing.is-true`,
`testing.is-false`, `testing.check`, `testing.approx`, and `testing.fail`.
Assertion failures use the existing source-mapped runtime-error boundary.

Version 1.59 adds `RECORD_MERGE`. It accepts a nominal Record and a Dict patch,
validates that every patch key names an existing field, and returns one fresh
Record with the patch applied. Neither input is mutated. The source compiler
uses it to lower multi-field `with` expressions without copying the complete
record once per field.

Version 1.60 adds `CALL_DIRECT` for non-tail calls to statically linked,
synchronous top-level functions. The instruction identifies its target and
argument count directly, eliminating a separate `LOAD_FUNCTION` instruction
and dynamic callee lookup. Validation binds the target, arity, argument window,
and synchronous contract. Calls through local function values and closures
continue to use `CALL`.

Implementations MAY derive immutable execution metadata for constant integer
division and remainder when a module is compiled or decoded. The current VM
precomputes an unsigned reciprocal for every nonzero Int constant and uses
full-width multiplication for `INT_BINARY_CONST` remainder. It checks that the
constant still matches before using the metadata and otherwise falls back to
ordinary checked remainder. This preparation is not serialized, consumes no
instruction-budget unit, and MUST preserve signed truncation, zero-divisor, and
`MinInt % -1` behavior exactly.

Live replacement is a host lifecycle operation rather than a bytecode opcode.
After validating and initializing replacement bytecode, a host MAY adopt the
previous immutable model when the application surface, top-level field set,
and runtime field value types match. TUI focus MAY also transfer when its pane
still exists. Pending tasks, event handlers, and rendered output MUST NOT cross
the bytecode boundary; incompatible model shapes retain the freshly initialized
replacement model.

Application lowering uses the ordinary static module linker. Lifecycle entries
may name exported functions or constructors through an imported namespace; the
compiler generates entry-module wrappers and records their final linked
indices. Relative and transitive imports, visibility, cycles, standard modules,
and per-function source paths therefore have one contract for application and
non-application artifacts.

A bare function name loads a function value. Strict built-ins with fixed arity
also lower to ordinary function values, so expressions such as `reduce + 0
values` do not require adapters. Special forms whose evaluation is lazy remain
special forms rather than function values. The source form `call function`
lowers to `CALL` with an argument count of zero; invocation is never inferred
from a bare name.

A function held in a lexical parameter or binding is invoked with the same
prefix syntax as a named function. Lexical bindings shadow module function
names. Anonymous `fn` values close over surrounding immutable lexical values;
each closure owns its capture array, including closures returned from another
function. Dynamic calls retain runtime arity validation.

All integers are unsigned big-endian values unless a field is explicitly
signed. Strings are UTF-8 byte sequences prefixed by a `u32` byte length. A
module may be at most 64 MiB.

### Container header

Every `.mgxc` file begins with this fixed 48-byte header:

| Offset | Size | Field |
| ---: | ---: | --- |
| 0 | 4 | ASCII magic `MGXC` |
| 4 | 2 | major version, currently `1` |
| 6 | 2 | minor version, currently `28` |
| 8 | 4 | feature flags, currently zero |
| 12 | 4 | payload byte length |
| 16 | 32 | SHA-256 digest of the payload |

A reader rejects unknown major versions, minor versions newer than it
implements, unsupported flags, an incorrect payload length, a checksum
mismatch, and bytes after the declared payload.

### Payload

The payload contains, in order:

1. the entry-function index (`u32`);
2. in version 1.20 and newer, a source count (`u32`) followed by path/content
   String pairs containing the immutable compilation snapshot;
3. in version 1.21 and newer, an application-present byte; when set, the app
   name and surface Strings, `init`, `update`, and `view` function indices,
   a start-present byte and optional `start` index, then a capability count and
   sorted capability Strings, followed in version 1.24 and newer by a
   main-present byte and optional CLI/server `main` function index;
4. a constant count (`u32`) followed by that many constants; and
5. a function count (`u32`) followed by that many functions.

Lifecycle indices are validated against the function table. GUI and TUI
`init` and `start` take zero parameters, `update` takes two (or two/three for
TUI), and `view` takes one. CLI and server `main` take one argument and replace
the GUI/TUI lifecycle table for their respective surfaces.
Capabilities must be known to version 1.21 and sorted without duplicates.
The source count may be zero. Compilers preserve sources by default, but may
offer an explicit stripped build for closed-source distribution; execution and
application lifecycle metadata do not depend on embedded source text.

The constant tag is one byte. Tags `0` through `4` represent `nil`, `Bool`,
`Int`, `Float`, and `String`. A Bool has a one-byte payload restricted to zero
or one. Int uses its signed 64-bit two's-complement representation. Float uses
its IEEE 754 binary64 bit pattern. String uses the length-prefixed encoding
defined above.

Each function contains its name string, parameter count (`u16`), register
count (`u16`), and source-path string. In version 1.43 and newer these are
followed by a parameter-type count (`u32`), that many type-name strings, and a
result-type string. Version 1.52 and newer then encode a one-byte async marker,
restricted to zero or one. A nonempty parameter-type table has exactly the declared
parameter count. The remaining fields are the instruction count (`u32`),
instructions, source-location count (`u32`), and source locations. The location
table is either empty or has exactly one `(line u32, column u32)` pair per
instruction; line and column are one-based.

### Instruction encoding

Every instruction is exactly eight bytes: opcode, registers A/B/C, and a
signed big-endian 32-bit immediate. Version 1.0 defines opcodes 0 through 7.
Version 1.1 adds opcodes 8 through 15. Version 1.2 adds opcodes 16 through 22.
Version 1.3 adds opcode 23. Version 1.4 adds opcodes 24 and 25. Version 1.5
adds opcodes 26 and 27. Version 1.6 adds opcodes 28 through 30. Version 1.7
adds opcodes 31 through 34. Version 1.8 adds opcodes 35 through 37. Version
1.9 adds opcodes 38 through 44. Version 1.10 adds opcodes 45 through 47.
Version 1.11 adds opcode 48. Version 1.12 adds opcodes 49 through 51. Version
1.13 adds opcodes 52 and 53. Version 1.14 adds opcodes 54 through 56. Version
1.15 adds opcodes 57 through 59. Version 1.16 adds opcode 60. Version 1.17
adds opcode 61. Version 1.18 adds no opcode; it expands the validated
deterministic intrinsic registry with `grid.*`. Version 1.19 similarly adds
`ray3d.*` without adding an opcode. Version 1.20 adds opcodes 62 through 67.
Version 1.21 adds opcode 68, version 1.22 adds opcode 69, version 1.23 adds
opcodes 70 through 72, versions 1.24 and 1.25 add no opcode, version 1.26 adds
opcode 73, versions 1.27 and 1.28 add no opcodes while extending the validated
intrinsic and host-task registries, version 1.29 adds opcode 74, version 1.30
adds opcode 75, version 1.31 adds opcode 76, version 1.32 adds no opcode while
extending the validated `INT_BINARY_CONST` selector, version 1.33 adds opcode
77, version 1.34 adds opcode 78, version 1.35 adds opcode 79, version 1.36 adds
opcode 80, version 1.37 adds opcode 81, version 1.38 adds no opcode, version
1.39 adds opcode 82, version 1.40 adds opcode 83, version 1.41 adds opcodes 84
through 91, version 1.42 adds opcodes 92 and 93, version 1.43 adds opcodes
94 and 95 along with function-signature metadata, version 1.44 adds opcode 96,
version 1.45 adds opcode 97, version 1.46 adds opcodes 98 through 102, and
version 1.47 adds no opcode while canonicalizing Record fields and Variant
payloads, version 1.48 adds opcode 103, version 1.49 adds opcode 104, version
1.50 adds opcode 105, version 1.51 adds no opcode while extending the
validated intrinsic registry with `server.encode-path`, version 1.52 adds no
opcode while extending function metadata with the async marker, versions 1.53
and 1.54 add opcodes 106 and 107, version 1.55 adds no opcode while
extending the validated intrinsic registry with `dicts.keys` and
`dicts.remove`, version 1.56 adds opcode 108, version 1.57 adds opcode 109,
version 1.58 adds no opcode while extending the validated intrinsic registry
with `testing.*`, version 1.59 adds opcode 110, and version 1.60 adds opcode 111:

| Opcode | Name | Operands | Meaning |
| ---: | --- | --- | --- |
| 0 | `LOAD_CONST` | A, Imm | Load constant Imm into register A. |
| 1 | `MOVE` | A, B | Copy register B into register A. |
| 2 | `LOAD_FUNCTION` | A, Imm | Load function Imm into register A. |
| 3 | `CALL` | A, B, C, Imm | Call the function in B with Imm arguments beginning at C; store the result in A. |
| 4 | `RETURN` | A | Return register A. |
| 5 | `JUMP` | Imm | Continue at absolute instruction offset Imm. |
| 6 | `JUMP_FALSE` | A, Imm | Continue at Imm when register A is false. |
| 7 | `ADD_INT` | A, B, C | Add integer registers B and C and store the result in A. |
| 8 | `SUBTRACT_INT` | A, B, C | Subtract integer C from B and store the result in A. |
| 9 | `MULTIPLY_INT` | A, B, C | Multiply integer registers B and C and store the result in A. |
| 10 | `DIVIDE_INT` | A, B, C | Divide integer B by C, truncating toward zero, and store the result in A. |
| 11 | `REMAINDER_INT` | A, B, C | Store the remainder paired with truncating division of B by C in A. |
| 12 | `EQUAL_INT` | A, B, C | Store whether integer B equals integer C in A. |
| 13 | `LESS_INT` | A, B, C | Store whether integer B is less than integer C in A. |
| 14 | `LESS_EQUAL_INT` | A, B, C | Store whether integer B is at most integer C in A. |
| 15 | `NOT_BOOL` | A, B | Store the Boolean negation of B in A. |
| 16 | `ADD_NUMBER` | A, B, C | Add Number registers B and C with numeric promotion and store the result in A. |
| 17 | `SUBTRACT_NUMBER` | A, B, C | Subtract Number C from B with numeric promotion and store the result in A. |
| 18 | `MULTIPLY_NUMBER` | A, B, C | Multiply Number registers B and C with numeric promotion and store the result in A. |
| 19 | `DIVIDE_NUMBER` | A, B, C | Divide Number B by C with numeric promotion and store the result in A. |
| 20 | `EQUAL_NUMBER` | A, B, C | Compare Number registers B and C exactly and store equality in A. |
| 21 | `LESS_NUMBER` | A, B, C | Compare Number registers B and C exactly and store whether B is less in A. |
| 22 | `LESS_EQUAL_NUMBER` | A, B, C | Compare Number registers B and C exactly and store whether B is at most C in A. |
| 23 | `EQUAL_VALUE` | A, B, C | Store structural equality of values B and C in A, using exact numeric equality when both are numbers. |
| 24 | `STRINGIFY` | A, B | Store the canonical String representation of B in A. |
| 25 | `CONCAT_STRING` | A, B, Imm | Concatenate Imm String registers beginning at B and store the result in A. |
| 26 | `CONVERT_INT` | A, B | Convert the Int, Float, or decimal String in B to Int and store it in A. |
| 27 | `CONVERT_FLOAT` | A, B | Convert the finite Int, Float, or decimal String in B to Float and store it in A. |
| 28 | `MAKE_VECTOR` | A, B, Imm | Construct a Vector from Imm registers beginning at B and store it in A. |
| 29 | `LENGTH` | A, B | Store the Unicode-scalar length of String B or element count of Vector B in A. |
| 30 | `EMPTY` | A, B | Store whether String or Vector B contains no values in A. |
| 31 | `VECTOR_FIRST` | A, B | Store the first element of non-empty Vector B in A. |
| 32 | `VECTOR_REST` | A, B | Store an immutable Vector containing all but the first element of B in A. |
| 33 | `VECTOR_APPEND` | A, B, C | Store an immutable copy of Vector B with value C appended in A. |
| 34 | `VECTOR_GET` | A, B, C | Store the element of Vector B at Int index C in A. |
| 35 | `MAKE_DICT` | A, B, Imm | Construct a Dict from Imm alternating String-key/value register pairs beginning at B. |
| 36 | `COLLECTION_GET` | A, B, C | Read Int-indexed Vector or String-keyed Dict B using key C and store the result in A. |
| 37 | `DICT_ASSOC` | A, B, C, Imm | Store an immutable copy of Dict B associating String key C with the value-register index in Imm. |
| 38 | `STRING_CONTAINS` | A, B, C | Store whether String B contains String C in A. |
| 39 | `STRING_TRIM` | A, B | Trim Unicode whitespace from String B and store it in A. |
| 40 | `STRING_UPPER` | A, B | Convert String B to Unicode uppercase and store it in A. |
| 41 | `STRING_LOWER` | A, B | Convert String B to Unicode lowercase and store it in A. |
| 42 | `STRING_REPLACE` | A, B, C, Imm | Replace every occurrence of String C in B with the String register indexed by Imm. |
| 43 | `STRING_SPLIT` | A, B, C | Split String B on String C and store the resulting Vector of Strings in A. |
| 44 | `STRING_JOIN` | A, B, C | Join the String elements of Vector B with String separator C and store the result in A. |
| 45 | `RANGE` | A, B, C | Construct an end-exclusive ascending or descending Int Vector from B toward C. |
| 46 | `SLICE` | A, B, C, Imm | Slice String or Vector B from Int register C to the Int register indexed by Imm, clamping to its length. |
| 47 | `IS_NIL` | A, B | Store whether B is `nil` in A. |
| 48 | `TAIL_CALL` | A, B, Imm | Replace the current frame with the function in A, passing Imm arguments beginning at B. |
| 49 | `MAP` | A, B, C | Invoke unary function B for each element of Vector C and store the result Vector in A. |
| 50 | `FILTER` | A, B, C | Retain elements of Vector C for which unary predicate B returns true and store them in A. |
| 51 | `REDUCE` | A, B, C, Imm | Fold the Vector-register index in Imm from initial value C using binary function B and store the result in A. |
| 52 | `MAKE_CLOSURE` | A, B, C, Imm | Create a value for function Imm with C captures copied from consecutive registers beginning at B and store it in A. |
| 53 | `LOAD_CAPTURE` | A, Imm | Load capture Imm from the current closure into register A. |
| 54 | `MAKE_RECORD` | A, B, C, Imm | Construct a nominal record whose String type name is constant Imm from C alternating String-name/value register pairs beginning at B. |
| 55 | `RECORD_GET` | A, B, C | Read the String-named field C from record B and store it in A. |
| 56 | `RECORD_WITH` | A, B, C, Imm | Copy record B, replace the String-named field C with the value in the register indexed by Imm, and store the new record in A. |
| 57 | `MAKE_VARIANT` | A, B, C, Imm | Construct the tagged variant described by String constant Imm; C is zero for no payload or one to copy payload B. |
| 58 | `VARIANT_TAG` | A, B | Store the case-name String from variant B in A. |
| 59 | `VARIANT_PAYLOAD` | A, B | Store the payload from variant B in A, trapping when the selected case has none. |
| 60 | `INTRINSIC` | A, B, C, Imm | Invoke the allowlisted intrinsic named by String constant Imm with C arguments beginning at B and store the result in A. |
| 61 | `LOAD_GLOBAL` | A, Imm | Load the immutable value produced by zero-argument initializer function Imm, evaluating and caching it on first access. |
| 62 | `MAKE_TASK` | A, B, C, Imm | Capture the function in B and Imm eager arguments beginning at C as a lazy Task in A. |
| 63 | `MAKE_HOST_TASK` | A, B, C, Imm | Construct a lazy named host task using C arguments beginning at B. |
| 64 | `AWAIT` | A, B | Execute Task B and store its Result in A. |
| 65 | `RESULT_UNWRAP` | A, B | Store an Ok payload in A or immediately return the Error Result. |
| 66 | `JSON_PARSE` | A, B | Parse String B into a Result in A. |
| 67 | `JSON_STRINGIFY` | A, B | Encode B deterministically into a Result in A. |
| 68 | `MAKE_TERMINAL_DRAW` | A, B, C, Imm | Construct an immutable terminal text/glyph drawing in A. B and C hold x/y; Imm packs content and color register indices plus the drawing kind. |
| 69 | `MAKE_VIEW` | A, B, C, Imm | Construct an immutable declarative View in A. B and C contain property-value and child Vectors; String constant Imm contains the tag and ordered property names. |
| 70 | `TRY_CONVERT_INT` | A, B | Attempt to convert B to Int and store `Ok Int` or `Error String` in A. |
| 71 | `TRY_CONVERT_FLOAT` | A, B | Attempt to convert B to Float and store `Ok Float` or `Error String` in A. |
| 72 | `PROTOCOL_CALL` | A, B, C, Imm | Dispatch to a linked protocol implementation using the first of C arguments beginning at B; constant Imm contains the closed type/function table. |
| 73 | `INT_BINARY_CONST` | A, B, C, Imm | Apply operation C to Int register B and Int constant Imm, storing the checked result in A. C selects add, subtract, multiply, divide, remainder, equal, less, less-equal, or not-equal as values 0 through 8; selector 8 requires version 1.32. |
| 74 | `INT_COMPARE_JUMP_FALSE` | A, B, C, Imm | Compare Int registers A and B and continue at absolute instruction offset Imm when the result is false. C selects equal, less, or less-equal using values 5 through 7. |
| 75 | `TAIL_CALL_DIRECT` | A, B, Imm | Tail-call linked function Imm with B arguments beginning at register A, reusing the current frame when capacity permits. |
| 76 | `INT_MULTIPLY_REMAINDER_CONST` | A, B, C, Imm | Multiply Int registers B and C with checked overflow, take the signed remainder by nonzero Int constant Imm, and store the result in A. |
| 77 | `INT_REMAINDER_PREDICATE_CONST` | A, B, C, Imm | Take the signed remainder of Int register B by Int constant Imm and store whether it is zero (C=0) or nonzero (C=1) as Bool in A. |
| 78 | `INT_RETURN` | A, B, C, Imm | Apply checked integer operation C and return its result directly. Imm=-1 selects register B as the right operand; otherwise Imm indexes an Int constant. Selectors 9 and 10 test constant remainder zero/nonzero. |
| 79 | `TAIL_CALL_DIRECT_3` | A, B, C, Imm | Tail-call linked three-parameter function Imm using independent argument registers A, B, and C, snapshotting all values before rebinding parameters. |
| 80 | `INT_ADD_REMAINDER_CONST` | A, B, C, Imm | Add Int registers B and C with checked overflow, take the signed remainder by nonzero Int constant Imm, and store the result in A. |
| 81 | `INT_ADD_REMAINDER_TAIL_SELF_3` | A, B, C, Imm | Add Int registers A and B with checked overflow, take signed remainder by the packed nonzero Int constant, then self-tail-call with first argument C, packed second argument, and the remainder as third argument. |
| 82 | `STRING_SLICE` | A, B, C, Imm | Copy the code-point range C through register Imm from String B into a new immutable String A, rejecting invalid bounds and clamping valid bounds to the source length. |
| 83 | `EQUAL_STRING` | A, B, C | Store in Bool A whether String B and String C contain exactly the same UTF-8 bytes. |
| 84 | `ADD_FLOAT` | A, B, C | Add finite Float B and Float C, storing a finite Float in A or trapping when the result is not finite. |
| 85 | `SUBTRACT_FLOAT` | A, B, C | Subtract finite Float C from Float B, storing a finite Float in A or trapping when the result is not finite. |
| 86 | `MULTIPLY_FLOAT` | A, B, C | Multiply finite Float B and Float C, storing a finite Float in A or trapping when the result is not finite. |
| 87 | `DIVIDE_FLOAT` | A, B, C | Divide finite Float B by nonzero Float C, storing a finite Float in A or trapping for either signed zero or a non-finite result. |
| 88 | `EQUAL_FLOAT` | A, B, C | Store in Bool A whether finite Float B equals finite Float C. |
| 89 | `LESS_FLOAT` | A, B, C | Store in Bool A whether finite Float B is less than finite Float C. |
| 90 | `LESS_EQUAL_FLOAT` | A, B, C | Store in Bool A whether finite Float B is less than or equal to finite Float C. |
| 91 | `INT_TO_FLOAT` | A, B | Convert Int B to its ordinary finite IEEE-754 binary64 value in Float A, using round-to-nearest-even when it is not exactly representable. |
| 92 | `COMPARE_INT_FLOAT` | A, B, C, Imm | Compare exact Int B with finite Float C and store the selected Bool result in A. Imm selects equal, less, or less-equal as 0, 1, or 2. |
| 93 | `COMPARE_FLOAT_INT` | A, B, C, Imm | Compare finite Float B with exact Int C and store the selected Bool result in A. Imm selects equal, less, or less-equal as 0, 1, or 2. |
| 94 | `BOX_DYNAMIC` | A, B, Imm | Store the canonical dynamic box for raw value B in A. Imm is the stable concrete payload tag. The reference VM may represent this as an identity. |
| 95 | `BOX_VECTOR_DYNAMIC` | A, B, Imm | Copy homogeneous Vector B into a Vector of canonical dynamic boxes in A using packed leaf-tag/nesting-depth descriptor Imm. The reference VM may share B because its elements are already tagged. |
| 96 | `DICT_GET` | A, B, C | Read String key C from Dict B into A as a canonical dynamic value. A missing key produces boxed `nil`. |
| 97 | `UNBOX_DYNAMIC` | A, B, Imm | Validate that canonical dynamic value B has concrete tag Imm, then store its raw payload in A. Trap on a tag mismatch without changing B. |
| 98 | `DYNAMIC_LENGTH` | A, B | Validate boxed B as a String, Vector, or Dict and store its logical length in Int A. String length counts Unicode code points. |
| 99 | `DYNAMIC_EMPTY` | A, B | Validate boxed B as a String, Vector, or Dict and store in Bool A whether its logical length is zero. |
| 100 | `DYNAMIC_IS_NIL` | A, B | Store in Bool A whether canonical dynamic value B has the `Nil` tag. |
| 101 | `DYNAMIC_GET` | A, B, C, Imm | Read from canonical dynamic collection B with key C and store its canonical dynamic value in A. Imm 0 requires a boxed Vector and Int index; Imm 1 requires a boxed Dict and String key. A missing Dict key produces boxed `nil`; an invalid kind, key mode, or Vector index traps. |
| 102 | `UNBOX_VECTOR_DYNAMIC` | A, B, Imm | Validate canonical dynamic elements of Vector B against packed leaf-tag/nesting-depth descriptor Imm and recursively copy raw payloads into a fresh homogeneous Vector A. Trap on any mismatch without changing B. |
| 103 | `DYNAMIC_EQUAL` | A, B, C | Structurally compare canonical dynamic values B and C according to the runtime equality contract and store raw Bool in A. Never compare box or heap addresses as language identity. |
| 104 | `DYNAMIC_SLICE` | A, B, C, Imm | Validate canonical dynamic B as a String or Vector, slice from Int register C through Int register Imm using the ordinary checked and clamped bounds contract, and store a newly boxed canonical result of the same concrete kind in A. String indexes count Unicode code points. |
| 105 | `DYNAMIC_STRINGIFY` | A, B | Convert canonical dynamic value B recursively to the stable Margeux human-readable representation and store the resulting ordinary String in A. Never expose box addresses, compact-heap addresses, host formatting, or internal module qualification. |
| 106 | `FLOAT_TO_INT` | A, B | Validate finite Float B is in [-2^63, 2^63), truncate it toward zero, and store the exact Int in A. Reject NaN, infinity, and out-of-range values. |
| 107 | `STRING_TO_INT` | A, B | Trim Unicode whitespace from String B, parse one optional ASCII sign and ASCII decimal digits with checked signed-64-bit accumulation, and store the Int in A. Invalid or overflowing text fails conversion. |
| 108 | `VECTOR_CONCAT` | A, B, C | Store a fresh flat Vector containing every element of Vector B followed by every element of Vector C in A. Neither input is mutated, and A MAY alias B or C. |
| 109 | `DICT_MERGE` | A, B, C | Store an immutable right-biased union of Dict B and Dict C in A. Neither input is mutated, and A MAY alias B or C. |
| 110 | `RECORD_MERGE` | A, B, C | Copy nominal Record B once, replace its existing fields from Dict patch C, and store the updated Record in A. Reject unknown fields and never mutate either input. |
| 111 | `CALL_DIRECT` | A, B, C, Imm | Call synchronous linked function Imm with C arguments beginning at register B and store its result in A. Validation requires C to equal the target parameter count. |

Registers are numbered from zero. A function may declare at most 256
registers. Jump targets are absolute offsets within the current function.

### Required validation

Validation happens before disassembly or execution. It rejects empty or
duplicate function names, missing code, invalid entry and table references,
out-of-range registers and jumps, invalid call argument windows, mismatched
location tables, zero source coordinates, oversized tables and strings, and
unknown tags or opcodes. Resource limits are part of the reader's hostile-input
boundary and must be checked before allocating table storage.

A host MAY retain a validated executor for an immutable loaded module. Calls
through that executor reuse the completed structural validation and normalized
execution limits; function indices, arity, callable identity, host results, and
all dynamic runtime checks remain enforced per invocation. Mutating a module
after constructing its executor is outside this contract. The native GUI/TUI
session, CLI, server, and task-continuation hosts use this load-once boundary.

The checksum detects corruption; it is not an authenticity mechanism. Systems
that require trusted authorship must authenticate the `.mgxc` file separately.

### Compatibility and inspection

A reader may accept an older minor version in the same major series. Any
change that reinterprets an existing field or opcode requires a new major
version. Additive opcodes require a newer minor version; optional semantics
that do not change the instruction set require a declared feature flag. A
reader must reject either mechanism when it does not understand it.

`margeux disassemble FILE.mgxc` validates the complete module before emitting
a deterministic textual listing. That listing is diagnostic output, not a
second serialization format.

### Execution limits

The initial VM validates a module before allocating frames. Execution has
explicit instruction-count and call-depth budgets, defaulting to 1,000,000
instructions and 1,024 frames. Hosts may select smaller positive limits.
Tail calls replace the current frame and therefore do not consume the call-depth
budget; they continue to consume the instruction budget.
Higher-order collection instructions suspend their caller while each callback
runs in an ordinary bounded frame. Callback instructions count toward the same
module instruction budget. An implementation MAY execute a validated
single-`INT_RETURN` callback directly without materializing that frame. It MUST
still consume one instruction unit per element, enforce the callback-depth
boundary, retain checked arithmetic and callback source locations, and produce
the same first error and collection value as ordinary callback execution.
After validation, an implementation MAY preselect a specialized direct loop for
a particular `INT_RETURN` operation and hoist immutable constants or prepared
remainder metadata out of that loop. Such specialization MUST preserve operand
type checks, signed arithmetic, overflow and zero-divisor behavior, collection
order, and the instruction-limit-before-instruction-error ordering above.
An implementation MAY also execute a validated straight-line callback subset
inside the collection loop without scheduling an ordinary callback frame. The
eligible subset MUST exclude calls, effects, captures, global initialization,
control flow, and alternate returns unless their complete behavior is
reproduced. Every original instruction MUST consume its ordinary budget unit;
failures MUST retain the original callback instruction's source location and
ordering. Unsupported callbacks MUST retain ordinary VM execution.
When collection storage already proves a homogeneous primitive type, a direct
loop MAY carry that primitive without reconstructing a tagged register for each
element. Selection MUST occur before iteration and MUST fall back unless source
storage, parameters, accumulator, and operation operands prove the required
type. Checked arithmetic, element order, original values retained by `filter`,
instruction accounting, and error/source behavior remain unchanged.
Closure captures are copied when `MAKE_CLOSURE` executes. They are therefore
stable values even after the creating frame returns; `LOAD_CAPTURE` traps if a
hostile module requests a capture not present in the invoked closure.
Record construction stores a nominal type name alongside an immutable field
map. The source compiler validates complete schemas, field types, and nominal
function annotations. The VM additionally rejects malformed field windows,
non-String names, duplicate construction fields, and updates or reads of fields
absent from the value. `RECORD_WITH` and `RECORD_MERGE` never mutate their
input records. `RECORD_MERGE` also rejects every patch key absent from the
record schema carried by the runtime value.
Generic functions use one shared portable body. `MAKE_RECORD` and
`MAKE_VARIANT` descriptors emitted inside that body erase its free declaration
parameters to `Any` (for example `Box[T]` becomes `Box[Any]`); concrete static
substitutions remain compiler metadata at each call site and are not duplicated
into specialized bytecode bodies.
Variant descriptors encode a non-empty nominal type and case name separated by
a NUL byte. Validation rejects malformed descriptors and invalid payload flags.
Source lowering checks constructor payloads and emits exhaustive `match`
control flow; branch payload bindings remain local to their selected branch.

`INTRINSIC` is not an unrestricted host-call mechanism. Validation rejects
unknown names, incorrect arities, non-String name constants, and invalid
argument windows before execution. Version 1.16 allowlists the deterministic
`math.*` surface declared by `std/math`; the reference evaluator and portable
VM execute the same shared checked implementation. Version 1.18 adds the three
bounded `grid.*` operations for connected-component traversal, legal placement,
and deterministic center selection. Version 1.19 adds bounded grid ray casting
through `ray3d.*`. Version 1.20's host tasks cover the declared HTTP, CLI, file,
workspace, storage, clock, process, and LLM capabilities; version 1.28 adds the
four-argument `http.request` and zero-argument `agent.identity` tasks. Constructing a task
performs no effect; only `AWAIT` or the embedding API's explicit
`ExecuteAndAwait` boundary calls the host. `agent.complete` is available only
under `[llm]`. `agent.identity` uses the same capability and returns nonempty
provider/model Strings; a host rejects a completion that disagrees with that
declared identity. Both request and completion JSON pass the canonical digest
and UTF-8 edit validator defined by `MARGEUX_LLM_0_1_SPEC.md`. Nondeterministic
entropy still requires a future capability contract.
Integer addition, subtraction, multiplication, and division are checked and
trap on overflow. Mixed arithmetic promotes to finite IEEE-754 binary64. Mixed
comparisons compare the exact Int value without first rounding it through a
Float. Division and remainder trap on a zero divisor; `MinInt % -1` is zero. A
runtime type failure or limit failure reports the source path, line, and column
when the module contains a location table.

A single `RANGE` instruction may produce at most 1,048,576 elements, preventing
one instruction from bypassing the VM's instruction budget through unbounded
allocation.

## Language: Command-line interface

Authoritative source: `MARGEUX_CLI_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented companion specification, version 0.1

### Launch contract

The native form is:

```text
margeux run FILE [-- ARG...]
```

GUI and TUI applications may receive launch arguments through a synchronous
`init` function that accepts zero parameters or one `Vector[String]`. CLI
applications declare a dedicated entry point:

```margeux
use "std/cli"

async def main [arguments: Vector[String]] -> cli.Response
  cli.success "done\n"

app Tool
  cli
    main main
```

The `main` function accepts exactly one `Vector[String]` and returns
`cli.Response`, either directly or from an async function. The argument vector
contains `ARG...` exactly, in order.
No shell parsing, quote processing, environment expansion, or glob expansion is
performed by Margeux. Hosts without native launch arguments supply an empty
vector.

`cli.Response` contains `stdout: String`, `stderr: String`, and
`exit-code: Int`. Exit codes range from 0 through 255. `cli.response` constructs
all three fields, `cli.success` writes stdout with code 0, `cli.failure` writes
stderr with a caller-selected code, and `cli.parse-failure` writes stderr with
code 2.

The native runner writes both streams without decoration or a JSON envelope and
terminates with the response exit code. Wasm returns the same response fields to
Studio, which renders the streams inline without changing their contents.

Bytecode version 1.24 stores the CLI main-function index in application
metadata. Native and Wasm hosts invoke that function directly in the portable
VM, including from stripped `.mgxc` artifacts; CLI execution does not require
source text or the reference interpreter.

The capability-gated `cli.arguments` task returns another copy of the native
argument vector. A CLI entry point normally uses its explicit parameter instead.

### Tool command catalog

The SDK binary exposes the following complete top-level command set. Commands
that accept a source `FILE` also accept the entry file of a multi-file project;
commands documented with `FILE|DIRECTORY` resolve the project entry or a
verified release directory according to that command's contract.

| Command | Contract |
| --- | --- |
| `margeux version [--json]` | Print the SDK version. The JSON form is stable machine-readable output. |
| `margeux new DIRECTORY` | Create a new project without overwriting an existing nonempty destination. |
| `margeux repl` | Start the incremental read-evaluate-print loop on standard input and output. |
| `margeux lsp` | Run the language server over standard input/output using JSON-RPC framing. |
| `margeux mcp [ROOT] [OPTIONS]` | Run the project-scoped MCP server over standard input/output. |
| `margeux test [FILE|DIRECTORY] [OPTIONS]` | Discover, compile, and execute Margeux source tests. |
| `margeux ai import-pi [OPTIONS]` | Import an explicitly selected Pi provider/model configuration. |
| `margeux package lock [ROOT]` | Resolve the manifest and atomically write the exact dependency lock. |
| `margeux package pack [ROOT] [-o ARCHIVE]` | Build a deterministic package archive. |
| `margeux package verify ARCHIVE` | Verify a package archive without installing or executing it. |
| `margeux release create FILE [OPTIONS]` | Create a verified portable application release directory. |
| `margeux release verify DIRECTORY` | Verify a release manifest, bytecode artifact, and bound digests. |
| `margeux check FILE` | Parse, expand, link, and type-check without executing. |
| `margeux expand FILE|DIRECTORY [OPTIONS]` | Print source macro expansion or expansion traces. |
| `margeux run FILE [-- ARG...]` | Compile and execute a source program or application. |
| `margeux gui FILE|DIRECTORY [-- ARG...]` | Run a GUI application with the native renderer. |
| `margeux serve FILE|DIRECTORY [OPTIONS]` | Run a server application with bounded native HTTP ownership. |
| `margeux render FILE|DIRECTORY [-o OUTPUT]` | Render one deterministic GUI or TUI snapshot. |
| `margeux compile FILE [-o OUTPUT] [--strip-source]` | Emit validated portable `.mgxc` bytecode. |
| `margeux exec FILE|DIRECTORY [-- ARG...]` | Execute bytecode or a verified release without recompiling source. |
| `margeux disassemble FILE` | Print the validated bytecode container and instruction stream. |

#### Tool options

`margeux test` accepts `--filter TEXT`, `--fail-fast`, and `--json`.
Filtering is deterministic and does not alter discovery order. The JSON mode
emits the same suite, case, diagnostic, and failure information as the human
report without terminal decoration.

`margeux expand` accepts `--all`, `--trace`, and `--json`. The default prints
the selected expansion. `--all` includes all expandable forms, `--trace`
includes ordered transformer steps and provenance, and `--json` selects the
machine-readable representation.

`margeux mcp` accepts `--read-only`, `--allow-run`, repeated
`--allow-capability NAME`, `--max-file-bytes N`, `--max-output-bytes N`, and
`--log-level LEVEL`. Read-only mode removes mutation tools. Execution and host
capabilities remain denied unless explicitly allowed.

`margeux serve` accepts `--listen ADDRESS`, `--read-header-timeout DURATION`,
`--read-timeout DURATION`, `--write-timeout DURATION`, `--idle-timeout
DURATION`, `--shutdown-timeout DURATION`, and `--max-header-bytes N`.
`MARGEUX_SERVER_0_1_SPEC.md` defines defaults, validation, and shutdown
behavior.

`margeux release create` accepts `-o DIRECTORY`, `--strip-source`, or
`--strip-unused-source`. The two stripping modes are mutually exclusive.
`--strip-source` removes all source; `--strip-unused-source` retains only
source required by runtime source capabilities.

`margeux ai import-pi` accepts `--models PATH`, `--auth PATH`, `--select
PROVIDER/MODEL`, `--name NAME`, `--approve`, `--root ROOT`, and `--replace`.
It never imports credentials or replaces an existing configuration without
the corresponding explicit selection and approval flags.

#### Exit and stream behavior

Usage errors exit with status 2. Compilation, validation, host, and execution
failures exit nonzero and write diagnostics to standard error. Commands whose
contract is structured (`check`, `compile`, and selected inspection commands)
write deterministic JSON to standard output. CLI applications are the
exception described by the launch contract: their declared stdout, stderr,
and exit code are forwarded without a JSON envelope.

### Option declarations

`std/cli` exports `Option`, `Parsed`, `flag`, `option`, `required-option`, and
`help-option`. Long names MUST be nonempty and MUST NOT begin with `-`. Short
names MUST be empty or exactly one character. Long and nonempty short names
MUST each be unique within a specification vector.

Flags store `"true"` when present and `"false"` by default. Valued options
store their declared default. A required option has no usable default and parse
fails unless it was explicitly supplied.

### Parsing

`cli.parse arguments specifications` processes tokens from left to right:

- `--name` selects a long option;
- `--name=value` supplies an inline long-option value;
- `-n` selects one short option;
- a valued option without `=` consumes the following token;
- `--` ends option parsing and is not retained;
- tokens after `--` are always positional;
- the first positional token becomes `Parsed.command`;
- later positional tokens become `Parsed.positionals`.

Grouped short flags such as `-abc` are rejected in version 0.1. Unknown options,
duplicate or invalid specifications, missing values, values supplied to flags,
and absent required options return Error String. Parsing is pure and does not
read environment variables or the file system.

`cli.flag? parsed name` reads a declared flag. `cli.value parsed name` reads a
declared option value. `cli.usage program summary specifications` returns
deterministic usage text in declaration order.

### Server operations

`margeux serve FILE|DIRECTORY` runs a server source file, bytecode artifact, or
verified release. Its explicit operational options control listen address,
header/read/write/idle deadlines, maximum header bytes, and graceful-shutdown
duration. SIGINT and SIGTERM stop admission, drain in-flight requests within
the declared window, then force closure and return an error if that window is
exceeded. `MARGEUX_SERVER_0_1_SPEC.md` defines the bounds and defaults.

### Release commands

`margeux release create FILE [-o DIRECTORY] [--strip-source]` creates an atomic
version 1 portable release directory. `margeux release verify DIRECTORY`
strictly verifies its manifest and artifact. `margeux exec DIRECTORY [--
ARG...]` executes a verified release, while `margeux serve DIRECTORY` serves a
verified server release. The complete format and trust boundary are specified
in `MARGEUX_RELEASE_0_1_SPEC.md`.

## Language: Numeric semantics

Authoritative source: `MARGEUX_NUMERIC_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented companion specification, version 0.1  
**Scope:** Numeric values, operators, conversions, comparison, and `std/math`.

This specification extends the core Margeux 0.1 specification. The words MUST,
SHOULD, and MAY have their usual normative meanings.

### 1. Numeric types

Margeux has two concrete numeric types:

- `Int`: a signed 64-bit integer in `[-9223372036854775808,
  9223372036854775807]`.
- `Float`: an IEEE-754 binary64 value. Ordinary language values MUST be finite.

`Number` is the annotation-level union `Int | Float`; it is not a third runtime
representation. Operations that preserve an `Int` return `Int`. Operations
that promote return `Float`.

### 2. Literals

Decimal integer literals contain an optional `-` followed by digits. Float
literals use a decimal point, an exponent, or both:

```margeux
42
-17
.5
-2.0
1e3
-4.2e-2
```

A leading `+`, digit separators, hexadecimal values, NaN, and infinity are not
source literals. An out-of-range `Int` or non-finite `Float` literal is a
diagnostic. `-0.0` is a valid Float and retains IEEE signed-zero behavior.

### 3. Arithmetic

`+`, `-`, `*`, and `/` take exactly two Number values and evaluate operands
left to right.

- With two Int operands, the result is Int. Every operation is checked for
  overflow. Int division truncates toward zero.
- If either operand is Float, both values participate in binary64 arithmetic
  and the result is Float. Converting a large Int for mixed arithmetic MAY
  round it to the nearest representable binary64 value.
- Division by positive or negative zero is a diagnostic.
- A Float result that is NaN or positive or negative infinity is a diagnostic.
  Finite rounding and underflow follow binary64 rules, including underflow to
  signed zero.

`%` takes two Int values. It is the remainder paired with truncating division,
so a nonzero result has the sign of the left operand. A zero divisor is a
diagnostic. `MinInt % -1` is zero and does not overflow.

There are no implicit String-to-number conversions.

### 4. Equality and ordering

`=`, `!=`, `<`, `<=`, `>`, and `>=` compare Int and Float values numerically.
Mixed comparison MUST compare the exact Int to the represented binary64 value;
it MUST NOT first round the Int to Float. Thus `9007199254740993` is greater
than the Float `9007199254740992.0`.

As a defensive host-boundary rule, NaN is unordered: `=`, `<`, `<=`, `>`, and
`>=` return false, while `!=` returns true. Normal language evaluation does not
produce NaN.

Equality on nonnumeric values follows structural value equality. Ordering is
numeric only.

### 5. Conversions and formatting

`int value` accepts Int, Float, or String. A Float is truncated toward zero and
MUST be finite and within Int range. A String is trimmed, then parsed as an
optional sign followed by base-10 digits; the complete trimmed string must be
consumed.

`float value` accepts Float, Int, or String. Int conversion uses IEEE binary64
rounding. A String is trimmed and accepts an optional sign, decimal digits and
point, and an optional decimal exponent. At least one mantissa digit and all
exponent digits are required. Hexadecimal forms, separators, NaN, and infinity
are rejected.

`int.try` and `float.try` have the same rules but return `Ok value` or
`Error message` instead of raising a conversion diagnostic.

`string` and `str` format Int in decimal and Float with the shortest decimal
spelling that round-trips to the same binary64 value. Formatting is locale
independent.

### 6. Standard math module

`use "std/math"` exposes the `math` namespace. Except for `math.finite?`,
`math.nan?`, and `math.infinite?`, every math function requires finite numeric
inputs and diagnoses a non-finite result.

Constants:

- `math.pi`, `math.tau`, and `math.e` are Float values.

Selection and sign:

- `abs` preserves Int or Float and diagnoses `abs MinInt`.
- `sign` returns Int `-1`, `0`, or `1`.
- `min`, `max`, and `clamp` return Int only when all operands are Int;
  otherwise they return Float. Clamp requires `minimum <= maximum`.

Rounding functions `floor`, `ceil`, `round`, `round-even`, and `truncate`
always return Float. `round` resolves halves away from zero; `round-even`
resolves halves toward the nearest even integer.

`sqrt`, `pow`, `exp`, `log`, `log2`, `log10`, `sin`, `cos`, `tan`, `asin`,
`acos`, `atan`, `atan2`, and `hypot` return Float. Invalid domains and
non-finite results are diagnostics rather than NaN or infinity values.

`degrees` and `radians` convert angles and return Float. `lerp`,
`inverse-lerp`, and `remap` do not clamp their interpolation amount.
`inverse-lerp` and `remap` require distinct input endpoints. `approx?` uses
absolute error and requires a non-negative tolerance.

### 7. Checked integer mathematics

`gcd` and `lcm` accept Int and return a non-negative Int. Results outside Int
range are diagnostics. `lcm` is zero when either operand is zero.

`factorial n`, `permutations n k`, and `combinations n k` require non-negative
Int values; the latter two require `0 <= k <= n`. Every intermediate result is
checked and overflow is a diagnostic.

### 8. Aggregates and vectors

`sum` and `product` accept numeric Vectors. Their empty identities are Int `0`
and Int `1`. If every element is Int, they use checked Int arithmetic and
return Int; otherwise they return finite Float.

`mean`, `median`, `variance`, and `standard-deviation` require a non-empty
numeric Vector and return Float. Variance and standard deviation use the
population definition. Implementations SHOULD use numerically stable summation
where practical.

`vector-add`, `vector-subtract`, `vector-scale`, and `dot` preserve Int only
when every participating value is Int; their Int operations are checked.
Otherwise their components or result are finite Float. Binary vector functions
require equal lengths.

`magnitude`, `distance`, and `normalize` return Float values or Vectors of
Float. The empty vector has magnitude zero; normalizing any zero-length vector
is a diagnostic. Empty equal vectors have distance zero and dot product zero.

### 9. Boundaries and reproducibility

Float literals, conversions, JSON decoding, numeric intrinsic arguments,
arithmetic results, and JSON encoding MUST enforce the finite-value boundary. Predicates
for NaN and infinity remain defined so hosts can safely inspect an invalid
foreign value before it enters ordinary arithmetic.

Basic arithmetic and conversions follow the rules above identically in native
Go and Wasm. Transcendental functions follow the host's correctly implemented
binary64 math library; applications SHOULD compare approximate results with an
explicit tolerance rather than requiring bit-identical transcendental output
across every future host.

## Language: Tasks, commands, and asynchronous functions

Authoritative source: `MARGEUX_ASYNC_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented companion specification, version 0.1  
**Scope:** Lazy tasks, sequential `await`, commands, capabilities, HTTP,
scoped text files, namespaced persistent values, clock operations, and native
child processes.

This specification extends the core Margeux 0.1 specification. The words MUST,
SHOULD, and MAY have their usual normative meanings.

### 1. Design model

Margeux separates describing an effect from executing it:

```text
event -> update(model, message) -> immediate model + lazy task
                                      |
                                      v
                                  host executes
                                      |
                                      v
result message -> update(current model, message) -> model or next command
```

`view`, `init`, `update`, and ordinary functions remain synchronous. An
`async def` or `async fn` call constructs a lazy `Task`; calling it does not
execute its body. `async fn` is the lexical-closure form and captures immutable
bindings by value under the same rules as `fn`.
A GUI `update` may return a `command` that installs an immediate model and
hands one task to the runtime. The host executes that task only when it resumes
the pending command.

Tasks and commands are runtime control values, not application data. A model
MUST NOT contain a Task or Command, including beneath a Vector, Dict, record,
or variant payload.

### 2. Async functions and tasks

```margeux
async def load-health [] -> Result[Dict, String]
  let response
    ? await http.get "/api/health"
  let health
    ? json.parse response.body
  Ok health
```

Anonymous asynchronous functions use the same prefix:

```margeux
def delayed-adder [increment: Int]
  async fn [value: Int]
    + value increment
```

Calling an async function evaluates its arguments immediately from left to
right, clones them into a Task, and defers the function body. The body runs at
most once when its owning command is resumed.

`await expression` is legal only inside an `async def` or `async fn`. Its
expression MUST return a Task. Await runs that task and produces its resolved value. Multiple awaits
in one function execute sequentially in source order; version 0.1 has no
parallel-task combinator.

`? expression` is ordinary Result propagation. With `? await task`, an Error
immediately becomes the async function's Error result and later forms are not
evaluated.

An async function used by a command MUST resolve to `Result[T, E]`. A task that
resolves to another value is rejected statically when known and diagnostically
before completion routing otherwise.

### 3. Commands

```margeux
Refresh
  command
    :model
      with model
        :loading true
    :run (call load-health)
    :ok Loaded
    :error Failed
```

`command` is legal only while evaluating the application update function and
has exactly four fields:

- `:model`: the complete immediate next application model;
- `:run`: one lazy Task resolving to Result;
- `:ok`: a unary message constructor for the Ok payload;
- `:error`: a unary message constructor for the Error payload.

The two constructors MUST belong to the same closed message variant. For a
parameterized `Result[T, E]`, their payload parameters MUST accept `T` and `E`
respectively. The message variant MUST be accepted by the GUI update function.

Version 0.1 supports commands in GUI applications only. TUI update functions
consume input-event Dicts and do not yet have a separate async completion
channel; using `command` in a TUI is a diagnostic.

### 4. State transitions and pending work

When update returns a valid command, the runtime MUST:

1. validate and install `:model`;
2. retain the task and constructors as one pending command;
3. render the immediate model with `snapshot.pending = true`;
4. perform no host effect until an explicit resume.

Only one command may be pending per session. A second command is rejected
without replacing the first command or executing either task. Ordinary
synchronous messages MAY update the model while a command is pending. When the
task completes, its message is reduced against the then-current model, not a
captured stale model.

A resume consumes exactly one pending command. It executes the task, chooses
`:ok` or `:error`, constructs the completion message, and calls the same pure
update function. That update may return another command; if so, the returned
snapshot remains pending and the next task requires another resume. This gives
explicit sequential workflows without recursive host execution.

Calling resume without pending work is a diagnostic. A language/runtime
diagnostic while executing a task consumes that command and leaves its
immediate model installed. Recoverable host failures SHOULD instead resolve to
Error so the application's `:error` branch can clear loading state.

### 5. Events, views, and initialization

An async function MUST NOT be used directly as a GUI event action. Events emit
ordinary messages, and update decides whether to create a command. This keeps
all model transitions visible in one function.

`view`, `init`, and `update` MUST be synchronous. A view cannot await, return a
Task, or trigger host work while constructing output. Re-rendering, editor
highlighting, and serialization MUST NOT execute pending tasks.

### 6. Capabilities and host effects

An application declares host authority explicitly:

```margeux
app Health
  capabilities [http]
  gui
    ...
```

Version 0.1 defines `http`, `files`, `workspace`, `storage`, `time`, `process`,
`cli`, and `llm` capabilities. `http.get url` and
`http.request method url body content-type` require `http` and return a lazy
`Task[Result[Dict, String]]`. The host request begins only when the containing
command resumes. `http.request` accepts `GET`, `POST`, `PUT`, `PATCH`, and
`DELETE`, limits request bodies to 2 MiB, and rejects content types containing
line breaks. A GET request body MUST be empty. The empty content-type String
omits that header.

An Ok response Dict contains:

- `status`: HTTP status as Int;
- `ok`: the host's successful-status Bool;
- `body`: complete response text as String;
- `url`: final response URL as String.

HTTP status codes, including non-2xx statuses, are successful transport results
and MUST be inspected through `status` or `ok`. Network failure, rejected host
promises, or an unavailable HTTP host resolves to Error String. Missing
capability is a language diagnostic, not a recoverable network response.

The `std/source` module exposes the file operations below. Each requires the
`files` capability and returns a lazy task:

```margeux
source.list []                    # Task[Result[Vector[String], String]]
source.load path                  # Task[Result[String, String]]
source.save path content          # Task[Result[String, String]]
source.delete path                # Task[Result[String, String]]
```

Paths are relative to the directory granted by the host. Bundled hosts reject
empty and absolute paths, parent traversal, and text files larger than 2 MiB.
`save` resolves with the normalized path. The native CLI scopes access to the
entry file's directory, the notes web app uses browser-local storage, and the
Android host uses its private application directory. Host I/O failures resolve
to Error String. Missing capability remains a language diagnostic.

The `std/storage` module provides application-scoped key/value persistence:

```margeux
storage.get key                  # Task[Result[Any, String]]
storage.set key value            # Task[Result[String, String]]
storage.delete key               # Task[Result[String, String]]
storage.keys []                  # Task[Result[Vector[String], String]]
```

`set` serializes through the deterministic JSON contract and `get` parses that
JSON back into Margeux values. The runtime supplies the declared application
name as the namespace; application code cannot select another namespace. Keys
MUST be nonempty UTF-8 strings no longer than 128 bytes. Encoded values MUST be
no larger than 2 MiB. `keys` is lexically sorted. Missing keys and host failures
resolve to Error String. Native hosts use private atomic files, browser workers
use IndexedDB, and the Android host uses private application preferences.

The `std/time` module uses integer milliseconds:

```margeux
time.now []                    # Task[Result[Int, String]]
time.sleep duration            # Task[Result[Int, String]]
time.after duration value      # Task[Result[Any, String]]
```

`now` resolves to Unix time in milliseconds. `sleep` resolves to the supplied
duration after that delay, and `after` resolves to its supplied value after the
delay. Durations MUST be integers from zero through 86,400,000 milliseconds.
These tasks require `[time]`. Browser hosts use a nonblocking platform timer;
the native command host blocks the command's caller while sleeping. A clock
host is replaceable, so tests can advance deterministic virtual time.

The `std/process` module provides native child-process execution:

```margeux
process.run program arguments    # Task[Result[ProcessResult, String]]
process.run-program program      # Task[Result[ProcessResult, String]]
```

The host MUST invoke `program` directly with the supplied `Vector[String]` and
MUST NOT implicitly pass either value through a command shell. `ProcessResult`
contains `program`, `arguments`, `exit-code`, `stdout`, and `stderr`. A nonzero
exit is an Ok result; failure to start, timeout, invalid output, or exceeded
limits is Error String. The native host inherits its environment, uses the
application directory as the child working directory, supplies no interactive
standard input, limits execution to 30 seconds, and captures at most 2 MiB for
each output stream. `[process]` grants broad operating-system authority and
SHOULD be enabled only for trusted code. Browser and Android hosts do not
implement it and resolve attempted execution to Error String.

`cli.arguments []` returns a lazy `Task[Result[Vector[String], String]]` under
the `[cli]` capability. The native host returns only arguments following the
`--` separator in `margeux run FILE -- ARG...`; executable, action, source path,
and separator are excluded. The returned vector is a copy and cannot mutate
host state. Browser and Android hosts resolve the task to Error String. Normal
application initialization can receive the same immutable vector directly as
the optional sole `init` parameter and does not require a capability because it
is explicit program input rather than ambient authority.

`llm.request value` returns a lazy
`Task[Result[llm.Completion, String]]` under `[llm]`. Its portable
`agent.complete` host operation accepts and returns bounded canonical JSON.
`llm.identity []` returns a lazy `Task[Result[llm.Identity, String]]` through
the zero-argument `agent.identity` host operation. It exposes the nonempty
provider/model identity before inference; the host MUST reject a completion
whose identity differs from that declaration.
The completion contains provider/model identity, input/output digests, and
structured source replacements. The task itself has no file-write or
code-execution authority. Exact schemas, snapshot validation, replay behavior,
and adapter policy are specified by `MARGEUX_LLM_0_1_SPEC.md`.

### 7. Scheduling and lifecycle

The Wasm worker serializes compile, event, key, pointer, and resume requests.
The browser waits for each resume response before requesting the next step in a
command chain. A completion belongs to its originating runtime session; stale
UI sessions MUST NOT replace the visible output of a newly compiled session.

Version 0.1 intentionally has no cancellation, timeout, retry, background
subscription, detached task, parallel task, or persistent task restoration.
These require explicit future contracts rather than hidden host behavior.

A `cli` application's `main` may be async. The host resolves its task chain
sequentially, then requires the final value to be `cli.Response`. This lifecycle
has no model, view, update, dispatch, or resume phase.

## Language: Programmable macros

Authoritative source: `MARGEUX_MACRO_0_2_SPEC.md`. Classification: **normative**.

**Status:** Implemented initial programmable-macro surface  
**Scope:** Phase-1 transformers, declarative rules, syntax objects, quotation,
insertion, splicing, binding identity, computed expansion, and diagnostics.

This specification extends the compatible template macros in
`MARGEUX_MACRO_0_1_SPEC.md`. Existing `macro ... syntax` declarations retain
their behavior.

### 1. Procedural declaration

A procedural macro uses one `expand` block. Its parameters receive syntax
values rather than evaluated runtime values:

```margeux
macro unless [condition: Syntax body: Syntax] -> Syntax
  expand
    syntax
      when (not (unsyntax condition))
        splice-syntax body
```

Parameter and result annotations are optional. When present, `Syntax` is the
type of a term, form, or form sequence. The header follows ordinary Margeux
parameter and return-annotation rules.

Inline macro arguments are `Syntax` terms. When one parameter remains, all
child forms are supplied as one `Syntax` sequence, preserving the 0.1 calling
convention. Arguments are never evaluated at expansion time.

The `expand` body is compiled and evaluated as an ordinary Margeux function in
a phase-1 transformer session. It MUST return a syntax form or form sequence.
A different result is an `S0010` diagnostic.

#### Declarative rules

Common structural rewrites can use ordered `rules` instead of manually
traversing syntax:

```margeux
macro unless
  rules
    rule [condition body ...]
      syntax
        when (not (unsyntax condition))
          splice-syntax body
```

The pattern vector matches the invocation's inline terms followed by its child
forms. A name binds one syntax object, `_` ignores one object, and final
`name ...` binds zero or more remaining objects as a syntax sequence. Literal
values match by literal kind and value. `:name` matches an identifier using its
resolved module binding rather than caller spelling alone.

Nested vector and parenthesized-group patterns destructure those term shapes.
Repetition may appear at the end of any nested pattern list. Repeated term
bindings can be inserted with inline `splice-syntax`; repeated child forms use
child `splice-syntax`.

Rules are attempted in source order. A template uses ordinary `syntax`,
`unsyntax`, and `splice-syntax`, receives normal hygienic contexts, and re-enters
recursive expansion. If no rule matches, `S0010` reports the received argument
count, every expected shape, the macro call as primary, and rule definitions as
secondary locations. Its structured macro stack is retained.

#### Standard derived control forms

`std/control` is a phase-only standard module. It exports `when`, `unless`, and
`cond`; importing them adds no runtime function or module dependency. `when`
and `unless` are declarative rule macros producing lazy `Views`. `cond` is a
procedural macro whose Margeux helper validates structural clauses and lowers
them recursively to nested `if` expressions:

```margeux
use syntax "std/control"
  cond

cond
  case first-condition
    first-value
  case second-condition
    second-value
  otherwise
    fallback-value
```

The final `otherwise` is mandatory. Each `case` has exactly one condition and
one result. Conditions execute in source order and unselected results remain
unevaluated. Malformed clauses produce `S0010` at the responsible clause with
the macro expansion stack attached.

### 2. Syntax quotation

`syntax` quotes one or more indented Margeux forms:

```margeux
syntax
  section
    h2 "Generated"
```

One quoted child produces a form syntax value. Several children produce a
form-sequence syntax value. Quotation records the transformer module's lexical
context and the original source span.

`unsyntax` inserts one syntax term or form:

```margeux
syntax
  p (unsyntax value)
```

Inline `unsyntax` inside parentheses MUST produce a term. A child-form
`unsyntax` may insert a term as a one-term form or insert one form. It MUST NOT
insert a sequence.

`splice-syntax` inserts a form sequence into a quoted child list:

```margeux
syntax
  div
    splice-syntax body
```

Using a non-sequence value with `splice-syntax`, or a sequence with
`unsyntax`, is `S0010`.

An inline grouped splice inserts a sequence of terms into a form or vector:

```margeux
syntax
  vector (splice-syntax values)
```

Inline splicing rejects form syntax, just as child splicing rejects syntax
that cannot occupy a child position.

Quotation is unavailable to ordinary phase-0 application evaluation.

### 3. Syntax API

The deterministic phase-1 runtime supplies these operations:

| Operation | Result |
|---|---|
| `syntax.kind value` | `form`, `sequence`, or the term kind |
| `syntax.head form` | form-head spelling |
| `syntax.text term` | decoded term spelling/value text |
| `syntax.terms form` | vector of term syntax values |
| `syntax.children form` | vector of child-form syntax values |
| `syntax.items term` | vector items for a vector term |
| `syntax.sequence value` | vector of forms in a sequence |
| `syntax.sequence-of forms` | sequence made from a vector of forms |
| `syntax.span value` | source module, byte offsets, lines, and columns |
| `syntax.identifier? value` | whether a term is an identifier/path |
| `syntax.identifier context name` | identifier term with explicit lexical context |
| `syntax.literal context value` | literal term with explicit lexical context |
| `syntax.form-of head terms children` | form assembled from syntax values |
| `syntax.same-binding? left right` | phase-1 lexical binding identity |
| `syntax.introduce-at-call-site context value` | explicitly give generated syntax the caller's context |
| `syntax.error value message` | immediate `S0010` at the value's source |

All returned syntax is immutable. Vector accessors return new vectors; changing
the vector does not change the syntax object.

The compiler exposes a versioned JSON syntax serialization for tooling process
boundaries. Version 1 round-trips recursive form/term/sequence data,
phase-indexed scope identities, exact source locations, and complete nested
origin chains. Independently decoded trees retain their own scope-identity
domain and must be explicitly recontextualized before composition.

`syntax.sequence-of` permits algorithmic expansion. For example, a transformer
may `map` a Margeux lambda over input forms, quote one generated form for each,
and return the resulting sequence. Expansion is therefore not limited to fixed
templates.

### 4. Lexical context and hygiene

Every identifier syntax object contains phase-indexed lexical scopes in
addition to its spelling. Phase 0 is runtime; phase 1 is macro transformation.

Quoted identifiers receive their definition module's phase-1 scope. Syntax
newly written by a quote also receives a fresh introduction scope for that
invocation. Syntax supplied by a caller receives the caller module scope plus a
fresh use-site scope, but never the introduction scope. `unsyntax` and
`splice-syntax` preserve those distinctions.

Introduced bindings and their references are hygienically renamed according to
binding identity for:

- sequential and nested `let`;
- `fn` parameters;
- `for` variables;
- `match` payload bindings.
- generated `def` and `async def` parameters.

A caller identifier with the same spelling but a different scope is not
renamed and cannot be captured. A free identifier quoted by an imported macro
resolves in the macro's defining module, including private helpers, rather than
being captured by a caller declaration.

The current string-keyed linker receives canonical names and generated local
spellings only after scope-aware expansion. Those spellings are an internal
compatibility lowering, not the definition of binding identity.

Intentional capture is possible only through the conspicuous
`syntax.introduce-at-call-site` operation. It replaces the introduced value's
context with the context syntax object's scopes. Ordinary quotation never does
this implicitly.

### 5. Expansion and provenance

The transformer result re-enters recursive macro expansion. It may therefore
contain template macros, procedural macros, or calls that expand into further
macro calls.

Generated syntax records an origin frame containing:

- transformer name;
- transformer definition module and span;
- invocation module and span;
- the previous origin frame for nested expansion.

`syntax.error` uses the supplied syntax location as its primary diagnostic.
Transformer failures include the macro declaration as secondary context.
Every diagnostic raised during expansion also carries a structured
`macroStack`, ordered from the innermost invocation outward, with each macro's
name, definition source, and invocation source. Diagnostic messages remain
stable for existing tooling.

The existing limits of 100 nested expansion steps and 10,000 invocations apply
to both macro kinds.

### 6. Determinism and capabilities

The phase-1 transformer session has no application host or declared
capabilities. Quotation, syntax inspection, pure core operations, functions,
conditionals, vectors, dictionaries, and collection transformations are
available. Runtime application state is not.

Filesystem, database, process, network, clock, random, UI, and other host
effects MUST NOT execute during expansion.

Phase-1-only helper declarations live in a `syntax` block and have their own
export list:

```margeux
syntax
  export [make-call]
  def make-call [name: Syntax arguments: Vector[Syntax]] -> Syntax
    syntax.form-of name arguments nil
```

They are imported explicitly and do not enter runtime bytecode:

```margeux
use syntax "macro-helpers"
```

Selected names may use the same indented selection syntax as ordinary imports.
Runtime `use "module"` behavior is unchanged; it continues to expose exported
top-level macros for compatibility. A `syntax` import resolves only phase-1
exports, and conflicting or private selections are diagnosed during linking.
Tracked build capabilities remain future work.

### 7. Current limitations

The browser editor, compiler API, `margeux expand` CLI, and `margeux/expand`
language-server request expose final modules and immediate trace steps. The
browser inspector shows definition/invocation sources and nesting depth;
displaying lexical binding identities remains future tooling work.

These limitations do not affect compatibility template macros or ordinary
phase-0 programs.

## Language: Packages and locks

Authoritative source: `MARGEUX_PACKAGES_0_1_SPEC.md`. Classification: **normative**.

Status: implemented, normative for package format 1 and exact registry
transport 1.

### 1. Goals

The package system gives a multi-project Margeux build one reproducible source
graph. Dependency discovery occurs before compilation. Only the explicit lock
operation may perform network access. The compiler, VM, and ordinary build
commands do not consult a registry or select versions.

### 2. Manifest

A package root contains `margeux.json`. Each dependency selects exactly one
source: a relative development path or a registry base URL.

```json
{
  "name": "example/application",
  "version": "0.1.0",
  "entry": "main.mgx",
  "dependencies": {
    "acme/greeting": {
      "version": "1.2.0",
      "path": "../greeting"
    },
    "acme/colors": {
      "version": "2.0.1",
      "registry": "https://packages.example"
    }
  }
}
```

Names contain at least two lowercase slash-separated segments. Versions and
dependency requirements are exact semantic versions; ranges and implicit
upgrades are not supported. The entry is a relative `.mgx` path. A dependency
path is relative to the manifest that declares it and is resolution input, not
runtime state. Registry URLs are normalized absolute HTTPS URLs without
credentials, queries, or fragments. HTTP is accepted only for loopback
development.

Unknown manifest fields are errors. Dependency packages use `main.mgx` as their
entry in format 1.

### 3. Locking and snapshots

`margeux package lock [ROOT]` recursively resolves local dependency manifests
and exact registry archives. It rejects missing packages, archive or manifest
name/version mismatches, conflicting source origins or versions, and cycles. It
writes:

- a deterministic `margeux.lock` containing the complete transitive graph,
  exact versions, sorted source-file lists, dependency edges, and SHA-256
  content digests; and
- immutable source snapshots under `.margeux/packages/<digest>/`.

The digest commits to the format tag, package name, version, dependency names
and versions, source paths, and exact source bytes. Repeating a lock operation
over identical inputs MUST produce identical lock bytes and digests.

Only `.mgx` files belong to the package source snapshot. Nested dependency
directories are excluded from their owner's source set. Build output,
`.margeux`, VCS metadata, `node_modules`, and `vendor` are excluded.

### 4. Build resolution

Every source-based CLI build inside a manifest workspace MUST verify the lock
before checking, compiling, running, or serving the program. A missing or stale
lock is an error instructing the user to run `margeux package lock`. Locked
source bytes are verified against their digest before compilation; edits to the
original dependency checkout do not affect a build until it is relocked.

Locked packages are materialized in the compiler's logical source graph as:

```text
pkg/<package-name>/main.mgx
pkg/<package-name>/<other-source>.mgx
```

The `pkg/` root is reserved and cannot be supplied by application source.

### 5. Imports and namespaces

Applications import a dependency explicitly:

```margeux
use "pkg/acme/greeting"

greeting.hello "Ada"
```

The package import resolves to `pkg/acme/greeting/main.mgx`, while its source
namespace remains `greeting`. Imports within that package remain relative to
the package's own directory. Qualified calls therefore reveal that a symbol is
external without exposing a content digest in source.

The compiler, reference implementation, language service, LSP module links,
native CLI, and browser Wasm compiler MUST agree on this resolution.

### 6. Artifacts and browser execution

Portable `.mgxc` artifacts statically link reachable package modules. Normal
artifacts retain their logical package sources for inspection and diagnostics;
`--strip-source` removes all embedded source, including package source, without
changing executable bytecode.

The browser VM consumes the same logical source map or a precompiled artifact.
It does not read `margeux.json` or resolve local paths in the browser. A host
that compiles source in the browser supplies the already locked/materialized
file map.

### 7. Portable package archives

`margeux package pack [ROOT] [-o ARCHIVE]` creates a deterministic `.mgxp`
archive for one source package. `margeux package verify ARCHIVE` validates it
without extracting or executing source. The uncompressed ZIP contains a
canonical `margeux-package.json` followed by sorted `src/*.mgx` entries. Entry
timestamps, modes, methods, names, and order are fixed; identical package input
produces identical archive bytes.

The archive manifest records protocol `margeux.package/1`, package name,
version, entry, exact dependency name/version edges, package content digest,
and a sorted source list with byte lengths and SHA-256 values. Local dependency
paths are resolution state and MUST NOT be published. The archive's package
digest uses the exact format-1 algorithm already stored in `margeux.lock`, so a
packed dependency has the same content address as its locked snapshot.

Verification limits archives to 64 MiB and 256 source files, rejects unknown
manifest fields, noncanonical ZIP entries, invalid paths, non-UTF-8 source,
missing or extra files, digest mismatches, and a missing entry module. Package
archives are transport and review artifacts. They never execute during
verification or locking.

### 8. Exact registry transport

A registry dependency is fetched only by `margeux package lock`. For registry
base `https://packages.example/root`, package `acme/colors`, and version
`2.0.1`, the canonical GET endpoint is:

```text
https://packages.example/root/v1/packages/acme/colors/2.0.1.mgxp
```

The client requests a format-1 `.mgxp`, limits the response to 64 MiB, and
applies a maximum 30-second request timeout. Redirects MUST retain the exact
scheme and host. The archive MUST pass canonical offline verification and MUST
declare the requested name, exact version, and `main.mgx` entry before any
source snapshot is written.

Format-1 archive dependency edges carry exact identities but no source URL.
Consequently, transitive edges inherit the registry of the archive that
declared them. Resolving the same package through different origins, or at
different exact versions, is an error.

After locking, all check, compile, run, serve, artifact, LSP, and browser flows
read only the verified content-addressed snapshots. They remain functional
while the registry is unavailable. Relocking is the only operation that
refetches registry archives.

### 9. Security and deferred features

All locked source paths are relative, normalized `.mgx` paths. Reads are
limited to the exact sorted file list in the lock. The root `pkg/` namespace is
reserved to prevent dependency shadowing.

Version solving, signatures, authentication, registry discovery/publication,
mirrors, caches, yanking policy, and binary dependencies are outside 0.1. The
exact read-only transport defined above preserves the lock and digest semantics
without granting registries a role during program execution.

## Language: Protocols and implementations

Authoritative source: `MARGEUX_PROTOCOL_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented companion specification, version 0.1  
**Scope:** Protocol declarations, implementations, constraints, and dispatch.

This specification extends the core Margeux 0.1 specification. The words MUST,
SHOULD, and MAY have their usual normative meanings.

### 1. Purpose

Protocols describe operations supported by multiple concrete types without
adding inheritance or mutable objects:

```margeux
protocol Describe
  describe [value] -> String

implement Describe Int
  describe [number]
    concat "number " (string number)
```

A protocol is a compile-time interface and a runtime dispatch table. Values do
not carry protocol wrappers or method tables. Dispatch uses the concrete type
of a method's first argument.

### 2. Protocol declarations

```margeux
protocol Measure
  measure [value] -> Float
  between [left other: Float] -> Float
```

A protocol MUST have a unique type name and at least one method. A method has a
unique simple name, a non-empty parameter vector, and an optional return type.
The first parameter is the dispatch parameter and MUST omit a type annotation.
This avoids pretending that it has one fixed concrete type. Remaining
parameters SHOULD be annotated when the protocol depends on their types.

Protocol method names enter the module's value namespace. They MUST NOT collide
with functions, constants, or other protocol methods. Record, variant, and
protocol declarations share one type namespace.

Version 0.1 has no default method bodies, associated types, protocol
inheritance, generic protocol parameters, or multiple dispatch.

### 3. Implementations

```margeux
record Person
  name: String

implement Describe Person
  describe [person]
    concat "person " person.name
```

`implement Protocol Type` provides exactly one body for every method in the
protocol. Unknown, missing, and duplicate method bodies are diagnostics. Each
body must use the protocol method's arity.

An implementation parameter without an annotation inherits its required type.
The first parameter inherits the implementation target type. An explicit
parameter or return annotation MUST exactly match the inherited protocol
signature. The implementation body is then checked like an ordinary
synchronous function.

Valid implementation targets are concrete runtime types: `String`, `Bool`,
`Int`, `Float`, `Result`, `Vector`, `Dict`, `Terminal`, and declared record or
variant types. `Number` is a union rather than a concrete runtime type and
cannot be an implementation target. `Any`, protocols themselves, functions,
Tasks, Views, and Views sequences are not version 0.1 targets.

### 4. Coherence

For a complete program there MUST be at most one implementation of a protocol
for a concrete type. A duplicate is a compile-time diagnostic, including when
the conflicting declarations originate in different modules.

Version 0.1 permits an implementation module to own neither the protocol nor
the target type. This supports application-level integration, while global
uniqueness keeps dispatch deterministic. Package distribution may add stricter
orphan rules later without changing dispatch semantics.

Implementations are closed over the compiled module graph. Loading order MUST
NOT choose between implementations.

### 5. Calls and dispatch

```margeux
describe value
```

Calling a protocol method evaluates every argument eagerly from left to right,
then obtains the runtime type of the first argument. It selects the unique
implementation for that protocol and concrete type and invokes the matching
method body with all original arguments.

Only the first argument controls dispatch. Later arguments never influence
implementation selection. A method call with a statically known concrete first
argument and no implementation is a compile-time diagnostic. If the concrete
type is not known until runtime, missing dispatch is a runtime diagnostic.

Protocol dispatch does not perform numeric promotion, structural record
matching, subclass search, or fallback selection. An `Int` implementation does
not handle Float, and a record implementation matches only that nominal record
type.

### 6. Protocol constraints

A protocol name may annotate a parameter:

```margeux
def label [value: Describe] -> String
  describe value
```

The annotation means the supplied concrete value MUST have an implementation
of that protocol. It does not box or convert the value. A known incompatible
argument is rejected at compile time; dynamically unknown values are checked
when the function is called.

Inside the function, the constrained parameter remains the original value and
may be passed to methods of its protocol. Version 0.1 does not support vectors
or Results parameterized by protocol constraints as existential collections.

### 7. Modules and visibility

Protocols, methods, target types, and implementations use canonical module
identity. Imported access is qualified:

```margeux
use "format"

implement format.Display Int
  display [number]
    string number

format.display 7
```

An explicit module export list controls whether another module may name a
protocol or target type in `implement`. Exporting a protocol also exposes its
methods unless the module's API explicitly chooses an allowed method export.
Private imported declarations MUST NOT be implemented through qualification.

Implementation bodies themselves are not ordinary exported functions. They
are reachable only through their protocol method.

### 8. Purity and serialization

Dispatch is an ordinary deterministic function call after implementation
selection. It creates no hidden mutable state and performs no host effect by
itself. Implementations remain subject to the same purity and async boundaries
as other functions.

Protocol identity and implementation tables are compiler/runtime metadata, not
serialized application data. Snapshots contain the original concrete values,
not protocol wrappers.

## Language: Readable styles

Authoritative source: `MARGEUX_STYLE_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented design, version 0.1

Margeux provides a readable styling vocabulary that lowers to checked CSS in
browser applications. Authors do not need to write CSS for ordinary layouts,
visual styling, reusable classes, interaction states, breakpoints, or print
rules. Raw CSS strings and the lower-level stylesheet builders remain available
for advanced browser features.

### Inline styles

An element may contain a `:style` block:

```margeux
section
  :style
    layout row
    align center
    justify between
    gap 4
    padding 4
    background white
    foreground navy
```

Supported readable declarations include:

- `layout row|column|grid`
- `align start|center|end|stretch`
- `justify start|center|end|between|around|evenly`
- `wrap true|false`
- `columns <positive Int>`
- `width fill|fit` and `height fill|fit`
- `grow true|false` and `shrink true|false`
- `foreground <color>` and `background <color>`
- `text-size <measurement>`
- `text-weight normal|medium|semibold|bold|<Int>`
- `rounded none|small|medium|large|full|<measurement>`
- `shadow none|small|medium|large`
- `keep-together true|false`

Other lowercase CSS properties remain valid in a readable block. Measurements
may separate their number and unit, such as `1.5 rem`, `12 px`, or `50 percent`.

A lone number on a layout measurement uses a quarter-rem spacing scale. For
example, `gap 4` is `1rem`, `padding 6` is `1.5rem`, and `margin-bottom 0`
remains zero. This scalable default applies to gaps, margins, padding,
dimensions, inset positions, and border radius. Explicit `px`, `rem`, `em`,
`percent`, `vh`, `vw`, `vmin`, `vmax`, and `fr` units remain available.
Properties whose numbers are inherently unitless, including `opacity`,
`z-index`, `line-height`, and numeric font weight, keep their CSS meaning.

### Reusable styles

The `styles` view defines application-scoped classes:

```margeux
styles
  style card
    layout column
    gap 4
    padding 4
    rounded medium
    shadow small

section :class "card"
  h2 "Card title"
```

Generated selectors are scoped to the application root and cannot leak into an
embedding page or another Margeux application.

### Interaction states

State blocks belong to a named style:

```margeux
styles
  style primary-button
    background navy
    foreground white
    on-hover
      background blue
    on-focus
      outline 2 px solid blue
    on-focus-visible
      outline 3 px solid blue
    when-disabled
      opacity 0.5
```

### Responsive and print rules

```margeux
styles
  when-width-below 40 rem
    style toolbar
      layout column
  when-width-above 70 rem
    style page
      width 68 rem
  when-printing
    style controls
      display none
```

Width rules lower to `max-width` and `min-width` media queries. Print rules
lower to a print media query. Each block may contain multiple named styles and
their state blocks.

### Raw compatibility

Existing CSS remains supported:

```margeux
div :style "position: sticky; top: 0"

stylesheet
  style-rule ".card > p:first-child"
    :margin-top "0"
  media-rule "(prefers-reduced-motion: reduce)"
    style-rule ".animated"
      :animation "none"
```

Readable styles and raw styles use the same deterministic validation,
application scoping, native rendering, bytecode VM, and Wasm runtime paths.

## Language: Testing

Authoritative source: `MARGEUX_TESTING_0_1_SPEC.md`. Classification: **normative**.

Status: implemented and test-backed.

This document defines the source, compiler, runtime, and command-line contract
for deterministic Margeux tests. Tests are language declarations, not specially
formatted application output and not Go test adapters.

### 1. Test declarations

A test file conventionally ends in `_test.mgx`. It may import ordinary source
modules and the bundled assertion module:

```margeux
use "std/testing"
use "price"

test "discount never produces a negative price"
  testing.equal (price.discount 10 20) 0
```

`test` requires exactly one non-empty String name and a non-empty indented body.
Its body must produce `Bool`. Duplicate names in one file are rejected. Tests
may use ordinary immutable bindings, calls, records, variants, collections, and
control flow.

The compiler lowers every declaration to a private zero-argument function. The
function and its source identity are retained in a `TestProgram`; the test is
not an application and does not require an `app` declaration.

Tests in imported modules do not run transitively. A `_test.mgx` file becomes a
test entry in its own right. This makes discovery explicit and prevents a
dependency's own suite from silently becoming part of its consumer's suite.

### 2. Assertions

`std/testing` exports these checked assertions:

| Assertion | Contract |
| --- | --- |
| `testing.equal actual expected` | Structural equality using Margeux numeric equality across `Int` and `Float`. |
| `testing.not-equal actual unexpected` | Structural inequality. |
| `testing.is-true value` | Requires `Bool` `true`. |
| `testing.is-false value` | Requires `Bool` `false`. |
| `testing.check condition message` | Requires a Bool condition and uses the supplied failure explanation. |
| `testing.approx actual expected tolerance` | Finite numeric comparison with non-negative absolute tolerance. |
| `testing.fail message` | Fails unconditionally with the supplied String. |

Successful assertions return `true`, so the final assertion naturally satisfies
the test body's `Bool` contract. Failed assertions stop only the current test
and produce a source-mapped VM failure containing deterministic expected and
actual values. The reported location is the assertion call in user source, not
the intrinsic declaration inside `std/testing`.

### 3. Discovery and execution

Run one file or recursively discover lexically ordered `_test.mgx` files:

```sh
margeux test price_test.mgx
margeux test .
```

Every test receives a fresh executor invocation with the normal instruction and
call-depth limits. Test cases cannot mutate each other's VM state. No capability
host is installed in 0.1, so effects are denied by default; pure tests are
portable and deterministic.

The runner continues after failures by default. `--fail-fast` stops after the
first failed case. `--filter TEXT` performs a case-insensitive name substring
match and reports how many cases were filtered out. A filter matching no tests
is an error rather than a silently green run.

Human output contains one `PASS` or `FAIL` line per executed test and a summary.
`--json` emits a stable object with `ok`, aggregate counts, and ordered case
records containing name, source path, position, outcome, and optional message.
Process status is `0` for a passing run, `1` for test failures, and `2` for
invalid invocation, discovery, or compilation failures.

### 4. Checking and tooling

`margeux check` recognizes test entries without requiring an application. The
shared semantic checker validates their bodies and the portable compiler then
validates the same lowered test program used by the runner. Editor metadata
classifies `test` as a declaration and block head and exposes all
`std/testing` exports for completion and highlighting.

### 5. Deliberate 0.1 boundaries

The initial contract does not grant effects, update snapshot files, hide
failures behind retries, or run cases concurrently. Property generation,
explicit capability fakes, coverage, and reviewed snapshot updates can extend
this contract later without changing the meaning of ordinary `test`
declarations or assertion failures.

## Language: Terminal user interfaces

Authoritative source: `MARGEUX_TUI_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented companion specification, version 0.1  
**Scope:** Terminal values, cell drawing, workspaces, pane focus, and input.

This specification extends the core Margeux 0.1 specification. The words MUST,
SHOULD, and MAY have their usual normative meanings.

### 1. Execution model

A TUI `view` is synchronous and returns a `Terminal` value. `terminal`, `text`,
`glyph`, `workspace`, `split`, and `pane` construct serializable terminal data;
they do not write directly to a physical terminal, read input, or mutate the
model. The host renders the returned cells and turns later input into events.

Language-authored cell content is a pure function of the view arguments.
Keyboard focus is ephemeral host state, like focus in a GUI: workspace
composition may add focused-pane metadata and border decoration without adding
focus to the application model. Applications that need durable semantic
selection MUST store that selection in their model.

### 2. Terminal values

```margeux
def view [model] -> Terminal
  terminal 32 8
    text 1 1 "Score: {model.score}" "white"
    glyph model.x model.y "@" "yellow"
```

`terminal width height` creates a rectangular cell grid. Width and height MUST
be `Int`; width is 1 through 200 and height is 1 through 100. A terminal MAY be
empty. Every unpainted cell contains a space with white foreground and black
background.

Cells are serialized row-major and contain exactly `glyph`, `foreground`, and
`background`. A host MUST render every cell at a fixed logical cell position.
Font rasterization MAY vary, but it MUST NOT alter input coordinates or cell
layout.

### 3. Drawing forms

`text x y content color` and `glyph x y content color` require `Int`, `Int`,
`String`, and `String` arguments respectively.

Coordinates identify zero-based cells. The starting position MUST be within the
terminal. Text paints one Unicode scalar value per successive cell, never
wraps, and clips at the right edge. `glyph` requires exactly one Unicode scalar
value. Later drawing forms replace earlier cells at the same position.

The 0.1 color names are `black`, `white`, `gray`, `red`, `green`, `yellow`,
`blue`, `magenta`, and `cyan`. Unknown names are errors. Their serialized RGB
values are fixed by the implementation and do not depend on host themes.

### 4. TUI applications and updates

```margeux
def update [model event: Dict]
  if (= event.kind "key")
    handle-key model event.key
    handle-click model event.x event.y event.button

app Example
  tui
    model
      :count 0
    update update
    view view
```

A TUI update uses either:

```margeux
update(model, event: Dict) -> Model
update(model, pane: String, event: Dict) -> Model
```

The two-argument form is convenient for one terminal. The three-argument form
also receives the focused or clicked pane ID; a terminal without panes supplies
`""`. Both forms receive the same event Dict:

- key: `kind = "key"`, `key` contains the host key, `x = -1`, `y = -1`, and
  `button = ""`;
- pointer: `kind = "click"`, `key = ""`, `x` and `y` are logical cell
  coordinates, and `button` is `"left"`, `"middle"`, `"right"`, or
  `"button-N"`.

The host MUST serialize key and pointer dispatches. Each update receives the
current model and its returned model atomically replaces application state.
Input outside the terminal is ignored. Input on a TUI without `update` produces
a diagnostic rather than executing an unknown function.

### 5. Workspaces

```margeux
workspace 72 24
  split "horizontal" 18
    pane "files" "FILES"
      files-view model
    split "vertical" 14
      pane "editor" "EDITOR"
        editor-view model
      pane "output" "OUTPUT"
        output-view model
```

`workspace width height` requires `Int` dimensions from 3 through 200 by 3
through 100 and exactly one root `pane` or `split`.

`pane id title` requires unique, non-empty String values and exactly one
terminal child. A pane draws a one-cell border. Its child terminal is copied
into the interior at local coordinate `0,0`; content larger than the interior
is clipped and unused interior cells remain blank.

`split direction size` requires exactly two pane or split children. Direction
is `"horizontal"` for left/right composition or `"vertical"` for top/bottom
composition. Size is the first child's outer width or height and MUST leave at
least three cells for both resulting surfaces.

Pane order is depth-first and stable. The first pane initially receives focus.
`Tab` and `Shift+Tab` cycle workspace focus and are reserved by the host; they
do not call `update`. On a terminal without panes, those keys are ordinary key
events. Clicking a pane border changes focus without dispatching an application
event. Clicking its interior focuses it and dispatches pane-local coordinates.
Other key events are routed with the focused pane ID.

### 6. Purity and portability

Terminal construction and application updates MUST remain separate. A drawing
form cannot dispatch input, execute a command, access the rendered framebuffer,
or retain hidden mutable application data. Re-rendering replaces the complete
cell grid; hosts MUST NOT infer application state from pixels.

The browser representation is a host renderer for the same `Terminal` value,
not the language runtime itself. Native, Wasm, and future ANSI hosts MUST use
the same cell ordering, clipping, pane geometry, focus routing, and event
payload contracts.

## Language: Canvas graphics

Authoritative source: `MARGEUX_GRAPHICS_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented companion specification, version 0.1  
**Scope:** Pure canvas display lists, drawing primitives, presentation timing,
pointer input, and frame-based controls.

This specification extends the core Margeux 0.1 specification. The words MUST,
SHOULD, and MAY have their usual normative meanings.

### 1. Execution model

`canvas` and its drawing primitives are pure view constructors. Evaluating a
view produces an immutable, serializable display list; it does not draw, read
pixels, dispatch events, or mutate application state. The browser host paints
that display list after evaluation.

The same model rendered twice produces the same display list. Exact rasterized
pixels MAY differ with browser font and graphics implementations. In
particular, CSS color and `draw-text` font resolution are host facilities.
`pixel-text` uses Margeux's bundled bitmap font and is the portable choice for
pixel-stable labels.

### 2. Canvas

```margeux
canvas
  :width 320
  :height 200
  :label "Interactive drawing"
  :on-pointer pressed
  rect :x 0 :y 0 :width 320 :height 200 :fill "#101820"
```

`:width` and `:height` MUST be finite whole numbers from 1 through 4096. They
define logical pixels. Device-pixel scaling MUST NOT change the logical
coordinate system. `:label` and `:class` are Strings. `:disabled` and
`:continuous` are Bool. `:frame-rate` is a Number greater than zero and no
greater than 240. Unknown properties are errors.

Children are flattened from `Views` before canvas validation and serialization.
The serialized children therefore contain drawing primitives only, in source
composition order. A canvas MUST reject ordinary HTML views and legacy
fragment nodes.

The canvas bitmap clips all drawing to `[0, width) × [0, height)`. Coordinates
outside that area are valid; their out-of-bounds pixels are not visible.

### 3. Common primitive rules

All numeric properties MUST be finite. `:delay`, when present, is a
non-negative number of milliseconds. Delays affect host presentation only:
they do not reevaluate a primitive or change the display list. Pointer input is
unavailable until the largest delay has elapsed.

Primitives are painted in display-list order when their delay becomes eligible.
Authors requiring strict overlapping order SHOULD give those primitives the
same delay. Primitives with equal delay retain display-list order.

`:fill`, `:stroke`, and `:font` are Strings interpreted by the browser host.
Invalid host paint or font strings MUST NOT change language state, though their
visual fallback is host-defined. `:line-width` is a non-negative Number.
Rectangle strokes are inset into their declared bounds.

Unknown primitive properties are errors.

### 4. Basic primitives

```margeux
rect :x 8 :y 8 :width 40 :height 24 :fill "#fff" :stroke "#000"
circle :cx 80 :cy 32 :radius 12 :fill "gold"
line :x1 0 :y1 0 :x2 100 :y2 50 :stroke "#fff" :line-width 2
```

- `rect` requires numeric `:x`, `:y`, `:width`, and `:height`. Width and height
  MUST be non-negative.
- `circle` requires numeric `:cx`, `:cy`, and `:radius`. Radius MUST be
  non-negative.
- `line` requires numeric `:x1`, `:y1`, `:x2`, and `:y2`. A missing stroke
  paints no visible line.

These primitives MUST NOT have children.

### 5. Text primitives

```margeux
draw-text :x 12 :y 24 :fill "#fff" :font "16px monospace" "Status"
pixel-text "SCORE 100" :x 8 :y 8 :fill "#fff" :scale 2
```

Text primitive children MUST be text values, not views.

`draw-text` requires numeric `:x` and `:y`. It MAY specify `:fill`, `:stroke`,
`:line-width`, `:font`, `:align`, and `:baseline`. Its defaults are a 16-pixel
sans-serif font, start alignment, and alphabetic baseline.

`pixel-text` requires numeric `:x` and `:y`. It MAY specify `:fill`, `:align`,
and `:scale`. Scale MUST be a positive whole number. Unsupported glyphs render
as `?`.

### 6. Batched primitives

`tile-map` requires numeric `:x`, `:y`, positive whole `:columns`, positive
`:cell-size`, and Vector values for `:cells` and non-empty `:colors`. Each cell
selects a color index and cells are painted row-major.

`ray-columns` is a specialized batched wall-column primitive. It requires
numeric `:x`, `:y`, positive `:width`, positive `:height`, positive
`:projection`, and non-empty `:hits` and `:colors` Vectors. Numeric packed hits
MAY use `:stride`; structured hits use Dict fields. Portal properties are
optional and do not alter language state. This primitive is part of graphics
0.1 for the bundled raycaster, but is not a replacement for ordinary reusable
Margeux view functions.

### 7. Pointer input

`:on-pointer` receives the current model and an event Dict according to the
core event contract:

```margeux
def pressed [model event: Dict]
  with model
    :x event.x
    :y event.y
```

The Dict contains:

- `kind`: `"pointer"`
- `x`, `y`: whole logical-pixel coordinates, clamped to the canvas bounds
- `button`: `"left"`, `"middle"`, `"right"`, or `"button-N"`

The host MUST focus the canvas on pointer input. It MUST serialize dispatches
so one canvas handler cannot concurrently replace the same model twice. A
disabled or delay-pending canvas MUST ignore pointer input.

### 8. Frame input

`:on-frame` receives `[model event: Dict]`. The event contains the complete
input state needed for one application update:

- `kind`: `"frame"`
- `delta`: finite elapsed seconds clamped to `0.0..0.1`
- `keys`, `pressed`, `released`: normalized lowercase key-name Vectors
- `buttons`: normalized pointer buttons currently held
- `pointer-x`, `pointer-y`: the latest logical canvas position
- `pointer-dx`, `pointer-dy`: movement accumulated since the prior dispatch
- `gamepads`: connected gamepad Dict values

Each gamepad has an `index`, `mapping`, `axes`, and `buttons`. Axis values are
finite and clamped to `-1.0..1.0`; button values are finite and clamped to
`0.0..1.0`. Missing and non-finite host values become `0.0`.

The host MUST collapse operating-system key repeat into held state: `pressed`
contains a key only on its up-to-down transition. It MUST retain transitions
until they are dispatched and MUST permit at most one outstanding frame update
per canvas. It SHOULD avoid dispatching idle frames unless the canvas declares
`:continuous true`; continuous canvases request frame dispatch even when input
is idle. An optional `:frame-rate` limits continuous dispatches to that many
times per second. Newly pressed or released keys and fresh pointer input still
wake the canvas on the next display frame, so lowering an idle or game tick
rate does not add input latency. The event's `delta` remains elapsed wall time,
not the requested interval. Pointer input MUST use capture so a drag remains
coherent outside the canvas bounds.

`std/input` is the pure Margeux interface to this Dict. Its action helpers map
multiple physical keys to one logical action, `axis` combines opposing action
sets, and its gamepad accessors return zero for absent pads, axes, or buttons.

### 9. Errors and portability

Invalid display-list data is a language diagnostic before host painting. Hosts
MUST NOT silently coerce NaN, infinity, negative sizes, unknown properties, or
non-drawing children into valid graphics.

Host renderers MUST share logical coordinate conversion, pointer button names,
text extraction, and inset rectangle-stroke geometry. The editor preview and a
frozen standalone application MUST interpret the same display list alike.

## Language: HTTP server applications

Authoritative source: `MARGEUX_SERVER_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented contract  
**Scope:** Portable HTTP request handlers and the native HTTP adapter.

### 1. Declaration

A server application declares one main function:

```margeux
use "std/server"

def handle [request: server.Request] -> server.Response
  server.text 200 "Hello from {request.path}"

app Example
  server
    main handle
```

The handler MUST accept exactly one `server.Request`. A synchronous handler
returns `server.Response` or `server.StreamResponse`. An `async def` handler
returns a `Result` containing either response kind and may use only capabilities
declared by the application.

### 2. Request

`server.Request` is an immutable record with:

- `method: String`, containing the HTTP method;
- `path: String`, containing the decoded URL path;
- `query: String`, containing the original raw query without `?`;
- `headers: Dict`, containing lowercase header names and joined String values;
- `body: String`, containing the request body interpreted as UTF-8 bytes.

The native 0.1 adapter accepts valid UTF-8 and at most 1 MiB per request body.
Invalid UTF-8 receives status 400; larger requests receive status 413. Neither
case invokes Margeux code.

### 3. Response

`server.Response` contains `status: Int`, `headers: Dict`, and `body: String`.
Status MUST be between 100 and 599. Header names MUST use the HTTP token
alphabet, and header values MUST NOT contain carriage returns or newlines.

`std/server` provides `response`, `text`, `html`, `json`, and `redirect`
constructors. The runtime rejects malformed response values before the native
adapter writes headers.

### 3.1 Portable routes

`std/server` provides immutable `Route` and `RouteMatch` records plus `route`,
`match-route`, and `param`. A route contains an exact HTTP method and a path
pattern. Patterns begin with `/` and consist of slash-separated segments:

- ordinary segments match literally;
- `:name` captures one nonempty decoded path segment as a String;
- `:name:Int`, `:name:Float`, and `:name:Bool` require that the segment can be
  converted to that type before the route matches;
- a final `*name` captures the remaining decoded segments joined by `/`, and
  may capture an empty remainder.

Parameter and wildcard names MUST be nonempty and unique. A wildcard MUST be
the final segment. An empty method, a pattern without an initial slash, or an
invalid capture produces a `RouteMatch` with `valid? false` and a stable
problem String. A method or path mismatch produces `valid? true` and
`matched? false`. A successful match contains an immutable String-valued Dict
of parameters. `param match name` returns `Result[String, String]`, so missing
parameters remain recoverable rather than becoming unchecked dictionary reads.
`int-param`, `float-param`, and `bool-param` return correspondingly typed
Results. Typed conversion failure is an ordinary route miss, allowing another
route or the application's not-found response to handle the request. Unknown
type names and malformed declarations such as `:id:Int:extra` invalidate the
route rather than being treated as literal segments.

`validate-route route` checks the complete declaration before considering any
request. Invalidity therefore cannot be hidden by a method mismatch, a short
path, or an earlier literal mismatch. `validate-routes routes` additionally
rejects same-method patterns whose accepted paths overlap. This includes
renamed parameters, String parameters overlapping any parameter, Int/Float
overlap, compatible literals, and terminal wildcards. Different methods and
provably disjoint literal or typed segments may coexist. Successful validation
returns the original immutable route value or Vector.
Because a terminal wildcard may capture an empty remainder, `/files` overlaps
`/files/*path` for the same method.

The checker partially evaluates literal schemas without changing these runtime
values. A call such as `route "GET" "/users/:id:Int"` is validated during
checking. When a literal Vector of literal route calls is passed directly to
`validate-routes`, pairwise ambiguity is checked at the same time. Diagnostics
point to the literal schema. Computed methods, patterns, and collections remain
ordinary Margeux values and retain the runtime `Result` contract; the compiler
does not pretend dynamic data is statically known.

`route-path route params` performs reverse construction and returns
`Result[String, String]`. Ordinary parameters must be present, nonempty, free
of `/`, and valid for their declared type. Values may already be Strings or may
be Int, Float, or Bool values converted through canonical `string` semantics.
Wildcard values may contain `/` and may be empty. The result is the decoded
application path consumed by `match-route`; it is not percent-encoded wire URL
text. A generated HTTP client MUST apply the platform URL encoder after route
construction rather than inventing a second route-template implementation.

Routing and matching remain ordinary Margeux library code and therefore behave
identically in the reference oracle and canonical bytecode VM. Static literal
checking duplicates only the deterministic validation rules, with parity tests
protecting its error text and overlap behavior.

### 3.2 Synchronous middleware

Synchronous middleware is ordinary lexical function composition. A handler has
the shape `Request -> Response`; middleware receives a handler and returns a
handler with the same shape. It does not require a special runtime protocol.

`with-header response name content` returns a new response whose headers contain
the supplied value. Header names are normalized to lowercase and the original
response is not mutated. `response-middleware handler transform` invokes the
handler once and passes its response to `transform` once.
`header-middleware handler name content` is the common response-header case.
Composition runs from the innermost handler outward:

```margeux
let identified
  server.header-middleware handle "x-application" "Margeux"
identified request
```

Async handlers have the shape `Request -> Task[Result[Response, E]]`.
`async-request-middleware` awaits an asynchronous request transform before the
handler, while `async-response-middleware` awaits the handler and then an
asynchronous response transform. `async-header-middleware` is the common pure
response decoration around an asynchronous handler:

```margeux
let identified
  server.async-header-middleware handle "x-application" "Margeux"
await (identified request)
```

These helpers are ordinary `async fn` closures. Calls remain lazy, `? await`
propagates handler or transform failures, and capability work occurs only when
the canonical runtime awaits the returned Task.

### 3.3 Route-derived clients

`client route base` returns a checked function from a parameter Dict to
`Result[ClientRequest, String]`. `json-client route base` additionally accepts
a body String and selects the JSON UTF-8 content type. Both functions reuse
`route-path`, so missing, incorrectly typed, empty, and slash-containing named
parameters fail before an HTTP task is created.

`ClientRequest` contains `method`, `path`, `body`, and `content-type` fields.
The path joins the supplied base with the route-derived path without producing
or removing an extra slash. The versioned deterministic `encode-path`
operation converts the decoded Unicode route path to its RFC 3986 wire
spelling. It preserves slash separators and percent-encodes UTF-8 bytes,
reserved characters, spaces, and literal percent signs exactly once. Encoding
therefore does not depend on browser, native HTTP, or JavaScript behavior.

Clients accept the same `GET`, `POST`, `PUT`, `PATCH`, and `DELETE` methods as
the portable HTTP task. An unsupported method produces a recoverable Error.
`send request` is async and returns the ordinary HTTP
`Result[Dict, String]`; execution still requires the application's explicit
`http` capability. A route-specific client is an ordinary lexical closure, so
it retains its checked route and base without a separate generated-code format.

### 3.4 Cookies and explicit sessions

`cookie`, `secure-cookie`, and `expired-cookie` construct checked immutable
`Cookie` values. Names are restricted to the portable HTTP token alphabet and
values to the portable cookie-octet alphabet. `with-cookie` validates the value
again and returns a new response with `Set-Cookie`; the fixed policy is
`Path=/`, `HttpOnly`, and `SameSite=Lax`, with `Secure` for secure and expired
cookies. Version 0.1 responses carry one `Set-Cookie` String because response
headers are a `Dict` rather than a multimap.

`cookie-value request name` parses the request's lowercase `cookie` header,
trims optional space around pairs, preserves `=` inside values, and returns a
recoverable Error when the cookie is absent or its name is invalid. Cookies are
transport values only. These helpers do not sign, encrypt, or authenticate
their contents.

`Session` contains an opaque `id: String` and immutable `values: Dict`.
`new-session` validates an application-supplied identifier. `load-session`,
`save-session`, and `delete-session` use the ordinary application-scoped
`storage` capability under a reserved `server-session:` key prefix. Saving
issues a secure cookie; deleting removes the stored value and expires the
cookie. The library deliberately does not generate session identifiers:
security-sensitive applications MUST supply an unpredictable identifier from
a suitable trusted source. Missing storage capability or host failures remain
ordinary task errors. No mutable session state is hidden in the VM.

### 3.5 Server-rendered GUI documents

`margeux render GUI_FILE [-o OUTPUT]` runs the GUI's initial lifecycle through
the canonical register VM and serializes its public `View` snapshot as a full
HTML document. Source files, `.mgxc` artifacts, and verified release
directories MUST produce identical output for the same module. The stable
`#margeux-root` carries application and surface metadata.

Rendering escapes text and scalar attributes, sorts properties and events,
maps the standard layout nodes to their browser CSS classes, preserves control
values, and emits event-specific handler IDs and kinds for hydration. It does
not execute a handler, settle a pending command, embed model state, include
source, grant a capability, or emit JavaScript. Canvas elements render as
canvas containers; their procedural draw children remain client-rendered.
`code-editor`, `code-diff`, and `runtime-preview` emit inert accessible shells
that the public hydration layer upgrades without replacing their stable outer
nodes. Unknown host-specific view nodes, compound HTML properties outside their
explicitly typed widgets, invalid UTF-8, and invalid attribute or event names
are errors rather than silent approximations.

Node-scoped `:style` Dicts are normalized by the application runtime before
serialization, so native HTML and browser hydration observe the same sorted
declaration String. Declarative `stylesheet`, `style-rule`, and `media-rule`
views are likewise compiled once by the canonical runtime. Native HTML emits
the resulting `<style>` text and browser hydration verifies that exact text.
Selectors are prefixed with the stable application-root scope, so reusable
rules, pseudo-selectors, and media queries cannot affect the embedding host.

The browser `hydrateMargeux` entry point verifies this HTML against a fresh
canonical-Wasm snapshot before attaching listeners. Initial nodes are retained;
later transitions replace the ordinary DOM from the committed snapshot.
Mismatches fail before mutation. Canvas drawing, continuous frames, TUI output,
CodeMirror editors/diffs, and nested runtime previews use specialized adapters
inside that one public hydration controller. Nested programs compile through
the owning canonical runtime.

### 3.6 Streaming responses

`server.stream-response status headers initial-state next` creates a
`server.StreamResponse`. `next` is a one-argument function receiving the
previous immutable state and returning `server.StreamStep` or
`Result[server.StreamStep, String]`. It may also be asynchronous. The two steps
are created with `server.emit body next-state` and `call server.end`.

Starting a request does not invoke `next`. The native adapter requests one step,
writes and flushes that chunk, and only then requests another. Capability work
inside an async callback is therefore lazy and occurs at the ordinary guarded
Task boundary. A HEAD request never advances the stream.

Streaming statuses MUST permit a body and therefore exclude informational
statuses, 204, and 304. Applications MUST NOT set `Content-Length`,
`Transfer-Encoding`, or `Trailer`, regardless of header-name casing. Chunks
MUST be valid UTF-8. One response is bounded to 4,096 chunks and 16 MiB.

An error before the first chunk produces status 500. Once headers or a chunk
have been committed, the adapter cannot replace the response; it stops and
sets the sanitized `Margeux-Stream-Error` trailer. Browser request simulation
collects the response deterministically and exposes both the joined `body` and
the original ordered `chunks`, because it has no HTTP writer to flush.

### 4. Execution and effects

Each request invokes the validated main-function index in the portable bytecode
artifact. The request itself is a nominal `std/server.Request` VM value.

Async handlers resolve through the ordinary lazy Task boundary. HTTP, files,
workspace, storage, time, and process operations remain denied unless the app
declares their capability. An `Error` handler result becomes a failed request;
the native adapter returns status 500.

Server VM invocations are stateless in version 0.1. Persistent state must use an
explicit capability such as `storage`, files, or an external service. The
standard session helpers are library composition over `storage`; they do not
alter request isolation. This allows independent concurrent requests and avoids
hidden mutable VM state.

### 5. Native adapter

Run source or a compiled artifact with:

```sh
margeux serve app.mgx --listen 127.0.0.1:8080
margeux serve app.mgxc --listen :8080
margeux serve app.release --listen :8080 --shutdown-timeout 20s
margeux render gui.mgx -o page.html
```

The native adapter sets positive bounded read-header, read, write, idle, and
graceful-shutdown timeouts plus a bounded maximum header size. Defaults are 5s,
30s, 30s, 60s, 15s, and 1 MiB respectively. Operators may set them with
`--read-header-timeout`, `--read-timeout`, `--write-timeout`, `--idle-timeout`,
`--shutdown-timeout`, and `--max-header-bytes`. Header size must be from 1 KiB
through 1 MiB; individual timeout maxima are enforced by the CLI.

The adapter listens before reporting readiness. On SIGINT or SIGTERM it stops
accepting new connections and calls the Go HTTP server's graceful shutdown,
allowing in-flight handlers to finish for the configured shutdown window.
After the window expires it force-closes remaining connections and exits with
an error. Shutdown never replays a handler or changes Margeux application
semantics.

A stripped `.mgxc` server remains executable because request handling depends
only on the validated application table and bytecode. A verified release
directory is accepted directly and becomes the capability root.

## Language: Relational databases

Authoritative source: `MARGEUX_DATABASE_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented 0.1 contract  
**Scope:** Capability-gated relational database access through `std/database`.

### 1. Design

Database access is an explicit host effect. Margeux source supplies SQL and
parameters; the host owns credentials, connection pools, drivers, deadlines,
and deployment policy. Database operations are lazy tasks and execute only when
awaited or dispatched by an application command.

The 0.1 native driver is PostgreSQL. The language API is backend-neutral so a
future driver does not require source-language changes.

Browser and Wasm applications MUST NOT receive PostgreSQL credentials. They MAY
use the same API only when the embedding page installs an explicit database host
that forwards requests to an authenticated server-side service.
An adapter MAY implement only the operations it supports; invoking an omitted
operation returns `Error` and MUST NOT panic or terminate the Wasm runtime.
Synchronous adapter exceptions and rejected adapter Promises are likewise
converted into `Error` results without terminating the runtime.

The Wasm boundary independently validates proxy responses before exposing them
to Margeux. Query results must contain unique declared columns, exact row
fields, portable scalar values, a nonnegative affected count, at most 256
columns and 10,000 rows, and at most 8 MiB of encoded response data.
Transaction and migration responses retain the native 1,024-item bounds.
The embedding runtime also rejects cycles, omitted/non-JSON values, non-finite
numbers, unsafe JavaScript integers, and oversized responses before they enter
Wasm or cross a worker boundary. A browser proxy MUST encode an integer outside
JavaScript's safe range as its exact decimal `String`; it must never round it.
Successful proxy results are serialized once during that preflight and the
validated JSON text is passed into Wasm directly; the VM does not stringify the
same result a second time.

### 2. Capability

Applications MUST declare `database`:

```margeux
app Catalog
  capabilities [database]
  gui
    init initial
    view view
```

Without that declaration, every `db.*` host task is rejected before reaching
the driver.

### 3. API

```margeux
use "std/database"

database.query sql parameters
database.execute sql parameters
database.query-prepared sql parameters
database.execute-prepared sql parameters
database.one-row result
database.query-one sql parameters
database.query-one-prepared sql parameters
database.optional-row result
database.query-optional sql parameters
database.query-optional-prepared sql parameters
database.expect-affected result expected
database.execute-one sql parameters
database.execute-one-prepared sql parameters
database.statement kind sql parameters
database.query-statement sql parameters
database.execute-statement sql parameters
database.transaction statements
database.migration version name statements
database.migrate migrations
```

`query`, `execute`, `query-prepared`, `execute-prepared`, and `transaction`
return lazy `Task[Result[..., String]]`
values through their async functions.

Prepared operations place stable SQL in a bounded host-owned statement cache.
Applications SHOULD use them for repeated hot-path statements and use ordinary
`query` or `execute` for one-off SQL. The native cache holds at most 128 SQL
statements and at most 1 MiB of aggregate SQL text; after either limit is full,
additional prepared operations use short-lived statements rather than growing
process memory without bound.

`QueryResult` contains:

- `columns: Vector[String]` in driver result order;
- `rows: Vector[Dict]`, with one field per column;
- `affected: Int`, which is zero for ordinary queries when the driver does not
  report an affected-row count.

`one-row` converts a `QueryResult` containing exactly one row into
`Result[Dict, String]` and returns `Error` for zero or multiple rows.
`query-one` and `query-one-prepared` combine that contract with the respective
query operation. They prevent an empty result from surfacing as an unchecked
`first` runtime failure while retaining explicit handling for non-unique data.
The bundled Studio database example demonstrates `query-one-prepared` and
`execute-one-prepared` alongside list loading, migrations, and atomic seeding.

`expect-affected` returns the original `QueryResult` in `Ok` only when its
nonnegative affected count equals the requested nonnegative count.
`execute-one` and `execute-one-prepared` combine their respective mutation with
an exact-one-row expectation, making missing or unexpectedly broad updates
explicit `Error` values.

`OptionalRow` contains `found?: Bool` and `row: Dict`. `optional-row` returns
`Ok` with `found? false` and an empty Dict for zero rows, `Ok` with the row for
one row, and `Error` for multiple rows. `query-optional` and its prepared form
combine that behavior with querying. This models valid absence without `Any`,
`nil`, or conflating it with a host/database failure.

`database.statement` constructs a portable transaction statement Dict. `kind`
MUST be `"query"` or `"execute"`. A transaction executes statements in order,
commits only if every statement succeeds, and otherwise rolls back and returns
`Error`. Transaction and migration Dicts reject unknown fields. All hosts
receive a normalized copy of the validated request; in particular migration
names are trimmed identically before native execution or browser forwarding.

`database.query-statement` and `database.execute-statement` construct the same
portable value without requiring an application to spell the `kind` string.
They SHOULD be preferred when the statement kind is known in source;
`database.statement` remains available for dynamically selected kinds.

`database.migration` constructs a portable migration description with a
positive integer version, a name, and one or more SQL strings. `database.migrate`
serializes concurrent PostgreSQL migration runners with a transaction-scoped
advisory lock, creates `margeux_schema_migrations` when necessary, and applies
all pending descriptions in one transaction. It returns the versions applied
by that invocation; an already-current database returns an empty Vector.

Migration versions MUST be strictly increasing in the supplied Vector. The host
records a SHA-256 checksum over each immutable definition and rejects reuse of
an applied version with a changed name or SQL body. A failure rolls back both
the schema changes and their tracking rows. The native host accepts at most
1,024 migrations, 256 statements per migration, and allows 60 seconds for the
complete locked transaction. It reads existing definitions only for the
versions in the validated input batch; migration memory and lookup work do not
grow with the complete lifetime history table.

### 4. Parameters

SQL values MUST be passed separately from SQL text:

```margeux
await database.query
  "select id, title from notes where owner_id = $1 order by id limit $2"
  [model.owner-id 100]
```

The 0.1 portable parameter set is `nil`, `Bool`, `Int`, `Float`, and `String`.
Collections, records, functions, tasks, and views are rejected. Applications
that need JSON MUST serialize it explicitly with `json.stringify` and cast it
in SQL when necessary.

Floats MUST be finite. At a browser host boundary, Margeux integers outside
JavaScript's safe-integer range are delivered to the database adapter as exact
JavaScript `bigint` values rather than rounded `number` values. An adapter that
uses a JSON protocol MUST encode those values losslessly (for example as tagged
decimal strings understood by its server); it MUST NOT coerce them to Number.

Native and Wasm hosts share one request validator. Empty or over-1-MiB SQL,
more than 65,535 parameters, non-scalar parameters, malformed transaction
statements, invalid migration batches, and requests whose aggregate SQL,
parameter, migration-name, and migration-statement payload exceeds 8 MiB are
rejected before opening a pool, starting a transaction, invoking JavaScript, or
contacting a proxy. The aggregate limit applies to a whole transaction or
migration batch, not independently to each item.

The library never interpolates parameters into SQL text.

### 5. Result conversion

Drivers convert database values to portable Margeux values:

- SQL `NULL` becomes `nil`;
- Boolean values become `Bool`;
- signed integer values become `Int` when representable;
- finite floating-point values become `Float`; PostgreSQL `NaN` and infinity
  values are rejected rather than creating non-portable runtime values;
- text, UUID, decimal, JSON, date, and timestamp representations become
  `String`;
- binary values become base64-encoded `String` values.

Duplicate result-column names are errors because a `Dict` cannot preserve both
values. Empty column names and negative affected-row counts are also errors.
Native and browser hosts enforce these same result-shape invariants. Results are
bounded by host-configured row and byte limits.

### 6. Native PostgreSQL host

The native CLI reads `MARGEUX_DATABASE_URL`. The URL is never exposed to
Margeux values, diagnostics, traces, driver-error strings, or the browser
runtime. Raw connection strings, URL passwords, and `password=` fields are
redacted before any open, query, execute, prepare, transaction, migration, or
shutdown failure crosses the host boundary. The host lazily opens one
process-local `database/sql` pool and reuses it across operations.

Pool initialization is serialized. A failed initial open or ping MUST NOT be
cached permanently: a later operation retries initialization so a long-running
Margeux process can recover when PostgreSQL becomes available. After a pool is
established, the Go driver owns ordinary connection replacement and recovery.
On host shutdown, new work stops first, in-flight tasks drain, cached prepared
statements close, and then the pool closes. Closing is idempotent and clears all
cached handles so an explicitly reused host cannot address the old pool.

The initial defaults are:

- 16 maximum open connections;
- 8 maximum idle connections;
- 30-minute connection lifetime;
- 15-second operation timeout;
- 128 cached prepared statements and 1 MiB of cached SQL text;
- 1,024 statements per transaction;
- 10,000 result rows;
- 8 MiB of converted result data.

These are safety limits, not query planner hints. PostgreSQL schema design,
indexes, migrations, and authorization remain application/deployment concerns.

### 7. Transactions and failures

Transactions use the driver's default isolation unless a later API explicitly
selects another level. The host MUST roll back after any failed statement,
conversion failure, cancellation, or result-limit failure.

Driver errors are returned as `Error String`. Implementations SHOULD avoid
including credentials or full connection URLs in those messages.

### 8. Performance contract

Hosts SHOULD reuse connection pools and MUST avoid reconnecting per query.
Queries stream driver rows into a preallocated result vector and enforce limits
while scanning. Transaction statements reuse one checked-out connection.

Performance claims MUST use a real PostgreSQL integration benchmark with the
schema, row counts, query text, parameters, pool state, and raw samples
published. In-memory fake-host tests prove language behavior but are not
database performance evidence.

The standard repository test gate starts an isolated temporary PostgreSQL
cluster when the environment permits Unix sockets and runs the production host
through ordinary and prepared queries, mutations, successful and rolled-back
transactions, and idempotent migrations. Environments that prohibit socket
creation still validate the SQL schemas in PostgreSQL single-user mode and
report the skipped lifecycle coverage explicitly.
Continuous integration additionally binds its PostgreSQL 16 service to
`MARGEUX_TEST_DATABASE_URL`, making the same production-host lifecycle a
mandatory TCP-backed test rather than relying on the optional local socket.

The repository's production-path harness and publication checklist are defined
in `DATABASE_BENCHMARKS.md`. `make benchmark-database` retains eleven raw
samples and refuses to run without an explicit `MARGEUX_BENCH_DATABASE_URL`.

## Language: Browser embedding API

Authoritative source: `MARGEUX_EMBED_0_1_SPEC.md`. Classification: **normative**.

Status: implemented, normative for embedding API version 1.

### 1. Purpose

The embedding API loads the Go/Wasm Margeux compiler and VM directly into a
browser realm. It does not require a Margeux server or an execution API. Source
compilation, bytecode validation, application sessions, and event transitions
occur locally in that realm.

The public module is `/margeux-runtime.js`. `margeux.wasm` and `wasm_exec.js`
are the default runtime assets. An embedder may serve them from another location
by passing explicit URLs or a base URL.

Precompiled GUI and TUI releases that declare no host capabilities MAY use
`margeux-runtime.wasm`. This artifact-only host runs the same validated
bytecode VM but intentionally omits source compilation, language services,
benchmarks, and capability adapters. Requests for omitted operations fail
explicitly.

Precompiled releases that declare browser host capabilities use
`margeux-runtime-host.wasm`. It adds only the capability adapter and still
omits the compiler and language services. This keeps the capability-free
runtime at the smallest cold-start and memory footprint without forcing
capability-bearing applications back onto the compiler build.

The default `margeux.wasm` and `margeux-runtime.wasm` omit ZIP/EPUB decoding so
ordinary applications do not download archive, deflate, and XML machinery.
`margeux-extended.wasm` and `margeux-runtime-extended.wasm` are API- and
bytecode-compatible builds that add the `std/archive` intrinsics. Editors that
promise the complete bundled standard library and applications that import
`std/archive` MUST select the corresponding extended asset with `wasmURL`.
Calling an archive operation on a core build returns an explicit `Error`; it
MUST NOT silently produce an empty archive result.

### 2. Version negotiation

```js
import {
  MARGEUX_EMBEDDING_API_VERSION,
  createMargeuxRuntime,
  createMargeuxWorkerRuntime,
} from "/margeux-runtime.js";

const runtime = await createMargeuxRuntime({ baseURL: document.baseURI });
console.log(runtime.info);
```

The Wasm runtime answers `runtimeInfo` before the public client becomes ready.
Version 1 reports:

- `embeddingApi: 1`;
- the supported bytecode major/minor version;
- the canonical engine identity `margeux-go-vm`; and
- the host identity `wasm`, which describes packaging rather than selecting a
  different runtime.

The client MUST reject a different embedding API version rather than guessing
at compatibility. Multiple calls in one JavaScript realm share one initialized
Go/Wasm runtime and retain separate execution-session objects.

### 3. Loading

`createMargeuxRuntime` accepts:

- `baseURL`, used to locate `wasm_exec.js` and `margeux.wasm`;
- explicit `wasmExecURL` and `wasmURL` overrides;
- `wasmBytes`, for bundlers, tests, offline applications, and preloaded bytes;
- `timeout`, bounding initialization; and
- optional capability hosts described below.

In a document, the loader can add `wasm_exec.js` itself. A module worker loads
that script before calling the API. Initialization uses streaming Wasm when
available and falls back to an ArrayBuffer when a server supplies an unsuitable
MIME type. Local `file:` documents are also supported where the browser permits
file-origin reads. In particular, a status-0 WebKit file response is treated as
readable and its body is still required to decode as valid Wasm; status checks
remain strict for HTTP and HTTPS responses.

The Go runtime remains alive for the lifetime of its JavaScript realm. Version
1 same-realm runtimes have no unload operation. `createMargeuxWorkerRuntime`
starts the shipped module worker and returns the same high-level runtime API in
an isolated realm. Its `isolated` property is true, `terminated` reports its
terminal state, and `terminate()` stops the worker and invalidates every session
owned by it.

All request-producing APIs accept `signal` and `timeout` controls. This includes
checking, compilation, artifact loading, language operations, benchmarks, and
execution-session transitions. `timeout` is a non-negative integer number of
milliseconds; zero disables it. Cancellation rejects with
`MargeuxCancellationError`, whose `reason` is `abort`, `timeout`, or
`terminated`.

Same-realm cancellation stops waiting for a result but cannot preempt synchronous
Wasm compute while the realm's event loop is occupied. Worker cancellation is
hard: an abort or timeout terminates the entire worker, rejects every outstanding
request, and loses all sessions in that realm. This is deliberate—execution
cannot continue invisibly after a host declares its resource budget exhausted.
Callers create a fresh worker runtime to run more programs.

### 4. Programs and artifacts

`runtime.check(program)` returns the structured check response without running
the application. A program is either:

```js
{ source: "...", entry: "main.mgx" }
```

or:

```js
{ entry: "main.mgx", files: { "main.mgx": "...", "lib/ui.mgx": "..." } }
```

`runtime.compile(program, options)` compiles and starts the portable VM. Its
options include launch `arguments`, `artifact: true`, `stripSource: true`, and
`previousSession` for compatible hot state adoption. `stripSource` affects only
the returned artifact; the source compilation retains its ordinary immutable
source host. There is no execution-engine option: source and artifact entry
points always use the canonical Go register VM compiled to Wasm.
`runtime.loadArtifact(base64, options)` validates
and starts an encoded `.mgxc` artifact without parsing source.
`runtime.loadRelease(url, options)` fetches a version 1 release directory,
strictly validates its manifest, verifies the artifact size and SHA-256 with
Web Crypto, and has the canonical Wasm VM decode the artifact without executing
it. It compares the decoded application name, surface, capabilities, bytecode
version, and source mode with the manifest before using the same bytecode
loading path. Browser origin and CORS policy remain in force.

Compilation and artifact loading accept `history: false` for an immediate
production session that does not expose debugger controls. Such a session
retains transactional rollback for failed updates but does not retain prior
models, event payloads, redo states, named checkpoints, or exportable traces.
History remains enabled when the option is omitted. The production page builder
uses the history-free mode for ordinary applications and preserves history for
Studio and editor surfaces.

The underlying `inspectArtifact` request is deliberately non-executing: it does
not construct an application session, invoke a lifecycle function, or expose a
host capability. Its metadata is derived from the validated `.mgxc` module.

`margeux-dom.js` exports `hydrateMargeux(root, execution)`. For an ordinary GUI
snapshot, hydration first reconstructs the expected DOM and compares it with
the server-rendered root. Any application, surface, structure, property, text,
or handler-metadata mismatch fails before listeners are attached. Successful
hydration preserves every initial DOM node, attaches event-specific handlers,
serializes transitions through the supplied canonical VM execution, and
renders later snapshots only after successful transitions. `settled()` exposes
the last queued transition for tests and host coordination; `destroy()` removes
listeners without terminating the execution.

Hydration restores focused input selection after rendering and preserves
click, submit, input, key, and pointer payload contracts. Errors may be handled
with `onError`; otherwise the root emits `margeuxerror`. Canvas snapshots made
from `rect`, `circle`, `line`, `draw-text`, `pixel-text`, `ray-columns`, and
`tile-map` primitives use the same entry point: hydration preserves the
server-rendered canvas element,
paints its canonical display list (including delayed nodes), blocks input until
that display list has settled, normalizes pointer positions to logical
coordinates, and dispatches pointer and key handlers through the VM transition
queue. Frame handlers accumulate held/pressed/released keys, pointer buttons
and deltas, bounded frame time, and available gamepad state; each frame is one
serialized VM transition, and rerendering preserves the live canvas node and
its input state. Pixel text and ray columns use one public renderer module
shared with the live runtime rather than maintaining hydration-specific
approximations.

For a TUI snapshot, native rendering emits a bounded accessible `pre` grid with
canonical glyph and foreground/background runs. Hydration verifies that grid,
preserves its terminal element, normalizes pointer positions to cell
coordinates, and routes key (including `Shift+Tab`) and pointer input through
`MargeuxExecution.key` and `.pointer`. Successful transitions update the grid
in place.

The `code-editor` and `code-diff` Views are specialized host widgets admitted
to this same server-rendering and hydration contract. Native rendering emits
stable, accessible shells containing inert `textarea` elements; hydration
verifies those shells, then mounts the shipped CodeMirror renderer inside them.
Editor shells and CodeMirror instances survive canonical-VM rerenders, while
`code-editor` `:on-input`, `:on-files`, `:on-navigate`, and `:on-run` are
serialized through the same execution queue as ordinary DOM events.
`:on-navigate` receives the destination project path as a String; the host
retains the exact cursor span so the application's file selection remains
ordinary immutable model state. `:on-files` receives a validated Vector of
`{path, source}` dictionaries so a project refactor becomes one atomic model
transition rather than a series of partially applied text events. A
Margeux-language editor MAY provide
`:entry`, `:path`, and a `:files` Vector of `{path, source}` dictionaries. The
host then sends completion, hover, definition, symbol-highlight, and non-executing
document-analysis requests through the owning `MargeuxRuntime`; the current
unsaved document replaces its file-set entry for every request. Definition
navigation uses F12 or Ctrl/Cmd-click and opens project files through
`:on-navigate`; Shift+F12 cycles project references, Ctrl/Cmd+F12 cycles
protocol implementations, Ctrl/Cmd+Shift+F12 cycles related protocol and
concrete types, and F2 applies a language-service-validated workspace rename
through `:on-files`. Ctrl/Cmd+T MAY open a workspace-symbol palette whose
ranking and locations come from the owning runtime's language service.
Shift+Alt+H MAY show compiler-resolved incoming and outgoing calls and navigate
their declaration selections. Diagnostics,
navigation, and edits retain UTF-8 source spans and are explicitly converted to
editor offsets, including structured compiler fixes and safe missing-import
actions. Supplying project files does not create another
compiler, evaluator, or execution session. Diff highlighting derives from the
validated UTF-8 source-edit protocol and explicitly converts its ranges to
editor offsets. The same batched document analysis supplies compiler-owned
semantic token and resolved-module-link decorations plus parser-owned folding
ranges. Symbol highlight requests distinguish declarations from reads using
resolved identity. Structural
selection requests use Shift+Alt+Right/Left and never execute application code.
`:key` provides explicit identity when more than one widget can
share a label. The stable `/margeux-editor-runtime.js` production entry owns
these host adapters; it is not a second language runtime.

`runtime-preview` emits an inert history/checkpoint/output shell. During
hydration it compiles the supplied source or file set through the owning
`MargeuxRuntime`, never through another evaluator. GUI and TUI previews recurse
through this same hydration contract; CLI and server previews use their public
execution results and request methods. Undo, redo, seek, named checkpoints,
trace export/replay, and nested events all operate on the nested canonical VM
execution. A depth limit prevents accidental unbounded preview recursion.

The canonical runtime normalizes node-scoped `:style` Dicts before a snapshot
crosses the embedding boundary. Native SSR and `margeux-dom.js` therefore
compare and apply the same deterministic declaration String rather than
independently serializing dictionaries in Go and JavaScript.
Declarative stylesheet trees are also compiled before this boundary. Their
selectors target the stable `data-margeux-scope` placed on the application root;
hosts render the canonical stylesheet text and MUST NOT widen or remove that
scope.

Both return a `MargeuxExecution`. Depending on the application surface it owns
a GUI/TUI snapshot, CLI result, or server session. An execution exposes its
session ID, surface, current snapshot, optional artifact, CLI result, timeline,
and most recent server response.

Compilation, loading, and language-service methods throw
`MargeuxRuntimeError` on failure. The error retains the original response and
structured diagnostics. `runtime.check` deliberately returns failed checks so
editors can consume every diagnostic without exception control flow.

### 5. Application sessions

A stateful execution provides:

- `dispatch(event)`, for a rendered handler ID and typed event payload;
- `key(value)` and `pointer(x, y, button)`, for TUI input;
- `resume()`, for an explicitly pending command;
- `history()`, `undo()`, `redo()`, and `seek(cursor)`;
- `checkpoints()`, `saveCheckpoint(name)`, `restoreCheckpoint(name)`,
  `deleteCheckpoint(name)`, and `diffCheckpoint(name)`;
- `exportTrace()` and `replayTrace(trace)`; and
- `serverRequest(request)` for server applications.

For a streaming server response, `serverRequest` deterministically consumes the
bounded stream because the embedding API has no network writer to flush. Its
response includes the joined `body` and the ordered `chunks`. Native HTTP
serving remains lazy and flushes chunks individually.

Dispatch, key, pointer, and resume settle pending command chains by default.
Passing `{settle: false}` returns after one transition. Automatic settlement is
bounded to 1,024 resumptions. It never bypasses capability checks and never
runs commands during view construction.

Trace replay returns a new execution session, leaving the original session
available. Compatible recompilation likewise creates a new session after
adopting the old immutable model; it does not mutate the old session.

### 6. Rendering boundary

The embedding API returns declarative Margeux View, Terminal, or workspace
values. It does not own the DOM, canvas, terminal renderer, focus policy, or
CSS. The host renders those values and routes user inputs back through session
methods. This keeps the language VM usable in webpages, workers, custom
editors, tests, and non-DOM JavaScript hosts.

The shipped runtime page is a thin client of this renderer rather than a second
renderer implementation. It loads application source, compiles it through the
public runtime, and selects GUI/TUI hydration or the public CLI/server result
surface. It is not part of the versioned embedding API.

### 7. Capability hosts

An embedder may provide these explicit host adapters while creating the runtime:

```js
const runtime = await createMargeuxRuntime({
  hosts: {
    files: fileHost,
    storage: storageHost,
    database: databaseHost,
    clock: clockHost,
    process: processHost,
    llm: llmHost,
  },
});
```

They map to the existing `std/source`, `std/storage`, `std/database`, `std/time`, and
`std/process` capability boundaries; `llm.complete(requestJSON)` supplies the
provider-neutral `std/llm` boundary specified separately. Supplying a
JavaScript adapter does not grant it to every program: the Margeux application
must still declare the corresponding capability. HTTP uses the realm's Fetch
implementation and is likewise gated by the application's `http` capability.

An LLM adapter returns an encoded completion proposal. The Wasm host validates
request identity, provider/model metadata, SHA-256 input/output bindings,
workspace paths, UTF-8 offsets, exact expected text, and non-overlap before the
program receives it. This adapter has no implicit access to file, workspace, or
execution hosts. Same-realm runtimes call adapters directly. Isolated runtimes
proxy only the allowlisted LLM and database methods (`query`, `execute`,
`queryPrepared`, `executePrepared`, `transaction`, and `migrate`) to the owning realm and
provide an AbortSignal; terminating the worker aborts outstanding adapter
requests. Database adapters must be authenticated server-side proxies and must
never embed PostgreSQL credentials in browser code.

Database adapter results are transport-preflighted before entering Wasm or
crossing an isolated-worker boundary. Cyclic values, undefined/function/symbol/
bigint values, non-finite or unsafe JavaScript numbers, and encoded responses
larger than 8 MiB are rejected. The Wasm host then enforces the shared native
query-result shape, scalar, column, row, transaction, and migration limits.
Wide database integers must cross this JSON boundary as exact decimal strings,
never rounded JavaScript Numbers.
The successful preflight output is the JSON text delivered to Wasm (or through
the worker transport), so database responses are serialized once rather than
stringified again after realm crossing.

Capability adapters SHOULD validate paths, sizes, durations, process names,
and output just as native hosts do. The embedding API is not a hostile-code
sandbox; isolation from untrusted programs requires a dedicated worker plus
resource and capability policy.

### 8. Tooling and low-level access

`runtime.syntax()`, `runtime.language(operation, options)`, and
`runtime.benchmark(...)` expose the same compiler-owned metadata, language
service, and benchmark operation used by Studio and conformance tests.

`runtime.request(payload)` remains available for forward-compatible low-level
operations. It returns the raw structured response, including `ok: false`.
Consumers using it own response validation. The JSON-string
`globalThis.margeuxRequest` function is internal transport and is not the public
embedding contract.

A low-level TUI `dispatch`, `key`, or `pointer` request MAY set
`terminalDelta: true`. The response then carries a compact snapshot header and
a `terminalDelta` containing dimensions, current panes, and indexed changed
cells; a geometry change sets `full` and carries every cell. The caller MUST
expand that response against the last terminal it received for the same
session. This mode deliberately omits the unchanged public model and full cell
grid. High-level `MargeuxExecution` methods do not select it and continue to
return complete public snapshots. Studio uses the opt-in mode only as an
internal rendering transport for its already-owned session.

### 9. Compatibility proof

`tests/embed-api.mjs` runs the public module against the real compiled Wasm. It
covers negotiation, singleton boot, checking, structured failures, GUI events,
async settlement, source artifacts, artifact loading, compatible recompilation,
TUI key/pointer input, CLI output, server requests, language navigation,
history, time travel, named checkpoint save/list/restore/delete and state
comparison, trace export/replay, and raw error responses.

`tests/embed-worker-api.mjs` covers isolated startup, explicit termination,
abort and timeout cancellation, rejection of collateral in-flight work, startup
timeouts, and the terminal-state contract. Studio, GridMaster5000, Ray3D, and
the source application use this public worker transport rather than maintaining
private request protocols.

## Language: Model Context Protocol server

Authoritative source: `MARGEUX_MCP_0_1_SPEC.md`. Classification: **versioned**.

**Status:** Implemented in SDK 0.1.3  
**Scope:** A local Model Context Protocol server for understanding, checking,
editing, testing, and running Margeux projects.

### 1. Purpose

The Margeux MCP server gives an LLM the same language facts and compiler
evidence available to a human using the SDK. It is a thin protocol adapter over
the canonical Margeux parser, compiler, language service, formatter, test
runner, VM, documentation, standard library, and examples. It MUST NOT contain
a second parser, type checker, source-edit model, or documentation database.

The initial executable is part of the ordinary SDK binary:

```sh
margeux mcp /path/to/project
```

The server communicates over standard input and standard output. Standard
output is reserved for MCP messages. Diagnostics and optional debug logs go to
standard error.

The 0.1 server targets the stateful MCP 2025-11-25 protocol revision because it
is supported by the major downloadable coding clients that SDK 0.1.3 targets.
The server MUST negotiate the revision during initialization and reject an
unsupported revision explicitly. Support for the stateless 2026-07-28
revision is a compatible future transport adapter, not permission to change
the tools or their data contracts.

### 2. Design principles

1. Compiler evidence outranks generated prose.
2. Reads are available by default; writes and execution are explicit.
3. Every edit is bound to the exact source revision the model inspected.
4. One server owns one normalized project root.
5. Paths never escape that root, including through symlinks.
6. Tool results are structured JSON with a short text summary for clients that
   do not consume structured output.
7. Tool failures are results the model can correct; malformed MCP requests are
   protocol errors.
8. No tool silently grants a Margeux host capability.
9. Documentation is versioned with the compiler and available in small,
   searchable chunks.

### 3. Project boundary and configuration

The positional root defaults to the current directory. It is resolved once at
startup with symlinks evaluated. A request path is a forward-slash relative
path. Empty paths, absolute paths, NUL bytes, `.` or `..` components, and paths
whose resolved target leaves the root are rejected.

By default, source tools may read and change:

- `*.mgx` files;
- `margeux.json`;
- `margeux.lock`; and
- Markdown documentation inside the project when explicitly named.

The server MUST ignore `.git`, `.margeux/mcp-transactions`, build output, and
SDK-internal files when enumerating the workspace. It MUST NOT follow a
directory symlink during enumeration.

The command accepts these options:

```text
--read-only             omit every mutating tool
--allow-run             expose margeux_run
--allow-capability NAME repeatable capability allowed during run
--max-file-bytes N      lower the default 2 MiB source-file limit
--max-output-bytes N    lower the default 2 MiB tool-output limit
--log-level LEVEL       write protocol-safe logs to stderr
```

There is no network transport in 0.1.3. A future HTTP transport requires a
separate authentication and origin policy and MUST NOT be enabled merely by
binding a command-line address.

### 4. Documentation and context

Yes, useful LLM editing requires language documentation. It does not require a
second LLM-specific language definition. The packaged documentation corpus is
generated at SDK build time from authoritative repository sources:

1. `docs/MCP_LANGUAGE_CONTEXT.md` — short orientation and routing guide;
2. `MARGEUX_0_1_SPEC.md` — normative core language;
3. `PHASE0_SYNTAX.md` — lexical and concrete syntax reference;
4. `TYPE_SYSTEM_BOUNDARIES.md` — inference and explicit type boundaries;
5. `MARGEUX_MACRO_0_2_SPEC.md` — macro and expansion semantics;
6. `MARGEUX_ASYNC_0_1_SPEC.md` — tasks, effects, and capabilities;
7. the runtime, GUI, graphics, TUI, server, database, package, testing, numeric,
   and style specifications;
8. `docs/STANDARD_LIBRARY_REFERENCE.md`, generated from the actual bundled
   standard-library source; and
9. the maintained examples and their verification metadata.

Each document chunk carries its source path, heading, line range, language
version, authority (`normative`, `test-backed`, or `informative`), lifecycle,
and SHA-256 digest. Search results MUST rank normative implemented material
above examples and proposed documents. A result MUST identify its authority so
the model cannot mistake a roadmap for implemented syntax.

The SDK build generates the corpus once. Starting `margeux mcp` MUST NOT
recompile every example or require PostgreSQL. The server loads the packaged
index and verifies that its recorded compiler version matches the running
binary.

#### 4.1 Resources

The server exposes read-only MCP resources and resource templates:

| URI | Contents |
| --- | --- |
| `margeux://docs/index` | Document catalog and compiler version |
| `margeux://docs/{slug}` | One documentation chunk or complete small document |
| `margeux://stdlib/index` | Modules, exports, signatures, and summaries |
| `margeux://stdlib/{module}` | Canonical bundled module source and reference |
| `margeux://examples/index` | Maintained examples and demonstrated concepts |
| `margeux://examples/{slug}` | Verified example files and entry point |
| `margeux://workspace/index` | Current project files and digests |
| `margeux://workspace/{path}` | Exact current UTF-8 file contents |

Workspace resources change when a successful edit commits. The server then
emits the resource-updated/list-changed notification supported by the
negotiated protocol. Documentation and SDK resources are immutable for the
life of the process.

### 5. Shared source representation

All internal spans are zero-based UTF-8 byte offsets into the exact source
bytes. Every externally reported span includes:

```json
{
  "startByte": 12,
  "endByte": 19,
  "start": { "line": 2, "column": 3, "utf16Column": 3 },
  "end": { "line": 2, "column": 10, "utf16Column": 10 }
}
```

Lines and human columns are one-based; `utf16Column` is zero-based for editor
clients. Newlines are not normalized before offsets are computed. Each source
file has a lowercase SHA-256 digest over its exact bytes.

The project revision is a SHA-256 digest over sorted pairs of normalized path
and file digest. Read tools return that revision. Mutating tools require the
revision observed by the caller. This detects changes made by a text editor or
another MCP client between inspection and application.

### 6. Tools

Tool names use a stable `margeux_` prefix for clients that do not accept dotted
tool names. JSON Schemas reject unknown fields.

#### 6.1 `margeux_project`

Returns the normalized root label, entry point, manifest and lock status,
compiler/bytecode versions, project revision, source paths and digests, and the
host capabilities declared by each application. It is read-only and performs
no compilation.

#### 6.2 `margeux_docs_search`

Input:

```json
{ "query": "record update", "kind": "language", "limit": 8 }
```

`kind` is optional and may be `language`, `stdlib`, `diagnostic`, or `example`.
The result contains bounded excerpts plus resource URIs, headings, source line
ranges, authority, lifecycle, and digests. The tool performs deterministic
lexical/symbol search; it makes no network or embedding request.

#### 6.3 `margeux_check`

Input names an entry path and optionally an in-memory overlay of path/content
pairs. Overlays are checked without writing them. The result contains `ok`,
the project revision, compiler and bytecode versions, and sorted structured
diagnostics with codes, severity, message, path, span, related spans, macro
expansion stack, and safe fixes.

This is the canonical validation tool. It invokes the same project loader and
compiler as `margeux check`.

#### 6.4 `margeux_format`

Input contains a path and either its expected digest or overlay content. The
formatter never writes. It returns canonical source, the original and result
digests, and one complete-file `SourceEdit`. Invalid source returns structured
parser diagnostics and no edit.

#### 6.5 `margeux_symbols`

Input contains an optional query and limit. It returns workspace and standard
library declarations with kind, signature, module, visibility, documentation,
and source location. An optional path/byte offset returns hover, definition,
references, and inferred type at that location. It reuses `internal/language`.

#### 6.6 `margeux_rename_plan`

Input contains path, byte offset, new name, and project revision. It returns a
validated set of source edits but does not write. Invalid identifiers,
collisions, private-boundary violations, and stale revisions are errors. The
plan may be passed unchanged to `margeux_apply_edits`.

#### 6.7 `margeux_apply_edits`

This is the only general source-mutation tool. Its schema reuses the source
proposal contract in `MARGEUX_LLM_0_1_SPEC.md`:

```json
{
  "revision": "project-sha256",
  "edits": [
    {
      "path": "main.mgx",
      "start": 10,
      "end": 15,
      "expected": "old bytes",
      "replacement": "new bytes"
    }
  ],
  "creates": [{ "path": "lib/math.mgx", "content": "..." }],
  "deletes": [{ "path": "old.mgx", "expectedDigest": "..." }],
  "checkEntry": "main.mgx"
}
```

Ranges for one file cannot overlap. A path cannot appear in more than one
operation class. Every expected range and digest must match. The server builds
an immutable candidate workspace, parses it, and, when `checkEntry` is set,
compiles it before writing. Any failure writes nothing.

On success, files are staged under a private transaction directory, fsynced,
and committed with a recovery journal. A failure during commit is rolled back;
an interrupted commit is recovered before the next request. The result returns
the old and new project revisions, changed file digests, a unified diff, and
post-commit diagnostics. Undo is possible because the inverse transaction is
retained until the next successful mutation in the same server session.

This tool is absent in `--read-only` mode. It is annotated as mutating and is
never invoked as a side effect of check, format, rename planning, or run.

#### 6.8 `margeux_undo_edit`

Input contains the exact post-commit revision returned by the immediately
preceding successful mutation. It atomically restores that transaction and
returns a diff and restored revision. It refuses if any affected file changed
after the commit. It is absent in read-only mode.

#### 6.9 `margeux_test`

Runs the canonical Margeux test runner against a path, optional filter, and
fail-fast flag. Tests execute with no host capabilities. The result contains
counts, durations, and structured failures. Output, instruction count, wall
time, and memory are bounded. The tool never changes project files.

#### 6.10 `margeux_run`

This tool is absent unless the server starts with `--allow-run`. Input names an
entry and arguments. It runs the canonical VM with instruction, time, memory,
and output limits. The program receives only capabilities named by
`--allow-capability`; source declarations cannot enlarge that allowlist.
Network, database, process, files, storage, LLM, and clock access are therefore
unavailable by default.

The result includes exit status, stdout/stderr, a bounded final snapshot for
applications, runtime diagnostics, elapsed time, and truncation flags. It does
not write an artifact or modify source.

### 7. Tool output and errors

Successful tool calls return both:

- `structuredContent`, validated against the tool's output schema; and
- one concise text content block summarizing the outcome.

Expected development failures such as syntax diagnostics, failed tests, stale
digests, or VM diagnostics use `isError: true` with structured details. Invalid
JSON-RPC, unknown methods, invalid schemas, and unavailable tools use protocol
errors. Host paths, environment values, credentials, and stack traces are
never returned.

Tool output is deterministic: paths and diagnostics are sorted, JSON object
contracts use stable fields, and timestamps are excluded unless the tool is
explicitly reporting elapsed execution time.

### 8. Prompts

SDK 0.1.3 MAY expose two optional user-selected prompts:

- `margeux_fix` asks a model to inspect diagnostics, consult relevant language
  resources, propose edits, check the overlay, and apply only after review.
- `margeux_implement` asks a model to inspect the project, find a maintained
  example of the relevant concepts, propose a small change, validate it, and
  report the diff.

Prompts are workflow hints, not authority. Merely retrieving a prompt MUST NOT
invoke a tool or mutate source.

### 9. Security requirements

- Evaluate path containment after symlink resolution for reads and writes.
- Refuse special files, devices, sockets, and named pipes.
- Create files without following a final-component symlink.
- Use bounded reads before decoding UTF-8.
- Reserve stdout exclusively for framed protocol messages.
- Cancel active compiler/VM work when the MCP request is cancelled.
- Enforce concurrency limits and serialize workspace mutations.
- Never invoke a shell.
- Do not inherit program capabilities from the server process.
- Redact absolute root paths to project-relative paths in normal results.
- Treat documentation, examples, tool descriptions, and project source as
  untrusted context rather than instructions that override user consent.

### 10. SDK 0.1.3 release gate

SDK 0.1.3 is releasable only when:

1. `margeux mcp` is present in every native SDK archive and `margeux version`
   reports 0.1.3;
2. protocol initialization, listing, resources, calls, cancellation, errors,
   and shutdown pass transcript tests;
3. every tool schema and structured result is snapshot-tested;
4. traversal, symlink, stale-revision, overlapping-edit, interrupted-commit,
   oversized-input, stdout-corruption, and capability-escalation tests pass;
5. clean extracted SDKs pass end-to-end check/edit/test flows;
6. Codex, Claude Code, and one generic MCP inspector complete the same
   documented smoke flow;
7. the generated documentation corpus matches the running compiler version and
   standard-library sources;
8. an MCP client can create a small multi-file Margeux application, compile
   it, correct an intentional diagnostic, and run its tests without directly
   editing the filesystem; and
9. the server remains useful in `--read-only` mode.

An example client configuration is:

```json
{
  "mcpServers": {
    "margeux": {
      "command": "margeux",
      "args": ["mcp", "/absolute/path/to/project"]
    }
  }
}
```

## Language: LLM tasks and source edits

Authoritative source: `MARGEUX_LLM_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented foundation with Codex, OpenAI-compatible local-model,
and supervised Pi adapters plus revision-bound PostgreSQL run history and
private content-addressed agent branches; the registry-generated Pi transitive
integrity lock and live-provider evidence remain.  
**Scope:** Provider-neutral LLM requests, reproducible metadata, structured source
edit proposals, capability policy, and editor/runtime boundaries.

### 1. Design boundary

LLM inference is a host effect. It is not syntax, a macro-expansion phase, or a
privileged compiler operation. Margeux programs request inference through a
lazy Task and require the explicit `llm` application capability.

The language core MUST NOT contain provider URLs, credentials, model names, or
provider-specific response parsing. A host adapter MAY route the same request
to Codex, Qwen, Pi, or another implementation.

An inference result is a proposal. It MUST NOT write files, execute generated
code, grant capabilities, or replace application state merely because the host
returned it. Applying edits and running the resulting program are separate,
explicit operations controlled by the editor or application.

### 2. Standard module

Programs import the provider-neutral library with:

```margeux
use "std/llm"
```

The module exports these records:

```margeux
record Identity
  provider: String
  model: String

record SourceFile
  path: String
  digest: String
  content: String

record Selection
  path: String
  start: Int
  end: Int
  expected: String

record Request
  id: String
  instruction: String
  profile: String
  entry: String
  files: Vector[SourceFile]
  selection: Selection
  constraints: Vector[String]

record SourceEdit
  path: String
  start: Int
  end: Int
  expected: String
  replacement: String

record SourceCreate
  path: String
  content: String

record SourceDelete
  path: String
  expected-digest: String

record Completion
  request-id: String
  provider: String
  model: String
  input-digest: String
  output-digest: String
  finish-reason: String
  summary: String
  edits: Vector[SourceEdit]
  creates: Vector[SourceCreate]
  deletes: Vector[SourceDelete]
```

Offsets are zero-based UTF-8 byte offsets into the exact `SourceFile.content`
identified by its lowercase SHA-256 `digest`. An empty `Selection.path` means
that the request has no selected range. `expected` MUST equal the bytes in the
referenced range; it is an optimistic-concurrency precondition, not optional
context. A create names a normalized path absent from the request and contains
valid UTF-8 source. A delete names a non-entry request file and binds its exact
source digest. One path cannot be edited, created, and deleted in the same
completion.

`llm.identity []` resolves the adapter's nonempty provider/model identity
without beginning inference. `llm.request value` serializes a `Request`, invokes the host, validates and
decodes its response, and resolves to `Result[Completion, String]`. Constructing
or calling it does not begin inference; ordinary Task/`await` rules apply.

`llm.digest source` computes the required lowercase SHA-256 source digest.
`llm.apply request completion` repeats the complete validation contract and
returns `Result[Vector[SourceFile], String]` containing an immutable candidate
snapshot with refreshed digests. It is deterministic and grants no write or
execution authority.

#### 2.1 Canonical digests

Digests are lowercase hexadecimal SHA-256 values over compact UTF-8 JSON with
no insignificant whitespace. Object keys occur in the order shown by the
record declarations above; adapters MUST NOT depend on map iteration order.

Before computing `input-digest`, files are sorted by `path` and encoded with
fields `path`, `digest`, then `content`. The request fields are encoded in this
order: `id`, `instruction`, `profile`, `entry`, `files`, `selection`, and
`constraints`. Selection fields are `path`, `start`, `end`, then `expected`.
Constraint order remains significant.

Before computing `output-digest`, edits are sorted by `path`, `start`, then
`end`; edits sharing a start offset are invalid. Creates and deletes are each
sorted by `path`. Each edit uses fields `path`, `start`, `end`, `expected`, then
`replacement`; each create uses `path`, `content`; each delete uses `path`,
`expected-digest`. The completion is encoded with an empty `output-digest` and
fields in this order: `request-id`, `provider`, `model`, `input-digest`,
`output-digest`, `finish-reason`, `summary`, `edits`, `creates`, and `deletes`.
Collection fields are always JSON arrays, including when empty. The SHA-256 of
those bytes becomes the transmitted `output-digest`.

This representation is a protocol format, not merely an implementation detail:
native processes and browser adapters MUST produce the same bytes before
hashing.

### 3. Portable host protocol

The portable tasks are zero-argument `agent.identity` and one-argument
`agent.complete`. Identity resolves to a Dict containing nonempty `provider`
and `model` Strings before inference. Complete accepts one canonical JSON
String containing a `Request` and resolves to an encoded JSON completion or a
host error. Both tasks are available only to applications declaring:

```margeux
app Assistant
  capabilities [llm]
  ...
```

The adapter MUST return every `Completion` metadata field. `provider` and
`model` identify what actually served the request; `request-id` correlates it
to the input; the two digests bind normalized input and output; and
`finish-reason` distinguishes complete, length-limited, refused, cancelled, and
adapter-defined terminal results. Missing, malformed, or oversized responses
resolve to `Error String`.

No host silently chooses a model. A host MUST obtain identity before sending a
request and MUST reject a completion whose provider/model differs. Same-realm
and isolated-worker browser embedders install an adapter through
`hosts.llm.identity(context)` and `hosts.llm.complete(requestJSON, context)`;
`context.signal` is aborted when an isolated runtime is terminated. Native
commands configure a direct adapter process with
`MARGEUX_LLM_COMMAND_JSON='["adapter", "argument"]'` plus an identity through
`MARGEUX_LLM_IDENTITY_JSON` or the equivalent provider/model variables. The request is its exact
stdin, its stdout must be one completion JSON value, and Margeux never inserts
a shell. This lets a small Pi bridge act as the orchestrator without making Pi
or any provider part of Margeux semantics. Android reports the capability as
unavailable until its host supplies the same protocol.

The official Codex adapter is built as `margeux-llm-codex`. It requires an
explicit model, invokes `codex exec` noninteractively in an empty read-only
sandbox, requests schema-constrained edits, and wraps those edits with Margeux
digests and metadata. A typical native configuration is:

```sh
export MARGEUX_LLM_COMMAND_JSON='["./build/margeux-llm-codex","-model","MODEL_ID"]'
export MARGEUX_LLM_IDENTITY_JSON='{"provider":"codex","model":"MODEL_ID"}'
```

The adapter uses an empty temporary working directory and places only the
request snapshot in its prompt. Codex CLI's read-only sandbox controls any
ambient filesystem reads; this adapter does not claim a stronger read allowlist.
It rejects every edit that does not match the transmitted snapshot. Explicit
`-turn` mode instead accepts `margeux.agent-turn/1`, gives Codex one strict
root-object decision schema, and returns either one validated completion or one
policy-declared host-tool request. Unused decision fields must be null. Codex
does not execute the declared host tool: the workspace controller executes only
its policy-declared built-in host, records the exchange, and sends the audited history in
the successor turn. The ordinary mode remains backward-compatible and
tool-free. Pi and local-Qwen adapters use the same stdin/stdout contract but are
separate packages.

#### 3.1 Pi configuration import

`margeux ai import-pi` reads Pi's custom-model configuration without importing
the Pi coding-agent loop. With no selection it emits a sanitized list of
compatible `openai-completions` and `openai-responses` models. It excludes
plaintext non-loopback endpoints and never emits credential values.

An import requires `--select PROVIDER/MODEL`, a Margeux capability `--name`, and
explicit `--approve` acknowledgement of the network and source-sharing scope.
It writes project-local `.margeux/ai.json` version 1 with mode `0600`, snapshots
the provider, model, API, endpoint, limits, and exact `pi-ai` transport version,
and stores only the delegated credential record's source kind, path, provider,
and SHA-256 digest. It does not copy the credential. A later bridge invocation
MUST reject a missing or changed credential record rather than silently using
new Pi state. Reimport is explicit and replacing a named capability requires
`--replace`.

The imported configuration is not executable authority by itself. The pinned
bridge reads the referenced credential under host policy, verifies its digest,
and restricts transport configuration to the recorded endpoint. It rejects Pi
credential commands, OAuth records in bridge 0.1, changed credential records,
unknown protocol fields, plaintext non-loopback endpoints, tool calls, and
oversized messages.

The bridge package pins `@earendil-works/pi-ai` to exact version 1.2.0 and MUST
commit an npm lockfileVersion 3 graph before release. `margeux-pi-lock` verifies
the manifest and lock offline: the root dependency map must match exactly,
every direct version must be exact, every package must be a non-linked HTTPS
`registry.npmjs.org` tarball with valid SHA-512 integrity, and the report binds
the reviewed lock with SHA-256. Installation MUST use `npm ci --ignore-scripts`.

`margeux-llm-pi` is the supervising Go adapter. Its ordinary mode sends a
bounded, no-tools `margeux.pi/1` JSONL request to
`integrations/pi/bridge.mjs` and supplies no workspace path. Explicit `-turn`
mode instead uses `margeux.pi-turn/1`, transmitting only the policy-declared
tool schemas and ordered audited exchanges from a validated
`margeux.agent-turn/1` envelope. The bridge reconstructs deterministic Pi
assistant/tool-result messages and accepts at most one complete, declared tool
call or one text proposal. It never executes the tool. The Go adapter validates
the call schema and logical-run budget again before returning it to the
workspace controller.

Both modes filter the child environment to network/TLS variables plus the
single explicitly referenced credential variable. The bridge uses the exact
`@earendil-works/pi-ai` version declared by its private package. Text proposals
remain untrusted: the Go adapter parses them with the strict Margeux proposal
schema and constructs a completion only after canonical snapshot, range,
digest, and overlap validation succeeds.

When no `MARGEUX_LLM_COMMAND_JSON` identity is configured, the native host
automatically selects `.margeux/ai.json`'s default capability and launches the
Pi adapter. `MARGEUX_LLM_CAPABILITY` selects another imported name; explicit
native LLM environment configuration always takes precedence.

`margeux-llm-openai-compatible` is the local-Qwen adapter for servers exposing
a schema-capable chat-completions endpoint. Its endpoint and model are always
explicit; an optional bearer token comes only from `MARGEUX_LLM_API_KEY`:

```sh
export MARGEUX_LLM_COMMAND_JSON='["./build/margeux-llm-openai-compatible","-url","http://127.0.0.1:8000/v1/chat/completions","-model","QWEN_MODEL_ID","-provider","local-qwen"]'
export MARGEUX_LLM_IDENTITY_JSON='{"provider":"local-qwen","model":"QWEN_MODEL_ID"}'
```

Its default mode performs one non-streaming request, exposes no tools, accepts
exactly one schema-constrained choice, and passes the same Margeux validator as
the Codex adapter. Explicit `-turn` mode instead consumes a
`margeux.agent-turn/1` envelope generated by the workspace service. It sends
only the envelope's digest-bound tool definitions, reconstructs prior audited
assistant/tool messages, and accepts either one schema-valid declared tool call
or one normal source-edit proposal. Its output is a strict turn response bound
to the run, provider, and model. Plaintext HTTP is restricted to loopback hosts
and redirects are rejected. Compatibility depends on the configured server
implementing the documented OpenAI-compatible JSON-schema and tool-call fields.

#### 3.2 Live adapter conformance

`margeux-llm-conformance` tests an ordinary provider adapter through the same
stdin/stdout protocol used by the runtime. It MUST invoke an explicit argument
vector without a shell and MUST bound each call's duration, stdout, and stderr.
It MUST NOT give the adapter a workspace path or mutate a workspace.

Version 1 runs two independent cases: an exact UTF-8 byte-range replacement,
then an exact new-file creation and digest-bound non-entry deletion. Every
response MUST pass the ordinary completion validator, and its atomically
applied candidate file set MUST exactly match the case expectation. Provider
and model identity MUST remain constant across the cases and MUST match any
operator-supplied expected identity.

A passing JSON report uses protocol `margeux.llm-conformance/1` and records the
safe adapter label, observed provider/model, UTC observation time, and canonical
input, output, and candidate SHA-256 digests for each case. Command arguments,
credentials, prompts, source contents, and provider-private transport data MUST
NOT appear in the report. A report is evidence only for the exact live adapter
and model named in it; implementation tests or an installed runner do not
substitute for a live passing report.

### 4. Source-operation validation and application

Before presenting or applying a completion, the editor MUST validate all source operations
against one immutable workspace snapshot:

1. every path is a normalized relative workspace path; edit and delete paths
   appear once in the request snapshot, while create paths are absent;
2. every source digest still matches;
3. `0 <= start <= end <= byte-length(content)` and both offsets are UTF-8 code
   point boundaries;
4. `expected` exactly matches `content[start:end]`;
5. edits for one file do not overlap, operations do not conflict by path, new
   contents are valid UTF-8, and the entry file is not deleted; and
6. configured file-count, edit-count, source-size, and replacement-size limits
   are respected.

Accepted operations are applied atomically to an in-memory candidate; edits are
ordered by descending start offset within each file. The candidate MUST pass the normal
Margeux project checker before it can replace editor buffers. A failure leaves
the original workspace unchanged. Persistent saving and program execution each
require a later explicit action.

The host or editor MAY require human confirmation, restrict paths, reject
capability changes, or forbid creating/deleting files. Those are policy choices
outside the language core and MUST be visible rather than inferred from prompt
text.

### 5. Re-execution, traces, and caching

Every execution of an awaited LLM task is a new effect unless a host cache
returns a completion for the exact canonical input digest and declared policy.
There is no hidden "regenerate on render" behavior. A REPL or editor command
may explicitly execute the task again.

Runtime traces capture the normalized completion Result. Verified replay injects
that captured result and MUST NOT contact the provider again. Credentials,
provider-private reasoning, and unredacted transport logs MUST NOT enter source
artifacts or traces.

### 6. Limits for version 0.1

Version 0.1 supports UTF-8 source edits, file creation, and non-entry file
deletion. File renaming, binary edits, streaming tokens, autonomous retry
loops, and provider-specific conversation state are deliberately outside this
language contract. Section 7 defines both a host audit record and the separate,
operator-configured boundary that MAY execute a declared external tool.
Recording an exchange by itself does not grant or execute the tool.

### 7. Audited workspace runs

The PostgreSQL workspace host MAY persist an inference attempt as an agent run.
This history is host infrastructure, not a language-core effect. A run begins
against one existing committed workspace revision and stores:

- the canonical `Request` and its computed input digest;
- an explicit provider and model that a completion cannot change;
- a canonical, digest-bound host tool policy, disabled by default;
- pending, tool-checkpointed, completed, failed, cancelled, or explicitly
  applied execution state;
- pending, approved, or rejected review state; and
- append-only requested, tool, terminal, and review events.

Starting a run MUST also create a private branch rooted at the exact starting
revision. Head revision zero reads the immutable base snapshot. A successful
completion MUST apply its edits to that snapshot, pass the normal project
checker, and atomically store the complete candidate as immutable branch
revision one with a canonical SHA-256 digest. It MUST NOT mutate the workspace
head. Failed and cancelled runs discard their branch; rejecting a completed
proposal also discards it.

The branch transaction for a successful complete response MUST also append a
model checkpoint containing the completion digest and resulting private branch
revision. Checkpoints are immutable and append-only. A failed, cancelled,
invalid, or partial provider response creates no checkpoint.

The optional host tool policy declares at most 64 uniquely named tools. Each
definition contains a bounded description, a canonical JSON input-schema
object, and an explicit `read`, `write`, or `execute` effect class. It also
sets cumulative logical-run call, argument-byte, and result-byte limits. The
policy is normalized, hashed, stored with the initial segment, copied exactly
to every successor, and protected with the rest of the immutable run identity.
An undeclared tool, schema-invalid call, or exhausted budget cannot become a
tool record. The schema dialect is deliberately bounded and rejects unsupported
keywords rather than pretending to enforce them. It covers objects, arrays,
scalar types, required and additional properties, enums, character/item limits,
and exact numeric bounds. Policy remains audit and negotiation metadata, not
execution authority: every tool host MUST separately enforce the effect before
performing it.

An external tool host is optional and disabled when the operator supplies no
bindings. Each binding MUST independently allowlist one exact tool name, effect
class, absolute executable argument vector, optional environment-variable names,
and bounded timeout. It MUST invoke the executable directly without a shell.
The child environment MUST be empty except for variables explicitly named by
the binding. A built-in workspace tool cannot be shadowed by an external binding.

The command receives one `margeux.agent-tool/1` JSON object on standard input.
It contains only the workspace, logical-run, segment, and call identities; the
tool name and effect; the pinned policy digest; canonical arguments and their
digest; a remaining result-byte limit; and a stable SHA-256 idempotency key. It
MUST NOT receive request source, instructions, provider history, or credentials
from the workspace controller. The command returns exactly one object with the
same protocol, segment, call, and tool identities, one JSON result, and an
`isError` flag. Unknown fields, trailing values, invalid UTF-8, oversized output,
identity changes, timeouts, and nonzero exits MUST fail the invocation without
creating a tool checkpoint.

Before invoking an external host, the controller MUST validate the pinned
definition, schema, effect, unused call identity, and remaining cumulative
budgets. After invocation, it MUST canonicalize and bound the result before
atomically recording it. A process can complete an external side effect and
fail before the database checkpoint commits, so the controller cannot promise
exactly-once execution. Every `write` or `execute` host MUST durably deduplicate
the supplied idempotency key before performing its side effect and return the
same result for a replay. Operator bindings are deployment authority and MUST
be protected like credentials.

Tools are disabled by default. A run MAY select the built-in `coding` profile
with `toolProfile: "coding"` instead of supplying an explicit policy; the two
forms cannot be combined. The profile expands before persistence into the same
canonical, digest-bound policy as any explicitly supplied policy. It grants:

- `source.list` and `source.read` over only the immutable request snapshot;
- `source.working.list` and `source.working.read` over an in-memory working copy;
- `source.patch`, which applies bounded UTF-8 byte edits with exact expected-text
  preconditions to that working copy;
- `source.create` and `source.delete`, which stage a new UTF-8 file or remove a
  non-entry file using its exact current working digest;
- `project.check`, which returns ordinary project diagnostics for that copy; and
- `project.run`, which executes GUI, TUI, CLI, or one synthetic server request
  in the bounded VM. Server execution defaults to `GET /` or accepts explicit
  method, path, query, String headers, and body fields.

The working copy is reconstructed deterministically from the immutable request
and successful source mutation records in the logical-run history. A failed
mutation is recorded as an error and is not replayed. It never writes the workspace
draft, database branch, or host filesystem. `project.run` denies every ambient
host capability and uses fixed instruction and call-depth limits. None of these
tools can observe another revision,
credential, process, or network resource. The host schema-validates arguments
before execution and transactionally records the bounded result afterward.

A failed or cancelled segment MAY resume from checkpoint zero, the committed
starting snapshot. A pending segment MAY instead be closed by atomically
recording one externally completed tool exchange and one matching tool
checkpoint. Tool names and call identifiers are bounded tokens; arguments and
results are bounded canonical JSON values with independent SHA-256 digests.
The checkpoint digest binds the call identifier, name, both payload digests,
and error flag. Tool records and checkpoints are append-only, and the segment's
empty private branch is discarded. This service records an observed exchange;
it neither invokes the tool nor claims transactional control over an external
side effect.

Either boundary can create one linked immutable successor segment in the same
logical run. Post-tool resume names the exact parent checkpoint. The host copies
the provider, model, instruction, profile, selection, constraints, files,
entry, and starting revision; the caller supplies only new run and request
identifiers. A segment can have at most one successor. Consequently resume
cannot switch models, alter source context, fork the history, replay a tool
record, or widen authority.

The request's entry path, file set, paths, and contents MUST exactly equal the
selected committed revision. A completion passes the validation in section 4
before the run can become completed. If the logical run contains a successful
source mutation, the completion MUST reproduce every file in the reconstructed
working copy exactly; both automatic orchestration and the manual HTTP
completion boundary enforce this invariant. Completion and review are separate state
transitions, and approval does not itself modify or execute the workspace. A
separate apply transition revalidates the stored completion, verifies it still
identifies the exact stored branch digest and files, and refuses the operation
if the current revision, entry, file set, or source differs from the starting
snapshot. On success it atomically commits that branch candidate as the next
workspace revision, marks the branch merged, and records the revision on both
the branch and run.
Database constraints bind runs to real revisions and reject inconsistent
terminal/review states; a database trigger rejects event updates and deletes.

The workspace HTTP boundary exposes the lifecycle beneath
`/api/workspaces/{workspace}/agent-runs`: creation and listing at the collection,
detail at `/{run}`, the effective private snapshot at `/{run}/branch`,
the provider-ready policy/history envelope at `/{run}/turn`,
completion at `/{run}/completion`, review at
`/{run}/review`, transactional completed-tool recording at `/{run}/tool`, base
or tool-checkpoint resumption at `/{run}/resume`, schema-enforced snapshot tool
execution at `/{run}/execute-tool`, bounded configured orchestration at
`/{run}/advance`, and explicit application at `/{run}/apply`.
Hosts without an
`AgentStore` do not gain this authority and return `501 Not Implemented`.

A Qwen tool round trip is explicit: fetch the authoritative turn, invoke the
OpenAI-compatible adapter in `-turn` mode, and strictly decode its response. A
tool-call response is sent to `/{run}/execute-tool` for the built-in host
or to `/{run}/tool` after an external policy host completes it, then the
checkpointed run is resumed and its successor turn is fetched. A completion
response goes to `/{run}/completion`. Each HTTP transition independently
revalidates the stored run, so a stale turn cannot mutate a terminal segment.

The workspace server MAY expose that same sequence as `POST .../{run}/advance`
when an operator configures a dedicated turn-protocol adapter command. The
controller obtains every turn from authoritative storage, validates every
adapter response against that turn, executes only policy-declared built-in
snapshot/working-copy tools, atomically checkpoints each completed exchange,
resumes one successor, and stops at the policy call bound plus one completion
turn. It MUST record provider, protocol, and validation failures as terminal
failures. It MUST NOT review, apply, mutate the persisted workspace, or grant
ambient capabilities. The command is an
explicit argument vector invoked without a shell; output sizes and duration
are bounded. The endpoint is unavailable when no turn adapter is configured.

The Margeux-written Studio first awaits `llm.identity`, commits its exact
request snapshot, and creates a provider/model-pinned pending run before it
awaits inference. It then uses the ordinary version 1.28 `http.request` task to
record the validated completion, approval/rejection, and explicit application.
The integration contract asserts this host-task order. Draft mutation controls
are locked during review. Studio displays the current and candidate snapshots
side by side with Margeux syntax highlighting and marks the exact validated edit
ranges after converting UTF-8 protocol offsets to editor UTF-16 positions. If
the audit service is unavailable, the validated
candidate remains visible as a clearly labelled local-only proposal; identity
or inference failure does not fabricate an audited run.

This initial history stores full request source, instructions, completion
summaries, edits, and failure reasons in PostgreSQL. Operators therefore MUST
treat the database as source-code-sensitive storage. Credentials,
provider-private reasoning, bearer tokens, and raw provider transport logs are
never accepted by this schema.

Retained histories remain append-only, but retention is explicitly finite and
operator-controlled. `margeux-retention -before TIMESTAMP -confirm` invokes one
database transaction that selects complete logical runs whose every segment is
terminal and whose newest segment predates the UTC cutoff. It removes all
segments, events, checkpoints, tool records, and private branch contents for
each selected logical run. It never removes a pending/partial logical run or a
committed workspace revision. Purging is permanent, returns logical-run and
segment counts, and is unavailable through the workspace HTTP API. The private
security-definer database procedure is the only supported bypass for retained
history's deletion triggers; deployments using separate migration and service
roles MUST grant only procedure execution to the retention operator.

The schema intentionally does not implement application-level column
encryption, because a workspace server must compile and review the stored source.
Production deployments MUST use encrypted database volumes and encrypted,
access-controlled backups, MUST use TLS for non-loopback database connections,
and SHOULD use a dedicated least-privilege database role. Retention remains the
mechanism for cryptographic-erasure-compatible removal from primary storage;
backup expiry must be no longer than the documented organizational retention
window. Pi session import remains a future layer.

## Language: Portable application releases

Authoritative source: `MARGEUX_RELEASE_0_1_SPEC.md`. Classification: **normative**.

**Status:** Implemented portable release directory

### 1. Purpose

A release packages one validated Margeux application artifact with enough
canonical metadata to verify its identity before execution or browser loading.
It is not a source package, registry publication, installer, or signature.

### 2. Directory format

A version 1 release directory contains:

```text
margeux-release.json
application.mgxc
```

The manifest is UTF-8 JSON ending in one newline. It contains only these
fields:

- `protocol`, exactly `margeux.release/1`;
- `application` and `surface`, copied from validated bytecode metadata;
- the sorted `capabilities` declared by the application;
- `bytecode`, the artifact's major/minor version;
- `artifact`, exactly `application.mgxc`;
- `artifactSha256`, the lowercase SHA-256 of the complete artifact;
- `artifactBytes`, its exact byte length; and
- `sourceMode`, either `embedded` or `stripped`.

The `.mgxc` checksum still protects its internal payload. The manifest digest
additionally binds the complete container and its release identity.

### 3. Creation

```sh
margeux release create main.mgx -o application.release
margeux release create main.mgx -o closed.release --strip-source
```

Creation compiles the complete locked module graph through the ordinary
compiler. `--strip-source` removes the bytecode source table but does not alter
application behavior, linked functions, or capability declarations. Without
it, the exact immutable compilation snapshot remains inspectable.

The output is reproducible for identical compiler, input workspace, lock, and
option values. Creation writes an adjacent temporary directory and renames it
only after both files succeed. It never replaces an existing destination.

### 4. Verification and execution

`margeux release verify DIRECTORY` strictly decodes the manifest, checks its
required protocol and fixed artifact path, verifies byte length and SHA-256,
validates the bytecode container, and reconstructs the expected manifest from
decoded application metadata. Unknown manifest fields or any disagreement are
errors.

`margeux exec DIRECTORY -- ARG...` executes a verified GUI, TUI, or CLI
release. `margeux serve DIRECTORY` accepts a verified server release. The
release directory becomes the native capability root. Verification occurs
before any application code or host effect runs.

### 5. Browser loading

The embedding API provides `runtime.loadRelease(url, options)`. It fetches
`margeux-release.json` and `application.mgxc`, bounds the declared artifact to
64 MiB, verifies its exact size and SHA-256 with Web Crypto, and asks the
canonical Wasm VM to decode and inspect the artifact without constructing a
session or executing application code. The loader reconstructs and compares
the application name, surface, capabilities, bytecode version, and source mode
before using the normal artifact-loading path. Unknown manifest fields,
unsorted or duplicate capabilities, and any metadata disagreement are errors.
Normal browser origin and CORS rules apply. Loading does not grant capabilities
beyond the hosts explicitly supplied when the runtime was created.

### 6. Trust boundary

Version 1 is deliberately unsigned. A digest detects corruption and mismatch;
it does not identify a publisher. Distribution systems requiring authenticity
must authenticate the transport or directory independently. A future signing
layer may sign the canonical manifest without changing `.mgxc` semantics.

## Language: Version 0.1 stabilization policy

Authoritative source: `V0_1_STABILIZATION_POLICY.md`. Classification: **policy**.

Margeux 0.1 is feature-frozen while the release gates in
[`MAIN_CONCERNS_IMPLEMENTATION_PLAN.md`](MAIN_CONCERNS_IMPLEMENTATION_PLAN.md)
remain open.

Until those gates pass, changes may:

- fix a documented semantic, compatibility, diagnostic, security, usability,
  or performance defect;
- complete an already specified 0.1 contract;
- simplify internals without changing observable semantics; or
- improve tests, examples, documentation, packaging, and renderer adapters.

Changes must not add a new keyword, syntax family, bytecode operation,
application surface, capability, host-task family, or standard-library domain
merely as feature expansion. Such proposals belong after stabilization. A true
compatibility hole may be fixed only with its normative specification,
bytecode/version decision, native and browser implementation, differential
tests, examples, and release-gate coverage in the same change.

“Implemented” is not “release-ready.” Margeux 0.1 requires the green full
suite, example matrix, canonical-runtime conformance, current three-engine
browser matrix, and performance regression gates listed in
[`SUPPORTED_HOST_CONTRACTS.md`](SUPPORTED_HOST_CONTRACTS.md).

## Language: Type-system boundaries

Authoritative source: `TYPE_SYSTEM_BOUNDARIES.md`. Classification: **normative**.

Margeux infers types for ordinary code and accepts explicit annotations when a
public contract should be visible. The useful rule is: **if the compiler knows
both sides of a boundary, it rejects a mismatch before execution; if the
program deliberately crosses `Any`, artifact, or host data, the VM validates
the value at the point where a concrete operation needs it.**

### What is checked when

| Construct | Compile time | Runtime |
| --- | --- | --- |
| Literals, arithmetic, comparisons, and ordinary calls | Operand types, arity, inferred arguments, and annotated results | Overflow, division by zero, bounds, and other value-dependent failures |
| Annotated functions | Every statically known call and the function body | Calls through dynamic function values validate arity and concrete boundaries |
| Records | Required, duplicate, unknown, and typed fields; field access; immutable `with` updates | Dynamically obtained record values retain and validate their nominal identity |
| Variants and `Result` | Constructor payloads, branch bindings, compatible branch results, and exhaustiveness for known closed variants | A dynamically obtained variant is checked before a concrete payload is unboxed |
| `Vector[T]` and `Dict[T]` | Element/value consistency and generic substitutions | Indices, missing values, and values entering through dynamic data are checked |
| Generic functions | Type parameters are inferred and substituted independently at each call | Free generic parameters are erased to `Any` only at the portable artifact boundary |
| Explicit `Any` | The boundary itself is accepted; known concrete values are tagged when crossing it | A later concrete operation checks the tag and reports the operation and source location on mismatch |
| Host tasks (`http`, database, storage, process, and similar modules) | Capability, operation name, arity, and statically known request types | The host response is bounded and validated before it re-enters Margeux code |
| Loaded bytecode | Version, opcode, register, constant, signature, and application metadata validation | Value-dependent checks still apply while instructions execute |

`Any` is never inferred merely to hide a type error. It appears when source code
declares it, when a heterogeneous or empty collection has no more precise safe
element type, or when a generic value must cross an erased external boundary.
Diagnostics name these values explicitly, such as `Vector[Any]`.

### Ordinary code

[`examples/type-boundaries.mgx`](examples/type-boundaries.mgx) is executable and
shows the intended path: inferred local values, an explicit public function,
one generic helper, a nominal record, a checked conversion returning `Result`,
and a deliberately explicit `Any` display boundary.

```sh
go run ./cmd/margeux check examples/type-boundaries.mgx
go run ./cmd/margeux run examples/type-boundaries.mgx
```

### Static rejection

This is rejected before bytecode executes because both types are known:

```margeux
def doubled [value: Int] -> Int
  * value 2

doubled "forty-two"
```

The diagnostic identifies the argument, the expected `Int`, the received
`String`, and the declaration that established the contract.

Record fields and collection elements follow the same rule. `Dict[Int]` cannot
silently accept a `String`, and an `if` whose branches are `Vector[Int]` and
`Vector[String]` cannot silently become `Vector[Any]`.

### Deliberate runtime checks

An explicit dynamic boundary can postpone a check:

```margeux
def add-one [value: Any] -> Number
  + value 1

add-one "not a number"
```

The definition is allowed because `Any` was requested. Execution fails at `+`
with its original source location because the tagged value is a `String`, not a
`Number`. Use a checked conversion such as `int.try` or decode external data
into a record/variant before ordinary domain logic when failure is expected.

Host results and loaded artifacts use the same principle: validate once at the
boundary, then keep the rest of the program precise.

### Related contracts

- [`MARGEUX_0_1_SPEC.md`](MARGEUX_0_1_SPEC.md) defines the normative language rules.
- [`MARGEUX_NUMERIC_0_1_SPEC.md`](MARGEUX_NUMERIC_0_1_SPEC.md) defines promotion, overflow, division, and conversion.
- [`MARGEUX_TYPE_DIAGNOSTICS_0_1.md`](MARGEUX_TYPE_DIAGNOSTICS_0_1.md) indexes the automated diagnostic evidence.
- [`MARGEUX_RUNTIME_0_1_SPEC.md`](MARGEUX_RUNTIME_0_1_SPEC.md) defines bytecode and host validation.

## Language: Type diagnostics and automated evidence

Authoritative source: `MARGEUX_TYPE_DIAGNOSTICS_0_1.md`. Classification: **evidence**.

This file records the automated evidence for section 4 of the 0.1 completion
checklist. It is an index, not a second specification. Normative inference rules
live in `MARGEUX_0_1_SPEC.md`; numeric rules live in
`MARGEUX_NUMERIC_0_1_SPEC.md`.

### Type contracts

- Inference boundaries and explicit gradual boundaries:
  `internal/phase0/semantic_check_test.go`, including inferred function chains,
  inferred parameter constraints, dynamic collection boundary rejection, and
  explicit `Any` acceptance.
- Functions, records, variants, results, collections, generics, and modules:
  `internal/phase0/semantic_check_test.go`,
  `internal/phase0/generic_types_test.go`,
  `internal/phase0/function_type_test.go`, and
  `internal/compiler/compiler_test.go`.
- Application lifecycle compatibility: `internal/phase0/init_test.go` and
  `internal/phase0/event_handlers_test.go`, plus
  `TestApplicationLifecycleKeepsOneNominalModelType`.
- Numeric promotion, overflow, division, comparison, and conversion:
  `MARGEUX_NUMERIC_0_1_SPEC.md`, `internal/phase0/numbers_test.go`,
  `internal/phase0/math_test.go`, and native/Wasm differential tests under
  `internal/appvm` and `internal/directwasm`.

An internally erased mixed or empty collection is named `Vector[Any]` or
`Dict[Any]` in diagnostics. It cannot cross a concrete collection boundary.
Only an explicit `Any` (or documented bare `Vector`/`Dict` shorthand) declares a
gradual API boundary.

### Diagnostic contracts

- `Diagnostic` carries a primary span, optional secondary spans, and exact edit
  fixes. Function argument and return mismatches identify the use as primary and
  the declaring function as secondary. Macro arity errors identify both call and
  definition.
- Type and arity diagnostics include expected and received values; tests live in
  `internal/phase0/semantic_check_test.go`.
- Conservative spelling fixes are tested in
  `internal/phase0/suggestions_test.go`; module import edits are tested in
  `internal/language/module_diagnostics_test.go`; indentation and parser fixes
  are tested in `internal/phase0/parser_test.go`.
- Macro and interpolation source mapping is tested in
  `internal/phase0/macro_test.go` and `internal/phase0/interpolation_test.go`.
- Exact UTF-8 byte offsets, Unicode columns, original CRLF offsets, malformed
  indentation recovery, and scanner recovery are tested in
  `internal/phase0/parser_test.go`.

### Verification

Run:

```sh
GOCACHE=/tmp/margeux-go-cache go test ./internal/phase0 ./internal/language ./internal/compiler ./internal/appvm ./internal/directwasm
```

The repository-wide test command remains:

```sh
GOCACHE=/tmp/margeux-go-cache go test ./...
```

## Language: Supported host contracts

Authoritative source: `SUPPORTED_HOST_CONTRACTS.md`. Classification: **normative**.

**Status:** implemented support matrix for bytecode 1.64  
**Runtime:** the canonical Go register VM, native or compiled to WebAssembly

This table defines what “supported” means for 0.1. A host changes adapters and
rendering, not language semantics. Source and `.mgxc` artifacts pass through
the same compiler/validator, instruction limits, immutable application state,
and capability checks.

### Execution surfaces

| Surface | Native host | Browser Go/Wasm host | Observable contract |
| --- | --- | --- | --- |
| Program/value | `margeux run` | embedding `compile`/`loadArtifact` response | Execute validated bytecode and return the public Margeux value or source-mapped error. |
| GUI | `margeux gui` with the native Tk View adapter | declarative View hydrated to DOM/canvas by the host | Pure `view`, immutable model transitions, serialized event dispatch, and explicit pending commands. |
| TUI | terminal input and terminal-cell output | declarative Terminal snapshot rendered by the host | Fixed terminal dimensions, normalized key/pointer events, pane focus, and the same update/view state machine. |
| CLI | native CLI application execution | embedding compile/load with launch arguments | Invoke `cli main` once and validate `cli.Response` (`stdout`, `stderr`, and exit code). |
| Server | `margeux serve` owns the HTTP listener | embedding `serverRequest` accepts a synthetic request | Invoke the same server main function and validate `server.Response`; only native serving owns sockets and streaming flushes. |
| Static render | `margeux render` serializes a GUI/TUI snapshot | host-defined serialization of the returned snapshot | Rendering does not rerun application code or grant capabilities. |

The browser API deliberately returns View and Terminal values independently of
the shipped DOM renderer. An embedder may use the standard renderer or another
adapter while preserving the event contract. Browser server sessions model
requests but do not open listening sockets.

### Capabilities

Every effect requires both an application declaration and an available host.
Omitting either produces a bounded `Error`; there is no ambient authority.

| Declaration | Task family | Native implementation | Browser implementation |
| --- | --- | --- | --- |
| `http` | `http.*` | bounded native HTTP client | realm Fetch, subject to origin/CORS policy |
| `files` | `fs.*` | paths confined to the application capability root | explicit `files` adapter (`margeuxFileSystem`) |
| `workspace` | `project.*` | isolated in-memory Margeux source workspace | isolated in-memory Margeux source workspace |
| `storage` | `store.*` | application-namespaced persistent storage | explicit `storage` adapter (`margeuxStorage`) |
| `database` | `db.*` | configured PostgreSQL pool with shared validation | authenticated server-side proxy adapter; PostgreSQL credentials never enter browser code |
| `time` | `clock.*` | native clock and bounded sleep | explicit `clock` adapter |
| `process` | `proc.*` | bounded child-process host | explicit `process` adapter; never implicit browser execution |
| `cli` | `argv.*` | copied launch arguments after `--` | copied embedding launch arguments |
| `llm` | `agent.*` | configured provider-neutral adapter | explicit `llm` adapter with request/completion validation |

Host results are validated before typed Margeux code consumes them. Invalid
dynamic data fails at its concrete operation with the Margeux source location;
malformed artifacts fail validation before execution.

### Explicit exclusions

- The source evaluator is a test oracle, not a public runtime.
- The frozen direct-Wasm experiment is not a supported execution target.
- Native GUI and browser DOM/canvas are renderer adapters, not separate VMs.
- Browser database and process support require explicit trusted adapters.
- The embedding API is not by itself a hostile-code sandbox; use a worker plus
  resource and capability policy for untrusted programs.

### Release evidence

Support claims require all of these gates for the exact bytecode/runtime build:

```sh
make test
make runtime-conformance
make example-matrix
make benchmark-smoke
make browser-compat
make browser-compat-check
```

The application benchmark report and cross-language kernel report remain
separate. Kernel results are not whole-application, renderer, startup, or
browser-performance claims.

## Library: Standard library reference


Generated from the bundled standard-module declarations. Do not edit by hand.

### Modules

- [`std/arrangement`](#stdarrangement)
- [`std/animation`](#stdanimation)
- [`std/archive`](#stdarchive)
- [`std/audio`](#stdaudio)
- [`std/cli`](#stdcli)
- [`std/control`](#stdcontrol)
- [`std/database`](#stddatabase)
- [`std/dicts`](#stddicts)
- [`std/fonts`](#stdfonts)
- [`std/grid`](#stdgrid)
- [`std/infix`](#stdinfix)
- [`std/instrument`](#stdinstrument)
- [`std/input`](#stdinput)
- [`std/llm`](#stdllm)
- [`std/markup`](#stdmarkup)
- [`std/math`](#stdmath)
- [`std/music_catalog`](#stdmusic_catalog)
- [`std/music_builder`](#stdmusic_builder)
- [`std/music_export`](#stdmusic_export)
- [`std/music_finder`](#stdmusic_finder)
- [`std/music_program`](#stdmusic_program)
- [`std/music_progressions`](#stdmusic_progressions)
- [`std/music_practice`](#stdmusic_practice)
- [`std/music_theory`](#stdmusic_theory)
- [`std/process`](#stdprocess)
- [`std/random`](#stdrandom)
- [`std/ray3d`](#stdray3d)
- [`std/results`](#stdresults)
- [`std/server`](#stdserver)
- [`std/sort`](#stdsort)
- [`std/source`](#stdsource)
- [`std/storage`](#stdstorage)
- [`std/strings`](#stdstrings)
- [`std/testing`](#stdtesting)
- [`std/time`](#stdtime)
- [`std/tui`](#stdtui)
- [`std/ui`](#stdui)
- [`std/vec3`](#stdvec3)
- [`std/vectors`](#stdvectors)
- [`std/workspace`](#stdworkspace)

## Library: `std/arrangement`

```margeux
use "std/arrangement"
```

### Quick example

```margeux
use "std/arrangement"

def move-first-track-to-end [tracks]
  arrangement.swap-at tracks 0 (- (length tracks) 1)
```

### `compact-grid`

function

```margeux
def compact-grid [count: Int capacity: Int] -> Vector[Int]
```

### `copy-range`

function

```margeux
def copy-range [T] [values: Vector[T] start: Int copy-count: Int fallback: T] -> Vector[T]
```

### `expanded-length`

function

```margeux
def expanded-length [active-length: Int capacity: Int] -> Int
```

### `grid-cell-for-item`

function

```margeux
def grid-cell-for-item [grid: Vector[Int] item: Int] -> Int
```

### `grid-item-at`

function

```margeux
def grid-item-at [grid: Vector[Int] cell: Int] -> Int
```

### `insert-copy-after`

function

```margeux
def insert-copy-after [T] [values: Vector[T] target: Int active-length: Int] -> Vector[T]
```

### `last-occupied-cell`

function

```margeux
def last-occupied-cell [grid: Vector[Int]] -> Int
```

### `paste-at`

function

```margeux
def paste-at [T] [values: Vector[T] copied: Vector[T] insertion: Int copy-count: Int active-length: Int] -> Vector[T]
```

### `remove-range`

function

```margeux
def remove-range [T] [values: Vector[T] start: Int removal-count: Int active-length: Int fallback: T] -> Vector[T]
```

### `repeat-active`

function

```margeux
def repeat-active [T] [values: Vector[T] active-length: Int] -> Vector[T]
```

### `replace-at`

function

```margeux
def replace-at [T] [values: Vector[T] target: Int replacement: T] -> Vector[T]
```

### `swap-at`

function

```margeux
def swap-at [T] [values: Vector[T] first: Int second: Int] -> Vector[T]
```

## Library: `std/animation`

```margeux
use "std/animation"
```

### Quick example

```margeux
use "std/animation"

def panel-x [progress]
  animation.lerp 0 320 (animation.ease-in-out progress)
```

### `FixedStep`

record

```margeux
record FixedStep
  count: Int
  remainder: Float
  dropped: Int
```

### `advance`

function

```margeux
def advance [elapsed: Number delta: Number rate: Number] -> Float
```

### `approach`

function

```margeux
def approach [current: Number target: Number speed: Number delta: Number] -> Float
```

### `damp`

function

```margeux
def damp [current: Number target: Number response: Number delta: Number] -> Float
```

### `ease-in`

function

```margeux
def ease-in [amount: Number] -> Float
```

### `ease-in-out`

function

```margeux
def ease-in-out [amount: Number] -> Float
```

### `ease-out`

function

```margeux
def ease-out [amount: Number] -> Float
```

### `fixed-step`

function

```margeux
def fixed-step [accumulator: Number delta: Number step: Number max-steps: Int] -> Result
```

### `fixed-step-unchecked`

function

```margeux
def fixed-step-unchecked [accumulator: Number delta: Number step: Number max-steps: Int] -> FixedStep
```

### `lerp`

function

```margeux
def lerp [start: Number end: Number amount: Number] -> Float
```

### `loop-progress`

function

```margeux
def loop-progress [elapsed: Number duration: Number] -> Float
```

### `ping-pong-progress`

function

```margeux
def ping-pong-progress [elapsed: Number duration: Number] -> Float
```

### `progress`

function

```margeux
def progress [elapsed: Number duration: Number] -> Float
```

### `smoothstep`

function

```margeux
def smoothstep [amount: Number] -> Float
```

## Library: `std/archive`

```margeux
use "std/archive"
```

### Quick example

```margeux
use "std/archive"

def files-in-zip [encoded]
  archive.zip-entries encoded
```

### `epub-book`

function

```margeux
def epub-book [encoded: String] -> Result[Dict, String]
```

### `zip-entries`

function

```margeux
def zip-entries [encoded: String] -> Result[Vector, String]
```

## Library: `std/audio`

```margeux
use "std/audio"
```

### Quick example

```margeux
use "std/audio"

def lead-synth []
  audio.synth (audio.patch "saw" (audio.envelope 0.01 0.2 0.7 0.4) (audio.low-pass 4200 0.15) (audio.lfo "sine" 5 0.08 "pitch") 2 7 0.03 "poly")
```

### `AudioSource`

record

```margeux
record AudioSource
  kind: String
  sample: String
  patch: SynthPatch
```

### `Envelope`

record

```margeux
record Envelope
  attack: Float
  decay: Float
  sustain: Float
  release: Float
```

### `Filter`

record

```margeux
record Filter
  cutoff: Float
  resonance: Float
```

### `LFO`

record

```margeux
record LFO
  waveform: String
  rate: Float
  depth: Float
  target: String
```

### `SynthPatch`

record

```margeux
record SynthPatch
  oscillator: String
  envelope: Envelope
  filter: Filter
  lfo: LFO
  voices: Int
  detune: Float
  glide: Float
  mode: String
```

### `default-patch`

function

```margeux
def default-patch [] -> SynthPatch
```

### `envelope`

function

```margeux
def envelope [attack: Number decay: Number sustain: Number release: Number] -> Envelope
```

### `lfo`

function

```margeux
def lfo [waveform: String rate: Number depth: Number target: String] -> LFO
```

### `low-pass`

function

```margeux
def low-pass [cutoff: Number resonance: Number] -> Filter
```

### `patch`

function

```margeux
def patch [oscillator: String envelope-value: Envelope filter-value: Filter lfo-value: LFO voices: Int detune: Number glide: Number mode: String] -> SynthPatch
```

### `sample`

function

```margeux
def sample [name: String] -> AudioSource
```

### `source`

function

```margeux
def source [kind: String sample-name: String patch-value: SynthPatch] -> AudioSource
```

### `synth`

function

```margeux
def synth [patch-value: SynthPatch] -> AudioSource
```

## Library: `std/cli`

```margeux
use "std/cli"
```

### Quick example

```margeux
use "std/cli"

def options []
  vector
    cli.option "output" "o" "report.txt" "Output file"
    cli.flag "verbose" "v" "Show progress"

def parse-command [arguments]
  cli.parse arguments (call options)
```

### `Option`

record

```margeux
record Option
  name: String
  short: String
  takes-value: Bool
  required: Bool
  default: String
  help: String
```

### `Parsed`

record

```margeux
record Parsed
  command: String
  positionals: Vector[String]
  values: Dict
  seen: Vector[String]
```

### `Response`

record

```margeux
record Response
  stdout: String
  stderr: String
  exit-code: Int
```

### `arguments`

async function

```margeux
async def arguments [] -> Result[Vector[String], String]
```

### `failure`

function

```margeux
def failure [stderr: String exit-code: Int] -> Response
```

### `flag`

function

```margeux
def flag [name: String short: String help: String] -> Option
```

### `flag?`

function

```margeux
def flag? [parsed: Parsed name: String] -> Bool
```

### `help-option`

function

```margeux
def help-option [] -> Option
```

### `option`

function

```margeux
def option [name: String short: String default: String help: String] -> Option
```

### `parse`

function

```margeux
def parse [args: Vector[String] specs: Vector[Option]] -> Result[Parsed, String]
```

### `parse-failure`

function

```margeux
def parse-failure [problem: String] -> Response
```

### `required-option`

function

```margeux
def required-option [name: String short: String help: String] -> Option
```

### `response`

function

```margeux
def response [stdout: String stderr: String exit-code: Int] -> Response
```

### `success`

function

```margeux
def success [stdout: String] -> Response
```

### `usage`

function

```margeux
def usage [program: String summary: String specs: Vector[Option]] -> String
```

### `value`

function

```margeux
def value [parsed: Parsed name: String] -> String
```

## Library: `std/control`

```margeux
use "std/control"
```

### Quick example

```margeux
use syntax "std/control"
  cond

def temperature-label [value]
  cond
    case (< value 0)
      "freezing"
    case (< value 30)
      "comfortable"
    otherwise
      "hot"
```

### `cond`

macro

```margeux
macro cond [body: Syntax] -> Syntax
```

### `unless`

macro

```margeux
macro unless
```

### `when`

macro

```margeux
macro when
```

## Library: `std/database`

```margeux
use "std/database"
```

### Quick example

```margeux
use "std/database"

async def recent-posts []
  await database.query
    "select title from posts order by published_at desc limit $1"
    [10]
```

### `OptionalRow`

record

```margeux
record OptionalRow
  found?: Bool
  row: Dict
```

### `QueryResult`

record

```margeux
record QueryResult
  columns: Vector[String]
  rows: Vector[Dict]
  affected: Int
```

### `execute`

async function

```margeux
async def execute [sql: String parameters: Vector] -> Result[QueryResult, String]
```

### `execute-one`

async function

```margeux
async def execute-one [sql: String parameters: Vector] -> Result[QueryResult, String]
```

### `execute-one-prepared`

async function

```margeux
async def execute-one-prepared [sql: String parameters: Vector] -> Result[QueryResult, String]
```

### `execute-prepared`

async function

```margeux
async def execute-prepared [sql: String parameters: Vector] -> Result[QueryResult, String]
```

### `execute-statement`

function

```margeux
def execute-statement [sql: String parameters: Vector] -> Dict
```

### `expect-affected`

function

```margeux
def expect-affected [result: QueryResult expected: Int] -> Result[QueryResult, String]
```

### `migrate`

async function

```margeux
async def migrate [migrations: Vector[Dict]] -> Result[Vector[Int], String]
```

### `migration`

function

```margeux
def migration [version: Int name: String statements: Vector[String]] -> Dict
```

### `one-row`

function

```margeux
def one-row [result: QueryResult] -> Result[Dict, String]
```

### `optional-row`

function

```margeux
def optional-row [result: QueryResult] -> Result[OptionalRow, String]
```

### `query`

async function

```margeux
async def query [sql: String parameters: Vector] -> Result[QueryResult, String]
```

### `query-one`

async function

```margeux
async def query-one [sql: String parameters: Vector] -> Result[Dict, String]
```

### `query-one-prepared`

async function

```margeux
async def query-one-prepared [sql: String parameters: Vector] -> Result[Dict, String]
```

### `query-optional`

async function

```margeux
async def query-optional [sql: String parameters: Vector] -> Result[OptionalRow, String]
```

### `query-optional-prepared`

async function

```margeux
async def query-optional-prepared [sql: String parameters: Vector] -> Result[OptionalRow, String]
```

### `query-prepared`

async function

```margeux
async def query-prepared [sql: String parameters: Vector] -> Result[QueryResult, String]
```

### `query-statement`

function

```margeux
def query-statement [sql: String parameters: Vector] -> Dict
```

### `statement`

function

```margeux
def statement [kind: String sql: String parameters: Vector] -> Dict
```

### `transaction`

async function

```margeux
async def transaction [statements: Vector[Dict]] -> Result[Vector[QueryResult], String]
```

## Library: `std/dicts`

```margeux
use "std/dicts"
```

### Quick example

```margeux
use "std/dicts"

def merged-settings [defaults saved]
  dicts.merge defaults saved
```

### `Entry`

record

```margeux
record Entry [T]
  key: String
  value: T
```

### `at`

function

```margeux
def at [T] [value: Dict[T] key: String] -> Result[T, String]
```

### `contains-key?`

function

```margeux
def contains-key? [value: Dict key: String] -> Bool
```

### `entries`

function

```margeux
def entries [T] [value: Dict[T]] -> Vector[Entry[T]]
```

### `get-or`

function

```margeux
def get-or [T] [value: Dict[T] key: String fallback: T] -> T
```

### `keys`

intrinsic

```margeux
intrinsic keys [value: Dict] -> Vector<String>
```

### `merge`

function

```margeux
def merge [T] [left: Dict[T] right: Dict[T]] -> Dict[T]
```

### `remove`

intrinsic

```margeux
intrinsic remove [T] [value: Dict[T] key: String] -> Dict[T]
```

### `values`

function

```margeux
def values [T] [value: Dict[T]] -> Vector[T]
```

## Library: `std/fonts`

```margeux
use "std/fonts"
```

### Quick example

```margeux
use "std/fonts"

async def choose-font [name]
  await fonts.select name
```

### `list`

async function

```margeux
async def list [] -> Result[Vector[String], String]
```

### `load`

async function

```margeux
async def load [name: String data: String] -> Result[String, String]
```

### `remove`

async function

```margeux
async def remove [] -> Result[String, String]
```

### `remove-named`

async function

```margeux
async def remove-named [name: String] -> Result[String, String]
```

### `restore`

async function

```margeux
async def restore [] -> Result[String, String]
```

### `select`

async function

```margeux
async def select [name: String] -> Result[String, String]
```

## Library: `std/grid`

```margeux
use "std/grid"
```

### Quick example

```margeux
use "std/grid"

def adjacent-cells [width height cell]
  grid.neighbors width height cell
```

### `centered-subset`

intrinsic

```margeux
intrinsic centered-subset [indices: Vector width: Int height: Int count: Int] -> Vector
```

### `column`

function

```margeux
def column [width: Int value: Int] -> Int
```

### `distance`

function

```margeux
def distance [width: Int height: Int allowed: Vector start: Int target: Int] -> Result
```

### `index`

function

```margeux
def index [width: Int x: Int y: Int] -> Int
```

### `matching-component`

intrinsic

```margeux
intrinsic matching-component [values: Vector width: Int height: Int start: Int] -> Vector
```

### `neighbors`

function

```margeux
def neighbors [width: Int height: Int value: Int] -> Vector
```

### `placement-indices`

intrinsic

```margeux
intrinsic placement-indices [values: Vector width: Int height: Int target] -> Vector
```

### `row`

function

```margeux
def row [width: Int value: Int] -> Int
```

### `valid-index?`

function

```margeux
def valid-index? [width: Int height: Int value: Int] -> Bool
```

### `valid-indices?`

function

```margeux
def valid-indices? [width: Int height: Int values: Vector] -> Bool
```

## Library: `std/infix`

```margeux
use "std/infix"
```

### Quick example

```margeux
use "std/infix"
  infix

def fahrenheit [celsius]
  celsius * 1.8 + 32.0
```

### `expression`

macro

```margeux
macro expression [body]
```

### `infix`

macro

```margeux
macro infix [body]
```

## Library: `std/instrument`

```margeux
use "std/instrument"
```

### Quick example

```margeux
use "std/instrument"

def playable-pitches [adapter tuning]
  instrument.all-pitches adapter tuning
```

### `InstrumentAdapter`

protocol

```margeux
protocol InstrumentAdapter
  instrument-id [adapter] -> String
  lane-count [adapter] -> Int
  step-count [adapter] -> Int
  pitch-at [adapter open-pitches lane step] -> Int
```

### `all-pitches`

function

```margeux
def all-pitches [adapter: InstrumentAdapter open-pitches: Vector[Int]] -> Vector[Vector[Int]]
```

### `instrument-id`

protocol method

```margeux
instrument-id [adapter] -> String
```

### `lane-count`

protocol method

```margeux
lane-count [adapter] -> Int
```

### `pitch-at`

protocol method

```margeux
pitch-at [adapter open-pitches lane step] -> Int
```

### `step-count`

protocol method

```margeux
step-count [adapter] -> Int
```

## Library: `std/input`

```margeux
use "std/input"
```

### Quick example

```margeux
use "std/input"

def horizontal-motion [frame]
  input.axis frame ["ArrowLeft" "a"] ["ArrowRight" "d"]
```

### `action-pressed?`

function

```margeux
def action-pressed? [frame: Dict keys: Vector] -> Bool
```

### `action-released?`

function

```margeux
def action-released? [frame: Dict keys: Vector] -> Bool
```

### `action?`

function

```margeux
def action? [frame: Dict keys: Vector] -> Bool
```

### `axis`

function

```margeux
def axis [frame: Dict negative: Vector positive: Vector] -> Float
```

### `gamepad-axis`

function

```margeux
def gamepad-axis [frame: Dict pad: Int axis-index: Int] -> Float
```

### `gamepad-button`

function

```margeux
def gamepad-button [frame: Dict pad: Int button-index: Int] -> Float
```

### `held?`

function

```margeux
def held? [frame: Dict key: String] -> Bool
```

### `normalize-key`

function

```margeux
def normalize-key [key: String] -> String
```

### `pointer-held?`

function

```margeux
def pointer-held? [frame: Dict button: String] -> Bool
```

### `pressed?`

function

```margeux
def pressed? [frame: Dict key: String] -> Bool
```

### `released?`

function

```margeux
def released? [frame: Dict key: String] -> Bool
```

## Library: `std/llm`

```margeux
use "std/llm"
```

### Quick example

```margeux
use "std/llm"

def source-file [path content]
  llm.file path (llm.digest content) content
```

### `Completion`

record

```margeux
record Completion
  request-id: String
  provider: String
  model: String
  input-digest: String
  output-digest: String
  finish-reason: String
  summary: String
  edits: Vector[SourceEdit]
  creates: Vector[SourceCreate]
  deletes: Vector[SourceDelete]
```

### `Identity`

record

```margeux
record Identity
  provider: String
  model: String
```

### `Request`

record

```margeux
record Request
  id: String
  instruction: String
  profile: String
  entry: String
  files: Vector[SourceFile]
  selection: Selection
  constraints: Vector[String]
```

### `Selection`

record

```margeux
record Selection
  path: String
  start: Int
  end: Int
  expected: String
```

### `SourceCreate`

record

```margeux
record SourceCreate
  path: String
  content: String
```

### `SourceDelete`

record

```margeux
record SourceDelete
  path: String
  expected-digest: String
```

### `SourceEdit`

record

```margeux
record SourceEdit
  path: String
  start: Int
  end: Int
  expected: String
  replacement: String
```

### `SourceFile`

record

```margeux
record SourceFile
  path: String
  digest: String
  content: String
```

### `apply`

function

```margeux
def apply [request-value: Request completion: Completion] -> Result[Vector[SourceFile], String]
```

### `digest`

intrinsic

```margeux
intrinsic digest [content: String] -> String
```

### `file`

function

```margeux
def file [path: String digest: String content: String] -> SourceFile
```

### `identity`

async function

```margeux
async def identity [] -> Result[Identity, String]
```

### `no-selection`

function

```margeux
def no-selection [] -> Selection
```

### `request`

async function

```margeux
async def request [value: Request] -> Result[Completion, String]
```

### `request-value`

function

```margeux
def request-value [id: String instruction: String profile: String entry: String files: Vector[SourceFile] constraints: Vector[String]] -> Request
```

### `selected-request`

function

```margeux
def selected-request [id: String instruction: String profile: String entry: String files: Vector[SourceFile] selected: Selection constraints: Vector[String]] -> Request
```

### `selection`

function

```margeux
def selection [path: String start: Int end: Int expected: String] -> Selection
```

## Library: `std/markup`

```margeux
use "std/markup"
```

### Quick example

```margeux
use "std/markup"

def article [markdown]
  section :class "article"
    markup.render markdown
```

### `Block`

variant

```margeux
variant Block
  Heading value: HeadingBlock
  Paragraph content: String
  Quote content: String
  List value: ListBlock
  Code value: CodeBlock
  Table content: String
```

### `Document`

record

```margeux
record Document
  blocks: Vector[Block]
```

### `parse`

function

```margeux
def parse [source: String] -> Document
```

### `render`

function

```margeux
def render [source: String] -> Views
```

## Library: `std/math`

```margeux
use "std/math"
```

### Quick example

```margeux
use "std/math"

def circle-area [radius]
  * math.pi (math.pow radius 2)

def safe-percentage [value]
  math.clamp value 0 100
```

### `abs`

intrinsic

```margeux
intrinsic abs [value: Number] -> Number
```

### `acos`

intrinsic

```margeux
intrinsic acos [value: Number] -> Float
```

### `approx?`

intrinsic

```margeux
intrinsic approx? [left: Number right: Number tolerance: Number] -> Bool
```

### `asin`

intrinsic

```margeux
intrinsic asin [value: Number] -> Float
```

### `atan`

intrinsic

```margeux
intrinsic atan [value: Number] -> Float
```

### `atan2`

intrinsic

```margeux
intrinsic atan2 [y: Number x: Number] -> Float
```

### `ceil`

intrinsic

```margeux
intrinsic ceil [value: Number] -> Float
```

### `clamp`

intrinsic

```margeux
intrinsic clamp [value: Number minimum: Number maximum: Number] -> Number
```

### `combinations`

intrinsic

```margeux
intrinsic combinations [count: Int chosen: Int] -> Int
```

### `cos`

intrinsic

```margeux
intrinsic cos [radians: Number] -> Float
```

### `degrees`

function

```margeux
def degrees [radians: Number] -> Float
```

### `distance`

intrinsic

```margeux
intrinsic distance [left: Vector right: Vector] -> Float
```

### `dot`

intrinsic

```margeux
intrinsic dot [left: Vector right: Vector] -> Number
```

### `e`

constant

```margeux
const e 2.718281828459045
```

### `exp`

intrinsic

```margeux
intrinsic exp [value: Number] -> Float
```

### `factorial`

intrinsic

```margeux
intrinsic factorial [value: Int] -> Int
```

### `finite?`

intrinsic

```margeux
intrinsic finite? [value: Number] -> Bool
```

### `floor`

intrinsic

```margeux
intrinsic floor [value: Number] -> Float
```

### `gcd`

intrinsic

```margeux
intrinsic gcd [left: Int right: Int] -> Int
```

### `hypot`

intrinsic

```margeux
intrinsic hypot [x: Number y: Number] -> Float
```

### `infinite?`

intrinsic

```margeux
intrinsic infinite? [value: Number] -> Bool
```

### `inverse-lerp`

function

```margeux
def inverse-lerp [start: Number end: Number value: Number] -> Float
```

### `lcm`

intrinsic

```margeux
intrinsic lcm [left: Int right: Int] -> Int
```

### `lerp`

function

```margeux
def lerp [start: Number end: Number amount: Number] -> Float
```

### `log`

intrinsic

```margeux
intrinsic log [value: Number] -> Float
```

### `log10`

intrinsic

```margeux
intrinsic log10 [value: Number] -> Float
```

### `log2`

intrinsic

```margeux
intrinsic log2 [value: Number] -> Float
```

### `magnitude`

intrinsic

```margeux
intrinsic magnitude [values: Vector] -> Float
```

### `max`

intrinsic

```margeux
intrinsic max [left: Number right: Number] -> Number
```

### `mean`

intrinsic

```margeux
intrinsic mean [values: Vector] -> Float
```

### `median`

intrinsic

```margeux
intrinsic median [values: Vector] -> Float
```

### `min`

intrinsic

```margeux
intrinsic min [left: Number right: Number] -> Number
```

### `nan?`

intrinsic

```margeux
intrinsic nan? [value: Number] -> Bool
```

### `normalize`

intrinsic

```margeux
intrinsic normalize [values: Vector] -> Vector
```

### `permutations`

intrinsic

```margeux
intrinsic permutations [count: Int chosen: Int] -> Int
```

### `pi`

constant

```margeux
const pi 3.141592653589793
```

### `pow`

intrinsic

```margeux
intrinsic pow [base: Number exponent: Number] -> Float
```

### `product`

intrinsic

```margeux
intrinsic product [values: Vector] -> Number
```

### `radians`

function

```margeux
def radians [degrees: Number] -> Float
```

### `remap`

function

```margeux
def remap [value: Number input-start: Number input-end: Number output-start: Number output-end: Number] -> Float
```

### `round`

intrinsic

```margeux
intrinsic round [value: Number] -> Float
```

### `round-even`

intrinsic

```margeux
intrinsic round-even [value: Number] -> Float
```

### `sign`

intrinsic

```margeux
intrinsic sign [value: Number] -> Int
```

### `sin`

intrinsic

```margeux
intrinsic sin [radians: Number] -> Float
```

### `sqrt`

intrinsic

```margeux
intrinsic sqrt [value: Number] -> Float
```

### `standard-deviation`

intrinsic

```margeux
intrinsic standard-deviation [values: Vector] -> Float
```

### `sum`

intrinsic

```margeux
intrinsic sum [values: Vector] -> Number
```

### `tan`

intrinsic

```margeux
intrinsic tan [radians: Number] -> Float
```

### `tau`

constant

```margeux
const tau
```

### `truncate`

intrinsic

```margeux
intrinsic truncate [value: Number] -> Float
```

### `variance`

intrinsic

```margeux
intrinsic variance [values: Vector] -> Float
```

### `vector-add`

intrinsic

```margeux
intrinsic vector-add [left: Vector right: Vector] -> Vector
```

### `vector-scale`

intrinsic

```margeux
intrinsic vector-scale [values: Vector scale: Number] -> Vector
```

### `vector-subtract`

intrinsic

```margeux
intrinsic vector-subtract [left: Vector right: Vector] -> Vector
```

## Library: `std/music_catalog`

```margeux
use "std/music_catalog"
```

### Quick example

```margeux
use "std/music_catalog"

def major-triad []
  music_catalog.quality 0
```

### `Quality`

record

```margeux
record Quality
  name: String
  symbol: String
  formula: String
  character: String
  intervals: Vector[Int]
```

### `Scale`

record

```margeux
record Scale
  name: String
  symbol: String
  formula: String
  character: String
  intervals: Vector[Int]
```

### `quality`

function

```margeux
def quality [index: Int] -> Quality
```

### `quality-count`

constant

```margeux
const quality-count 18
```

### `quality-intervals`

function

```margeux
def quality-intervals [index: Int] -> Vector[Int]
```

### `scale`

function

```margeux
def scale [index: Int] -> Scale
```

### `scale-count`

constant

```margeux
const scale-count 15
```

### `valid-quality?`

function

```margeux
def valid-quality? [index: Int] -> Bool
```

### `valid-scale?`

function

```margeux
def valid-scale? [index: Int] -> Bool
```

## Library: `std/music_builder`

```margeux
use "std/music_builder"
```

### Quick example

```margeux
use "std/music_builder"

def select-next [builder]
  music_builder.select builder (+ builder.slot 1)
```

### `Builder`

record

```margeux
record Builder
  positions: Vector[Position]
  grid: Vector[Int]
  length: Int
  slot: Int
  selection-anchor: Int
  selection-end: Int
  columns: Int
  clipboard: Vector[Position]
  clipboard-length: Int
  name: String
  key: Int
  roots-locked: Bool
```

### `add-at-cell`

function

```margeux
def add-at-cell [builder: Builder cell: Int position: Position] -> Builder
```

### `beats`

function

```margeux
def beats [builder: Builder] -> Vector[Int]
```

### `can-move-selection?`

function

```margeux
def can-move-selection? [builder: Builder delta: Int] -> Bool
```

### `capacity`

function

```margeux
def capacity [builder: Builder] -> Int
```

### `compact`

function

```margeux
def compact [builder: Builder] -> Builder
```

### `copy-selection`

function

```margeux
def copy-selection [builder: Builder] -> Builder
```

### `duplicate-loop`

function

```margeux
def duplicate-loop [builder: Builder] -> Builder
```

### `duplicate-selection`

function

```margeux
def duplicate-selection [builder: Builder] -> Builder
```

### `editable-cell?`

function

```margeux
def editable-cell? [builder: Builder cell: Int] -> Bool
```

### `extend-selection`

function

```margeux
def extend-selection [builder: Builder index: Int] -> Builder
```

### `grid-cell-for-item`

function

```margeux
def grid-cell-for-item [builder: Builder item: Int] -> Int
```

### `grid-item-at`

function

```margeux
def grid-item-at [builder: Builder cell: Int] -> Int
```

### `grid-span`

function

```margeux
def grid-span [builder: Builder include-open-row: Bool] -> Int
```

### `initial`

function

```margeux
def initial [positions: Vector[Position] active-length: Int columns: Int] -> Builder
```

### `insert-selected-copy`

function

```margeux
def insert-selected-copy [builder: Builder] -> Builder
```

### `item-selected?`

function

```margeux
def item-selected? [builder: Builder item: Int] -> Bool
```

### `move-selected-one`

function

```margeux
def move-selected-one [builder: Builder delta: Int] -> Builder
```

### `move-selection`

function

```margeux
def move-selection [builder: Builder delta: Int] -> Builder
```

### `paste-count`

function

```margeux
def paste-count [builder: Builder] -> Int
```

### `paste-selection`

function

```margeux
def paste-selection [builder: Builder] -> Builder
```

### `playback-beats`

function

```margeux
def playback-beats [builder: Builder] -> Vector[Int]
```

### `playback-position-at`

function

```margeux
def playback-position-at [builder: Builder cell: Int] -> Position
```

### `playback-span`

function

```margeux
def playback-span [builder: Builder] -> Int
```

### `position-at`

function

```margeux
def position-at [builder: Builder index: Int] -> Position
```

### `remove-selection`

function

```margeux
def remove-selection [builder: Builder] -> Builder
```

### `reorder-selected`

function

```margeux
def reorder-selected [builder: Builder delta: Int] -> Builder
```

### `replace-beats`

function

```margeux
def replace-beats [builder: Builder index: Int value: Int] -> Builder
```

### `replace-position`

function

```margeux
def replace-position [builder: Builder index: Int position: Position] -> Builder
```

### `replace-quality`

function

```margeux
def replace-quality [builder: Builder index: Int quality: Int] -> Builder
```

### `replace-root`

function

```margeux
def replace-root [builder: Builder index: Int root: Int] -> Builder
```

### `replace-scale`

function

```margeux
def replace-scale [builder: Builder index: Int scale-index: Int] -> Builder
```

### `replace-voicing`

function

```margeux
def replace-voicing [builder: Builder index: Int voicing: Int] -> Builder
```

### `select`

function

```margeux
def select [builder: Builder index: Int] -> Builder
```

### `selection-finish`

function

```margeux
def selection-finish [builder: Builder] -> Int
```

### `selection-length`

function

```margeux
def selection-length [builder: Builder] -> Int
```

### `selection-start`

function

```margeux
def selection-start [builder: Builder] -> Int
```

### `set-columns`

function

```margeux
def set-columns [builder: Builder value: Int] -> Builder
```

### `set-key`

function

```margeux
def set-key [builder: Builder value: Int] -> Builder
```

### `set-name`

function

```margeux
def set-name [builder: Builder value: String] -> Builder
```

### `set-roots-locked`

function

```margeux
def set-roots-locked [builder: Builder value: Bool] -> Builder
```

### `with-positions`

function

```margeux
def with-positions [builder: Builder positions: Vector[Position]] -> Builder
```

## Library: `std/music_export`

```margeux
use "std/music_export"
```

### Quick example

```margeux
use "std/music_export"

def printable-progression [builder]
  music_export.progression-svg builder "guitar"
```

### `position-detail`

function

```margeux
def position-detail [item: Position] -> String
```

### `position-notes`

function

```margeux
def position-notes [builder: Builder item: Position] -> String
```

### `position-title`

function

```margeux
def position-title [builder: Builder item: Position] -> String
```

### `progression-svg`

function

```margeux
def progression-svg [builder: Builder instrument: String] -> String
```

### `progression-url`

function

```margeux
def progression-url [builder: Builder instrument: String] -> String
```

### `svg-data-url`

function

```margeux
def svg-data-url [value: String] -> String
```

### `title`

function

```margeux
def title [builder: Builder instrument: String] -> String
```

## Library: `std/music_finder`

```margeux
use "std/music_finder"
```

### Quick example

```margeux
use "std/music_finder"

def matching-chords [selected-pitches]
  music_finder.chord-exact-codes selected-pitches
```

### `chord-compatible-codes`

function

```margeux
def chord-compatible-codes [selected: Vector[Int]] -> Vector[Int]
```

### `chord-compatible?`

function

```margeux
def chord-compatible? [selected: Vector[Int] root: Int quality-index: Int] -> Bool
```

### `chord-containing-codes`

function

```margeux
def chord-containing-codes [selected: Vector[Int]] -> Vector[Int]
```

### `chord-exact-codes`

function

```margeux
def chord-exact-codes [selected: Vector[Int]] -> Vector[Int]
```

### `chord-exact?`

function

```margeux
def chord-exact? [selected: Vector[Int] root: Int quality-index: Int] -> Bool
```

### `scale-compatible-codes`

function

```margeux
def scale-compatible-codes [selected: Vector[Int] exact-threshold: Int] -> Vector[Int]
```

### `scale-compatible?`

function

```margeux
def scale-compatible? [selected: Vector[Int] root: Int scale-index: Int exact-threshold: Int] -> Bool
```

## Library: `std/music_program`

```margeux
use "std/music_program"
```

### Quick example

```margeux
use "std/music_program"

def four-bar-progression []
  vector
    music_program.chord 0 0 4
    music_program.chord 5 0 4
    music_program.chord 7 0 4
    music_program.chord 0 0 4
```

### `Position`

record

```margeux
record Position
  root: Int
  item-type: Int
  quality: Int
  scale: Int
  custom-name: String
  pitches: Vector[Int]
  voicing: Int
  beats: Int
```

### `beats`

function

```margeux
def beats [items: Vector[Position]] -> Vector[Int]
```

### `chord`

function

```margeux
def chord [root: Int quality: Int beats: Int] -> Position
```

### `chord-item`

constant

```margeux
const chord-item 0
```

### `chord?`

function

```margeux
def chord? [item: Position] -> Bool
```

### `copy-range`

function

```margeux
def copy-range [items: Vector[Position] start: Int copy-count: Int fallback: Position] -> Vector[Position]
```

### `custom`

function

```margeux
def custom [root: Int name: String pitches: Vector[Int] beats: Int] -> Position
```

### `custom-item`

constant

```margeux
const custom-item 2
```

### `custom?`

function

```margeux
def custom? [item: Position] -> Bool
```

### `insert-copy-after`

function

```margeux
def insert-copy-after [items: Vector[Position] target: Int active-length: Int] -> Vector[Position]
```

### `note-set`

function

```margeux
def note-set [root: Int name: String locations: Vector[Int] beats: Int] -> Position
```

### `note-set-item`

constant

```margeux
const note-set-item 4
```

### `note-set?`

function

```margeux
def note-set? [item: Position] -> Bool
```

### `paste-at`

function

```margeux
def paste-at [items: Vector[Position] copied: Vector[Position] insertion: Int copy-count: Int active-length: Int] -> Vector[Position]
```

### `remove-range`

function

```margeux
def remove-range [items: Vector[Position] start: Int removal-count: Int active-length: Int fallback: Position] -> Vector[Position]
```

### `repeat-active`

function

```margeux
def repeat-active [items: Vector[Position] active-length: Int] -> Vector[Position]
```

### `replace-at`

function

```margeux
def replace-at [items: Vector[Position] target: Int replacement: Position] -> Vector[Position]
```

### `rest`

function

```margeux
def rest [beats: Int] -> Position
```

### `rest-item`

constant

```margeux
const rest-item 3
```

### `rest?`

function

```margeux
def rest? [item: Position] -> Bool
```

### `scale`

function

```margeux
def scale [root: Int scale-index: Int beats: Int] -> Position
```

### `scale-item`

constant

```margeux
const scale-item 1
```

### `scale?`

function

```margeux
def scale? [item: Position] -> Bool
```

### `swap-at`

function

```margeux
def swap-at [items: Vector[Position] first: Int second: Int] -> Vector[Position]
```

### `transpose-roots`

function

```margeux
def transpose-roots [items: Vector[Position] active-length: Int semitones: Int] -> Vector[Position]
```

### `with-beats`

function

```margeux
def with-beats [item: Position beats: Int] -> Position
```

### `with-custom`

function

```margeux
def with-custom [item: Position name: String pitches: Vector[Int]] -> Position
```

### `with-note-set`

function

```margeux
def with-note-set [item: Position name: String locations: Vector[Int]] -> Position
```

### `with-quality`

function

```margeux
def with-quality [item: Position quality: Int] -> Position
```

### `with-root`

function

```margeux
def with-root [item: Position root: Int] -> Position
```

### `with-scale`

function

```margeux
def with-scale [item: Position scale-index: Int] -> Position
```

### `with-voicing`

function

```margeux
def with-voicing [item: Position voicing: Int] -> Position
```

## Library: `std/music_progressions`

```margeux
use "std/music_progressions"
```

### Quick example

```margeux
use "std/music_progressions"

def first-template []
  music_progressions.progression-template 0
```

### `ChordSuggestion`

record

```margeux
record ChordSuggestion
  degree: Int
  quality: Int
  numeral: String
  reason: String
```

### `ProgressionTemplate`

record

```margeux
record ProgressionTemplate
  name: String
  category: String
  feel: String
  numerals: String
  description: String
  degrees: Vector[Int]
  qualities: Vector[Int]
  labels: Vector[String]
  length: Int
```

### `make-chord-suggestion`

function

```margeux
def make-chord-suggestion [degree quality numeral reason] -> ChordSuggestion
```

### `next-chord-suggestion`

function

```margeux
def next-chord-suggestion [degree: Int index: Int] -> ChordSuggestion
```

### `progression-category-count`

constant

```margeux
const progression-category-count 16
```

### `progression-category-first-template`

function

```margeux
def progression-category-first-template [category: Int] -> Int
```

### `progression-category-name`

function

```margeux
def progression-category-name [index: Int] -> String
```

### `progression-category-template-index`

function

```margeux
def progression-category-template-index [category: Int slot: Int] -> Int
```

### `progression-template`

function

```margeux
def progression-template [index: Int] -> ProgressionTemplate
```

### `progression-template-count`

constant

```margeux
const progression-template-count 96
```

### `progression-templates-per-category`

constant

```margeux
const progression-templates-per-category 6
```

## Library: `std/music_practice`

```margeux
use "std/music_practice"
```

### Quick example

```margeux
use "std/music_practice"

def practice-tracks [beats]
  music_practice.timelines beats 4 false
```

### `beat-offset`

function

```margeux
def beat-offset [beats: Vector[Int] item-index: Int] -> Int
```

### `item-limit`

function

```margeux
def item-limit [beats: Vector[Int] count: Int item-index: Int] -> Int
```

### `parsed-beats`

function

```margeux
def parsed-beats [value: String fallback: Int limit: Int] -> Int
```

### `parsed-bpm`

function

```margeux
def parsed-bpm [value: String fallback: Int] -> Int
```

### `parsed-count-in`

function

```margeux
def parsed-count-in [value: String fallback: Int] -> Int
```

### `timelines`

function

```margeux
def timelines [beats: Vector[Int] count: Int muted: Bool] -> Vector[Timeline]
```

### `total-beats`

function

```margeux
def total-beats [beats: Vector[Int] count: Int] -> Int
```

## Library: `std/music_theory`

```margeux
use "std/music_theory"
```

### Quick example

```margeux
use "std/music_theory"

def c-major-pitches []
  music_theory.pitches 0 [0 2 4 5 7 9 11]
```

### `compatible-scale?`

function

```margeux
def compatible-scale? [root: Int intervals: Vector[Int] selected: Vector[Int] exact-threshold: Int] -> Bool
```

### `contains-pitches?`

function

```margeux
def contains-pitches? [candidate: Vector[Int] selected: Vector[Int]] -> Bool
```

### `exact-pitches?`

function

```margeux
def exact-pitches? [candidate: Vector[Int] selected: Vector[Int]] -> Bool
```

### `interval-name`

function

```margeux
def interval-name [interval: Int] -> String
```

### `normalize`

function

```margeux
def normalize [pitch: Int] -> Int
```

### `pitch-class-count`

constant

```margeux
const pitch-class-count 12
```

### `pitch-name`

function

```margeux
def pitch-name [key: Int pitch: Int] -> String
```

### `pitches`

function

```margeux
def pitches [root: Int intervals: Vector[Int]] -> Vector[Int]
```

### `relative`

function

```margeux
def relative [root: Int pitch: Int] -> Int
```

### `transpose`

function

```margeux
def transpose [pitch: Int semitones: Int] -> Int
```

## Library: `std/process`

```margeux
use "std/process"
```

### Quick example

```margeux
use "std/process"

async def git-status []
  await process.run "git" ["status" "--short"]
```

### `ProcessResult`

record

```margeux
record ProcessResult
  program: String
  arguments: Vector[String]
  exit-code: Int
  stdout: String
  stderr: String
```

### `run`

async function

```margeux
async def run [program: String arguments: Vector[String]] -> Result[ProcessResult, String]
```

### `run-program`

async function

```margeux
async def run-program [program: String] -> Result[ProcessResult, String]
```

### `success?`

function

```margeux
def success? [result: ProcessResult] -> Bool
```

## Library: `std/random`

```margeux
use "std/random"
```

### Quick example

```margeux
use "std/random"

def roll-die [seed]
  random.int seed 1 7
```

### `Sample`

record

```margeux
record Sample
  seed: Int
  value: Any
```

### `at`

function

```margeux
def at [initial: Int slot: Int] -> Int
```

### `bool`

function

```margeux
def bool [current: Int] -> Sample
```

### `chance`

function

```margeux
def chance [current: Int probability: Number] -> Sample
```

### `float`

function

```margeux
def float [current: Int] -> Sample
```

### `int`

function

```margeux
def int [current: Int minimum: Int maximum: Int] -> Sample
```

### `int-at`

function

```margeux
def int-at [initial: Int slot: Int minimum: Int maximum: Int] -> Int
```

### `next`

function

```margeux
def next [current: Int] -> Int
```

### `pick`

function

```margeux
def pick [current: Int values: Vector] -> Sample
```

### `seed`

function

```margeux
def seed [value: Int] -> Int
```

## Library: `std/ray3d`

```margeux
use "std/ray3d"
```

### Quick example

```margeux
use "std/ray3d"

def camera-view [world width height player-x player-y angle]
  ray3d.cast-view world width height player-x player-y angle 1.1 160 24
```

### `cast-frame`

intrinsic

```margeux
intrinsic cast-frame [cells: Vector width: Int height: Int origin-x: Number origin-y: Number angle: Number fov: Number columns: Int max-distance: Number] -> Vector
```

### `cast-view`

intrinsic

```margeux
intrinsic cast-view [cells: Vector width: Int height: Int origin-x: Number origin-y: Number angle: Number fov: Number columns: Int max-distance: Number] -> Vector
```

### `frame-hits-cell?`

intrinsic

```margeux
intrinsic frame-hits-cell? [frame: Vector cell-x: Int cell-y: Int] -> Bool
```

### `frame-width`

constant

```margeux
const frame-width 5
```

## Library: `std/results`

```margeux
use "std/results"
```

### Quick example

```margeux
use "std/results"

def doubled [result]
  results.map
    fn [value]
      * value 2
    result
```

### `and-then`

function

```margeux
def and-then [transform result]
```

### `error?`

function

```margeux
def error? [T E] [result: Result[T, E]] -> Bool
```

### `get-or`

function

```margeux
def get-or [T E] [result: Result[T, E] fallback: T] -> T
```

### `map`

function

```margeux
def map [transform result]
```

### `map-error`

function

```margeux
def map-error [transform result]
```

### `ok?`

function

```margeux
def ok? [T E] [result: Result[T, E]] -> Bool
```

### `recover`

function

```margeux
def recover [transform result]
```

## Library: `std/server`

```margeux
use "std/server"
```

### Quick example

```margeux
use "std/server"

def health-route []
  server.route "GET" "/health"

def health-response []
  server.json 200 "\{\"ok\":true\}"
```

### `ClientRequest`

record

```margeux
record ClientRequest
  method: String
  path: String
  body: String
  content-type: String
```

### `Cookie`

record

```margeux
record Cookie
  name: String
  value: String
  max-age: Int
  secure?: Bool
```

### `Request`

record

```margeux
record Request
  method: String
  path: String
  query: String
  headers: Dict
  body: String
```

### `Response`

record

```margeux
record Response
  status: Int
  headers: Dict
  body: String
```

### `Route`

record

```margeux
record Route
  method: String
  pattern: String
```

### `RouteMatch`

record

```margeux
record RouteMatch
  matched?: Bool
  valid?: Bool
  params: Dict
  problem: String
```

### `Session`

record

```margeux
record Session
  id: String
  values: Dict
```

### `Stream`

record

```margeux
record Stream
  state: Any
  next: Any
```

### `StreamChunk`

record

```margeux
record StreamChunk
  body: String
  state: Any
```

### `StreamResponse`

record

```margeux
record StreamResponse
  status: Int
  headers: Dict
  stream: Stream
```

### `StreamStep`

variant

```margeux
variant StreamStep
  Emit value: StreamChunk
  End
```

### `async-header-middleware`

function

```margeux
def async-header-middleware [handler name: String content: String]
```

### `async-request-middleware`

function

```margeux
def async-request-middleware [handler transform]
```

### `async-response-middleware`

function

```margeux
def async-response-middleware [handler transform]
```

### `bool-param`

function

```margeux
def bool-param [value: RouteMatch name: String] -> Result[Bool, String]
```

### `client`

function

```margeux
def client [value: Route base: String]
```

### `cookie`

function

```margeux
def cookie [name: String value: String] -> Result[Cookie, String]
```

### `cookie-value`

function

```margeux
def cookie-value [request: Request name: String] -> Result[String, String]
```

### `delete-session`

async function

```margeux
async def delete-session [value: Response cookie-name: String session: Session] -> Result[Response, String]
```

### `emit`

function

```margeux
def emit [body: String state] -> StreamStep
```

### `encode-path`

intrinsic

```margeux
intrinsic encode-path [path: String] -> String
```

### `end`

function

```margeux
def end [] -> StreamStep
```

### `expired-cookie`

function

```margeux
def expired-cookie [name: String] -> Result[Cookie, String]
```

### `float-param`

function

```margeux
def float-param [value: RouteMatch name: String] -> Result[Float, String]
```

### `header-middleware`

function

```margeux
def header-middleware [handler name: String content: String]
```

### `html`

function

```margeux
def html [status: Int body: String] -> Response
```

### `int-param`

function

```margeux
def int-param [value: RouteMatch name: String] -> Result[Int, String]
```

### `json`

function

```margeux
def json [status: Int body: String] -> Response
```

### `json-client`

function

```margeux
def json-client [value: Route base: String]
```

### `load-session`

async function

```margeux
async def load-session [request: Request cookie-name: String] -> Result[Session, String]
```

### `match-route`

function

```margeux
def match-route [value: Route request: Request] -> RouteMatch
```

### `new-session`

function

```margeux
def new-session [id: String values: Dict] -> Result[Session, String]
```

### `param`

function

```margeux
def param [value: RouteMatch name: String] -> Result[String, String]
```

### `redirect`

function

```margeux
def redirect [location: String] -> Response
```

### `response`

function

```margeux
def response [status: Int headers: Dict body: String] -> Response
```

### `response-middleware`

function

```margeux
def response-middleware [handler transform]
```

### `route`

function

```margeux
def route [method: String pattern: String] -> Route
```

### `route-path`

function

```margeux
def route-path [value: Route params: Dict] -> Result[String, String]
```

### `save-session`

async function

```margeux
async def save-session [value: Response cookie-name: String session: Session] -> Result[Response, String]
```

### `secure-cookie`

function

```margeux
def secure-cookie [name: String value: String] -> Result[Cookie, String]
```

### `send`

async function

```margeux
async def send [request: ClientRequest] -> Result[Dict, String]
```

### `stream`

function

```margeux
def stream [state next] -> Stream
```

### `stream-response`

function

```margeux
def stream-response [status: Int headers: Dict state next] -> StreamResponse
```

### `text`

function

```margeux
def text [status: Int body: String] -> Response
```

### `validate-route`

function

```margeux
def validate-route [value: Route] -> Result[Route, String]
```

### `validate-routes`

function

```margeux
def validate-routes [routes: Vector[Route]] -> Result[Vector[Route], String]
```

### `with-cookie`

function

```margeux
def with-cookie [value: Response item: Cookie] -> Result[Response, String]
```

### `with-header`

function

```margeux
def with-header [value: Response name: String content: String] -> Response
```

## Library: `std/sort`

```margeux
use "std/sort"
```

### Quick example

```margeux
use "std/sort"

def smallest-first [numbers]
  sort.ascending numbers
```

### `ascending`

function

```margeux
def ascending [T] [values: Vector[T]] -> Vector[T]
```

### `descending`

function

```margeux
def descending [T] [values: Vector[T]] -> Vector[T]
```

### `using`

function

```margeux
def using [T] [less?: Function values: Vector[T]] -> Vector[T]
```

## Library: `std/source`

```margeux
use "std/source"
```

### Quick example

```margeux
use "std/source"

async def load-note [path]
  await source.load path
```

### `delete`

async function

```margeux
async def delete [path: String] -> Result
```

### `list`

async function

```margeux
async def list [] -> Result
```

### `load`

async function

```margeux
async def load [path: String] -> Result
```

### `paths`

intrinsic

```margeux
intrinsic paths [] -> Vector
```

### `read`

intrinsic

```margeux
intrinsic read [path: String] -> String
```

### `save`

async function

```margeux
async def save [path: String content: String] -> Result
```

### `tokens`

intrinsic

```margeux
intrinsic tokens [line: String start: Int end: Int] -> Vector
```

## Library: `std/storage`

```margeux
use "std/storage"
```

### Quick example

```margeux
use "std/storage"

async def remember-theme [name]
  await storage.set "theme" name
```

### `delete`

async function

```margeux
async def delete [key: String] -> Result[String, String]
```

### `get`

async function

```margeux
async def get [key: String] -> Result[Any, String]
```

### `keys`

async function

```margeux
async def keys [] -> Result[Vector[String], String]
```

### `set`

async function

```margeux
async def set [key: String value] -> Result[String, String]
```

## Library: `std/strings`

```margeux
use "std/strings"
```

### Quick example

```margeux
use "std/strings"

def indented-lines [content]
  strings.indent content "  "
```

### `at`

function

```margeux
def at [value: String index: Int] -> Result<String, String>
```

### `blank?`

function

```margeux
def blank? [value: String] -> Bool
```

### `capitalize`

function

```margeux
def capitalize [value: String] -> String
```

### `drop`

function

```margeux
def drop [value: String count: Int] -> String
```

### `ends-with?`

function

```margeux
def ends-with? [value: String suffix: String] -> Bool
```

### `indent`

function

```margeux
def indent [value: String prefix: String] -> String
```

### `lines`

function

```margeux
def lines [value: String] -> Vector<String>
```

### `repeat`

function

```margeux
def repeat [value: String count: Int] -> String
```

### `splice`

intrinsic

```margeux
intrinsic splice [value: String start: Int end: Int insertion: String] -> String
```

### `starts-with?`

function

```margeux
def starts-with? [value: String prefix: String] -> Bool
```

### `take`

function

```margeux
def take [value: String count: Int] -> String
```

### `unlines`

function

```margeux
def unlines [values: Vector<String>] -> String
```

## Library: `std/testing`

```margeux
use "std/testing"
```

### Quick example

```margeux
use "std/testing"

test "addition"
  testing.equal (+ 2 2) 4
```

### `approx`

intrinsic

```margeux
intrinsic approx [actual: Number expected: Number tolerance: Number] -> Bool
```

### `check`

intrinsic

```margeux
intrinsic check [condition: Bool message: String] -> Bool
```

### `equal`

intrinsic

```margeux
intrinsic equal [actual: Any expected: Any] -> Bool
```

### `fail`

intrinsic

```margeux
intrinsic fail [message: String] -> Bool
```

### `is-false`

intrinsic

```margeux
intrinsic is-false [value: Bool] -> Bool
```

### `is-true`

intrinsic

```margeux
intrinsic is-true [value: Bool] -> Bool
```

### `not-equal`

intrinsic

```margeux
intrinsic not-equal [actual: Any unexpected: Any] -> Bool
```

## Library: `std/time`

```margeux
use "std/time"
```

### Quick example

```margeux
use "std/time"

def five-minutes []
  time.minutes 5

def has-expired [now deadline]
  time.expired? now deadline
```

### `after`

async function

```margeux
async def after [duration: Int value] -> Result[Any, String]
```

### `day`

constant

```margeux
const day 86400000
```

### `days`

function

```margeux
def days [amount: Int] -> Int
```

### `deadline`

function

```margeux
def deadline [start: Int duration: Int] -> Int
```

### `elapsed`

function

```margeux
def elapsed [start: Int finish: Int] -> Int
```

### `expired?`

function

```margeux
def expired? [current: Int target: Int] -> Bool
```

### `hour`

constant

```margeux
const hour 3600000
```

### `hours`

function

```margeux
def hours [amount: Int] -> Int
```

### `millisecond`

constant

```margeux
const millisecond 1
```

### `milliseconds`

function

```margeux
def milliseconds [amount: Int] -> Int
```

### `minute`

constant

```margeux
const minute 60000
```

### `minutes`

function

```margeux
def minutes [amount: Int] -> Int
```

### `now`

async function

```margeux
async def now [] -> Result[Int, String]
```

### `remaining`

function

```margeux
def remaining [current: Int target: Int] -> Int
```

### `second`

constant

```margeux
const second 1000
```

### `seconds`

function

```margeux
def seconds [amount: Int] -> Int
```

### `sleep`

async function

```margeux
async def sleep [duration: Int] -> Result[Int, String]
```

## Library: `std/tui`

```margeux
use "std/tui"
```

### Quick example

```margeux
use "std/tui"

def divider [width]
  tui.horizontal-line 0 0 width "─" "#888888"
```

### `box-line`

function

```margeux
def box-line [x: Int y: Int width: Int height: Int row: Int color: String]
```

### `clamp-index`

function

```margeux
def clamp-index [index: Int count: Int] -> Int
```

### `horizontal-line`

function

```margeux
def horizontal-line [x: Int y: Int width: Int character: String color: String]
```

### `repeat-character`

function

```margeux
def repeat-character [character: String count: Int] -> String
```

### `scroll-start`

function

```margeux
def scroll-start [current: Int selected: Int viewport: Int count: Int] -> Int
```

### `wrap-index`

function

```margeux
def wrap-index [index: Int count: Int] -> Int
```

## Library: `std/ui`

```margeux
use "std/ui"
```

### Quick example

```margeux
use "std/ui"

def next-menu-item [current count event]
  ui.focus-index current count event "ArrowUp" "ArrowDown"
```

### `activate?`

function

```margeux
def activate? [event: Dict] -> Bool
```

### `focus-index`

function

```margeux
def focus-index [current: Int count: Int key: String previous: String next: String] -> Int
```

### `hit`

function

```margeux
def hit [regions: Vector x: Int y: Int] -> Result
```

### `horizontal-index`

function

```margeux
def horizontal-index [current: Int count: Int key: String] -> Int
```

### `inside?`

function

```margeux
def inside? [x: Int y: Int region: Dict] -> Bool
```

### `key-event`

function

```margeux
def key-event [key: String] -> Dict
```

### `normalize-event`

function

```margeux
def normalize-event [event: Dict] -> Dict
```

### `pointer-event`

function

```margeux
def pointer-event [x: Int y: Int button: String] -> Dict
```

### `vertical-index`

function

```margeux
def vertical-index [current: Int count: Int key: String] -> Int
```

## Library: `std/vec3`

```margeux
use "std/vec3"
```

### Quick example

```margeux
use "std/vec3"

def moved-forward [position]
  vec3.add position (vec3.vec3 0 0 1)
```

### `Vec3`

record

```margeux
record Vec3
  x: Float
  y: Float
  z: Float
```

### `add`

function

```margeux
def add [left: Vec3 right: Vec3] -> Vec3
```

### `cross`

function

```margeux
def cross [left: Vec3 right: Vec3] -> Vec3
```

### `distance`

function

```margeux
def distance [left: Vec3 right: Vec3] -> Float
```

### `dot`

function

```margeux
def dot [left: Vec3 right: Vec3] -> Float
```

### `length`

function

```margeux
def length [value: Vec3] -> Float
```

### `normalize`

function

```margeux
def normalize [value: Vec3] -> Vec3
```

### `scale`

function

```margeux
def scale [value: Vec3 amount: Number] -> Vec3
```

### `subtract`

function

```margeux
def subtract [left: Vec3 right: Vec3] -> Vec3
```

### `vec3`

function

```margeux
def vec3 [x: Number y: Number z: Number] -> Vec3
```

## Library: `std/vectors`

```margeux
use "std/vectors"
```

### Quick example

```margeux
use "std/vectors"

def positive-values [values]
  vectors.matches
    fn [value]
      > value 0
    values
```

### `all?`

function

```margeux
def all? [T] [predicate values: Vector[T]] -> Bool
```

### `any?`

function

```margeux
def any? [T] [predicate values: Vector[T]] -> Bool
```

### `at`

function

```margeux
def at [T] [values: Vector[T] index: Int] -> Result[T, String]
```

### `concat`

function

```margeux
def concat [T] [left: Vector[T] right: Vector[T]] -> Vector[T]
```

### `contains?`

function

```margeux
def contains? [T] [values: Vector[T] target: T] -> Bool
```

### `count`

function

```margeux
def count [T] [predicate values: Vector[T]] -> Int
```

### `drop`

function

```margeux
def drop [T] [values: Vector[T] count: Int] -> Vector[T]
```

### `find`

function

```margeux
def find [T] [predicate values: Vector[T]] -> Result[T, String]
```

### `find-index`

function

```margeux
def find-index [T] [predicate values: Vector[T]] -> Result<Int, String>
```

### `first`

function

```margeux
def first [T] [values: Vector[T]] -> Result[T, String]
```

### `index-of`

function

```margeux
def index-of [T] [values: Vector[T] target: T] -> Result<Int, String>
```

### `last`

function

```margeux
def last [T] [values: Vector[T]] -> Result[T, String]
```

### `matches`

function

```margeux
def matches [T] [predicate values: Vector[T]] -> Vector[T]
```

### `maximum`

function

```margeux
def maximum [T] [values: Vector[T]] -> Result[T, String]
```

### `minimum`

function

```margeux
def minimum [T] [values: Vector[T]] -> Result[T, String]
```

### `replace-at`

function

```margeux
def replace-at [T] [values: Vector[T] index: Int replacement: T] -> Result[Vector[T], String]
```

### `reverse`

function

```margeux
def reverse [T] [values: Vector[T]] -> Vector[T]
```

### `take`

function

```margeux
def take [T] [values: Vector[T] count: Int] -> Vector[T]
```

### `unique`

function

```margeux
def unique [T] [values: Vector[T]] -> Vector[T]
```

## Library: `std/workspace`

```margeux
use "std/workspace"
```

### Quick example

```margeux
use "std/workspace"

async def create-program []
  await workspace.create "main.mgx" "app Hello"
```

### `create`

async function

```margeux
async def create [path: String content: String] -> Result
```

### `delete`

async function

```margeux
async def delete [path: String] -> Result
```

### `paths`

async function

```margeux
async def paths [] -> Result
```

### `read`

async function

```margeux
async def read [path: String] -> Result
```

### `run`

async function

```margeux
async def run [entry: String] -> Result
```

### `write`

async function

```margeux
async def write [path: String content: String] -> Result
```
