Variables, templates, file loading, executables, and built-in methods form mlld's core syntax. exe defines reusable functions (templates, js, node, python, shell, commands); call them as @f(). run runs commands (run cmd { … }). => returns values from scripts and blocks. Records describe the shape and trust of data; sessions and tapes hold state across model calls and runs.
Variables
const vs exe: const creates a value (no parameters). exe creates a function (takes parameters).
const @name = "Alice" >> value - no params
exe @greet(who) = `Hi ${@who}!` >> function - takes params
>> Use const for computed values, exe for reusable functions
const @result = @greet(@name) >> "Hi Alice!"
show @result
A const never changes after it is created. It cannot be reassigned, and its fields cannot be set (@obj.key = 1 is an error). To make a changed copy, build a new value with spread: const @updated = { ...@obj, key: 1 }.
Inside a block (an exe body, an if or match block, a loop body, a try or box body), let declares a name that lives only in that block. Statements in that same block can change it with = or +=; a nested block cannot. See Local Variables.
Primitives, arrays, objects:
const @n = 42
const @price = 19.99
const @ok = true
const @arr = [1, 2, 3]
const @obj = {"key": "value"}
const @merged = { ...@obj, "extra": 1 } >> object spread
const @more = [0, ...@arr, 4] >> array spread: [0, 1, 2, 3, 4]
exe @add(a, b) = js { return a + b }
const @sum = @add(@n, 8) >> 50 (number preserved)
const @date = cmd {date} >> command result
const @readme = <README.md> >> file contents
An object literal names each key once: { a: 1, a: 2 } is a parse error that names both places, and "a", 'a' and a are the same key. A spread may still be overridden ({ ...@obj, key: 1 }).
A key in brackets is computed: { [@key]: @value } reads @key when the line runs and keeps the labels and proof on @value, so building an object with dynamic keys needs no js block.
Labels. Write security labels before the name: const .secret @apiKey = "sk-123". See the security docs for what labels do.
Object field destructuring:
Use from to bind same-name fields from an object or record. Missing fields bind as null; add ?? for per-field defaults.
const @cfg = { clean_task: "ship", model: "haiku" }
const { clean_task, model ?? "stub", harness ?? null } from @cfg
show `${@clean_task} ${@model} ${@harness}`
Inside blocks, use the same pattern with let:
exe @describe(cfg) = [
let { clean_task, model ?? "stub" } from @cfg
=> `${@clean_task} via ${@model}`
]
show @describe({ clean_task: "ship" })
Names are not reused. A const or let may not take a name that is already visible where it is declared, such as a top-level const seen from inside an exe. mlld reports an error and asks for a new name. Function parameters and loop variables are the exception: they may reuse a name.
See Also
- Conditional Inclusion - Omitting empty values and nullish fallbacks.
- Templates Basics - Putting values into text with backtick templates.
- Exe Basics - When to switch from
constvalues to reusableexefunctions.
Conditional Inclusion
Nullish fallback (@a ?? @b): use the right side when the left is null or missing. Chains work.
Conditional text (@c ? a : b): pick text based on a condition, with "" to leave it out.
Conditional items (@x? in arrays, "key"?: in objects): drop an item when its value is falsy.
>> In expressions: nullish fallback, chained
const @primary = null
const @secondary = "backup"
const @chosen = @primary ?? @secondary ?? "fallback"
show @chosen
>> In templates: fallback text
const @nickname = null
show `Hello, ${@nickname ?? "friend"}`
>> In templates: include a piece only when a value is set
const @title = "MyTitle"
const @empty = ""
show `DEBUG${@title ? `: ${@title}` : ""}`
show `DEBUG${@empty ? `: ${@empty}` : ""}`
In arrays and objects, a trailing ? on an item drops it when the value is falsy:
const @a = "first"
const @b = ""
const @c = "third"
const @list = [@a, @b?, @c]
show @list
const @n = "Ada"
const @t = null
const @obj = {"name": @n, "title"?: @t}
show @obj
In commands, work out the optional flag in mlld first, then pass it to the command as a shell variable with using { env }. Leave that variable unquoted in the command, so an empty value adds nothing:
const @tools = "json"
const @none = ""
const @toolsArg = @tools ? `--tools ${@tools}` : ""
const @emptyArg = @none ? "--empty" : ""
run cmd { echo $tools_arg $empty_arg } using { env: { tools_arg: @toolsArg, empty_arg: @emptyArg } }
This prints --tools json; --empty is left out because @none is empty.
What counts as falsy is listed in Truthiness Rules.
Truthiness Rules
Truthiness decides which branch if, match and for … if take. Falsy values: null, undefined, false, "", "false" (in any case, so "False" too), "0", "NaN", 0, NaN, [], {}. Everything else is truthy, including " false ", "0.0" and "null".
Numeric coercion
Truthiness governs conditions. A separate set of rules applies when a value is used in arithmetic (+, -, *, /, % — see Conditions and Operators). Each operand is coerced to a number first:
| Value | Becomes |
|---|---|
true |
1 |
false |
0 |
null |
0 |
numeric string ("11") |
the parsed number (11) |
non-numeric string ("hello") |
NaN |
| array or object | NaN |
missing field read (@obj.absent) |
0 |
So true + false is 1, "11" + 1 is 12, and null + 5 is 5. Adding a non-numeric string or an array yields NaN — + is arithmetic, not string concatenation. Use a backtick template to join text.
Because booleans coerce to 1/0, summing comparison results gives a count of how many passed. See the truthy-tally example in Conditions and Operators.
Templates
mlld has plain strings, which never interpolate, and three template forms, which do.
| Form | Puts values in with | Escapes |
|---|---|---|
"text", 'text' |
nothing: always literal | \n \t \r \0 \\ \" \' \u{…} |
`text ${@x}` |
${…} |
as above, plus \` and \${ |
::text ${@x}:: |
${…} |
none, except \${ and \:: (raw) |
:::text {{x}}::: |
{{…}} |
\{{ and \}} |
Strings. Double and single quotes are literal text. @ is an ordinary character in them:
const @name = "Ada"
show "Contact: ada@example.com"
show 'Line one\nLine two'
Backtick templates put a value in with ${…}:
const @name = "Ada"
const @items = ["a", "b", "c"]
show `Hello ${@name}, you have ${@items.length} items`
Any mlld expression can go inside ${}: a field, a call, a pipe, a method, arithmetic, or a file load.
exe @shout(s) = js { return s.toUpperCase() }
const @user = { name: "ada", tags: ["x", "y"] }
show `Name: ${@user.name | @shout}`
show `Tags: ${@user.tags.join(", ")}`
show `Next year: ${2026 + 1}`
File loads work the same way: ${<README.md>} puts in the file's text, ${<guide.md # Setup>} puts in one section, and ${<notes.md>?} puts in nothing when the file is missing (without the ? a missing file is an error). A <file.md> written outside ${} is plain text.
Templates can span lines:
const @status = "green"
const @count = 3
const @report = `
Status: ${@status}
Count: ${@count}
`
show @report
Every reference must exist. A typo such as ${@mesage} is an error when the template runs; it never turns into literal text. To write ${ as text, escape it as \${. A bare ${name} without @ is an error that suggests this escape:
show `Shell style: \${HOME} costs $5`
An unknown escape such as "\d" is an error too; write \\d for a backslash followed by d.
Raw templates, ::…::. Use these for text full of backticks and backslashes, such as prompts that contain code fences. Backticks are ordinary characters, and backslashes are kept as written. Only \${ and \:: are escapes (\:: writes ::, for text like std\::io):
const @lang = "rust"
const @prompt = ::Review this ${@lang} code. Keep `use std\::io;` and C:\temp\new as written.::
show @prompt
Mustache templates, :::…:::. Inside these, only {{name}} puts in a value. @, ${…} and <file> are all plain text, which suits text that is itself mlld, or prompts that mention @path references for a model:
const @name = "World"
show :::Hello {{name}}, keep @path/to/file and <config.md> and ${this} verbatim:::
Longer templates can live in their own files: see External Template Files. Templates can also repeat lines with /for … /end: see Loops in Templates.
External Template Files (.att, .mtt)
For templates longer than a short paragraph, put the text in a file and define a function with exe … = template:
exe @welcome(name, role) = template "./prompts/welcome.att"
exe @systemPrompt(context) = template "./prompts/system.att"
>> Call like any other function
show @welcome("Alice", { title: "admin", permissions: ["read", "write"] })
.att files use ${…}, the same as a backtick template. The function's parameters are available by name:
Hello ${@name}!
Your role: ${@role.title}
/for @perm in @role.permissions
- ${@perm}
/end
${<prompts/house-rules.md>}
With @welcome("Alice", { title: "admin", permissions: ["read", "write"] }) this renders:
Hello Alice!
Your role: admin
- read
- write
(the contents of prompts/house-rules.md)
Key points:
- Parameters from
exe @func(params)are available as${@param}in the template. - Anything that works inside
${}in a backtick template works here: fields, calls, pipes, methods, and file loads such as${<file.md>}. /for … /endrepeats lines: see Loops in Templates.- An
.attfile is raw text like a::…::template: backticks and backslashes are kept as written, and@is an ordinary character. Only\${(a literal${) is an escape. - A reference that does not exist, such as
${@mesage.body}when the parameter ismessage, is an error that names the reference and the template file. - Call template files through
exe … = template. Loading an.attfile with<…>gives you its raw text, not a rendered template.
When to use external templates:
- Prompts longer than two or three lines
- Templates with loops or other structure
- Reusable prompt components
- Agent system prompts
.mtt files use {{name}} instead, like a :::…::: template:
exe @codeReview(files, instructions) = template "./prompts/review.mtt"
show @codeReview("src/utils.ts", "Look for unhandled errors.")
Review these files: {{files}}
{{instructions}}
Reference @src/utils.ts and <tests/utils.test.ts> for context.
In an .mtt file, @, ${…} and <file> are all plain text; only {{name}} puts in a value. Use it when the text itself is full of @ references or ${ that should reach the reader unchanged: mlld source, CLAUDE.md files, or prompts that quote paths for a model. An undefined {{name}} is an error; write \{{name\}} for literal braces.
| Extension | Values go in with | File loads | Loops | Use when |
|---|---|---|---|---|
.att |
${@var} |
${<file.md>} |
/for … /end |
The default |
.mtt |
{{var}} |
none | none | The text is full of @ or ${ meant for the reader |
The same two styles are available inline, without a file: backtick or ::…:: templates for .att-style text, :::…::: for .mtt-style text. See Templates Basics.
Loops in Templates
Inside a template, /for … /end repeats the lines between them once per item. It works in backtick templates, ::…:: templates and .att files.
const @items = ["alpha", "beta", "gamma"]
const @toc = ::
/for @item in @items
- ${@item}
/end
::
show @toc
This prints:
- alpha
- beta
- gamma
The lines between /for and /end use the same ${…} as the rest of the template, so fields and calls work:
const @people = [{ name: "Ada", role: "admin" }, { name: "Lin", role: "dev" }]
const @table = `
| Name | Role |
|------|------|
/for @p in @people
| ${@p.name} | ${@p.role} |
/end
`
show @table
Rules inside templates:
/forand/endmust start at the beginning of their line.- There is no
=>: the lines between/forand/endare the body. /forand/endare the only directives a template understands. Any other line that starts with/is plain text and appears in the output as written.- The loop takes one variable (
/for @item in @items), or a key and a value as a top-levelfordoes (/for @key, @value in @obj): over an object the key is each property name, over an array each index. :::…:::templates and.mttfiles have no loops.
Top-level for vs template /for. Outside templates, for is a statement:
const @items = [{ name: "alpha" }, { name: "beta" }]
for @item in @items => show `- ${@item.name}`
Without a loop. For a one-line list, a method call inside ${} is often shorter:
const @items = ["alpha", "beta"]
show `Items: ${@items.join(", ")}`
File Loading
>> Basic loading
const @content = <README.md>
const @config = <config.json> >> auto-parsed as object
const @events = <events.jsonl> >> auto-parsed as array of JSON objects
const @author = <package.json>.author >> field access
show @events[0].event >> first JSONL record
>> Globs (returns array)
const @docs = <docs/**/*.md>
show @docs.length
for @doc in @docs => show @doc.mx.filename
>> JSON globs - each item is auto-parsed
const @configs = <configs/*.json>
const @first = @configs[0]
show @first.name >> access parsed JSON
show @first.mx.data.name >> explicit parsed-data view
show @first.mx.text >> raw file text
show @first.mx.filename >> file metadata still available
>> One line per file, with @item bound to each file
const @toc = @docs.map(`- [${@item.mx.fm.title}](${@item.mx.relative})`).join("\n")
The same list, written on the load:
const @toc = <docs/**/*.md> as `- [${@item.mx.fm.title}](${@item.mx.relative})`
show @toc.join("\n")
An as template on a whole-file load or a glob renders each file, with @item bound to it as .map binds it: its text, and its .mx (relative, filename, fm, …). A single file gives one string, a glob an array of strings (an empty glob gives [], and an optional load of a missing file stays null). @item for a .json file is its parsed value. Pipes written in the load run first, on each file (<docs/*.md>|@upper as …``); a { … } code query's pipe instead receives the whole result once (see AST Selection). The rendered strings keep the files' labels. A quoted as "Title" renames a section, so it needs a selected section (below).
Structured values loaded from files are data-first:
@config.apiUrland@config.mx.data.apiUrlare equivalent.@config.mx.textis the raw text representation..mxis always the metadata view, even when the data has anmxkey. Read that key with brackets:@config["mx"].
Section selection - extract markdown heading blocks:
>> Single section (includes child headings)
const @overview = <guide.md # Overview>
>> Multi-section include list (comma-separated)
const @selected = <guide.md # "Quick Start", Other>
>> Include/exclude sets
const @filtered = <guide.md # "Quick Start", "Titled section", Other; !# "Another section title">
>> Optional include (no error if missing)
const @maybe = <guide.md # "Migration Notes"?, "Quick Start">
>> Fuzzy heading matching (case/punctuation-insensitive, prefix-based)
const @tldr = <guide.md # tldr> >> matches heading "TL;DR"
>> A heading path: the Install section directly under Setup
const @install = <guide.md # Setup > Install>
show @install.mx.qualified >> e.g. "Guide > Setup > Install"
>> A web page: the page is converted to markdown, then the section is selected
const @pricing = <https://example.com/product # Pricing>
Rules:
- Include items are comma-separated after
#. - Exclude items are comma-separated after
; !#(or; #). - Use quotes for multi-word titles and punctuation-heavy titles. Quoted titles are literal:
# "[@v]"looks for the heading[@v]. - To build a title from variables, write the selector as a backtick template:
<CHANGELOG.md # `[${@version}]`>. A bare# @namealso works and uses the variable's text. - Add trailing
?to an include selector to avoid errors when missing. - Missing non-optional include selectors throw an error.
- Heading matching is fuzzy prefix-based and picks the first heading match.
>separates the names of a heading path:# Setup > Installselects anInstallheading whose parent heading isSetup. A heading's parent is the nearest heading above it with fewer#s. The path need not start at a top-level heading, soSetup > Installalso matches inside# Guide/## Setup/### Install. Inside a path every name must match a whole heading (still ignoring case, spaces,_,-and punctuation), so# Setup > Instdoes not matchInstall.- When a path matches several headings (two
## Installunder one# Setup), the load is an array with one record per section, in document order, each withtext,title,body,level,qualifiedandparents. A path that matches once gives the section's text, as a single name does. In a list (# Setup > Install, Usage) every match is merged into one text. Paths also work in excludes (; !# Setup > Installremoves every match), with?, and through a variable (# @pathholding"Setup > Install"). - A quoted name is one heading:
# "A > B"looks for a heading titledA > B. Unquoted, a title that contains>is reached by leaving the>out, which matching ignores anyway. - A heading can carry an explicit id that keeps working when its text changes: write
## Install on Linux {#install}, and load it with<doc.md # install>or<doc.md # Setup > install>. An id goes wherever a heading name goes (lists, excludes,?, a variable, a quoted name). Ids compare exactly (case and all, no prefix), while titles match loosely; with one name, the first heading in the document that matches by title or by id wins. The id block is not part of the title:.mx.qualified,# ??listings,@item.titleand record titles leave it out, while the loaded text keeps it. A block counts as an id only in the form{#id}(letters, digits,_and-), optionally with.classorkey=valueentries, separated from the title by a space. Renaming a section withaskeeps its id unless the new text brings its own. - A
#line inside a fenced code block (three or more backticks or tildes) is code, not a heading: it is never selected and# ??does not list it. - A selected section knows where it sits:
.mx.qualifiedis its full heading chain ("Guide > Setup > Install", the document's titles rather than what you typed) and.mx.parentsthe titles above it, outermost first. A list that merges several sections has neither. See File Metadata. as "## New Title"renames a single selected section and keeps its body.aswith a backtick template replaces the whole section with the template, with@itembound to the section (@item.title,@item.body). To change only the heading, include the body:<guide.md # Setup> as `### ${@item.title}\n\n${@item.body}`. Both forms need exactly one selected section; over a glob they apply to each file's section. A heading listing (# ??) gives names and takes neither.- Use
; !#to start excludes.<file.md # tl;dr !# later>is invalid. - A URL load selects from the page after it is converted to markdown, so a heading is named as the converted page shows it. The selected text keeps the page's
.src:netlabel. - What a section load selects carries the file's labels, and the labels of any variable the selector reads:
<guide.md # @topic>is.secretwhen@topicis. - Section selection is done by mlld's built-in content selector. A program can import its own selector to serve its
#and{ … }loads; see Content Selectors.
Optional load - returns null for missing files, empty array for empty globs:
>> Missing file returns null
const @optional = <config.json>?
if @optional => show "Config loaded"
>> Empty glob returns []
const @matches = <*.nonexistent>?
show @matches.length >> 0
>> Existing file works normally
const @readme = <README.md>?
show @readme >> file content
As a function argument - pass a file reference directly:
exe @summarize(text) = `Summary: ${@text}`
show @summarize(<README.md>) >> loads the file, then calls @summarize with its content
This loads the file the same way as const @x = <README.md>: the argument carries the file's content and its security labels, and a missing file is an error. A quoted "<README.md>" is just text.
Variables in paths - a variable inside <…> is filled in: <@dir/guide.md>, <@dir/*.md>, <@root/@file>. @root starts at the project root.
In templates - load inside ${}: `Notes: ${<notes.md>}`. A <file> outside ${} in a template is plain text. See Templates Basics.
See Also
- File Loading Metadata - Access
.mx.filename,.mx.relative, and related metadata. - File Loading AST - Parse source into AST for structural analysis.
- Content Selectors - Write or import the selector that serves
#and{ … }loads. - Variables Basics - Combine file-loaded values with standard variable patterns.
AST Selection
A query in braces after a source file's path selects definitions from it by name. Leave a space before the {:
const @fns = <src/api.ts { createUser, deleteUser }>
show @fns
show prints the selected code, each definition separated by a blank line.
This page describes mlld's built-in code selection. A program can import a different selector for its { … } loads, such as one that reads paths in JSON; see Content Selectors.
Code selection reads every language listed under Languages, choosing the grammar by the file's extension in any case (.PY reads as .py). A file whose extension is not listed is an error that names it, so a glob such as <src/* { createUser }> that reaches a notes.txt fails, and one that reaches a README.md fails because markdown takes quoted patterns only. Narrow the glob to the source files (<src/*.ts { createUser }>).
Query forms
| Query | Selects |
|---|---|
createUser |
the definition with that exact name |
Invoice.total, Invoice.total.helper, Invoice.get* |
the definitions at that path through their enclosing classes, functions and modules, at any depth (see Paths) |
handle*, *Validator, *Request*, get? |
every definition whose name matches: * is any run of characters, ? exactly one |
*fn, *class, *var, *interface, *type, *enum |
every definition of that kind (*fn is functions and methods, *type is type aliases) |
* |
every definition |
(helper) |
the definitions that mention helper (never a variable) |
??, fn??, class?? |
a sorted list of names, not records |
"console.log($$$)" |
every match of an ast-grep pattern |
Separate several items with commas. Definitions are top-level functions, classes, interfaces, enums, type aliases and variables, plus the methods of top-level classes: abstract methods and overload signatures count, and a method's code starts at its decorators. A class selected by * includes its methods, which are not listed again on their own.
A variable can supply the kind:
const @kind = "class"
const @classes = <src/api.ts { *@kind }>
const @classNames = <src/api.ts { @kind?? }>
show @classNames.join(", ")
The variable's value is read as one kind keyword, so it never adds items to the query. A variable that is not defined, or is empty, is an error.
A query cannot mix a name list (??) with other items: <src/api.ts { createUser, fn?? }> is the error Cannot mix content selectors with name-list selectors.
Paths
A name joined to the names it sits inside by . is a path. { Invoice.total } selects the total method of class Invoice and not one in class Receipt, and a path reaches definitions at any depth, such as a function declared inside a method:
const @total = <src/billing.ts { Invoice.total, Invoice.total.helper }>
show @total[0].qualified
A path matches the last names of a definition's full path. The names in a path are the classes, structs, traits, interfaces, enums, modules, namespaces, functions and methods a definition sits in. Blocks, closures, callbacks, anonymous classes and anonymous namespaces have no name and are skipped. So { total.helper } finds Invoice.total.helper, and { Invoice.helper } does not, because total is in between. Each name may be a wildcard ({ Invoice.get* }, { *.total }). A kind filter (*fn, *class, …) is not a name, so it cannot be part of a path: { *fn.helper } is an error, and { *.helper } finds helper inside any definition. A name a path cannot spell, such as a quoted Nix attribute ("org/gnome/shell"), a computed TypeScript member (['key']()), a C++ operator or a Dart getter, is still part of the path of everything inside it, written as in the source, so a wildcard reaches it: { settings.*.enable }. A C++ operator, a C# property, event, indexer or operator, a Dart getter, setter or operator, and a TypeScript member with a computed, private or quoted name (or a module named by a string) are never results themselves.
A path that matches several definitions returns all of them, in source order, each in its own position: { Invoice.total } also finds the method of a class Invoice inside a namespace Billing. A path that matches nothing is null in its position.
How names read as paths:
- Rust: the methods of
impl Invoiceand ofimpl Display for InvoiceareInvoice.total; type parameters are dropped (impl<T> Cache<T>isCache). A trait's methods are under the trait. Animplis not a result itself. - Go: a method is under its receiver's type, without
*or type parameters:func (b *Box[T]) Open()isBox.Open. - C++:
int Invoice::tax() { … }written outside its class isInvoice.tax, inside any namespace it sits in. - Ruby:
class Billing::ServiceisBilling.Service, anddef self.buildinsideclass FooisFoo.build, so{ Foo.build }finds both a class method and an instance method namedbuild. - TypeScript and JavaScript:
const helper = () => { … }andconst helper = function () { … }are a scope namedhelper, so{ helper.inner }reaches inside them. Nested inside another definition,helperhas the typefunction; at the top of a file it keeps the typevariable, as a name query gives it. A class field holding a function (handler = () => { … }) is amethodnamed by the field, its code the whole field with its decorators, so{ Invoice.handler.inner }reaches inside it. - Kotlin: an extension function is under its receiver's type, without type parameters:
fun <T> Box<T>.open()isBox.open. A companion object has no name of its own here, so a companion'screateisInvoice.create. - Swift: the members of
extension Invoice { … }are underInvoice. An extension is not a result itself. - Dart: a constructor is under its class and named by its parts, so
Point.origin()in classPointisPoint.Point.origin, and{ Point.origin }finds it. - C#:
namespace Billing.Core { … }andnamespace Billing.Core;both put what is inside them underBilling.Core. A destructor is~Invoice, which a path reaches by a wildcard:{ Invoice.?Invoice }. A property, an event, an indexer (namedthis) and an operator (operator+,operator int) are names in the path of what their accessors and bodies define, so a local function in a property's getter isInvoice.Total.Helper; they are never results themselves. - PHP:
namespace App\Billing { … }isApp.Billing. A namespace written without braces (namespace App;) is not part of a path. - Lua:
function M.fandM.f = function … endareM.f, andfunction M:fis the methodM.f. - Elixir:
defmodule Billing.InvoiceisBilling.Invoice. Consecutive clauses of one function are one result, as for a name query. Adefimplblock has no name here, so what it defines is under the module around it. - Haskell: functions and bindings in
whereandletare under the function they belong to (total.helper). The equations of a top-level function are one result, as for a name query; those of a function in awhereblock are one result each. - Nix: an attribute path is a path, so
a.b = …isa.b, andservices = { web = { port = 80; }; };givesservices.web.port. - HCL: a block's labels are its names, and its block type is its
type:resource "aws_s3_bucket" "logs" { … }isaws_s3_bucket.logs, typedresource. An attribute is avariableat any depth, so{ logs.bucket }selects thebucket = …line of that resource. A block without labels (locals,lifecycle) adds no name.
Paths work in every language that takes name queries. The separator is . only ({ Billing::Service } is not a code query), and a path cannot be a usage search: ( Invoice.total ) is not a code query either.
A file nested thousands of levels deep can give results whose paths add up to more than the larger of the file's size and 10 MiB. A query without a path then returns its records without qualified and parents, which read null. A query with a path is an error that says how large the paths are.
A definition the language's reader lists under Languages gives the same record by its path as by its name. One found only by a path, deeper than the reader reads, has the type its kind gives (function, method, class, …) and its own source as code: a TypeScript or Python decorator written above it is not included.
A quoted pattern is not checked for typos: one that does not parse as code in the file's language, such as "function (", is not an error and usually matches nothing, so a pattern that returns only null is worth checking. Many valid patterns parse only in context (C# "x => x * 2", Rust "|a| a * 2"), which is why a parse error is not refused. A token the parser can supply on its own still counts: "foo($A" reads as foo($A). A lone "$" is not a metavariable; in TypeScript and JavaScript it matches identifiers named $.
A name list (??) sorts by byte order, so a name with non-ASCII letters sorts after every ASCII one. A file with TypeScript-only syntax should be named .ts: read as JavaScript, the definitions that use it are lost.
Results
A definition query returns an array with one position per match, in query order. A match inside an earlier one is not returned again: * gives a class without listing its methods, and a pattern match inside another match is dropped. A pattern match on the same code as a definition the query also names is one entry, recorded as the definition. A name that matches nothing is null in its position rather than an error, so <src/api.ts { createUser, missing }> has two entries, the second null. A query that matches nothing never makes an optional load (<…>?) null; only a file that cannot be loaded does (it does not exist, cannot be read, or is not UTF-8 text).
Each record has these fields:
| Field | Value |
|---|---|
name |
the definition's name |
type |
the kind of definition, as its language names it (see Languages); match for a pattern match |
line |
the line the definition starts on |
qualified |
the definition's path joined by . (Invoice.total; Ruby's Billing::Service is Billing.Service; see Paths) |
parents |
the names the definition sits inside, outermost first (["Invoice"]). Both are null in a result whose paths pass the size limit |
code |
the definition's source, including a leading export |
file |
the file's absolute path |
relative |
the file's path relative to the project, starting ./ |
text |
the same as code |
.mx.name, .mx.type, .mx.line, .mx.qualified, .mx.parents, .mx.file and .mx.relative read the same values from a record's metadata:
const @handlers = <src/handlers.ts { handle* }>
for @h in @handlers => show `${@h.mx.name} (${@h.mx.type}) at ${@h.mx.relative}:${@h.mx.line}`
A record carries the labels of the file it came from and of any variable the query read.
.mx.fingerprint is a hash of a definition's code that ignores whitespace and comments, so a reformat or a comment edit leaves it the same and a change to the code changes it. See File Metadata.
Languages
Name queries work in these languages. Each reads the definitions listed, at the depth given, and the *kind filters and kind?? lists reach the types shown: *fn is function and method, *var is variable and constant, *type is type-alias, and *class, *interface, *enum, *struct, *trait and *module are the type of that name. A type no filter reaches (record, contract, event, …) is selected by name, by * or by ??.
| Language | Extensions | Definitions and their type |
|---|---|---|
| TypeScript, JavaScript | .ts .cts .mts .tsx .js .cjs .mjs .jsx |
top-level function, class, interface, enum, type-alias and variable; the methods of top-level classes as method |
| Python | .py .py3 .pyi .bzl .bazel |
module-level function, class and variable (each name an = assignment binds, a, b = … included); every def inside a class as method |
| Go | .go |
file-level function, method (by its own name), struct, interface, type (any other type declaration) and variable (var and const) |
| Rust | .rs |
file-level function, struct, enum, trait and variable (const and static); the fns of an impl as method |
| Java | .java |
top-level class, interface and enum; a top-level class's methods as method and constructors as constructor |
| Ruby | .rb .rbw .gemspec |
class and module at any depth, named with their enclosing names (Billing::Service); def as method inside a class and function elsewhere (def self.build is named self.build); NAME = … as constant |
| C, C++ | .c, and .cc .cpp .cxx .c++ .hpp .hh .hxx .h .cu .ino |
named class, struct, union and enum with a body, at any depth, function bodies included (a specialization Box<int> is named Box); function, or method inside a class (an inline friend too) or written Widget::compute; file-level variable. Namespaces, templates, extern "C" blocks and #if blocks are read through |
| C# | .cs |
class, struct, interface, enum and record, also inside namespaces; a class's or struct's methods as method (a destructor is the method ~Name), constructors as constructor, also inside #if blocks; a top-level public static int Count = 0; as variable |
| Solidity | .sol |
contract, interface and library with their function, constructor (named constructor), modifier, event, struct, enum and error members; top-level function, struct, enum and error |
| Kotlin | .kt .ktm .kts |
top-level function, class (an object too), interface, enum, type-alias, and properties as variable (constant for const val); in a top-level class, enum class or object (and its companion object), functions as method and secondary constructors as constructor |
| Swift | .swift |
top-level function, class (an actor too), struct, enum, protocols as interface, type-alias and let/var as variable; in a top-level type or extension, functions as method and init as constructor |
| PHP | .php |
top-level function, class, interface, trait, enum and const as constant, also inside a namespace { … } block; in a top-level class, trait or enum, methods as method and __construct as constructor |
| Scala | .scala .sc .sbt |
top-level function (a Scala 3 def), class (a case class or object too), trait, enum, type with a right-hand side as type-alias and val/var names as variable, also inside a package c { … } block; in a top-level class, object, trait or enum, and in an extension, every def as method |
| Dart | .dart |
top-level function, class (an extension type too), mixins as trait, enum, typedef as type-alias and variables as variable (constant for const); in a top-level class, mixin, enum or extension, methods as method and constructors as constructor, named Point or Point.origin |
| Lua | .lua |
top-level function (local and global ones too), M:f as method, and assignments: a function value as function, any other value as variable for a plain name |
| Elixir | .ex .exs |
defmodule as module and defprotocol as interface, at any depth; in them, def, defp, defmacro, defguard and defdelegate (and their private forms) as function, operators by their symbol (def a + b is +) |
| Haskell | .hs |
top-level function (a binding too, when its value is a lambda or its signature a function type; any other binding is a variable), data and newtype as struct, type as type-alias, and class as interface |
| Bash | .sh .bash .zsh and others |
top-level function and assignments as variable, including each name in export, readonly, declare, typeset and local |
| HCL | .hcl .tf .tfvars and others |
top-level blocks with a label, named by their last label and typed resource, data, variable, output, module or provider (any other block type is block); top-level attributes and those in locals as variable |
| Nix | .nix |
the bindings of the file's outermost attribute set, reached through a function, let, with, parentheses or an application such as mkDerivation (finalAttrs: { … }), and of every let on the way: a function value as function, any other value as variable |
A definition's code is its own source: a Python decorator or a Rust attribute written above it is not included, a C# attribute or Java annotation is. A Kotlin property's get() and set() are not part of its code.
In Kotlin, Swift, PHP, Scala and Dart, the members of a Kotlin or PHP interface and of a Swift protocol are not definitions, nor are nested types, enum cases, getters, setters, operators and fields. A query names a definition by letters, digits and _ only: a definition whose name has any other character (Dart's Point.origin) is reached by its path, { Point.origin }, or by a wildcard that spans the whole name, such as { *origin } or { Point?origin }. A Kotlin member written on the same line as its type's { is not read, and an object written that way (object O { fun f() {} }) is lost with its members; write members on their own lines. A Scala case class and its companion object are two class definitions with one name: { Point } gives the first. A Scala auxiliary constructor (def this(x: Int)) is a method named this, a destructuring val defines only the plain names at its top level (val (a, (b, c)) defines a), and a typed one (val (a: Int, b: String)) defines none. In PHP, the first declaration after a ?> … <?php break in the middle of a file is not read. A Dart member with no return type is a constructor only when it is named after its class.
In Lua, Elixir, Haskell, Bash, HCL and Nix, a qualified name is named by its last part: Lua's M.f is f, Elixir's defmodule MyApp.User is User, HCL's resource "aws_s3_bucket" "logs" is logs and Nix's a.b = … is b. Two definitions can then share a name; { logs } gives the first. Consecutive Elixir clauses and Haskell equations of one name are one definition whose code runs from the first to the last (an Elixir attribute such as @doc between them does not separate them; any other statement does); a clause written apart from the others is a definition of its own. A statement that names several variables (Lua local a, b = 1, 2, Bash export A=1 B) is each one's code. Not definitions: Lua M.x = 1 and t[k] = …; Elixir defimpl and what is in it, defstruct, defexception and module attributes; a Haskell pattern binding such as (a, b) = …, instance and type signatures; Bash += appends, array elements and an assignment before a command (Z=1 cmd); an HCL block with no label other than locals; Nix inherit and nested attribute sets. In Bash, a line with two assignments (a=1 b=2) followed by more assignment or blank lines and then a command can be read as one command, and then those assignments are not definitions; export -f name exports a function and is not a variable.
These languages take quoted ast-grep patterns only: CSS (.css .scss), HTML (.html .htm .xhtml), JSON, YAML (.yaml .yml) and markdown (.md .markdown). A name, wildcard, *kind, ?? or (name) item on one of them is an error, even beside a quoted pattern:
const @ports = <config/app.yaml { "port: $V" }>
show @ports
A pattern is parsed with the file's grammar, so it has to be something that grammar accepts on its own: in Solidity that is a declaration ("event $E($$$A);"), not an expression.
Globs
A definition query over a glob runs on each file in turn and joins the results into one array, each file's nulls included. A name list over a glob returns one { file, names } entry per file that has at least one matching name, file being the file's name:
const @byFile = <src/*.ts { class?? }>
for @entry in @byFile => show `${@entry.file}: ${@entry.names.join(", ")}`
A pipe on a query load receives the whole result once, the array of every file's positions on a glob, and what the last stage returns is the load's value: <src/*.ts { createUser, User }>|@json is the JSON of every position from every file, and a stage that returns the array keeps it an array. An as template after the pipe renders each element of what the pipe returned. If a stage fails on an optional load, a glob gives [] and a single file null.
Loading whole source files works without a query, one at a time or with a glob:
const @files = <src/**/*.ts>
for @f in @files => show @f.mx.relative
See File Loading, Content Selectors and File Metadata.
Content Selectors
A content selector decides what a load with a query returns. Every <file # Section> and <file { query }> load goes through one: mlld reads the file (or fetches the URL), hands the text to the selector with the query, and makes the selector's answer the load's value.
Without anything else in your program, the built-in selector serves every load:
# Sectionselects markdown sections, from a file or from a web page converted to markdown, and# Setup > Installselects by heading path. See File Loading Basics.{ … }selects code definitions by name or by pattern. See AST Selection.
A selected value's .mx.selector names the selector that produced it: "builtin", or the custom selector's module, name and a short hash of its code.
const @intro = <README.md # Introduction>?
show @intro.mx.selector
Writing a selector in mlld
A selector is declared like an executable, with four parameters and a block body:
selector @csvColumn(content, source, type, query) = [
if @source.ext != "csv" [ => null ]
if @type != "selector" [ => null ]
let @lines = @content.trim().split("\n")
let @header = @lines[0].split(",")
let @col = @header.indexOf(@query.trim())
if @col < 0 [ => [] ]
=> for @line in @lines.slice(1) => { text: @line.split(",")[@col], row: @line }
]
export { @csvColumn }
Saved as csv.mld, it selects one column of a CSV file. A program uses it by importing it by name:
import { @csvColumn } from "./csv.mld"
const @names = <people.csv { name }>
show @names
show @names[0].row
show @names.mx.selector
With people.csv holding name,role, ada,admin and bob,user, this prints ada and bob, then ada,admin, then ./csv.mld:@csvColumn#sha256: followed by 12 hex digits.
Which loads it serves
Importing a selector by name makes it serve every # and { } load written in the importing file, including loads written above the import line. Only the importing file is affected: a module it imports keeps its own selector, and an executable defined in another file loads with that file's selector.
These do not activate a selector:
- a namespace import (
import @mlld/selectors as @sel); - a selector declared in the same file as the load.
A file can activate one selector: importing two by name is an error before the program runs. To use different selectors for different files, load them from different modules.
Inputs
| Parameter | Value |
|---|---|
content |
the loaded text. A web page has already been converted to markdown for a # load |
source |
where the text came from: path (the file's absolute path), url (for a URL load), ext (the extension without its dot, such as "csv") and mime (such as "text/markdown"). A field that does not apply is null |
type |
"md" for a # load, "selector" for a { } load |
query |
the text after #, or between { and }, with any variables filled in; a quoted # "Name" gives the name without its quotes |
A selector never receives anything it could open. source.path is information only.
What it returns
| Return | Meaning |
|---|---|
an array of objects, each with a string text |
the selection: one entry per object, in order. Other fields stay on the entries (@names[0].row above) |
[] |
nothing matched. The load fails with Nothing in <file> matches the selection, and an optional load (<…>?) is null |
null |
hand back: the built-in selector serves the load as if no selector were active |
Handing back is how one selector covers only some files or some kinds of load. @csvColumn hands back every file that is not CSV and every # load, so <README.md # Introduction> in the same program still selects a markdown section.
The load is always an array, even for one entry. show prints each entry's text.
A selector may not set .mx on what it returns, or add labels. The selection carries the labels of the file and of any variable used in the query, plus .src:selector (below).
What a selector may do
A selector computes its answer from its inputs and nothing else. It cannot read data the load did not name, and it cannot act on the world.
- It may read its four parameters, its own
letandforvariables, other selectors, and the selectors of a namespace import. Any other name is refused, including the variables of its own module and ambient names such as@mx,@now,@root,@state,@payloadand@env. - It may use
let,if,for(notfor parallel),match,loop,=>returns, templates, objects and arrays, expressions,typeof, string, array and object methods that compute a value, and parsing transformers such as@parse,@jsonand@parse.yaml. - It may call other selectors and builtins that compute a value.
- It may not call an
exe, run a command or code (cmd,sh,js,py,node), load a file or URL (<…>), useshow,log,output,appendorrun, write state, use regular expressions (~=,.match, a regex.replace), or run in parallel (||).
Regular expressions are refused because a slow match cannot be stopped in time.
A refusal is an error that names the selector and what it refused:
mlld: @secret is not visible inside selector @leaky: a selector reads only its inputs (content, source, type, query), its own variables and other selectors
mlld validate reports what it can tell from the selector's body alone, with the code selector-purity.
Limits
mlld-config.json sets two limits for each selector call:
{
"selectors": {
"timeout_ms": 2000,
"max_memory_mb": 256
}
}
timeout_ms(default 2000) is how long one load's selection may run.max_memory_mb(default 256) is how much memory it may hold at once. Over it, the load fails withselector @s used more than N MB of memory (selectors.max_memory_mb in mlld-config.json). Only themlldcommand counts memory; a program that embeds mlld as a library gets the time limit and the next one, not this one.- Each value a selector builds, and the total text of a selection, may be at most 10 MB.
- A selector calling selectors counts toward the recursion limit (
MLLD_RECURSION_DEPTH).
Every value carries its file's paths, so a selector over a large file in a deeply nested directory uses more memory per line than the text alone suggests.
Errors
Any error inside a selector that the selector does not catch itself fails the load, like a missing file does, and a try around the load catches it. The error names the selector and the file. An error the selector raises does not show its own message, because that message could contain the file's content. For a selector @boom whose @content | @json fails on a markdown file:
mlld: Selector ./raise.mld:@boom#sha256:d3e9e837e9b7 raised an error while selecting from ./doc.md
A refusal from the rules above is never caught inside the selector: a try or denied => arm in its body does not turn one into a value.
Hooks and guards
No hook or guard fires for a selector call or for anything inside it, the same as for a plain load. Hooks and guards never see a selection's inputs: the whole file and the query. Guards see the load's result, with its labels, when the program uses it.
The .src:selector label
Every value a custom selector produces carries the label .src:selector. A selection by the built-in selector does not, including one the custom selector handed back. A policy can match it like any other label:
policy @selected = { .src:selector { deny: [.op:tool:w] } }
exe .op:tool:w @publish(d) = `sent:${@d}`
With this policy, passing a custom-selected value to @publish is refused, and the built-in's selections still pass. See Labels for how labels flow.
WASM selectors
A selector can also be compiled to WebAssembly. Declare it with the path of the compiled file:
selector @csvColumns = wasm "./csv_columns.wasm"
export { @csvColumns }
It activates the same way: a program imports @csvColumns by name.
Where the file may be:
- inside your project, by a path relative to the declaring file. An absolute path, a path that leaves the project, or a symlink that points outside it is refused;
- beside the
.mldfile of a registry module, which is how a published module ships one. mlld checks it against the lock file, as it checks the module.
A module from a URL, from GitHub or from another resolver may not declare one. A registry module's WASM selector starts serving at its import line, so a load written above that import is refused.
A local .wasm file is read under your filesystem policy, and a binary attestation rule applies to it at every load it serves. A registry module's file is attested by the lock file's content hash instead.
What the module must be:
- It may import nothing. That is what keeps it from reading files, the network or the clock, so WASI modules are refused. Build Rust for
wasm32-unknown-unknown. - It exports
memory,alloc(len: i32) -> i32andselect(ptr: i32, len: i32) -> i64. - mlld writes the input as UTF-8 JSON,
{ "content", "source": { "path", "url", "ext", "mime" }, "type", "query" }, into memory fromalloc, and callsselect.selectreturns the result's pointer shifted left 32 bits, joined with its length. The result is UTF-8 JSON in the shape an mlld selector returns: an array of objects with a stringtext,[], ornull. - The module may be at most 4 MB, and none of its functions may have more than 100 locals, parameters included. Its returned JSON may be at most 40 MB, and the selected text at most 10 MB.
timeout_ms and max_memory_mb apply as for an mlld selector. A WASM selector's time is counted in instructions, priced so that the budget stops the slowest code a module could run, so ordinary code finishes well inside it.
A WASM selector serves loads only; calling @csvColumns() from mlld code is refused.
crates/mlld-selector-sdk in the mlld repository is a Rust crate that provides the glue: write fn select(input: Input) -> Output and call selector!(select). crates/mlld-selector-sdk/test-selectors/csv-columns is a complete example.
@mlld/selectors
The @mlld/selectors module holds two ready-made selectors:
@jsonSelectselects values by path from JSON and YAML:<config.json { servers.*.port }>;@htmlSelectselects elements by CSS selector from HTML files and web pages:<page.html { article h2 }>.
import { @jsonSelect } from @mlld/selectors
const @ports = <config.json { servers.*.port }>
show @ports
The module's README describes both selectors in full.
See Also
- File Loading Basics - Sections, globs and optional loads.
- AST Selection - The built-in code queries.
- File Loading Metadata -
.mxon loaded values.
File Metadata
Metadata fields (via .mx):
const @file = <README.md>
show @file.mx.filename >> "README.md"
show @file.mx.ext >> "md"
show @file.mx.relative >> path relative to the project root
show @file.mx.absolute >> absolute path
show @file.mx.path >> alias for absolute path
show @file.mx.dirname >> parent directory name
show @file.mx.relativeDir >> relative path to directory
show @file.mx.absoluteDir >> absolute path to directory
show @file.mx.tokens >> token count estimate
show @file.mx.fingerprint >> "sha256-…", a hash of the content
show @file.mx.fm.title >> frontmatter field
show @file.mx.text >> raw text representation
show @file.mx.fm >> frontmatter object
.mx.selector names the selector that picked the content of a # … load: "builtin", the markdown section selector that serves every load today. A load that selects nothing, such as a whole file or a whole glob, ran no selector, so .mx.selector is undefined there.
A markdown section selected on its own (<guide.md # Install> or <guide.md # Setup > Install>) also has .mx.qualified, its full heading chain as the document titles it ("Guide > Setup > Install"), and .mx.parents, the titles of the headings above it, outermost first (["Guide", "Setup"], or [] for a top-level heading). Both are read from the file, so they carry the file's labels. A section whose heading carries an id (## Install on Linux {#install}) also has .mx.heading, the id ("install"), read from the file with its labels; it is undefined when the heading has none. A selection that merges several sections (# Install, Usage) has none of the three: they are undefined. When a path matches several sections the load is an array, and each record carries qualified and parents as fields, and heading when its heading has an id. (.mx.id is a state's id and stays null on a section.)
.mx.fingerprint is a hash of the content as it was loaded, so you can store it and compare later to see whether the content changed. It is sha256- followed by 64 lowercase hex digits. A whole file, a URL page, a section, each element of a glob, and each record a selector returns has one. Two rules decide what counts:
- Text (files, pages, sections, and records from a custom selector): all text counts, except that every run of spaces, tabs and newlines counts as one space and the ends are trimmed. An HTML file is hashed as its original markup, so an edited attribute or comment changes it.
- Code (definitions the built-in code selector returns, such as
<api.ts { createUser }>): the definition's syntax tree counts, so reindenting it or editing its comments leaves the fingerprint the same, while renaming something, changing a string, or moving a statement into or out of a block changes it. Layout never changes it, and that has one cost: in some languages (YAML and Solidity strings, Scala and HCL string interpolation) an edit that changes only the spaces inside a string is not detected, though any other edit to it is. See Code Selection.
The fingerprint describes the content as loaded: a value made from it keeps it, so @record | @json has the record's fingerprint, not one of the JSON text. It carries the content's labels. It is undefined where nothing was loaded on its own: a glob's list, a code query's list of results, a name listing, and a value read back from a checkpoint or run tape. It is computed only when you read it, and it is not part of the whole .mx view or what a js block sees of .mx.
.mx.ext is the last extension without the dot, as written ("gz" for a.tar.gz, "" for a name with none). A URL load (<https://…>) also has .mx.url, the full URL, and .mx.domain, its host without the port; both are null on a file load. .mx.ext carries no label. The fields that repeat the path or URL you wrote (filename, relative, absolute, path, dirname, relativeDir, absoluteDir, url, domain) carry that reference's labels and trust, so <@secretPath>.mx.relative stays .secret wherever it goes.
For frontmatter metadata, use .mx.fm:
@file.mx.fm.titleaccesses thetitlefrontmatter field.- Use
.mx.textand.mx.fmwhen you need explicit control. - If frontmatter has an
mxkey, read it with brackets:@file.mx.fm["mx"].
In loops - metadata works directly:
const @files = <docs/*.md>
for @file in @files => show @file.mx.filename
for @file in @files => show @file.mx.fm.status
Saved pointers
A saved pointer is a short string that names one definition or one section, so a decision, a doc or a ticket can point at it and find it again later. It is the same as a load, written compactly:
| Pointer | The load it stands for |
|---|---|
src/billing.ts:{Invoice.total} |
<@root/src/billing.ts { Invoice.total }> |
notes/spec.md:#Setup>Install |
<@root/notes/spec.md # Setup > Install> |
@pointerOf(value) writes the pointer for something you loaded, and @resolve(pointer) loads it again:
const @install = <notes/spec.md # Setup > Install>
const @p = @pointerOf(@install)
show @p
show @resolve(@p)
This shows notes/spec.md:#Setup>Install, then the Install section's text.
- The path is relative to the project root (
@root), whatever folder the script is in, and uses/. It names one file in the project: no absolute path,.., URL, glob characters or@. - The
{or#after the colon is what makes a pointer, so a line citation (main.py:123) or a record address (contact:44d1) is never read as one.@resolvesays which one it looks like. - A code pointer names one definition by its path,
{Invoice.total}or{helper}: no list, wildcard or kind filter. A section pointer names one heading path,#Setup>Installor#Install: no list, exclude or?. @pointerOfwrites the definition's full path (qualified) or the section's full heading chain, not what you typed:<notes/spec.md # Inst>givesnotes/spec.md:#Setup>Installwhen that is where Install sits. A heading is written as one word, with every run of spaces and punctuation as one-(Getting StartedisGetting-Started), which matches the same heading because matching ignores case, spaces and punctuation.@resolvereturns exactly what the load returns: a code pointer gives a list (a definition that is gone isnullin it), one section gives its text, and a heading that matches several sections gives a list of section records. A missing file or heading is the load's error. The result carries the file's labels and the pointer string's own, and the read is checked by your policy as the load would be.@pointerOfgivesnullfor anything it cannot write a pointer for: a list (pass one element,@pointerOf(@defs[0])), a whole file, a merged selection (# A, B), output of a custom selector, a page loaded from a URL, a file outside the project or under a folder with[or@in its name, a definition with no path (a quoted pattern match), a section under a heading made only of characters matching ignores (an all-emoji or all-CJK title), and a value that no longer carries its load metadata (@x.text,@upper(@x)).- Both work as pipeline stages:
@p | @resolve,@record | @pointerOf. A script's own@resolveor@pointerOftakes precedence over the built-in. @resolve(pointer, { optional: true })is the load's optional form: a missing file or a heading that matches nothing givesnullinstead of an error (a missing definition is stillnullin the list). Every other failure, such as a malformed pointer or a read your policy denies, is still raised. Thenullcarries the labels the error would have carried.- To pin a pointer with its target's fingerprint and check later whether the target changed, use the
@mlld/linksmodule; see Links.
A pointer selects what its load selects, so it finds the same target only while that load is unambiguous. A one-name pointer ({total}, #Setup) takes the first match, which an earlier definition or a heading starting with the same words can change. A path matches the end of a chain, so #Setup>Install also finds an Install under # Guide > ## Setup, and every match is returned.
Links
The built-in module @mlld/links keeps track of something a decision, doc or ticket points at, and tells you later whether it changed. A link is a saved pointer together with the fingerprint of what it pointed at when it was made:
import { @link, @linkOf, @check } from @mlld/links
const @pinned = @link("notes/spec.md:#Setup>Install", "the install steps")
const @state = @check(@pinned)
show @state.status
This shows same until the Install section changes. Store @pinned (it is a plain object, { target, fingerprint, focus }) and check it again later.
@link(pointer, focus?)pins whatpointernames now.focusis an optional note for people; the check never reads it. It refuses when the pointer names nothing, or more than one target.@linkOf(value, focus?)pins a definition or section you loaded, through@pointerOf. It refuses a value no pointer can be written for.@check(link)gives{ status, fingerprint }:
status |
Means | fingerprint |
|---|---|---|
same |
the target's fingerprint is the pinned one | the current one |
changed |
the target is there but different | the current one, to re-pin with |
gone |
the file, heading or definition is not there | null |
ambiguous |
the pointer now names more than one target | null |
A code target's fingerprint ignores layout and comments, so reformatting it reads same; a section's counts all of its text, so a one-character edit reads changed.
The check reloads the target with @resolve(…, { optional: true }), so it meets the same read checks and policy a load does, and what it reads carries the file's labels. A read your policy denies is raised as a denial, which a denied => arm or try in your code can catch; it is never reported as gone.
Limits:
- A pointer selects what its load selects. A one-name pointer (
{total},#Setup) takes the first match, so it is never reportedambiguous, and a one-name section pointer matches the first heading that starts with its words: a## Setup Guideadded above# Setupcaptures#Setup, and the check then compares against the wrong section.@pointerOfwrites the full chain, which narrows this, but a top-level heading or function is still a one-name pointer. - Renaming the target reads as
gone.
JSON Parsing
Parse JSON explicitly with transforms:
>> When you have a JSON string and need to parse it
const @jsonStr = '[{"name":"Alice"},{"name":"Bob"}]'
const @parsed = @jsonStr | @parse
show @parsed.0.name >> Alice
>> When you have an object and need the JSON string
const @obj = {"name": "Alice"}
const @str = `${@obj}`
show @str >> {"name": "Alice"}
>> LLM replies often wrap JSON in prose or a code fence; @parse.llm extracts it
exe @llm(prompt) = js { return 'Here you go:\n```json\n{"items": ["a", "b"]}\n```' }
const @response = @llm("return JSON") | @parse.llm
show @response.items >> ["a", "b"]
Frontmatter
A YAML metadata block at the very top of an mlld file is its frontmatter. Read its fields through @fm:
---
name: my-module
author: alice
version: 1.0.0
about: Brief description
license: CC0
---
const @author = @fm.author
const @version = @fm.version
>> Build a metadata object
const @meta = {
name: @fm.name,
author: @fm.author,
version: @fm.version
}
show @meta.name >> my-module
Reading a field the frontmatter does not have gives null and prints a warning. A file with no frontmatter has no @fm, and reading it is an error.
exe
exe vs const: exe defines functions (takes parameters). const creates values (no parameters). Use exe when you need to pass arguments; use const for computed values.
Parameters are local to the call: a parameter named data does not change the caller's @data.
Simple forms:
>> Command — each parameter is a shell variable in the body
exe @list(dir) = cmd {ls -la "$dir" | head -5}
>> JavaScript — a plain JS sandbox: no require, process, or Buffer
exe @add(a, b) = js { return a + b }
>> Node.js — real Node: require, process, Buffer (no fetch; use @http)
exe @hash(text) = node {
const crypto = require('crypto');
return crypto.createHash('sha256').update(text).digest('hex');
}
>> Python
exe @addPy(a, b) = py { print(a + b) }
exe @calculate(x, y) = py {
result = x ** 2 + y ** 2
print(result)
}
>> Template
exe @greet(name) = `Hello ${@name}!`
>> Defaults
exe @welcomePerson(name, greeting = "Hello") = `${@greeting}, ${@name}!`
show @welcomePerson("Ada")
show @welcomePerson("Ada", "Hi")
>> Options object dispatch for multi-parameter exes
exe @compose(greeting = "Hello", name, punctuation = "!") = `${@greeting}, ${@name}${@punctuation}`
show @compose({ name: "Mina" })
>> External template file
exe @welcome(name, role) = template "./prompts/welcome.att"
Command notes:
- Each parameter reaches a
cmdbody as a shell variable of the same name, and the shell expands it: write"$dir". Quote it unless you want the shell to split it into words. - Because the value arrives as a variable, the shell never reads it as part of the command.
- To use any other value, pass it with
using { env: { name: @value } }, written before the=. An env value must be a bare@variable, so bind a field or a computed value to its own name first:
const @config = { target: "staging" }
const @target = @config.target
exe @deploy() using { env: { target: @target } } = cmd { echo "deploying to $target" }
show @deploy()
Effect labels limit the body: an exe can declare the effects its body has with .fs: and .net: labels, as in exe .net:w @send(msg) = cmd { … }. Once an exe carries any of these labels, its cmd, sh, bash, py or node body runs in a box that allows only what it declared: no network without a .net: label, and no file writes without .fs:w or .fs:rw. So exe .net:w @send(…) can reach the network but cannot write files. An exe with no .fs: or .net: label is not boxed. See Labels for the full rules.
Python notes:
- Use
print()to return values (captured as string output) - Parameters preserve their original mlld types (
int,float,bool,str,list,dict,None) - Standard library available:
import json,import math, etc. - Cast only when you intentionally need conversion
Parameter defaults:
- Use
name = valuein the parameter list. A parameter with a default can be omitted. - Passing
nullalso uses the default; other falsy values (false,0,"",[],{}) are passed as-is. - Defaults evaluate when the exe is called and can reference earlier parameters.
- For multi-parameter exes, a single object argument whose keys match parameter names binds by field name. This is the named-argument idiom:
@compose({ name: "Mina" }).
Extra arguments: an argument with no parameter to receive it is an error, not silently dropped. The error names the function, its parameters and the extra argument. In a pipeline stage the piped value fills the first parameter, so it counts too:
exe @greet(name) = `Hello ${@name}`
show @greet("Mina")
>> show @greet("Mina", "Lee") error: @greet takes 1 parameter (name); "Lee" has no parameter to receive it
>> show "Mina" | @greet("Lee") error: ... and the piped value fills name; "Lee" has no parameter to receive it
mlld validate reports the same mistake (call:extra-argument) for calls to an exe declared in the same file.
By-name arguments:
Any call can name its arguments. A name: value pair (a bare name, a colon, and a space) inside a call's parentheses is a by-name argument, and an unquoted value there is text, the same as when it is positional:
exe @greet(msg, tone) = `${@tone}: ${@msg}`
show @greet(msg: "hi", tone: "warm")
show @greet("hi", tone: "warm")
show @greet(tone: warm)
- Positional and by-name arguments may mix, positional first. A positional argument after a named one is an error.
- An unknown name is an error naming the parameter and the real ones.
- A parameter given twice — by position and by name, or by name twice — is an error.
- A left-out parameter behaves as one left off the end of a short positional call: a declared default fills it (
@d("x", c: "z")fillsbfrom its default); without a default it is absent (a template body errors on the reference, ajsbody seesundefined, ashbody sees an empty shell variable). name: valuewith no space after the colon stays one positional text argument (@f(a:b)passesa:bas text).
Typed parameters: a parameter can declare its type, and every call is checked against it. Nothing is converted, so a call passing a number where a string belongs is refused. See exe-metadata for the types and what a field type such as @contact.email requires.
exe @repeat(text: string, times: number) = js { return text.repeat(times) }
show @repeat("ab", 3)
LLM executables: An LLM-call executable is its own kind of exe. Define it with the llm keyword — this is the canonical form, and the outside calls it makes are recorded on the run tape:
llm @review(file) = template "review.att"
mlld run <script> --resume continues an interrupted run from its last snapshot, answering calls it already made from the tape instead of calling the model again. See Checkpoint & Resume.
See Also
- Exe Blocks - More
exebody styles including multi-step blocks. - Run Basics -
rundirective patterns and when to preferrunoverexe. - Run Params - Parameter passing semantics for command and shell execution.
Script Return
=> @value at the top level of a script ends the script immediately. if blocks are transparent to =>, so a => inside a top-level if block ends the script, not just the block. The same holds for the arm blocks of a match used as a statement.
Basic script return:
=> "final result"
show "unreachable"
Script return from conditionals:
if @condition [
=> "early exit"
]
=> "fallback"
const @mode = "fast"
if @mode == "fast" [
if @ready [
=> "immediate"
]
]
=> "deferred"
Module default export:
Imported .mld modules expose script return values through default:
>> module.mld
const @status = "active"
=> { code: 200, status: @status }
const @unreachable = "never runs"
>> main.mld
import { default as @result, status as @s } from "./module.mld"
show @result.code >> 200
show @s >> active
Scripts without => do not emit implicit final return output. Use => explicitly when module consumers need a default export value.
In exe blocks:
=> @value returns from the function body. See exe-blocks for function return syntax.
=> always acts on the innermost of these that encloses it: an exe body (it returns), a for body (it gives the value for that item), or an arm block of a match used as a value (it gives the arm's value). if blocks and statement match arm blocks pass it through. A loop body does not accept =>; a loop ends with done.
exe @validate(input) = [
if !@input [
=> { error: "missing" }
]
=> { ok: @input }
]
Returning different values to mlld code vs. LLM tool callers:
An exe can split its return into two channels — the => canonical return (for mlld code) and a -> tool return (for an LLM that called it as a tool). See exe-tool-return for the -> and =-> sigils, strict mode semantics, and the multi-reach polymorphism rule. Exes without any -> or =-> are in classic mode — the => value is used for both consumers.
Exe Tool Return (-> and =->)
An exe can return one value to mlld code that called it and a different value to an LLM that called it as a tool. The two return channels are => (mlld-canonical) and -> (LLM-facing).
This matters when an exe has two different consumers:
- the canonical mlld/runtime path, which often wants a domain record or full internal result
- the LLM tool caller, which may need either the same projected domain result or a deliberately different planner-facing envelope
In practice this yields two common secure patterns:
- canonical record return for domain data —
=> @value as record @Type,=> record @schema, or=> @cast(@value, @schema)so the bridge applies the active.role:*read projection - explicit
->return for differentiated planner-facing results — status, counts, summaries, or a planner-specific object that intentionally differs from the canonical return
No session protocol, no callbacks — just two return paths from a single function.
The three sigils
| Sigil | Writes to | Returns? | Meaning |
|---|---|---|---|
=> |
canonical slot | yes (early return) | mlld-canonical — what const @r = @exe(...) binds to |
-> |
tool slot | no (passive slot write) | LLM-facing — what an LLM sees as the tool result |
=-> |
both slots | yes (early return) | "both consumers see this value" — the dual sigil |
=> and -> are not two flavors of the same thing. They are two different relationships between the exe and its consumers. =-> is a convenience sigil for the common "both consumers see this value" case.
Basic usage
import { @agent } from @mlld/multi-harness
exe @sendEmail(recipient, subject, body) = [
let @result = run cmd { email-cli send --to "$recipient" --subject "$subject" --body "$body" }
let @parsed = @result | @parse
-> { status: "sent", recipient: @recipient }
=> { ok: true, message_id: @parsed.id, full_response: @parsed }
]
>> Called from mlld code — binds the `=>` value:
const @r = @sendEmail("alice@example.com", "hi", "body")
>> @r is { ok: true, message_id: "...", full_response: {...} }
>> Called as a tool by an LLM — LLM sees the `->` value:
const @reply = @agent("Email alice", { tools: [@sendEmail] })
>> The LLM receives { status: "sent", recipient: "alice@example.com" } as the tool result
Ordering matters. => terminates the block; -> is a passive write that continues execution. When using both, -> MUST come before =>. A statement after => is a parse error: "Unreachable statement in exe block. => terminates the block; move statements before it."
Where -> can go. -> and =-> work at the top level of the exe block and inside if, match and for blocks. Every -> the call reaches at runtime counts toward what the LLM sees (see multi-reach below), and mlld code calling the exe still gets the => value wherever the -> sits. Because a path that reaches no -> gives the LLM null (an mlld mcp client receives it as an empty text result), the safest way to give it different results on different paths is to compute the value first and write one -> (see the gate example below).
mlld validate, and running the file, print advisory warnings for an exe that writes ->: thin-arrow-exe-not-surfaced when no tools collection in the file lists it, and strict-tool-return-without-record when its => has no record. They are advice, not errors; the -> value still reaches the LLM or MCP client that calls the exe as a tool.
Strict mode
If the exe source contains ANY -> or =->, the exe is in strict mode. In strict mode:
- Tool dispatch ALWAYS uses the tool slot. The runtime does NOT fall back to the
=>value if no->was reached at runtime. - If no
->is reached (for example, an earlier=>inside anifreturned first), the tool slot isnull— NOT the=>value. - mlld code calling the exe still uses the
=>slot. Strict mode only affects what LLMs see as tool results.
Why strict mode matters. Suppose an exe returns its full internal state through =>, and only some paths write a ->. Under a "fall back to =>" rule, every path that missed its -> would hand the LLM the full internal state — the leak happens in exactly the case the developer meant to gate. Strict mode never falls back, so a missed -> gives the LLM null, not the state.
The safe pattern is to decide the LLM's view as a value, then write it with a single -> that every path reaches:
exe @gate(req) = [
let @toolView = match [
@req.flagged => { status: "blocked", reason: @req.flag_reason }
* => { ok: true, processed_state: @req.processed }
]
-> @toolView
=> { ok: !@req.flagged, full_state: @req.full_internal_state }
]
The LLM sees { status: "blocked", ... } when flagged and { ok: true, processed_state: ... } when not. It never sees full_internal_state; mlld code calling @gate still gets the full => value.
Multi-reach polymorphism
The tool slot's final value is determined by counting how many -> (or =->) statements were reached at runtime:
| Reaches at runtime | Slot value |
|---|---|
| 1 | the single value (any shape) |
| N > 1 | array of N values, in order of reach |
| 0 | null |
One -> [1, 2, 3] is one reach — the tool slot holds the array as a single value. Three separate -> "a", -> "b", -> "c" statements reached in sequence are three reaches — the slot holds ["a", "b", "c"]. Both produce the same JSON output, but the count rule is "wrap if more than one write," not "wrap if the value is an array."
A null slot means no -> covered the path that ran — usually a gap in the exe that strict mode surfaces rather than silently leaking the => value.
Composition: inner -> is invisible
import { @agent } from @mlld/multi-harness
exe @innerEmail(to, subj, body) = [
-> { status: "sent" }
=> { full: "..." }
]
exe @sendBatch(emails) = [
let @results = for @email in @emails => @innerEmail(@email.to, @email.subject, @email.body)
>> @results is an array of => values (the full ones).
>> The -> values from @innerEmail are NOT visible here. @sendBatch is mlld code
>> calling mlld code; -> only fires at LLM tool dispatch boundaries.
-> { sent: @emails.length }
=> { count: @emails.length, results: @results }
]
const @reply = @agent("Send all", { tools: [@sendBatch] })
>> LLM calls @sendBatch as a tool.
>> @sendBatch internally calls @innerEmail multiple times using the => path
>> because that's mlld-to-mlld, not LLM-to-tool.
>> @sendBatch returns its own -> value to the LLM: { sent: 3 }
-> has no semantics outside of LLM tool dispatch. Inner exe -> values do not propagate, accumulate, or bubble. Each exe's -> is consulted only when an LLM directly invokes that exact exe as a tool. There is no composition rule, no session protocol, no accumulator.
Only--> exes (LLM-only tools)
exe @logForLLM(msg) = [
-> { logged: @msg, ts: @now }
]
An exe with only -> and no => is in strict mode. Called from mlld code, its canonical slot is empty (effectively "returns nothing useful"). Called as a tool by an LLM, it returns the -> value. This is the pattern for tools that only make sense when invoked by an LLM.
Interaction with read projection and record coercion
-> bypasses producer-side reshaping:
- No implicit producer-side read projection on
->values. If you want the standard record-mediated planner view, prefer the canonical path —=> @value as record @Type,=> record @schema, or=> @cast(@value, @schema)— and let the bridge apply the active.role:*read projection. - No record coercion on
->values.=>still flows through the exe's output record adapter;->does not. - Producer-side taint follows the
->/=->expression itself. Values referenced in the tool-return expression contribute their labels and taint. Earlier tainted work elsewhere in the exe body does not taint the tool slot unless that data is used in the returned expression. - Explicit casts are still allowed before
->. If you want validation and record metadata on an intermediate value, do it yourself with@cast(@raw, @contact)or@raw as record @contactbefore writing->.->still will not add another coercion or projection step on top. - No
with { … }processing on->values: apipelineor otherwithoption on the exe does not run on them.
Consumer-side defenses still fire:
- Tool results are still labeled
.untrustedwhen they reach the LLM. If the LLM passes a->value on to a later tool call, that value does not count as a trusted, known input for authorization. - Source labels and provenance are attached when the result crosses to the LLM, the same as for
=>tool results. - Policy on tools applies to a call that returns through
->the same as to one that returns through=>.
See Security Getting Started for labels and policy.
Strict mode and -> give the developer control over the data SHAPE the LLM sees. They do not bypass the runtime's security model on the consumer side. A developer who returns sensitive data via -> does not thereby unlabel it.
Audit story: -> and =-> are grep-able by design. grep -rn "^\s*-> \|^\s*=-> " src/ finds every place data flows to LLMs via these channels.
When to use each
=>only (classic mode) — the default. Most exes. Use this when the LLM should see the normal projected record/domain result and there is no reason for a differentiated planner-facing tool result.=> + ->— when the planner-facing tool result should intentionally differ from the canonical return. Common cases: the exe processes tainted content or full state that mlld code needs to log/persist, but the LLM should only see clean attestation; or the planner should see a wrapper like{ found, contacts, summary }instead of the plain domain record alone.=->alone — when both consumers should see the same value and you want strict mode's explicit coverage. It replaces writing-> @vand=> @vas two statements.->only — when the exe is an LLM-facing tool with no mlld-code consumer. The canonical slot is deliberately empty.
See pattern-planner for the canonical persistent-session agent pattern that uses -> to expose workers as tools to a planning LLM.
Exe Metadata
Executables can include metadata for tooling and type safety. Tool-surface security contracts live on the entries of a tools collection, through inputs: @record, not on the executable itself.
Typed parameters:
exe @greet(name: string, times: number) = js { return "Hello " + name; }
exe @process(payload: object, format: string) = js { return payload; }
exe @count(items: array) = js { return items.length; }
exe @welcome(name: string = "Ada") = `Hello ${@name}`
Type annotations use : type syntax after the parameter name. A type is a primitive (string, number, boolean, object, array, handle), a record written @contact, or one record field written @contact.email. Add [] for a list (tags: string[], people: @contact[]) and ? for an optional value (tags: string[]?). The same syntax types record fields and state slots (see records-basics). A type names something defined above it: an unknown name, or one that is both a field definition and a record, stops the script when the executable is defined. A parameter takes a type or as record, not both.
Every call checks its arguments against these types and refuses one that does not fit, and nothing is converted: "5" is not a number. The check runs on every way of calling the executable: a direct call, a pipeline stage, a for body, a tool call from an LLM or an MCP client, and a guard resume. In a tool's JSON Schema a list is an array and a record is an object.
What a type requires:
- A primitive type (
body: string) is payload: the value is checked for its shape and needs no proof, like a record field without a kind. - A field type (
to: @contact.email, or afielddefinition with a kind) is that field's contract: its type, and proof of its kind. A value carrying.fact:*:emailfrom any record, or a value the user typed (@cite.user.intent.literal), is admitted; a bare string is refused. - A record type (
who: @contact) checks the value's shape and the proof of each field inside it that has a kind. - A parameter left untyped beside typed ones is not checked. On a tool that writes, it stays a control argument, as every parameter of an executable without an input record is.
A type only checks. The parameter is bound to the value the caller passed, with its labels unchanged: a typed parameter never creates proof.
record @contact [ email: string [ kind "email" ] ]
exe @lookup() = js { return { email: "ada@example.com" } } => contact
exe @send(to: @contact.email, body: string) = `sent to ${@to}: ${@body}`
const @c = @lookup()
show @send(@c.email, "hi")
const @r = match [
denied => `refused: ${@mx.guard.reason}`
* => @send("eve@evil.com", "hi")
]
show @r
The first call runs; the second is refused with Tool 'send' input 'to' must carry .src:user:intent:literal or fact proof, a denial a denied => arm can catch. A wrong type reads Tool 'g' input 'p' must be string, and a missing argument Tool 'g' is missing required input 'p'.
Typed parameters are checked one by one: nothing in a signature says two of them must come from the same record. To require that, give the executable an input record with correlate (see tool-definition). An executable takes its input record from its typed parameters or from with { inputs }, not both.
Optional parameters and defaults:
Defaults use = after the optional type annotation. A typed parameter with neither ? nor a default is required, and a call that leaves it out is refused. A T? parameter may be left out, which leaves it absent (@exists is false), or passed null. A defaulted parameter takes its default when it is left out or passed null. A literal default must fit its type, and a type that needs proof can't have a literal default, because a literal carries none; both stop the script when the executable is defined.
exe @greet(name: string, greeting: string = "Hello", note: string?) = `${@greeting}, ${@name}. note=${@exists(@note)}`
show @greet("Ada")
show @greet("Ada", null, "hi")
mlld validate reports an unknown parameter type (exe-param-type-unknown), a direct call passing a literal of the wrong type (exe-param-literal-mismatch), and a tool that writes whose parameters are all typed without a kind, so that nothing it takes is a control argument (exe-write-signature-without-kind).
Description metadata:
exe @greet(name: string) with { description: "Greet a user by name" } = `Hello ${@name}`
The with { description: "..." } clause adds a description that appears in MCP tool listings. On a definition, clauses go between the parameter list and =.
Combined example:
exe @ghSearch(repo, query, limit) = cmd {
gh issue list -R "$repo" --search "$query" -L "$limit" --json number,title
}
exe @searchIssues(repo: string, query: string, limit: number) with { description: "Search GitHub issues by query" } = [
=> @ghSearch(@repo, @query, @limit)
]
MCP integration:
When exported as tools, type annotations and descriptions generate JSON Schema for the MCP tool listing. For surfaced tool collections, richer tool docs and runtime validation come from the collection entry's inputs: @record, labels, description, instructions, and bind fields. See mcp-tool-gateway and records-basics.
Parameter types vs runtime:
A type only checks. The parameter is bound to the value the caller passed, with its labels unchanged.
Exe Block Syntax
Block syntax (multi-statement bodies):
exe @process(payload) = [
let @validated = @validate(@payload)
let @transformed = @transform(@validated)
=> @transformed
]
>> A loop returns what it collects
exe @activeNames(items) = [
let @names = for @item in @items if @item.active => @item.name
=> @names
]
Block rules:
- A body reads names where the exe was written: its parameters, its own
lets, and the top level of the module that defines it (its bindings and imports). It never reads its caller's variables or parameters, so pass a value in as an argument. A name none of those bind is an error naming the exe. An exe imported from another module reads that module's names, never the importer's. - Use
[...]for multi-statement bodies let @var = valuefor block-scoped variables. Aletorconstin a block may not reuse a name visible from outside it (a module binding, an import, a parameter, a loop variable, or an outer block'slet); pick a new name. Parameters, loop variables and@inputmay reuse any name.@var += valueextends aletdeclared earlier in the same block (arrays/strings/objects); to collect across a loop or branch, return the values from it (let @xs = for @x in @items => …)=> valueends the body and returns from the exe. A=>inside anifblock, or inside a statementmatcharm block, also returns from the exe; a=>inside aforbody only gives that item's value (seescript-return)-> valuewrites the LLM-facing tool slot without terminating;=-> valuewrites both slots and terminates (seeexe-tool-return)- When using both
=>and->,->must come before=>—->is a passive write that continues execution,=>terminates the block
js {} blocks share globals for the run. Every js {} body in a run sees the same global object, so a value one call stores on globalThis is there in the next:
exe @tick() = js { globalThis.n = (globalThis.n || 0) + 1; return globalThis.n }
show @tick()
show @tick()
Output:
1
2
The js language tool an agent calls is different: each of its calls gets a fresh engine, so nothing one call sets reaches the next (see language-tools).
Exe Match
Match as an exe body (first match wins). The function returns the value of the arm that matched:
exe @classify(score) = match [
@score >= 90 => "A"
@score >= 80 => "B"
* => "F"
]
show @classify(85)
With a subject, each arm is a pattern (see Match on a Subject):
exe @httpStatus(code) = match @code [
200 => "ok"
404 => "not found"
>= 500 => "server error"
* => "other"
]
show @httpStatus(503)
In a block body, return a match with =>:
exe @price(item) = [
let @subtotal = @item.cost * @item.qty
=> match [
@subtotal > 100 => @subtotal * 0.9
* => @subtotal
]
]
show @price({ cost: 30, qty: 4 })
Early return with if. Inside an exe block, => in an if block returns from the function:
exe @guard(x) = [
if !@x [
=> "missing"
]
=> "ok"
]
show @guard("")
if has no value of its own, so it cannot be an exe body. Use match, or a block that returns a ternary: exe @yesNo(b) = [ => @b ? "yes" : "no" ].
Exe Shadow Environments
Shadow environments expose helpers to all code blocks of that language:
>> JavaScript shadow environment
exe @double(n) = js { return n * 2 }
exe @cap(s) = js { return s[0].toUpperCase() + s.slice(1) }
exe js = { double, cap } >> expose to all js blocks
const @out = js { cap("hello") + ": " + double(5) } >> "Hello: 10"
>> Python shadow environment
exe @square(x) = py {
result = int(x) ** 2
print(result)
}
exe @greet(name) = py {
print(f"Hello, {name}!")
}
exe py = { square, greet } >> expose to all py blocks
run py {
square(4)
greet("World")
}
>> Output:
>> 16
>> Hello, World!
Cross-function calls: Shadow functions can call each other:
exe @add(a, b) = py { return int(a) + int(b) }
exe @multiply(x, y) = py { return int(x) * int(y) }
exe py = { add, multiply }
exe @calculate(n) = py {
sum_result = add(n, 10) # calls a shadow function
product = multiply(n, 2) # calls a shadow function
print(f"Sum: {sum_result}, Product: {product}")
}
show @calculate(5) >> Sum: 15, Product: 10
Inside a py or js body, comments use that language's syntax (# in Python, // in JavaScript); mlld's >> is not a comment there.
Supported languages: js, node, py/python
Calling mlld exes from code: shadow capture is the only way to call an mlld exe inside a code block. An exe passed as a runtime parameter arrives as a placeholder string ("[executable: greet]"), not a callable — calling it fails with not a callable function:
exe @greet(name) = `Hello ${@name}`
exe @callit(fn) = js { return fn("World") }
>> show @callit(@greet) fails: not a callable function
Capture the exe into the shadow environment instead, then call it by name:
exe @double(n) = js { return n * 2 }
exe js = { double }
exe @run() = js { return double(21) } >> 42
run
Decision tree:
- Single line + pipes only →
cmd { ... }(safe, recommended) - Needs
&&,||, control flow →sh { ... }(full shell; off until a policy setscapabilities: { sh: true }, seepolicy-capabilities) - JavaScript code →
js { ... }(plain JS sandbox) ornode { ... }(Node withrequireandprocess) - Python code →
py { ... }orpython { ... }(subprocess)
Every body names its language: write run cmd { … }, run sh { … } and so on.
Getting values in: a cmd body does not read mlld variables; pass each value in as a shell variable with using { env }, and in an exe a parameter is already $name. sh, js, node and py bodies likewise see only their own declared parameters. See run-params.
const @name = "Ada"
run cmd { echo "hi $name" } using { env: { name: @name } }
Calling an executable as a statement:
run @task()runs it and writes what it prints to the output.- A bare
@task()line runs it for its effects and discards its result. (Output ajsbody writes withconsole.logstill appears.) show @task()shows its result.
>> cmd (pipes only, safe)
run cmd {echo Hello | tr '[:lower:]' '[:upper:]'}
const @date = cmd {date}
>> sh (full shell scripts), switched on by a policy
policy @allow_sh = { * { capabilities: { sh: true } } }
run sh {
echo "testing" && echo "building" || echo "Build failed"
}
>> JavaScript — plain JS sandbox: no require, process, or Buffer
run js {console.log("hello")}
const @result = js {return 42}
>> Node.js — real Node: require, process, Buffer
const @hash = node {
const crypto = require('crypto');
return crypto.createHash('md5').update('hello').digest('hex');
}
>> Python (subprocess)
run py {print("hello from python")}
const @sum = py {
result = 2 + 2
print(result)
}
Processes a command leaves running
A command can start something that keeps running after the command returns: sleep 60 &, setsid server &, node's spawn(..., { detached: true }). mlld lets it run until the run ends, then stops it, whether the run succeeds, fails, is stopped with Ctrl-C, or is killed. A process that redirects its output (server >/dev/null 2>&1 &) lets the command return at once; one that keeps the command's output open holds the command until it exits.
Two kinds can still outlive the run:
- A daemon that forks twice, where the process in the middle exits at once. On macOS mlld catches it only when it sees that middle process before it exits; on Linux it is not caught.
- On Linux, a process that left its command's process group (
setsid) after the process that started it has already exited.
Apart from those two kinds, nothing a run starts outlives it, and there is no option to keep a process past the run. That includes programs that put themselves in the background: on macOS, gpg-agent --daemon and git credential-cache started from a run are still there for later calls in the same run, and both stop when the run ends. To hold a long-lived process for many calls within a run on purpose, use a service.
What js { } can reach
js { } is mlld's built-in JavaScript sandbox. Code inside it cannot reach the disk, the network or your environment: fetch, process and require are undefined, and import() of a file fails with "module resolution is disabled for this context". It can only compute with the values you pass in. When you need files, environment variables or npm packages, use node { }. For network calls, use the built-in @http:
const @res = @http.get("https://example.com")
show @res.status
@res has status, ok (true for a 2xx status), headers and body; a JSON body is parsed for you.
What node { } can reach
node { } runs real Node, but its code sees a fixed set of globals: require, process, Buffer, global, module, exports, __dirname, __filename, console, setTimeout, setInterval, setImmediate, their clear… partners, queueMicrotask, Promise, URL and URLSearchParams. Browser-style globals such as fetch, TextEncoder, TextDecoder, AbortController, Headers, structuredClone, atob, btoa and crypto are not defined. Node's built-in modules are available through require:
run node {
const { TextDecoder } = require('node:util');
console.log(new TextDecoder().decode(Buffer.from('hi')));
}
Language comparison:
| Language | What the code can reach | Use case |
|---|---|---|
js |
Plain JavaScript only — no require, process, Buffer, global |
Fast calculations, simple transforms |
node |
Real Node — require, process, Buffer, global; no fetch (use @http) |
Files, environment variables, npm packages |
py/python |
A Python subprocess | Python libraries, data science |
Run Command Working Directory
Working directory override:
run cmd:/ {pwd} >> runs in /
const @myPath = "/tmp"
run cmd:@myPath {pwd} >> runs in /tmp
run cmd:~ {pwd} >> runs in home directory
run node:/tmp {console.log(process.cwd())}
run cwd supports absolute paths, @var references, and ~ home expansion. An sh body takes one the same way (run sh:/tmp {pwd}) once a policy switches sh on; see run-basics.
Run Command Stdin
Stdin support:
const @data = '[{"name":"Alice"}]'
run cmd { cat | jq '.[]' } with { stdin: @data }
>> Pipe sugar (equivalent)
run @data | cmd { cat | jq '.[]' }
Run Parameter Syntax
Parameter syntax by language:
cmd: parameters as shell variables,"$param"; other values viausing { env }sh: use shell variables as$param(shis off by default; seerun-basics)js/node: parameters as JavaScript variablespy/python: parameters as Python variables (typed values)
A code body sees only its own parameters. sh, js, node and py bodies do not see variables from the surrounding script — not a top-level const, and not a let earlier in the same block. Parameters are the only way in.
mx is taken in js bodies. The runtime puts mx into a js/node body's scope, so declaring your own (const mx = …) fails with a JavaScript SyntaxError about mx being declared twice. Give your local another name.
In cmd and sh this is quiet rather than loud, because an undefined shell variable expands to the empty string. mlld prints a warning, but the command still runs, so a path built that way is built wrong, not left unbuilt:
const @runDir = "out/run-1"
>> WRONG - runDir is not a parameter, so "$runDir" is empty and this
>> means `mkdir -p /prompts`
run cmd { mkdir -p "$runDir/prompts" }
>> Pass it in
exe @setup(dir) = cmd { mkdir -p "$dir/prompts" }
run @setup(@runDir)
>> Or pass it in as an environment variable
run cmd {mkdir -p "$run_dir/prompts"} using { env: { run_dir: @runDir } }
How values reach a cmd body. Each value arrives as a shell variable and the shell expands it. The value is never read as part of the command itself, so quotes, semicolons or $(…) inside it stay plain text.
- Inside an exe, each parameter is already a shell variable:
exe @greet(name) = cmd { echo "hello $name" }. That holds for arun cmdinside the exe's block too. - A pipeline stage
@value | cmd { … }reads the piped value as$input(it also arrives on stdin), and an enclosing exe's parameters as$name. - Any other value comes in with
using { env: { name: @value } }. On arun,usinggoes after the body; on an exe, it goes before the=. An env name that is also a parameter's name is refused. - A
nullargument is an empty string in the shell, as insh; test it with[ -z "$name" ]. An argument left out is not set at all. Anullpassed throughusing { env }is an empty string too. - An env value must be a bare
@variable. To pass a field or a computed value, bind it to its own name first. - Quote the variable (
"$name") unless you want the shell to split it into words. @nameinside acmdbody is an error whennameis known at that point: a variable, exe, import, loop variable or parameter, or one of the built-ins that always hold a value (@root,@now,@debug,@mx,@hash,@fyi). The message gives both fixes: pass the value in and write"$name", or keep the@as text with'@name'or\@name(inside double quotes, end the quotes around it:"a "'@name'" b").${@name}is always an error.- Any other
@nameis plain text for the shell, sonpm install @types/nodeandcurl -d @data.jsonrun as written. An@glued to a word, as inme@host, is always text. Built-ins that hold a value only in some places are text elsewhere:@payloadand@testat top level,@inputoutside a pipeline stage. - One tradeoff: adding a variable later whose name matches a literal (say
const @types) turns that line into an error.mlld validateandmlld runcheck the whole file, so they report a name declared further down too; a run that skips that check refuses only names already bound when the command runs.
const @user = { name: "Ada" }
const @user_name = @user.name
run cmd { echo "hello $user_name" } using { env: { user_name: @user_name } }
sh bodies reach the shell verbatim too, and read their parameters the same way (see escaping-at).
>> JavaScript - parameters are typed values
exe @process(items) = js { return items.map(x => x * 2) }
const @result = @process([1, 2, 3]) >> [2, 4, 6]
>> Python - parameters are typed values
exe @add(a, b) = py { print(a + b) }
const @sum = @add(5, 3) >> 8
>> Python with complex types (a dict arrives as a dict)
exe @analyze(payload) = py {
import json
print(json.dumps(payload))
}
What a Python body receives: plain Python values. Strings arrive as str, arrays as list, objects as dict. Labels and other metadata do not travel into the body, and there is no mlld helper object inside it. A kept value (@x.keep) also arrives as the plain value. sh bodies refuse kept values: pass the @x.mx.* fields you need as separate arguments instead.
Builtins
Reserved Variables
@root- project root path@now- current UTC ISO timestamp, sampled on every read (for example,2026-09-22T19:33:50.123Z)@input- run inputs, read through a channel:@input.stdin,@input.env,@input.cli,@input.sdk(a bare@inputat the top level is an error). A script that declares its flags withargs ( … )reads them as typed names (@topic);@input.clistill holds the raw flags, and anargsparameter can't be namedinputorargs. Inside a guard or a pipeline stage,@inputis the value being checked or transformed.@state- the state the host supplied when it started the run (the SDKstateoption, or--stateon the command line). Declarestate external @app = { … }to read it with types and write it back; seesdk-state@debug- a fresh markdown snapshot of visible variables and statistics; system names omit their values, and user values are truncated to 50 characters@fm- current file's frontmatter (in modules)@mx-mxis the mlld execution context — ambient@mxis the context you're standing in, per-value.mxis the context of the value you're holding. Two distinct usage patterns:- Per-value:
@someValue.mx.fieldreads the execution context attached to a specific value: its labels, its taint, where it came from, and (for a loaded file) its frontmatter. - Ambient:
@mx.namespace.fieldreads runtime state for the current execution context (@mx.handles,@mx.llm.*,@mx.history). Seebuiltins-ambient-mx.
- Per-value:
@test- test-mode ambient namespace. Available only throughmlld test, hidden--test-mode, SDK{ testMode: true }, or SDKMLLD_TEST_AMBIENT=1(SDK embeds only — the CLI does not read that environment variable).
@uuid() returns a fresh UUID v4 string on every call, using the operating system's random source. It takes no arguments and requires no shell capability. Like other helper functions, a local binding can shadow it.
const @id = @uuid()
const @started = @now
show `Job ${@id} started at ${@started}`
@debug is display text, not a structured record. Each read reflects the current scope without executing lazy bindings or executable bodies. Partially computed values display a placeholder rather than an incomplete object or array. It groups environment, global, and user variables, followed by statistics. Output nodes is always 0. Its security metadata carries the labels of user values included in the snapshot.
@root resolution algorithm:
- Start at the current file directory and walk upward.
- Check mlld markers first (in order):
mlld-config.jsonmlld-lock.jsonmlld.lock.json
- If none are found, check fallback project markers:
package.json.gitpyproject.tomlCargo.toml
- The first directory containing any marker becomes
@root.
Built-in transformer/helper names are available for const/let declarations and are shadowable per scope:
@exists,@fileExists,@typeof@parse,@xml,@csv,@md@upper,@lower,@trim,@pretty,@sort@keep,@keepStructured@resolve,@pointerOf(saved pointers; seefile-loading-metadata)
Security primitives (dev-callable only — not exposed to agents directly):
@mintUserValue(value, options?)— marks a value as coming from the user and returns the value, so a tool that requires user-supplied input will accept it when your code passes it on.@mintUserValueHandle(value, options?)— the same mark, returned as a handle, for handing the value to an agent. Only a tool call the agent makes, into an input field with akind, turns the handle back into the value; your own code passing the handle passes the{ handle: … }object.
Code an agent controls (a worker downstream of untrusted data, or code an agent wrote) cannot call either one. Wrap, don't expose: build your own user-facing tools on top of them, each with its own check that the value really came from the user. See security-getting-started and facts-and-handles.
@project(value, readMode?) returns the record read-projected view of a value without invoking an LLM. Use it to audit what a role would see, for example @project(@recordValue, ".role:planner"). Non-record values pass through. If readMode is omitted, mlld uses the active scoped/default read selection. Outside an LLM bridge, handle-mode fields return null handles rather than minting bridge handles. Unlike the helper names above, it cannot be rebound, at the top level or in a block.
mlld validate reports builtin shadowing as informational output.
@keep / @keepStructured are embedded-language escape hatches. Use them when a value is about to cross into js, node, py, or sh and the block needs .mx / .data access. They do not preserve wrappers across ordinary mlld-to-mlld calls, and they do not survive object spread.
Reserved names
Some names cannot be bound at the top level with const or exe. Attempting it errors with "this name is already reserved by the system or a resolver prefix". This catches resolver prefixes too, so @root cannot be bound:
const @root = { one: 1 }
>> error: Cannot create variable '@root': this name is already reserved
>> by the system or a resolver prefix
The reserved set:
- System/static:
fyi,shelf,shelve,cast,mintUserValue,mintUserValueHandle,sigFind,sigWrite,sigVerify - Builtin resolvers:
now,debug,input,root,keychain - Execution context:
mx,test
Soft-reserved names can be bound, but mlld validate warns because the runtime injects them contextually (SDK @payload/@state, frontmatter @fm, pipeline context @pipeline/@p/@ctx): fm, payload, p, state, ctx, pipeline
shelf and shelve are reserved: mlld validate refuses binding either name, and calling a helper under either name stops with an error naming the state operation to use instead (see session-state and the migration guide).
Any configured resolver or module prefix is also reserved (e.g. a @work/ prefix reserves work).
@policy is not reserved.
The restriction is binding-only for most reserved names. test is stricter: binding @test is rejected at parse time in const, let, exe, import alias/selected import, hook name, guard name, and exe parameter positions. The match is exact; @test_mx and other test* names remain legal.
mlld validate flags reserved-name bindings ("conflicts with reserved name") so the conflict surfaces without running the file.
Transformers
Used with | in pipelines. Each receives the previous value.
@parse- parse JSON (default mode)@parse.strict- strict JSON only@parse.loose- relaxed JSON: single quotes, unquoted keys, trailing commas,//and/* */comments (the default@parseis the same). Hex numbers, a leading+or., andInfinity/NaNare not accepted@parse.llm- extract JSON from LLM response text. When the text holds no JSON it returnsnull, not an error, so check fornullbefore using the result@parse.fromlist- one line per item to an array of strings@parse.yaml/@yaml- parse YAML / structured text into a value@xml- convert a value to XML text@upper- uppercase string@lower- lowercase string@trim- strip whitespace@sort- sort an array, exactly as its.sort()method does (seebuiltins-methods)@pretty- serialize a value to a pretty-printed (2-space indented) JSON string. Given an object or array it returns the JSON text, not a structured value — use it when you want a human-readable string, not for further field access.
const @users = cmd { echo '[{"name":"Ada"}]' } | @parse
const @llmResponse = "Sure! {\"ok\": true}"
const @extracted = @llmResponse | @parse.llm >> { "ok": true }
const @items = <list.txt> | @parse.fromlist >> ["apple", "banana", "cherry"]
const @config = { name: "Ada", roles: ["lead"] }
const @text = @config | @pretty >> pretty JSON string
const @raw = " Hello World "
const @clean = @raw | @trim | @lower >> hello world
const @reply = "Sorry, I could not do that."
const @data = @reply | @parse.llm >> null
if @data == null [ show "the reply held no JSON" ]
These transformers are not available in mlld 2.2.0: @parse.address, @ndjson / @jsonl / @parse.ndjson / @parse.jsonl, @csv and @md.
YAML
@yaml (and the @parse.yaml variant) parse YAML text into a value. The same
loader handles a flat Name: value dict and a Name: block sequence:
const @config = `name: Ada
roles:
- lead
- review` | @yaml
>> { "name": "Ada", "roles": ["lead", "review"] }
Values come back as strings: count: 42 is "42", active: true is
"true", and a key with no value is null.
A value can also be coerced to a record with => record, which decodes JSON and
falls back to YAML — see Records for the => record
form. Use @yaml when you want a pipe stage, and => record when you are shaping
a value to a schema.
Deprecated: @json
@json (and @json.loose / @json.strict / @json.llm / @json.fromlist) is a deprecated alias for @parse. It still works, but new code should use the canonical name: @parse, @parse.loose, @parse.strict, @parse.llm, and @parse.fromlist.
Checks
@exists(target)- returnstrue/false. Works with file paths, variables, object fields, array indices, and globs. Note:@exists(@var)checks if the variable is defined, not if a file at that path exists.@fileExists(path)- returnstrue/false. Always resolves argument to a path string, then checks filesystem. Unlike@exists(@var),@fileExists(@var)resolves the variable and checks the file.@typeof(value)- returns type as string
const @obj = { field: 1 }
const @arr = [1, 2, 3, 4, 5, 6]
const @settings = { configPath: "config.json" }
>> File existence (literal paths)
if @exists("config.json") [ show "config found" ]
if @exists(<src/**/*.ts>) [ show "has ts files" ]
>> Variable/field existence
if @exists(@obj.field) [ show "field defined" ]
if @exists(@arr[5]) [ show "index 5 exists" ]
>> File existence with dynamic paths
const @configPath = "config.json"
if @fileExists(@configPath) [ show "config found" ]
if @fileExists(@settings.configPath) [ show "found" ]
Type Checks
.isArray()/.isObject()/.isString().isNumber()/.isBoolean()/.isNull()/.isDefined().isHandle()- returnstruefor a handle wrapper ({ handle: "h_xxx" }),falseotherwise. Inspection only: it never resolves the handle, so it is safe on a value whose handle may not be registered. A multi-key object that merely carries ahandlekey (e.g.{ handle: "x", value: "y" }) is a payload, not a wrapper, and returnsfalse.
.isDefined() vs @exists()
These look similar but treat an explicit null differently:
.isDefined()means present and non-null. It returnsfalsefor a field that is absent and for a field whose value isnull.@exists(...)returnstruefor any field that is present, including one whose value isnull. It only returnsfalsewhen the field is truly absent.
const @obj = {"present": 1, "nullish": null}
show @obj.present.isDefined() >> true
show @obj.nullish.isDefined() >> false (present but null)
show @exists(@obj.present) >> true
show @exists(@obj.nullish) >> true (present, even though null)
show @exists(@obj.absent) >> false (truly absent)
Reach for .isDefined() when you want a usable, non-null value; reach for @exists() when you only care whether the key was set at all.
Handle-safe inspection
@typeof(value) and .isHandle() are handle-safe: they read the value's shape without resolving any handle it carries.
Warning:
.isArray(),.isObject(), and.length()resolve handle-bearing values before inspecting them. On a value that carries a handle which is not registered in the current environment, these fire the handle resolver and can crash withHANDLE_NOT_FOUND. To branch on whether a value is a handle wrapper, use.isHandle()(or@typeof), not.isObject().
Methods
String methods:
@str.length- string length@str.includes(sub)- true if contains substring@str.indexOf(sub)- index or -1@str.startsWith(prefix)/endsWith(suffix)@str.toLowerCase()/toUpperCase()@str.trim()- remove whitespace@str.split(separator)- split to array@str.slice(start, end?)- extract substring by position@str.substring(start, end?)- extract substring (no negative indices)@str.replace(search, replacement)- replace the first match of a string or regex (.replace(/b/, "X")); a regex with/grefuses: use.replaceAll@str.replaceAll(search, replacement)- replace all matches (accepts string or regex)@str.replaceAll({"old": "new", ...})- bulk replacement via object map (applied sequentially)@str.match(pattern)- match against string or regex, returns match array or null@str.padStart(length, char?)/padEnd(length, char?)- pad to target length@str.repeat(count)- repeat string N times@str.parseTime()- an RFC 3339 timestamp as{ seconds, nanos }since 1970, ornull(see Timestamps and paths)@str.isUnder(folders)- true when the path is one of the folders, or inside one
Array methods:
@arr.length- array length@arr.includes(value)- true if contains value@arr.indexOf(value)- index or -1@arr.join(separator)- join to string@arr.slice(start, end?)- extract sub-array by position@arr.concat(other)- combine arrays@arr.reverse()- reverse order (returns new array)@arr.sort()- sort alphabetically (returns new array)@arr.flat(depth?)- flatten nested arrays (default depth 1)@arr.at(index)- element at index (supports negative indices)@arr.unique()- each value's first appearance, in order (returns new array)
@arr.minBy(key) and @arr.maxBy(key) return the element with the smallest or largest key, and @arr.sortBy(key) orders the elements by a key (see below).
unique keeps a value the first time it appears and drops every later copy. Two values are copies when they are of the same kind and == holds between them: 1 and "1" are both kept, though 1 == "1" is true. null and an undefined value count as one value. Lists are compared item by item and objects field by field, in any field order. A list holding a function is an error. Each kept element keeps its own labels.
Wildcard projection collects one field from every element: @users[*].name is the list of names, the same as @users.map(@item.name). It takes one field; for a deeper path, use .map.
Helpers:
@keep(value)- provenance/wrapper-preservation escape hatch. Takes a single value and returns it with its structured wrapper and provenance (trust, labels, facts) intact. The standard, preferred way to keep data intact is to keep mlld objects natively in mlld — pass the object itself as an argument instead of interpolating it into a string, and provenance is preserved without any helper. Reach for@keeponly when a value has already crossed a boundary that strips its wrapper (a js or shell result, an interpolated template) and you need what remains of the provenance to survive. It is not an object key-filter: extra arguments are a hard error. To pick or drop keys, build a new object explicitly. A value with no structured envelope — a plain string, number, or bare object literal — is refused:@keeppreserves a wrapper, it cannot create one.
Per-value provenance predicates (return boolean, usable in if/match/refine/guard conditions):
@value.mx.allFields(pattern)- every leaf field's mx satisfies the descriptor pattern@value.mx.anyField(pattern)- at least one leaf field's mx satisfies the descriptor pattern
The pattern is an object whose keys describe what to look for: trust, influenced, factsource (where a field's proof came from), labels, and source (one of "user", "fact", "handle", "value"). See builtins-ambient-mx for the full pattern shape and where these predicates can be used.
Method chains can continue across lines when continuation lines start with .
const @fruits = ["apple", "banana", "cherry"]
const @message = "Hello World"
show @fruits.includes("banana") >> true
show @fruits.join(" and ") >> apple and banana and cherry
show @message.toLowerCase() >> hello world
show @message.split(" ") >> ["Hello", "World"]
>> Method chaining
show @message.trim().toLowerCase().startsWith("hello") >> true
>> Multiline method chaining
exe @normalize(text) = @text
.trim()
.toLowerCase()
.replace("hello", "hi")
Array filtering and higher-order idioms
The filter, find, some, every, map, reduce, minBy, maxBy and sortBy methods evaluate one expression per element, with @item bound to that element. Nested calls get their own @item; any outer binding is restored afterwards.
const @rows = [{name: "a", score: 1}, {name: "b", score: 3}]
show @rows.filter(@item.score > 1) >> [{"name":"b","score":3}]
show @rows.find(@item.score > 1).name >> b
show @rows.some(@item.score > 2) >> true
show @rows.every(@item.score > 0) >> true
show @rows.map(@item.name) >> ["a","b"]
show @rows.reduce(@acc + @item.score, 0) >> 4
filter keeps matching elements in order; map collects expression results. find returns the first match, or null. some and every return booleans and stop as soon as the answer is known. On an empty array, some is false and every is true. Conditions use normal mlld truthiness. Each method except reduce takes exactly one expression, and all of them require an array receiver. Write @rows.filter(@item.score > 1), without an arrow lambda or function value.
reduce folds a list into one value. It takes a step and a start value: the start is evaluated once, then the step runs for each element with @acc bound to the value so far and @item to the element, and the last step's result is the answer. An empty list gives back the start value. The step can call a function, which is how a fold builds up a state object:
exe @tally(state, row) = { count: @state.count + 1, best: @row.score > @state.best ? @row.score : @state.best }
show @rows.reduce(@tally(@acc, @item), { count: 0, best: 0 }).best >> 3
The result carries the labels of every element the step read, as map does. There is no early stop and no position binding.
minBy and maxBy return the element whose key is smallest or largest, in one pass. A key is a number, a string (in the order .sort() puts strings), or a list of them compared item by item, so [@item.at.seconds, @item.at.nanos] orders by seconds and then nanoseconds. On a tie the element listed first wins. Elements whose key is null are left out, and when none is left the answer is null. Keys of different kinds (a number and a string) are an error. The element keeps its own labels and picks up the labels of every key compared, since each one decided the answer.
const @runs = [{id: "a", score: 3}, {id: "b", score: 1}, {id: "c", score: 3}]
show @runs.maxBy(@item.score).id >> a
show @runs.minBy(@item.score).id >> b
show @runs.sortBy(@item.score).map(@item.id) >> ["b","a","c"]
show @runs.map(@item.score).unique() >> [3,1]
sortBy returns the elements ordered by their key, smallest first. Keys follow the rules minBy uses. Elements with equal keys keep their order in the list. Elements whose key is null are not left out: they go last, in their order in the list. Each element keeps its own labels; the list carries the labels of every key, since together they decided the order. To sort largest first, add .reverse(), which also reverses the order of equal keys.
Invocation control clauses such as with { policy: ... } are refused directly on these methods. To scope their evaluation, place the method inside an exe and attach the clause to that call.
Selected elements keep their own labels and proof. Newly constructed lists do not inherit proof that attested only to the original whole list.
A for loop with an if filter (see for-collection) is useful when you want to name the iteration variable or use a block:
const @nums = [1, 2, 3, 4, 5]
>> filter: keep elements that match a condition
const @big = for @n in @nums if @n > 2 => @n
show @big >> [3, 4, 5]
>> count: filter, then read .length
show @big.length >> 3
>> all/any over booleans: includes(false) tells you if any failed
const @checks = [true, true, false]
show @checks.includes(false) >> true (so: not all passed)
The @arr[?condition] filter expression
A subscript with a leading ? filters an array. Bind the @item expression form to a variable (const @x = @arr[?@item > 2]); it does not parse inline inside show, in a direct exe body, or with a chained field tail. The bare-field form also works inline, for example show @people[?age = 30]. Two predicate forms work:
const @nums = [1, 2, 3, 4, 5]
>> @item-predicate: @item refers to each element
const @big = @nums[?@item > 2]
show @big >> [3, 4, 5]
const @people = [{"name": "a", "age": 30}, {"name": "b", "age": 20}, {"name": "c", "age": 30}]
>> record-field form: compare a field of each element
const @thirty = @people[?age = 30]
show @thirty >> [{name:"a",age:30}, {name:"c",age:30}]
The bare-truthy form @arr[? @item] (filter on truthiness alone, with no comparison) does not parse — it raises a parse error. Use an explicit comparison instead, e.g. @arr[?@item != null].
The bare-field form supports dotted fields, =, ==, !=, <, <=, >, >=, and substring containment ([?name ~ "al"]). Comparison values can be literals or variables. Numeric comparisons fall back to string ordering when the values are not numeric. A duration such as [?created > 7d] selects RFC 3339 timestamps older than seven days; < selects newer timestamps. Duration units are ms, s, m, h, d, w, and y (365 days); equality uses a one-minute tolerance. Invalid timestamps do not match.
A bare field, such as [?enabled], tests field truthiness: null, missing, false, "false", "", and numeric zero are false. Unlike an @item condition, text "0" and "nan", empty arrays, and empty objects are true in this form.
Array slices
@array[start:end] selects elements from start (included) to end (excluded). Omit either bound for the beginning or end; negative bounds count from the end, and out-of-range bounds clamp to the array. Reversed bounds produce an empty array. Variables used as bounds must contain numbers. A negative ordinary index such as @array[-1] remains a missing element, not a slice.
const @items = [0, 1, 2, 3, 4]
const @start = 1
show @items[:2] >> [0,1]
show @items[-2:] >> [3,4]
show @items[@start:4] >> [1,2,3]
show @items[1:4].length >> 3
Slices and filters require array receivers. They retain the selected elements' own proof and labels, while dropping proof for the original whole array even when the selected range includes every element.
Timestamps and paths
@str.parseTime() reads an RFC 3339 timestamp such as 2026-11-16T10:00:03.25Z and returns { seconds, nanos }: whole seconds since 1970-01-01 UTC, and nanoseconds. The two are kept apart because nanoseconds since 1970 are too large for an exact mlld number. To compare two timestamps, compare seconds, then nanos, or order a list with .minBy([@item.seconds, @item.nanos]).
It reads timestamps as Go's time.Parse(time.RFC3339Nano, …) does, so it orders events the same way Go and Rust tools that wrote them do. It accepts:
- a date, an upper-case
T, and a time:YYYY-MM-DDThh:mm:ss, where the hour may be one digit; - an optional fraction after
.or,, of any length; the first nine digits count; Z, or an offset+hh:mmor-hh:mm, with the hour at most 24 and the minute at most 60.
The day must exist (leap years included), the hour must be 0 to 23, and minutes and seconds 0 to 59. Anything else gives null.
@path.isUnder(folders) is true when the path equals one of the folders, or starts with it followed by /. A folder may be written with or without a trailing /. Paths are compared as written: nothing is normalized, so ./api/a.go is not under api, and api/../etc/passwd is. An empty folder "" holds every path that starts with /. folders is one string or a list of strings, and an empty list holds nothing. Because .. is not resolved, .isUnder() is not a check that a path stays inside a folder on disk; use it for paths that are already clean, such as the ones git reports.
const @t = "2026-11-16T10:00:03.25Z"
const @when = @t.parseTime()
show @when.nanos >> 250000000
const @file = "api/server/main.go"
show @file.isUnder(["web", "api"]) >> true
show @file.isUnder("ap") >> false
.match() semantics and regex literals
@str.match(pattern) behaves differently depending on the regex /g flag:
- With
/git returns an array of all matched substrings. - Without
/git returns a first-match array where index0is the whole match and1..nare the capture groups (ornullif nothing matched). Access a group by index, e.g..1.
const @s = "foo bar foo baz"
show @s.match(/foo/g) >> ["foo", "foo"] (all matches)
const @email = "alice@example.com bob@test.org" >> @ is plain text in a string
const @cap = @email.match(/(\w+)@(\w+)/)
show @cap >> ["alice@example", "alice", "example"]
show @cap.1 >> alice (first capture group)
With a regex, .replace replaces the first match and .replaceAll replaces every match. Both take $&, $1 and $<name> in the replacement. .replace refuses a /g pattern and points at .replaceAll, because /g would mean "every match" on a method that replaces one:
const @t = "abcb"
show @t.replace(/b/, "X") >> aXcb (first match)
show @t.replaceAll(/b/, "X") >> aXcX (every match)
show @t.replace(/(b)/, "[$1]") >> a[b]cb
To build a pattern from a variable, use a backtick template: .match() reads a string argument as a regex. Only ${…} interpolates, so <, > and @ stay as written, and a backslash the regex needs is written \\:
const @x = "id"
const @pattern = `(^|[<\\[{])${@x}(?:[>\\]}]|$)`
const @s = "a <id> b"
show @s.match(@pattern) >> ["<id>", "<"]
Two regex-literal limitations to know:
- No escaped forward slash. A
\/inside a regex literal (e.g./a\/b/) does not parse, and neither does a slash inside a character class (/a[/]b/). To match a literal slash, use the hex escape\x2f, e.g./a\x2fb/. - The receiver must be a variable. Calling a regex-literal method directly on a string literal —
"alice@x.com".match(/(\w+)@/)— is a parse error. Bind the string to a variable first, then call the method on the variable.
Object introspection
Objects have no .length — reading @obj.length returns null, which show prints as an empty line. Use the .mx key/value/entry views instead:
const @o = {"a": 1, "b": 2, "c": 3}
show @o.length >> (empty line: objects have no length)
show @o.mx.keys >> ["a", "b", "c"]
show @o.mx.keys.length >> 3 (count keys this way)
show @o.mx.values >> [1, 2, 3]
show @o.mx.entries >> [["a", 1], ["b", 2], ["c", 3]]
See builtins-checks for existence/type checks and builtins-ambient-mx for the full .mx surface.
No
.charAt(i). There is nocharAtmethod. To read a single character by position use@str.slice(i, i + 1).
Hash
@hash is a built-in namespace for content digests. It needs no import.
@hash.sha256(s)— SHA-256 hex digest ofs@hash.sha256(s, n)— the digest truncated to the firstnhex characters@hash.md5(s)— MD5 hex digest (and@hash.md5(s, n)to truncate)@hash.bytes.sha256(s)— the SHA-256 digest as a byte array (number[])@hash.bytes.md5(s)— the MD5 digest as a byte array
Each member also has a declassifying twin spelled with a trailing !
(@hash.sha256!(s), @hash.bytes.md5!(s), ...). The standard form CARRIES the
input's security labels onto the digest — a digest of a low-entropy secret is a
content oracle over that secret, so it cannot be used to launder them. The bang
form deliberately strips the labels: it is the sanctioned redaction-by-hashing
form for writing a stable pseudonymous id (e.g. @hash.sha256!(@email)).
The bang form is grant-gated and denies by default: it runs only when the
policy in force opts in, in its * settings block —
policy @hashing = { * { defaults: { declassify_hashes: true } } }
Without that grant (no policy, or a policy that does not set it), every !
form refuses. MD5 is cryptographically broken: use it for deduplication and
legacy ids, never for security.
const @id = @hash.sha256("hello")
>> 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
const @shortId = @hash.sha256("hello", 8)
>> 2cf24dba
Strings, numbers and booleans hash their plain text. Containers (arrays,
objects) hash their canonical encoding, which is independent of key order.
null hashes as "null". Digests are deterministic — the same input always
produces the same output.
@hash is shadowable: if you define your own @hash (for example
exe @hash(text) = ...), your definition wins and the built-in namespace is not
in scope. The built-in only resolves when no @hash is defined.
Comments
A comment starts with >> or << and runs to the end of the line. Either can start a line or follow code.
>> This is a comment
const @x = 5 << end-of-line comment
show @x >> also works here
Escaping
Only backtick templates and ::…:: templates insert values, and only through
${…}. Double- and single-quoted strings never do, and @ is ordinary text
everywhere (see escaping-at).
Escapes by form:
| Form | Inserts values | Escapes it understands |
|---|---|---|
"text", 'text' |
never | \n \t \r \0 \\ \" \' \u{…} |
`text ${@x}` |
${…} |
the same, plus \` and \${ |
::text ${@x}:: |
${…} |
only \${ and \:: — everything else is raw |
:::text {{x}}::: |
{{…}} |
\{{ and \}} |
.att file |
${…} |
raw, like :: |
.mtt file |
{{…}} |
as ::: |
Any other backslash sequence in a quoted string or backtick template is an
error, not a silent drop. "\d" refuses with a message telling you to write
"\\d" for a backslash followed by d.
const @name = "Ada"
show "one\ntwo \"quoted\" \u{41}"
show `backtick: \` literal: \${name} value: ${@name}`
show ::raw: \n `code` \${name} \:: value: ${@name}::
Output:
one
two "quoted" A
backtick: ` literal: ${name} value: Ada
raw: \n `code` ${name} :: value: Ada
${ must start an expression. In a template, ${name} without the @ is
an error. Write \${name} when you mean the literal text.
Text right after a value is just text. `${@x}(y)` writes the value
followed by (y), and `${@x}?` writes the value followed by ?. The
closing } ends the expression, so nothing after it needs escaping.
Choosing a form:
- Backticks
`...`- the default template. - Double-colon
::...::- when the text has backticks or backslashes you
want kept as they are, such as prompts with code fences. - Triple-colon
:::...:::- when you want{{name}}placeholders.
Writing a literal {{name}}:
Inside a triple-colon template, {{name}} is a placeholder and mlld replaces
it. To print the braces themselves, escape both ends. A }} with no
opening {{ is a syntax error, so escaping only the front one fails:
>> The value is the literal text: Use {{name}} in your handlebars file
const @tip = :::Use \{{name\}} in your handlebars file:::
The same escape works in .mtt template files.
For a bare }} that is not part of a placeholder, escape it on its own:
>> The value is the literal text: Handlebars uses }} to close
const @note = :::Handlebars uses \}} to close:::
Markup with @ in it needs nothing special:
const @id = "u1"
const @name = "Ada"
const @user = `<USER id="${@id}">${@name}</USER>`
const @elem = `<input type="email" placeholder="user@example.com">`
See Also
- @ in Text -
@is ordinary text; where it still means something. - Escaping Defaults - Fallbacks for missing values.
- Templates Basics - Template forms and interpolation rules.
@ in Text
@ is ordinary text in every string and template form. Only ${…} inserts a
value, so a literal @ needs no escape. (For cmd { } bodies, see below.)
const @name = "Ada"
const @email = `user@example.com` >> "user@example.com"
const @handle = "@username" >> "@username"
const @note = "@name stays as text" >> the text "@name stays as text"
const @hello = `Hi ${@name}` >> "Hi Ada"
When the word after a literal @ is the name of a variable in scope, mlld
warns: This @name is literal text; did you mean ${@name}?. The warning is a
hint only; the text is kept as written.
The same holds in .att and .mtt template files:
Contact: user@example.com
Follow @username on Twitter
Command bodies take values as shell variables. A value reaches a cmd { }
body as a shell variable, and the shell expands it: an exe's parameters are
shell variables already, and any other value comes in with
using { env: { name: @value } }. An env value must be a bare @variable,
so bind a field or a computed value to its own name first. An @ inside a
word, as in an email address, is plain text to the shell and needs no escape.
const @name = "Ada"
run cmd {echo "$name and user@example.com"} using { env: { name: @name } }
>> Ada and user@example.com
exe @greet(who) = cmd {echo "hi $who"}
show @greet("Ada")
>> hi Ada
sh { }, js { }, node { } and py { } bodies are passed to their language
exactly as written, with no @ processing (see run-params).
Default Values
Problem: Need default values when data might be missing.
Solutions:
const @user = { name: "Ada", address: { city: "Paris" } }
const @item = { title: "Notes" }
const @post = { tags: ["a", "b"] }
>> 1. Nullish fallback with ??: used when the value is null or missing
const @title = @item.title ?? "Untitled"
const @subtitle = @item.subtitle ?? ""
show `Title: ${@item.title} ${@subtitle}` >> empty when there is no subtitle
>> 2. A missing path anywhere along the way is just missing
const @zip = @user.address.zip ?? "Unknown" >> Unknown
const @tags = @post.tags ?? [] >> ["a", "b"]
>> 3. Ternary expressions, when any falsy value should fall back
const @name = @user.name ? @user.name : "Anonymous"
?? falls back only on null or a missing field: "", 0 and false are kept. Reading a field of a missing value (@user.nope.deeper) is not an error; it is missing too, so one ?? at the end covers the whole path. See Conditional Variables.
Records
@fyi.recordsis not available in mlld 2.2.0: reading it stops with an error.@fyi.actorsworks (see Inspecting read projections below).
A record describes structured data field by field: what type each field has,
which fields name something real (an email address, a file id) and so can be
used as proof, and which fields are just content that could say anything. The
same record syntax serves two directions:
- Output records shape values with
=> record/as recordcoercion and control what an LLM sees through the record'sreadlists. - Input records shape the tools you give an LLM, through
inputs: @recordon a tool collection entry.
Define a record
A record is a list of lines inside [ … ]. Each line is a field or a setting.
Lines are separated by newlines or ;; indentation does not matter.
field @email [ type string; kind "email" ]
record @contact [
key id
id: string [ kind "contact_id" ]
email: @email
trusted name: string
notes: string?
* { read: [id, name] }
]
name: typedeclares a field.name: type?makes it optional.- A field's settings go in its own
[ … ]:kind,accepts,labels, and the field actions below. field @email [ … ]defines a reusable field.email: @emailuses it, with its type and kind.key,hash,labels,correlate,exact,update,allowlist,blocklist,validate,mitigates,refine,useandinheritare settings lines, covered below.* { read: [ … ] }and.role:x { read: [ … ]; write: { … } }are role blocks: what each actor sees and may write. Covered under Read projections and Write permissions below.
Supported field types: string, number, boolean, object, array, handle. The
handle type requires a resolvable handle; plain strings fail validation. Use
it for worker return fields that carry identity across phases.
Field types use the same syntax as parameter and state slot types (see
exe-metadata): ? marks an optional field, and email: @email adopts a
field definition. Add [] for a list: tags: string[], to: @email[].
Write [] against the type: tags: string [] is refused, because a spaced
[ … ] after a type opens the field's config block. A record as a field type
(address: @address, items: @item[]) nests that record (see Nested records
below).
x: @contact.email adopts that field of another record: its type, kind,
accepts, labels and trust marking (untrusted stays untrusted). Its field
actions stay with @contact. Adding any of the adopted settings again
(x: @contact.email [ kind "other" ]) is an error when the record is defined,
and so is a field the record does not have. @contact.email[] is a list of
them. The source record has to be defined above.
A string field holds one value. A number or boolean given to it becomes text,
but a list or an object is a type error, handled like any other (see
Validation modes): strict refuses the coercion, and no mode mints proof on
the value.
A field that takes a list is declared as a list (see List fields below).
Which fields carry proof
Two things decide how a field is treated:
- A kind. A field has a kind when its settings say
kind "x"(or a list of kinds), or its type is afielddefinition that has one. A kind names what the value points at. A field with a kind carries proof: it gets a.fact:@record.fieldlabel, and that label can satisfy a tool's requirement that an argument name something real. A field with no kind never carries proof. trusted/untrusted. These only say whether the text is clean. They never add or remove proof.
Defaults follow from the kind: a field with a kind is trusted unless it says
untrusted; a field without one is untrusted unless it says trusted. So
untrusted handle: string [ kind "handle" ] names a real account (it carries
proof) while its attacker-chosen text stays tainted.
Important: if a field holds values that a downstream write tool needs as a
control argument (recipients, participants, file ids), give it a kind. Fields
without a kind get no handles and no proof, so they cannot satisfy positive
checks or flow into authorized tool calls. For list fields such as
recipients or participants, the kind applies to each element, so each gets
its own handle.
Trust from an untrusted source
When an executable is labeled .untrusted, the record decides trust field by
field:
- A trusted field (one with a kind that does not say
untrusted, one without a kind writtentrusted, or one arefinearm marks withdata { field: "trusted" }) takes effect only when the policy authorizes the record: itsself_attestation.recordslist names the record, or holds"*"for every record. Then the field clears the inherited.untrustedand its value reads trusted. On a record the policy does not list, the marking does nothing: the value keeps the trust it arrived with, so routing attacker text through a record cannot launder it. A field with a kind carries proof either way. - The exception is a coercion made inside a privileged guard (
guard!, seelabel-modification): there a record's trusted marking takes effect whether or not the policy lists the record. - Any other field (one marked
untrusted, or one with no kind that is not marked trusted) keeps.untrusted. Labels such as.src:mcpare preserved.
On a listed record, whether a trusted field clears .untrusted depends on how the value reaches the record. On a record the policy does not list it clears nothing, on every route:
| How the value reaches the record | A value labeled .untrusted (an .untrusted exe's result) |
Content with only a source label (<file> under unlabeled: .untrusted) |
|---|---|---|
An exe's result, => note |
cleared | cleared |
Inline, { body: @v } as record @note |
kept | cleared |
A parameter check, exe @f(p as record @note) |
kept | kept |
policy @trust_contacts = { * { self_attestation: { records: [@contact] } } }
record @contact [
id: string [ kind "contact_id" ]
untrusted handle: string [ kind "handle" ]
name: string
notes: string?
* { read: [id, name] }
]
exe .untrusted @emitContact() = js {
return { id: "c1", handle: "@ada", name: "Ada", notes: "hi" };
} => contact
const @c = @emitContact()
show `${@c.id.mx.trust} ${@c.handle.mx.trust} ${@c.name.mx.trust} ${@c.notes.mx.trust}`
Output:
trusted untrusted untrusted untrusted
Without the policy line, id also reads untrusted. See security-policies for the
self_attestation grant.
Connect to an exe with => record
record @contact [
email: string [ kind "email" ]
name: string?
]
exe @emitContact() = js {
return { email: "ada@example.com", name: "Ada" };
} => contact
const @ada = @emitContact()
show @ada.email
show @ada.email.mx.labels[0]
show @ada.mx.schema.valid
Output:
ada@example.com
.fact:@contact.email
true
The email field carries .fact:@contact.email. Schema validation metadata is
available on .mx.schema.valid and .mx.schema.errors.
For tool results, this is also the secure way to return data to an LLM caller.
Returning through => contact or => record @schema turns on record-mediated
return filtering at the bridge: the active .role:* read projection shapes what
the LLM sees.
Checking a value against a record: is
@value is @record checks a value against a record's fields and types without
coercing it. It returns true or false:
record @person [
name: string
]
const @ada = { name: "Ada" }
const @bad = { age: 1 }
const @adaOk = @ada is @person
const @badOk = @bad is @person
show @adaOk
show @badOk
Output:
true
false
A record with a field that has a kind and no read list is checked the way a
tool input is (see @cast below): a plain value fails, because its kind field
carries no proof. Add a read list to such a record, or check it with @cast
when proof is what you want to test.
Speculative validation with @cast
@cast(value, record) validates a value as the input to a tool with that input
record. A bad record reference still throws, but validation failures return a
structured false value with details at .mx.error:
const @result = @cast(@pending, @pending.mx.tool.record)
match [
@result => show "valid"
* => show @result.mx.error.message
]
Because it checks tool input, a field with a kind needs proof here: a plain
literal fails with must carry .src:user:intent:literal or fact proof. This is
useful in hydrated decision scripts, where @cast can also consult
@mx.history for user-intent and fact proof (see facts-and-handles). It does
not replace dispatch-time tool validation.
Field actions
A field's [ … ] can hold actions that run whenever the record materializes:
as record, => record, and record-backed tool input dispatch. Write them in
the order they run: enrich, transform, check, apply, and then any
input/output arm lists. Another order is a parse error that says which line
comes first.
record @note [
body: string [
transform "secret" => "[redacted]"
check "password" => deny
]
]
const @n = { body: "the secret plan" } as record @note
show @n.body
Output:
the [redacted] plan
enrich /pattern/ as namerecords every match of the regex at.mx.enrich.nameon the field, as a list of{ text, path, groups }. The value itself is unchanged. The regex takes no flags.transform "from" => "to"rewrites the value.check <matcher> => denyrefuses the record when the matcher fires.apply .labeladds a label every time the record materializes.
class .reviewed = { kind: "data", effect: "restrict", description: "A person checked this." }
record @link_note [
body: string [
enrich /https?:\/\/\S+/ as urls
apply .reviewed
]
]
const @n = { body: "see https://example.test" } as record @link_note
show @n.body.mx.enrich.urls[0].text
const @reviewed = @n.body is .reviewed
show @reviewed
Output:
https://example.test
true
A matcher in transform or check can also be an executable, @name. It is
called once per text value in the field as @name(value, ctx) and returns
true/false, or { matches: [{ text, start, end }], transformed }. In
transform, each match's text is replaced with to, or the whole field
becomes transformed when the matcher returns one; in check … => deny, a
match refuses the record. A matcher that throws, or returns anything else,
refuses the record too, rather than counting as no match.
exe @secret_words(value, ctx) = js {
const at = value.indexOf("secret");
return at < 0 ? { matches: [] } : { matches: [{ text: "secret", start: at, end: at + 6 }] };
}
record @memo [ body: string [ transform @secret_words => "[x]" ] ]
const @m = { body: "the secret plan" } as record @memo
show @m.body
Output:
the [x] plan
The runtime stamps each applied action on the field value at
.mx.appliedActions, so an unchanged field does not re-run the same action when
it crosses another materialization boundary, such as a state write or tool
dispatch.
Matchers receive the field value as their primary input. They can inspect
sibling fields through the in-flight record binding @input.<field> in mlld
matchers, or ctx.input.<field> in JavaScript matchers. @input is the record
being materialized; it is not session-ambient state.
apply and field labels can add any label except .trusted. Approval labels
(.fact:*, .mitigates:*, .src:*) are refused when a policy sets
self_attestation: { code: false } (see security-policies); for fact proof a tool's
accepts floor will take, use a kind, mitigates, or privileged guard flows.
A field's apply also refuses controlled policy labels (operation, risk,
actor and attestation labels such as .op:cmd or .fact:*) when the record
materializes.
When you use parameterized #id[...] labels, mlld validate checks record
labels and record action labels before runtime. Malformed IDs, unknown slots,
missing required slots, and field-level attempts to mint controlled IDs are
validation errors. Whole-record input arms are the record-authorized boundary
for controlled ID labels.
Arm lists: input and output
An arm list is a set of pattern => action lines, and the two lists act on
different copies of the field:
inputarms change the value that is stored when the record is built.
Everything that reads the field afterwards sees the changed value.outputarms leave the stored value alone. They change only the copy that
leaves the program: what an LLM or an MCP tool is shown, and what
@project(...)returns.
Every matching arm applies, not only the first. So * is not a fallback:
it also applies to values an earlier arm matched. Arms are separated by
newlines or ;.
record @public_note [
body: string [
input [ "secret" => "clean" ]
output [ "private" => "[redacted]" ]
]
* { read: [body] }
]
const @n = { body: "a secret, private note" } as record @public_note
show @n.body
show @project(@n)
Output:
a clean, private note
{"body": "a clean, [redacted] note"}
In the example, show @n.body reads the stored value, which the input arm
changed and the output arm did not. @project(@n) builds the outgoing copy,
so it carries both changes.
An arm's rewrite is written as the new value, as transform writes it. A
matched text arm rewrites the part of the value it matched; a * arm replaces
the whole text. Inside an arm, @input is the field's current value, and
"secret" => @input = "clean" is a longer way to write "secret" => "clean":
the two mean the same.
An output arm can only replace text. It cannot refuse (deny), add
labels, run a check or enrich, or match with an executable. A run stops
at the record that has one, and mlld validate reports it.
An arm can also add labels (* => labels += [.reviewed]) or refuse
("bad" => deny "no bad words").
A none => arm is the fallback: it applies only when no earlier arm in the
same list matched. With input [ "secret" => "clean"; none => "other" ], the
body "a secret note" becomes "a clean note" and the body
"plain note" becomes "other". none => works in input, output and
refine arm lists. A refine list of rules (conditions like
@input.status == "x") takes no none =>; use a nested match [ … ] with a
* arm there.
Derive a record from another record
A record can extend an earlier record in the same module:
record @article_base [
id: string [ kind "article_id" ]
trusted body: string
comments: array?
* { read: [id] }
]
record @article_summary extends @article_base [
inherit trusted body
summary: string
* { read: [id, summary] }
]
The derived record is expanded before validation, so @article_summary behaves
like a flat record with id, body, comments, and summary. A derived record
cannot redeclare a field from its base.
Trust-bearing base sections are fail-loud. If the base has trusted fields
without a kind, the child must name them on an inherit trusted <fields> line;
leaving it out is an error that shows the line to add. If the base has write grants,
refine, or mitigates, the child must either restate that section or opt into
inheritance with inherit write, inherit refine, or inherit mitigates.
Fields with a kind inherit normally; proof is not a trust-bearing content
channel.
If the base record has no read list (so every field is visible) and the child
adds fields, the child must declare its own read list or acknowledge the
inherited read with inherit read.
Reuse record presets
Use a preset when several records share the same fields or settings but do not
form a base/child relationship:
class .message = { kind: "data", effect: "restrict", description: "A message body." }
preset @message_identity [
id: string [ kind "message_id" ]
labels .message
]
preset @trusted_body [
trusted body: string
]
record @message_summary [
use @message_identity, @trusted_body
inherit trusted body
summary: string
* { read: [id, body, summary] }
]
Presets are same-module and earlier-definition only. A record expands use
presets in list order, then adds its local fields, and the result validates as
one flat record. Duplicate fields are invalid. A preset cannot extend a record
or use another preset.
Trust-bearing preset sections are fail-loud like derived records: list a
preset's trusted fields on an inherit trusted line, and restate or inherit
its write grants, refine or mitigates.
Composing and labeling records
Records share structure and classification through three related features:
- Extending — derive a record from a base record with
extendsto add fields to an existing contract. - Presets — pull shared field groups into several records with
usewhen they don't form a base/child relationship. - Field labels — attach classification to individual fields. Define a reusable labeled field once with
field @name [ … ]and reference it across records, or label fields inline withlabelsorrefine. Seelabels-fieldsfor the reusable form,labels-classesfor defining the labels themselves, andlabels-parameterized-idsfor fields that carry per-instance identity.
Record identity and hashes
Every record-coerced object has:
value.mx.key— opaque record instance identity for stateupsert, fact correlation, and read-projection handlesvalue.mx.address— stable opaque address{ record, key, string }, wherestringis<record>:<mx.key>addressValue.mx.resolved— trusted-scope explicit dereference for an address-valued expression; the expression itself still renders as its original textvalue.mx.hash— deterministic content fingerprint for change detection
The key and hash lines choose identity inputs:
record @deal [
key [account_id, deal_id]
hash status, amount
account_id: string [ kind "account_id" ]
deal_id: string [ kind "deal_id" ]
status: string
amount: number
notes: string?
]
const @d = { account_id: "a1", deal_id: "d7", status: "open", amount: 5 } as record @deal
show @d.mx.address.record
key id names one field. The runtime stores an opaque key in mx.key; read
record.id when you need the original field value. mx.address.string is a
cross-call address for the record instance, not the source field value. Omit
key when the full canonical record value is the identity for the current mlld
run. Use key hash(field, ...) only when content-derived identity is
intentional; mlld validate warns with record-identity-data-field if that
identity uses fields without a kind.
If hash is omitted but key is declared, mx.hash is derived from all
non-key fields. If both are omitted, mx.hash is derived from the canonical
record value.
Record slots in a state use mx.key to merge records. A record[] slot,
declared directly or made by state @s from @records, keeps the existing row
when a later upsert has the same key; incoming non-null fields replace stored fields, while incoming null or
missing fields leave the stored values intact. mx.hash determines whether the
merged row actually changed.
Use records as tool input contracts
An exe can also take its contract from typed parameters, exe @send(to: @contact.email, body: string): each parameter's type is checked on every call, and a field type needs that field's proof. A record is what you need for allowlist, blocklist, exact, update and correlate. See exe-metadata and tool-definition.
A tools collection entry can point at an input record with inputs: @record:
const @approvedRecipients = ["ada@example.com", "team@example.com"]
record @send_email_inputs [
recipient: string [ kind "email" ]
cc: string? [ kind "email" ]
bcc: string? [ kind "email" ]
trusted subject: string
body: string?
exact subject
allowlist recipient @approvedRecipients
allowlist cc @approvedRecipients
allowlist bcc @approvedRecipients
validate "strict"
]
exe .op:tool:w @sendEmail(recipient, cc, bcc, subject, body) = cmd {
mail-cli send --to "$recipient" --cc "$cc" --bcc "$bcc" --subject "$subject" --body "$body"
}
tools @agentTools = {
send_email: {
mlld: @sendEmail,
inputs: @send_email_inputs,
labels: [.op:execute:w, .risk:exfil:send, .op:comm:w]
}
}
For record-backed tool inputs:
- an input record must say
validate "strict"orvalidate "drop"; a record with the defaultvalidate "demote"is refused as tool inputs - the tool's visible arguments are the record fields that also appear in the executable's parameter list. Other entry forms read the field list differently; see
tool-reshaping. - on write surfaces, fields with a kind become the tool's control args
- on read-only surfaces, fields with a kind become the tool's source args
trustedfields must stay trusted at dispatch time, but without a kind they carry no proof- other fields are payload fields, not authorization-grade identifiers
validate "strict"enforces required fields and types before the executable body runsexact,update,allowlist, andblocklistare input-only settings for surfaced tools?on a field's type declares it optional at dispatch. Its absence is valid, but if the field is present its normal rules still apply: an optional field with a kind must satisfy the same proof requirement as a required one.
Fact kinds and accepted proof
Input-record fields declare a kind to say what kind of authoritative value a
tool argument expects. Output-record fields declare the same kinds to say what
they produce:
record @contact [
email: string [ kind "email" ]
]
record @slack_msg [
sender: string [ kind "slack_user_name" ]
body: string
]
record @invite_user_to_slack_inputs [
user: string [ kind "slack_user_name" ]
user_email: string [ kind "email" ]
validate "strict"
]
An input field with a kind accepts a value that carries fact proof of the
same kind, or was typed by the user (.src:user:intent:literal). The kinds
are compared: .fact:@contact.email satisfies user_email, and
.fact:@slack_msg.sender (kind slack_user_name) does not. A value that
fails is refused at dispatch, by a grant, and by @cast, with an error saying
the input "must carry .src:user:intent:literal or fact proof", followed by the
proof the value carries and the patterns the field accepts. For a list field
every element has to meet it. The check is about proof, not trust: proof from a
tool marked untrusted still meets it.
Use accepts to replace what one input field takes, with an explicit pattern
list. Accept entries are dotted
labels, written without quotes:
record @send_email_inputs [
recipient: string [
kind "email"
accepts .src:user:intent:literal, .fact:*:email
]
validate "strict"
]
.fact:*:email matches proof from a field whose kind is email, whatever
the field is named: a recipient: string [ kind "email" ] value passes, and a
field named email whose kind is address does not. The kind is read from
the proof the value carries, not from its label. .fact:@contact.email names
one exact field instead. See labels-facts for the full pattern list.
accepts replaces the derived list for that field. Include
.src:user:intent:literal when verified user-literal values should still be
allowed. accepts on a field with no kind also makes that field a control
argument: the tool's description lists it with the facts, and its value has
to meet its accepts.
An accepts entry may also be an object naming the mint contexts it admits. A
.mitigates:* endorsement carries the record and field it was minted on; a
scoped entry admits it only when that context matches:
body: string [ accepts { label: ".mitigates:influenced", from: [{ record: "@composed", field: "value" }] } ]
The label is a value under the fixed label: key, and from is required.
Plain entries keep their label-only meaning. Cross-purpose endorsements refuse
with a message naming both the mint context and the accepted context.
Naming a floor once and reusing it
When several fields share the same accept list, writing it out per field means
every later edit has to be made in every copy, and a typo in any one copy
changes only that copy. accepts therefore also takes the name of a variable
holding the list:
const @write_floor = [".src:user:intent:literal", ".fact:*:email"]
record @send_email_inputs [
recipient: string [ accepts @write_floor ]
reply_to: string [ accepts @write_floor ]
validate "strict"
]
The list is read where the record is declared, so the variable must be bound
earlier in the same file. It is fixed at that moment: rebinding the name later,
or importing the record into a file that binds the same name to something else,
cannot change the floor the record already carries.
A floor that does not resolve to a usable list stops the program with an error
naming the field and the reference. That covers a name that is not bound, a
value that is not an array, an array holding anything but text, a blank entry,
an empty array, and a list assembled from other variables ([@part_one, ".x"]),
which is not read until it is used and so is not available when the record is
declared. None of these narrow the list quietly — an accept list that came out
empty would admit values carrying no proof at all.
A named floor holds plain label text. The scoped object entry above is written
inline.
What mlld validate catches before you run anything. Checking a file
reports two mistakes in a named floor, and your editor shows the same two:
- the name is misspelled, or nothing in the file declares it
(accepts @write_flor); - the name is declared right there in the file and what it holds cannot be a
floor — a plain string instead of a list, an empty list, a list with a
number in it, or a list with a blank entry.
Everything else it leaves alone, on purpose. If the floor comes in from
another file, is produced by a function, is a copy of another variable, or is
built out of other variables, the check has no way to see what is in it, and a
checker that guessed would start reporting programs that work perfectly well.
Silence from the checker is not a promise the floor is good — it means the
checker could not tell. The program itself still refuses any floor that does
not resolve to a usable list, as described above.
Accept patterns prefix-match greedily
accepts patterns prefix-match greedily on the colon-separated proof token. A bare token admits both itself and its refined descendants:
knownadmitsknown(exact) andknown:msg:0(descendant)..src:useradmits.src:user,.src:user:msg:0, and.src:user:intent:literal.
So listing both known and known:* is redundant — either spelling alone covers the whole family. Family wildcards are base-inclusive: X:* (and the fused spelling X*) matches the bare X as well as every X:descendant, on component boundaries only:
known:*admits both bareknownandknown:msg:0..src:user:intent*admits.src:user:intentand.src:user:intent:literal, but never.src:user:intentional(no substring matching)..src:user:intent:literaldoes not admit the bare.src:user(a more specific pattern never admits a less specific token).
This is the same most-specific-wins matching used in label flow; see labels-overview.
User-literal proof tokens
User-typed values earn a .src:user family proof token. Which floor token admits which minted form follows the greedy rule above:
Floor token (in accepts) |
Admits | Does not admit |
|---|---|---|
.src:user |
.src:user, .src:user:msg:0, .src:user:intent:literal |
(none in the family) |
.src:user:intent:literal |
.src:user:intent:literal |
.src:user, .src:user:msg:0 |
.src:user:msg:0 |
.src:user:msg:0 |
.src:user, .src:user:intent:literal |
.src:user:intent:literal is the canonical "the human user typed this exact value" proof. The narrower .src:user:msg.N forms are minted per source message. List the broadest token your floor should accept; it covers its descendants automatically. See facts-and-handles for how .src:user proof is minted and how it satisfies positive checks.
Same-source checks and the other input settings
When a write-tool input record has more than one field with a kind, a
correlate line requires that those values came from the same source record
instance:
record @send_payment_inputs [
recipient: string [ kind "iban" ]
tx_id: string [ kind "tx_id" ]
body: string
correlate
validate "strict"
]
That turns on the same-source check for multi-fact write inputs without any
extra per-exe metadata. correlate covers fields with a kind only.
Each element of a list of a kind is checked on its own, as a single value
would be. With to: @iban[] beside tx_id, every iban in to must come from
the same record as the tx_id, and a list gathered from several records is
refused, naming the element (to[1]). Declare correlate false when that
mix is intended. A list that is the only field with a kind is not checked
against itself.
The input-only settings are:
exact field, ...— each listed field's value must be cited from the task with@cite.user.intent.literal(value, task); at dispatch an uncited value is refused withexact_not_cited(seesecurity-citations)update field, ...— mutation fields for update-style tools; at least one must be present, and the surfaced tool must carry.op:update:winlabelsallowlist field @set— values must be present in the named setblocklist field @set— values must not be present in the named set
The named set is read where the tool is defined: the tools collection
entry, or the exe @f(…) with { inputs: @rec } that cites the record. Bind
it before that line; a set bound later is refused there. A tool imported from
a module keeps the module's set, and a same-named variable where the tool is
called never replaces it.
Proof for fields with a kind, allowlist, blocklist, update and
correlate are checked when the tool is dispatched. To authorize one specific
call ahead of time, mint a grant with as grant for @tool (see
security-grants).
read applies when a record value crosses an LLM/MCP boundary. The input
settings apply when the same record is used as tool input. A record can carry
both when it participates in both phases. Composing a coerced record value into
an object literal ({ wrapper: @rec }) does not carry the projection along with
the reshape — mlld validate warns on that shape so you can check the
boundaries the wrapped value reaches; returning the record directly keeps its
projection.
Read projections
A record's read lists control how fields cross the LLM boundary. With no read list, the
strict default holds: fields with a kind cross as handles, the rest stay hidden.
A read list may show any field.
| Mode | Syntax | LLM sees in JSON | In schema notes | Handle? |
|---|---|---|---|---|
| Bare | name |
full value | yes | No |
| Value | { value: name } |
{value, handle, address} |
yes | Yes |
| Masked | { mask: email } |
{preview, handle, address} |
yes | Yes |
| Handle | { handle: id } |
{handle, address} |
yes | Yes |
| Protected | { protected: ssn } |
nothing | yes | No |
| Omit | { omit: raw } |
nothing | nothing | No |
| (not listed) | — | nothing | yes (defaults to protected) | No |
Schema notes are the system-prompt block (<*_notes>) and @fyi.tools()
output that lists declared fields. Schema visibility lets the LLM construct
correct field references without seeing values; value visibility is the actual
content.
record @contact [
email: string [ kind "email" ]
name: string [ kind "name" ]
phone: string? [ kind "phone" ]
notes: string?
* { read: [name, { value: email }] }
]
const @ada = { email: "ada@example.com", name: "Ada Lovelace", notes: "Met at conference" } as record @contact
show @project(@ada)
@project shows the projected view without calling an LLM:
{
"email": {
"value": "ada@example.com",
"handle": null
},
"name": "Ada Lovelace"
}
Inside a live LLM call, email also carries a real handle and an address.
name is bare (readable, no handle). email is value mode (readable, plus a
handle for downstream tool calls and a stable address for cross-call lookup by
mlld code). phone and notes are unlisted, so they default to protected: the
LLM sees the field names in schema notes but not the values.
{ protected: x } and unlisted both produce no JSON value. The explicit
protected form documents intent for security audits — "the author considered
this field and chose to protect its value." Unlisted fields are the implicit
default.
{ omit: x } is structurally different: the field disappears from every
surface (JSON, schema notes, tool docs). Use it when the field's existence
should be invisible to the role.
This does not change ordinary runtime behavior — show @ada.email still
prints the actual email, and show @ada renders the whole record ungated:
developer-local display sinks (show, output, run-interpolation) are deliberately
outside the projection (the console is the trusted party). Read projection
applies at the agent-facing boundaries — the LLM bridge, MCP serve, and
@fyi/@mx inspection.
Read projection (and @project) tolerate missing optional fields: an absent
optional field is left out of the projected view rather than causing an error.
You do not need to backfill optional fields with placeholders to make a partial
record projectable.
Named read modes
Different agents need different visibility. A .role:x { read: [ … ] } block
applies to that role; the * { read: [ … ] } block is the default. A role's own
read replaces the * list rather than adding to it, and read: [] gives a
role an explicitly empty view.
record @email_msg [
from: string [ kind "email" ]
message_id: string [ kind "message_id" ]
subject: string
body: string
needs_reply: boolean
.role:worker { read: [{ mask: from }, subject, body] }
.role:planner { read: [{ value: from }, { value: message_id }, needs_reply] }
]
const @m = { from: "ada@example.com", message_id: "m1", subject: "Hi", body: "See you", needs_reply: true } as record @email_msg
show @project(@m, ".role:worker")
Output:
{
"from": {
"preview": "a***@example.com",
"handle": null
},
"subject": "Hi",
"body": "See you"
}
Worker sees subject and body (its job to read them), and from is masked.
Planner sees from and message_id in value mode (readable plus handle), sees
needs_reply, and sees unlisted fields as protected schema-only fields. Use the
exact role you declared: .role:planner is not an alias for planner.
A record with only a * block gives every reader, any role included, the *
view. Add .role:* { read: [] } beside it so that any role the record does not
name sees nothing, while a reader with no role keeps the * view:
record @note [
id: string [ kind "id" ]
* { read: [id] }
.role:* { read: [] }
]
A read mode can be selected in three places. From least to most specific:
- exe definition —
exe @worker(...) using { read: .role:worker } = .... The default mode every invocation of this exe uses. - box —
box using { read: .role:worker } [...]. Applies to LLM calls inside the box. - call site —
@agent(...) using { read: .role:worker }. Applies to a single LLM call.
A more specific selection overrides a less specific one. The call site is the
most specific and always wins. If no explicit read is set, mlld also checks the
active LLM executable's labels. A label such as .role:planner selects the
matching read mode by default.
>> Box-level: every llm call inside this box uses worker mode
box using { read: .role:worker } [
show @agent(@prompt, { tools: @readTools })
]
>> Call-site: this single llm call uses worker mode
const @result = @agent(@prompt, { tools: @readTools }) using { read: .role:worker }
Code inside a box reads state through @fyi.state, limited to the slots the box's state: { read } scope lists (see box-config).
Idiomatic pattern: for dispatcher-style orchestrators that run multiple LLM
calls under different modes, set using { read } on each @agent(...) call
rather than wrapping each call in its own box. The dispatch is the natural unit
of mode selection — one prompt, one tool surface, one read mode.
Each named mode is a strict value whitelist on its own: unlisted fields are
protected, so they appear in schema notes but not in JSON. Switching modes
replaces the prior whitelist; there's no cross-mode union. Use
{ omit: field } when the field's existence should be hidden too.
What an actor-less boundary shows. When a record crosses a boundary with no
active actor — a served MCP tool after its exe has returned, for example — a
record with role modes and no * block shows nothing: the served
value is {}. Two fail-closed rules go together here:
- The default mode fires only when NO selection is active. If an actor IS active — the call site, the box, or the exe labels selected a
.role:mode — the default never substitutes for it. - An active actor that is not listed selects nothing: every field is protected. An unlisted role seeing the default view would silently widen the record to every actor the author forgot to list.
So if a role must see something, give that role a read list. The no-actor
behavior is pinned by the MCP conformance suite (a served role-keyed record with
no actor serves {}, byte-exact); the unlisted-role behavior is enforced by the
same selection logic and is intentional, not a gap.
See facts-and-handles for the boundary model and pattern-planner for the
cross-phase pattern.
Inspecting agent-visible records: @fyi.records
@fyi.records is not available in mlld 2.2.0: reading it stops with unsupported (unported) construct. This section describes its intended shape.
@fyi.records is a read-only reflection of records reachable through the active agent tool/authorization context, keyed by record name. It is projected by the same active read selector as record values crossing the LLM boundary: protected fields stay schema-visible, and {omit} fields are absent so their existence is not leaked. Records that are merely declared in the module but not reachable through the active tool context do not appear.
The "read selector" here, and .read.selector below, is a record's read mode (such as .role:planner). It is unrelated to the content selectors that serve <file # …> and <file { … }> loads (Content Selectors).
It is still an inspect surface — declarations are not data flow, so reflecting a record never coerces, validates, or moves a value; enforcement (such as refusing to coerce an input-only record for output) still throws where it always did. It lives under @fyi, the agent-explorable namespace, not under @mx.
Each entry exposes the projected record facets plus a normalized field list:
| Facet | Meaning |
|---|---|
.name |
the declared record name |
.direction |
"input", "output", or "hybrid" |
.labels |
declared security labels (present only when declared) |
.read.selector |
active selector when one is known, such as .role:planner |
.read.fields |
visible fields mapped to their effective read mode |
.fields |
projected field list (below) |
Each .fields entry is a plain object — never a wrapped value, so no .value unwrap is needed:
| Field key | Meaning |
|---|---|
name |
field name |
classification |
"fact" for a field that carries proof, "data" otherwise |
kind |
"input" or "computed" |
optional |
whether the field is optional |
readMode |
effective mode for this field in the active projection |
schemaOnly |
true when the field is schema-visible but value-hidden |
dataTrust |
"trusted" / "untrusted", when set |
Raw write grants are not exposed here. The returned entries are deep-copied and frozen, so mutating a reflected entry cannot change the underlying declaration.
Inspecting read projections: @fyi.actors
@fyi.actors is a read-only projection inspector for declared actor read modes. It does not project a record value; it reports the effective schema-level mode each field would use for each declared .role:* actor key.
Use bracket access for actor keys because they contain colons. Bracket access works on a variable, so bind @fyi.actors first:
const @actors = @fyi.actors
show @actors[".role:planner"].projection.email_msg
The shape, with @actors bound as above, is:
@actors[".role:planner"].projection.<recordName>.<fieldName>->"value","mask","handle","protected", or"bare"- unlisted fields report
"protected" - fields declared with
{ omit: field }are filtered out completely, so the inspector does not reveal that the omitted field exists - inside a read-scoped box or LLM context,
@fyi.actors.projectiondefaults to the active actor's projection; outside an actor-scoped context, the rootprojectionis absent
@mx.actors is the current-context counterpart. It is scoped to the active actor only and indexes records at @mx.actors[".role:planner"].records.<recordName>. Outside an actor-scoped context, @mx.actors is empty. It also filters omitted fields.
@fyi.actors is for agent awareness and debugging. Enforcement still happens at projection boundaries such as LLM/MCP result rendering, @project, and scoped state reads.
Write permissions
A role's write grant controls whether that actor can write a record value into a state.
Records with no write grant cannot be written to a state. Which role may
authorize a tool is declared in policy, not in the record:
.role:planner { can_authorize: [@sendEmail] } (see policy-authorizations).
Tool submission is allowed when the tool is included in the provided tool
catalog, unless the policy turns on records_require_tool_approval_per_actor
(below). Records used purely for
=> record coercion (no write surface participation) need no write grant.
record @contact [
email: string [ kind "email" ]
name: string
notes: string?
* { read: [name, { value: email }] }
.role:worker { write: { state: [upsert] } }
]
record @send_email_inputs [
recipient: string [ kind "email" ]
subject: string [ kind "subject" ]
body: string
validate "strict"
]
record @update_password_inputs [
trusted password: string
exact password
]
A write grant sits in its role's block, .role:x { write: { <target>: [<capabilities>] } };
write is refused in the * block, so every grant names its role. Roles use the
same .role:planner / .role:worker labels as read. Each target takes a list
of capabilities, or true / false.
Target types: tools (tool dispatch via inputs: @record) and state (writes to a state's record slots).
Capabilities per target:
| Target | Capabilities |
|---|---|
state |
upsert, clear, remove (true grants upsert only) |
tools |
submit |
Tool dispatch has two phases. The planner authorizes (certifies the dispatch);
the worker submits (executes it). A role's authority to authorize a tool is
declared in policy as .role:planner { can_authorize: [@tool] }; a record
grant write: { tools: [authorize] } is retired and fails to load, naming that
form. Worker submission comes from membership in the provided tool catalog.
A policy can require more: with * { records_require_tool_approval_per_actor: true } in force, a tool whose inputs: record is @plan_inputs runs only
for a role whose block in that record grants write: { tools: [submit] }. Any other role,
or a call with no role, is refused with TOOL_SUBMIT_DENIED: record '@plan_inputs' cannot submit tool '<tool>' before the tool runs, and try
does not catch it. The switch can be set by a policy directive, by an
imported policy, or for one call with using { policy }; once any policy in
force turns it on, a false elsewhere does not turn it off. A tool with no
inputs: record, and an executable called directly, are not affected.
record @plan_inputs [
recipient: string
subject: string
.role:planner { write: { tools: [submit] } }
validate "strict"
]
exe .op:tool:w @sendEmail(recipient, subject) = `sent to ${@recipient}`
tools @writeTools = {
sendEmail: { mlld: @sendEmail, inputs: @plan_inputs, labels: [.op:tool:w] }
}
policy @approval = { * { records_require_tool_approval_per_actor: true } }
exe .role:planner @plan() = @writeTools.sendEmail("ada@example.com", "hi")
show @plan()
This prints sent to ada@example.com. The same call from an
exe .role:worker is refused.
When a model calls the tool through an llm call's tools:, the role is the
one that llm call runs as: the .role of the executable that makes the
call, a .role label on the llm executable itself, or the call's
using { read: ".role:planner" }. So
exe .role:planner @plan() = @ask("…", { tools: @writeTools }) lets the model
send, and the same call from .role:worker, or with no role, does not.
State writes name each capability. clear and remove are never implied by
upsert:
.role:worker { write: { state: [upsert, remove] } }
A state built from records is checked through the same state target.
state @book from @records creates one record_type[] slot per record type,
and writes check the concrete slot, such as @book.contact.
A capability cannot be narrowed to specific instances. A write capability
covers every in-scope instance or none. Narrow with box scoping instead, which
decides slot access before record permissions are consulted, or by controlling
the provided tool catalog.
To deny a worker access to a tool, do not include that tool in the provided
catalog, or list it under policy.authorizations.deny.
Deny-by-default for record write checks. A missing write grant, missing
role, missing target, missing capability, or scope mismatch rejects state
writes and planner authorization. Tool submission is controlled by the
provided tool catalog; use
policy.authorizations.deny or omit the tool from that catalog to deny
execution.
Composition with input-record constraints. write is orthogonal to
update, allowlist, blocklist, and correlate. All applicable constraints
fire at dispatch; any failure rejects the call.
The active actor at the write site comes from the LLM bridge's display selection
(using { read }, box config, or matching .role:* exe label). Writes from
non-bridge contexts have no active actor; deny-by-default applies to state
writes and planner authorization if the record declares a write grant.
Field remapping and computed fields
Remap a source field with @input.field as alias, and compute a field from a
template with { name: template }:
record @contact [
email: string [ kind "email" ]
@input.organization as org: string?
{ full_name: `${@input.first} ${@input.last}` }: string
]
const @ada = { email: "ada@example.com", organization: "Acme", first: "Ada", last: "Lovelace" } as record @contact
show @ada.org
show @ada.full_name
Output:
Acme
Ada Lovelace
@input.organization from the source becomes org in the record. Remapped and
computed fields follow the same rules as any other field: give one a kind
([ kind "person_name" ]) and it carries proof.
Root adapters
Records default to object-root input (@input.field accesses fields on the
input object). For non-object inputs, root adapters make scalars and maps
first-class.
Scalar root — coerce a single value:
record @username [
@input: string [ kind "username" ]
]
const @u = "alice" as record @username
show @u.mx.labels
When applied to "alice", the result carries .fact:@username.input. When
applied to ["alice", "bob"], each element is coerced individually.
Map entries — coerce an object as key-value pairs:
record @channel_member [
@key: string [ kind "channel" ]
@value: string [ kind "username" ]
]
const @members = { general: "alice", random: "bob" } as record @channel_member
show @members[0].key
When applied to { "general": "alice", "random": "bob" }, this produces two
records, one for each key-value pair. Each key and value carries its own fact
label.
Root adapters compose with read projections, trust refinement, and all other
record features.
Refine rules
refine [ … ] classifies records conditionally, based on the input data:
record @contact [
email: string [ kind "email" ]
internal: boolean?
refine [
match [
@input.internal => tiers += ["internal"]
* => tiers += ["external"]
]
]
]
const @a = { email: "a@example.com", internal: true } as record @contact
const @b = { email: "b@example.com" } as record @contact
show @a.email.mx.labels[0]
show @b.email.mx.labels[0]
Output:
.fact:internal:@contact.email
.fact:external:@contact.email
The nested match reads the internal field from the input and uses
first-match semantics: internal contacts get .fact:internal:@contact.email,
the rest get .fact:external:@contact.email. The * arm is the default.
Top-level refine entries are all-match: every matching rule can contribute
actions. A nested match [ … ] group is first-match, which makes default arms
explicit. Supported actions are:
labels += [.label]to add operation labelstiers += ["tier"]ortiers.email += ["tier"]to add fact tiersunprovenorunproven emailto drop proof, from every field or one. A
field it drops keeps theuntrustedit arrived with, even when the record
is listed inself_attestation.recordstrusted bodyoruntrusted bodyto set a field's trustattest { fact: "contact:email" }to attest the whole record, so
@c.mx.attestationslists.fact:contact:email. The name cannot contain a
dot:attest { fact: "contact.email" }is refused where it is written,
because no policy key could name the label it would make, and the error
suggestscontact:emailorcontact-email
labels also works as a settings line, to attach static labels to the
record's values whenever the record is used — on coercion with as record or
=> record, and as a tool input contract:
class .review:issue = { kind: "data", effect: "describe", description: "An issue under review" }
record @issue [
id: string [ kind "issue_id" ]
author: string [ kind "user" ]
title: string
body: string
author_association: string
labels .review:issue
refine [
match [
@input.author_association == "MEMBER" => [
tiers += ["maintainer"]
trusted title
]
* => unproven
]
]
]
Maintainer issues: fields with a kind get the maintainer tier and title is
trusted content. External issues: unproven drops proof from every field, so
no fact labels are minted, and inherited exe untrusted is preserved on all
fields.
A rule's left side is a condition, so a quoted string there is a constant:
refine [ "APPROVED" => labels += [.reviewed] ] labels every record, whatever
its text, and mlld validate warns about it. To label records whose text
contains a string, write the arm form, refine input [ "APPROVED" => labels += [.reviewed] ].
Label refinement is monotonic. Records can add labels, but removing labels
belongs to privileged guards.
Refine on a tool's input record. When the record checks a parameter
(exe @f(p as record @r)), the value comes from the caller, so the record
does not make it a fact: a value keeps the proof it arrived with. A tier
lands on that proof instead: a .fact:@contact.email value matched by
tiers += ["internal"] also carries .fact:internal:@contact.email, and a
value with no proof gets no tier. labels += still adds its labels, and
untrusted and unproven still apply, but nothing the record does raises
trust here — neither trusted body nor an input arm's data { body: "trusted" }
— because the caller wrote every field the rule reads.
Conditional classification via field-provenance predicates. Refine
conditions can use .mx.allFields(pattern) / .mx.anyField(pattern) to add
ordinary labels when the input's per-field provenance justifies it:
record @planner_output [
selection_refs: handle
refine [
>> declare review routing only if every leaf field is user-originated, fact-backed, or handle-backed
@input.mx.allFields({ source: ["user", "fact", "handle"] }) => labels += [.review:bounded]
]
]
Use a record mitigates line plus privileged record check actions when you need
authorization-relevant mitigation proof. Ordinary labels += is for
routing/classification; it may add an approval label unless a policy sets
self_attestation.code, and it never adds .trusted. See labels-influenced
and builtins-ambient-mx.
Validation modes
A validate line controls what happens when fields fail type coercion:
"demote"(default) — any validation error drops proof from the whole record; no fact labels are minted"strict"— any invalid field fails the entire record"drop"— invalid fields are dropped; remaining valid fields with a kind still get normal fact labels
record @contact [
email: string [ kind "email" ]
age: number
]
const @c = { email: "a@example.com", age: "old" } as record @contact
show @c.mx.schema.valid
show @c.email.mx.labels
Output:
false
[]
Arrays
When an exe returns an array, each element is coerced individually:
record @contact [
email: string [ kind "email" ]
]
exe @emitContacts() = js {
return [
{ email: "a@example.com" },
{ email: "b@example.com" }
];
} => contact
const @contacts = @emitContacts()
show @contacts[0].email
show @contacts[1].email.mx.labels[0]
Output:
a@example.com
.fact:@contact.email
List fields
A list field holds one value per element, each of the element type:
field @email [ type string; kind "email" ]
record @send_inputs [
to: @email[]
cc: string[] [ kind "email" ]
tags: string[]
validate "strict"
]
- With a kind, each element carries its own fact label and its own proof, so
@v.to[1]keeps.fact:@send_inputs.towhen it is read on its own. - As a tool input, every element has to meet the field's floor (see Fact kinds
and accepted proof). One element without proof, or with proof of another
kind, refuses the whole list and the error names the element. - Each element is coerced on its own. Under
validate "strict"an element of
the wrong type is an error that names its position (tags[0]); a
non-list value is always an error. allowlistandblocklistcheck every element.- Read projections apply per element: masked lists render each element as
{ preview, handle, address }when record-backed.
This is important for .risk:exfil:send operations where the destination is a
list of recipients. Positive checks like no-send-to-unknown verify each
element individually.
A field typed array also holds a list, with no element type. With a kind,
each element gets the field's fact label:
record @event [
participants: array [ kind "email" ]
organizer: string [ kind "email" ]
title: string?
* { read: [title, { mask: organizer }] }
]
const @e = { participants: ["a@x.com", "b@x.com"], organizer: "c@x.com", title: "Standup" } as record @event
show @e.participants[1].mx.labels
Prefer a typed list (string[] [ kind "email" ]) for a tool input: its
elements are checked one by one against the field's type and floor.
Nested records
A field whose type is a record holds an object shaped by that record, or a
list of them. Every nested shape is a named record; there are no inline object
types.
record @address [
street: string [ kind "street" ]
city: string
* { read: [city] }
]
record @item [ sku: string [ kind "sku" ]; name: string ]
record @order [
id: string [ kind "order_id" ]
ship_to: @address
items: @item[]
.role:planner { read: [id, ship_to, items] }
]
exe @load() = js {
return { id: "o1", ship_to: { street: "1 Main", city: "Town" },
items: [{ sku: "s1", name: "Pen" }] };
} => order
const @o = @load()
show @o.ship_to.street.mx.labels
show @o.items[0].sku.mx.labels
- Proof is named by the outermost record and the path.
streetabove
carries.fact:@order.ship_to.street, and each element'sskucarries
.fact:@order.items.sku(the element's position is on its proof record, not
in the label). The record that coerced the value is the authority over it,
so two records that both nest@addressmint different proof. A kind
pattern matches either way:.fact:*:streetreads the nested field's kind. - Bracket patterns stay one level deep.
.fact:@order[*]matches the
order's own fields and notship_to.street. Name a nested proof exactly
(.fact:@order.ship_to.street) or by kind (.fact:*:street). - Trust. The nested record's field defaults apply inside it: a field with
a kind is trusted, one without is untrusted. A record-typed field has no
trust of its own.untrusted ship_to: @addresstaints every field inside
while they keep their proof, andtrusted ship_to: @addressis an error. - Self-attestation is decided by the outermost record. Listing
@orderin
self_attestation.records(see Trust from an untrusted source) covers the
fields nested inside it. Listing@addressalone elevates nothing inside an
@order. - No settings on the field that belong inside. A kind,
accepts, or
field actions on a record-typed field are errors: put them on the nested
record's fields.key,hash,exact,update,allowlist,blocklist
andcorrelatename top-level fields only.keyandhashover a nested
field use its whole value. - Validation. A nested value has to be an object (each element, for a
list), and the nested record checks its fields. Errors name the path
(ship_to.street,items[1].name), and the outermost record'svalidate
mode decides what an error does. - Read projections. The outer
readlist names top-level fields. A nested
field it shows is rendered through the nested record's view for the same
actor: its role block, else its*list, else the strict default. The
planner above seesship_to.citybut notship_to.street. A list is
rendered element by element.{ mask: ship_to }masks the whole nested
value. - Parameters.
p as record @orderchecks each nested field with a kind
against its floor and mints nothing, as it does for top-level fields. - Not as a tool input when a kind is inside. A tool's arguments each carry
one role, so a record with a kind field at any depth can't be a tool input:
a catalog entry'sinputs:,mlld mcp, and anllmcall's tools refuse it
with "nested record@addresshas kind fields; make each kind field its own
argument". An exe whose ownwith { inputs }record nests one still loads
and runs when called directly. A nested record without kind fields is a fine
tool input, checked by shape. - A record can't contain itself (
record @node [ kids: @node[] ]is refused).
The nested record is the one defined when the outer record is, and a later
record of the same name does not change it.
Schema metadata
Record coercion attaches validation metadata:
.mx.schema.valid— boolean, whether validation passed.mx.schema.errors— array of{ path, code, message }objects.mx.schema.mode— the validation mode used
An after-guard can use this for retry or denial. Bind it in a policy:
record @contact [
email: string [ kind "email" ]
age: number
]
guard @checkSchema = match [
@output.mx.schema.valid == false && @mx.guard.try < 2 => retry "Fix the fields that failed validation"
@output.mx.schema.valid == false => deny "Schema invalid"
* => allow
]
policy @schemas = { .op:named:emitContact { after: @checkSchema } }
exe @emitContact() = js { return { email: "a@example.com", age: 3 } } => contact
const @ada = @emitContact()
show @ada.email
Fact sources
Record-derived values carry mx.factsources metadata — normalized source
handles for provenance tracking:
show @contact.email.mx.factsources[0].ref
Returns @contact.email — the canonical source reference.
Records as first-class values
A record @foo declaration registers two things: the record definition (used
for static coercion via => foo) and a record value (@foo) that can be passed
around like any other mlld value. show @foo prints a short summary of the
record's fields.
Import and export
Records flow through the standard variable import/export paths:
>> domain/records.mld
record @contact [ email: string [ kind "email" ] ]
record @email_msg [
from: string [ kind "email" ]
body: string
]
export { @contact, @email_msg }
>> agent.mld
import { @contact, @email_msg } from "./domain/records.mld"
exe @fetchContact(id) = cmd { contacts-cli get "$id" } => contact
The imported records work identically to records declared in the same file.
Records as parameters and in collections
Records can be passed as exe parameters and stored in objects or arrays:
record @email_task_payload [
trusted subject: string
trusted body: string
recipients: string
]
record @assignment_rows [
rows: array
]
const @contracts = {
email: @email_task_payload,
tasks: @assignment_rows
}
exe @extract(source, contract) = @agent(`Extract from: ${@source}`) => record @contract
const @result = @extract(@source_text, @contracts.email)
A record stored in an object or array displays as a JSON description of its
fields.
Dynamic coercion: => record @schema and as record @schema
Static coercion uses a bare record name:
exe @emitContact() = js { return { email: "ada@example.com" } } => contact
Dynamic coercion uses a variable reference prefixed by the record keyword.
There are two forms:
=> record @schemafor exe return coercion@value as record @schemafor inline value coercion in ordinary expressions
exe @validate(input, schema) = @input => record @schema
const @checked = @raw as record @schema
The record keyword disambiguates — => @schema alone could be ambiguous, but
=> record @schema is explicitly "coerce the output against the record
referenced by @schema." The same applies to inline coercion:
@raw as record @schema means "take this value and coerce it against the record
referenced by @schema."
Inline coercion is terminal postfix syntax: producer clauses come before it.
run cmd { ... } using { policy: @p } as record @schema
Nested references work:
const @contracts = {
email: @email_task_payload,
tasks: @assignment_rows
}
exe @extract(source, contractName) = [
let @contract = @contracts[@contractName]
let @extracted = @agent(`Extract from: ${@source}`)
=> @extracted as record @contract
]
const @result = @extract(@source, "email")
Resolution happens at runtime. If @contract doesn't reference a record,
coercion fails with a clear error.
When to use dynamic coercion
Static => contact is the common case — use it whenever the record is known at write time. Dynamic => record @schema and @value as record @schema are for patterns where the contract is passed in as configuration:
- Framework-driven coercion. A framework (like the capability agent pattern) takes a contract map from the developer and coerces extract output against the appropriate record at runtime.
- Contract-per-write-tool patterns. The extract phase emits data shaped for a downstream write tool. The contract for each write tool is defined once, passed into the extract worker, and coerced dynamically.
- Shared validation exes. A single
@validateexe that takes both data and a schema, used across many records. - Inline validation within larger expressions. Coerce a pipeline result, object field, array item, or direct variable before continuing the expression.
If you're writing a single-use exe with a known record, static coercion is simpler. Reach for dynamic coercion when the same exe or expression path needs to validate against different contracts at different call sites.
=> record works on every kind of executable (js, cmd, sh, node, py, and imported MCP tool wrappers), and @value as record @schema works inline. Arrays of records, and records written to and read back from a state, keep their proof.
Labeling a whole record
A label on a const composes with inline as record @schema. The label is
applied to the whole coerced record and each field, and per-field fact proof is
preserved:
record @contact [
email: string [ kind "email" ]
notes: string?
]
const @raw = { email: "ada@example.com", notes: "hi" }
const .secret @c = @raw as record @contact
show @c.mx.labels
show @c.email.mx.labels
Output:
[
".secret",
".fact:@contact.email"
]
[
".secret",
".fact:@contact.email"
]
The .secret label rides the whole record and each field, while email keeps
its .fact:@contact.email proof.
For field-level trust from an untrusted source, route the value through a
.untrusted exe that returns => record, as in
Trust from an untrusted source. There is no
as untrusted record form, and a .untrusted label on the const does not
reach the record's fields with a kind. The inline cast is for stamping a
record-wide label such as .secret.
Coercing a top-level null
When the value being coerced is itself null (the whole exe return, not a
field), => record / as record keeps it as null and prints a warning:
record @contact [
email: string [ kind "email" ]
name: string?
]
exe @maybe() = js { return null; } => contact
const @r = @maybe()
show @r.isNull()
Output:
true
The warning reads record '@contact' received a null where an object is required, so the null was preserved as absence rather than coerced into the record. This differs from null field-merge semantics, where a null field leaves
the stored value intact.
What records are not
Records are data-shaping definitions: their settings and field actions check,
reshape and label values, and do not run commands or reach the filesystem or
network. The one exception is a computed field whose template calls an
executable ({ big: `${@up(@input.name)}` }: string): that executable runs with its
normal effects. Keep such calls to pure functions so the record stays
predictable, testable and easy to review.
See facts-and-handles for how records, fact labels, and handles work together
in the security model. See labels-facts for the fact label system. See
pattern-schema-validation for the dynamic coercion pattern in
extract-to-write contracts.
State
state declares a named set of typed slots that the program changes through operations such as set and append. Ordinary variables never change once set; a state is the one place a value is meant to change.
There are four kinds:
| Declaration | Lives for |
|---|---|
state @s = { … } |
the run (or one call, when declared in an exe body) |
state @book from @records |
the same, with one record list per record type |
state session @planner = { … } |
one LLM call it is attached to |
state external @app = { … } |
the host program that started the run (see SDK state) |
Declare and change a state
state @todo = { count: number?, notes: string[]? }
@todo.set({ count: 5 })
@todo.increment("count")
@todo.append("notes", "first")
show @todo.count
show @todo.notes
This prints 6 and ["first"].
Each slot has a declared type, in the same syntax parameters and record fields use (see exe-metadata). Supported primitives are string, number, boolean, object, array and handle. Record-backed slots use @record or @record[] (a bare record name also works in a slot), and @record.field takes that field's type. A record-typed slot checks a value's shape against the record's declared fields, whichever record the value came from; extra keys are allowed. A handle slot takes a handle that resolves in this run. ? makes a slot optional; an unwritten slot reads as null.
Operations:
@s.set({ slot: value, ... })writes one or more slots.@s.append("slot", value)adds to a list slot.@s.increment("slot", delta?)adds to a number slot.@s.clear("slot")empties a slot.@s.update("slot", @fn)replaces a slot with@fnapplied to it;@fnmust be a localjs,nodeor data exe.
Read a slot by name: @todo.count. Every value read from a state carries the label .src:state:@todo.count (and matches .src:state), so guards and policy can tell where it came from. Every write is the policy operation .op:state:w.
State built from records
state @book from @records takes a map of record types and makes one list slot per type, named by its key. Writes to record slots go through upsert, and the record must grant the writing role permission:
record @contact [
key id
id: string [ kind "contact" ]
name: string
* { read: [id, name] }
.role:worker { write: { state: [upsert] } }
]
exe @mkContact(i, n) = { id: @i, name: @n } => contact
const @recs = { contact: @contact }
state @book from @recs
exe .role:worker @file(st, r) = [
let @w = @st.upsert("contact", @r)
=> "stored"
]
const @a = @file(@book, @mkContact("c1", "Ann"))
const @b = @file(@book, @mkContact("c1", "Annie"))
const @addr = @book.contact[0].mx.address.string
show @addr
show @book.byAddress("contact", @addr).name
show @book.contact.mx.version
This prints contact:69d3c20c81180863, Annie and 2. A record type with a key replaces the stored record with the same key, so the slot holds one contact after two writes. @book.byAddress("contact", addr) and @book.byKey("contact", key) (the key is the record's .mx.key) look one up, @book.remove("contact", record) deletes one, and @book.contact.mx.version counts the writes to the slot. A plain state can have record-typed slots too (pick: contact?).
The write grant is a list of operations, such as state: [upsert, clear, remove]; state: true grants upsert only. See Records for grants and State slots and agent scopes for showing a state to an agent. The @mlld/shelf module adds lookups by address, rendering for agents, and change tracking on top of a record-built state.
Labels on a declaration
A label written before the name applies to every value read from the state:
state .secret @vault = { key: string? }
@vault.set({ key: "abc" })
show @vault.key.mx.labels
This prints [".secret", ".src:state:@vault.key"].
State inside an exe
A state declared in an exe body belongs to that call. Each call gets a fresh one:
exe @mk() = [
state @c = { n: number? }
@c.increment("n")
=> @c.n
]
show @mk()
show @mk()
This prints 1 twice. A state can be declared at module level or directly in an exe body, not inside a nested block:
A `state` is declared in an exe body, where it belongs to that call, or at module level; not inside a nested block (`for`, `if`, `match`, `try`, `loop`, `box`, or a value block). Move the declaration up to the exe body.
Passing a state
state @s = { count: number?, items: string[]? }
exe @bump(st) = [
@st.increment("count")
=> @st.count
]
exe @add(slot, v) = [
@slot.append(@v)
=> @slot
]
show @bump(@s)
show @add(@s.items, "a")
This prints 1 and ["a"].
@f(@s)passes the state itself: the exe reads and writes the same slots.@f(@s.items)passes one slot. Its operations take no slot name:@slot.append(v).@s[@name]naming a declared slot passes that slot the same way.@f(@s.readonly())passes a reference that can be read but not written. A write through it is refused (STATE_READONLY_REFERENCE): "@st is a read-only reference to @s, passed as@s.readonly(), soappendcannot change it. Pass@sitself to let this exe write."- A slot copied into a variable or object (
const @c = @s.items) is plain data and has no operations.
Session state
state session gives one fresh instance to each LLM call it is attached to. It is the working state of a single planner or worker call.
state session @planner = {
count: number?,
previous_count: number?,
trail: string[]?
}
exe .op:tool:w @track() = [
@planner.increment("count")
let @snapshot = @planner
@planner.increment("count")
@planner.set({ previous_count: @snapshot.count })
@planner.append("trail", "tracked")
=> @planner.count
]
llm @agent(prompt, config) = [
const @n = @track()
=> `count ${@n}, previous ${@planner.previous_count}, trail ${@planner.trail}`
]
show @agent("Plan the work", {}) using { session: @planner, seed: { count: 0 } }
>> count 2, previous 1, trail ["tracked"]
Attach the session and its starting values with using { session, seed } on the call; with { session } is refused, and so is a session on an exe definition. seed sets slots before the first read; a slot that is not seeded reads as null. A session supports set, append, increment, clear and update.
let @snapshot = @planner copies the current values into a plain object. Later writes to @planner do not change @snapshot.
Where a session is live:
- Inside the attached call, and inside anything that call runs (an exe it calls, an inner
llmcall),@planner.countreads the attached call's state. - An inner call that attaches the same session joins the enclosing call's state: it reads and writes the same slots and does not get a fresh one.
- Outside any attached call, a read gives
nulland a write is refused: "@planner isstate session, which is live only inside an LLM call it is attached to:@agent(…) using session: @planner."
Reading a session's final state from the call's result is not available in mlld 2.2.0. To get a value out, return it from the call.
A convenience wrapper can attach a session on its inner call. Pass the starting values as an argument when the caller chooses them:
state session @planner = {
count: number?
}
llm @agent(prompt, config) = `${@planner.count}`
exe @agentWithState(prompt, config, initialState) = [
=> @agent(@prompt, @config) using {
session: @planner,
seed: @initialState
}
]
show @agentWithState("hello", {}, { count: 2 })
The inner call receives count: 2. When the wrapper is itself called inside a call that already attached @planner, its inner call joins that state, and its seed is refused whatever its value. This program raises that error: @inner asks for count: 9, but @outer has already seeded @planner with count: 5.
state session @planner = {
count: number?
}
llm @inner(prompt, config) = `inner sees ${@planner.count}`
llm @outer(prompt, config) = [
=> @inner("x", {}) using { session: @planner, seed: { count: 9 } }
]
show @outer("x", {}) using { session: @planner, seed: { count: 5 } }
session @planner is already attached by an enclosing call, so its frame is already seeded; remove `seed` from this call, or call it outside that attach to get a fresh frame
Remove seed: { count: 9 } and it prints inner sees 5.
External state
state external @app = { theme: string? } is the host program's state, supplied when the host starts the run (the SDKs' state option, or --state '{…}' on the command line). A run with no host state cannot read it. @app.set({ theme: "dark" }) writes it, and each write is sent to the host as a state:write event. Values read from it are untrusted by default (@app.theme.mx.trust is "untrusted"). See SDK state.
Older programs may use spellings that mlld refuses; see the migration guide.
Tapes
A tape is a durable record of calls. Every run already writes one of its own, which is what --resume uses to continue a run that stopped (see Checkpoint & Resume); you do not need a named tape for that. A named tape is a second record that holds only the calls you attach to it, under a name you choose, and it keeps growing across runs.
Use one when a script should keep something between runs:
- an agent's research: attach the lookups to a tape, and a later run reads back what earlier runs found;
- a conversation: keep an agent's turns on a tape, and pick the conversation up again in a later run with
.continue(seetape-methods); - a record of what was sent where, kept apart from the run tapes, which
mlld checkpoint cleandeletes.
Scripts read a tape back with the tape methods (see tape-methods).
Declare a tape and attach calls
tape @rick = { name: "rick" }
exe @lookup(city) = cmd { echo "weather in $city: sunny" }
const @paris = @lookup("Paris") with { tape: @rick, thread: "europe" }
const @lima = @lookup("Lima") with { tape: @rick, thread: "americas" }
show @rick.select({ type: "tool_call", thread: "europe" }).length
The first run shows 1. The tape keeps every run's calls, so each later run shows one more.
tape @name = { name: "..." } declares the tape. with { tape: @rick } on a call records that call on it, and thread (optional) groups calls inside the tape so they can be selected together. Tape and thread names follow the same rule (see Tape names).
A tape records the outside calls the attached call makes: commands, sh, node and python bodies, and llm calls, with what each one returned. An in-process js body is not an outside call and is not recorded. For an llm call whose module can locate the agent's conversation, the tape keeps that conversation too (see .conversation() in tape-methods).
The tape lives at .llm/tapes/<name>/, one file per run (<run-id>.tape.jsonl), with large results in a payloads/ folder beside them. Reading a tape reads every run's file, oldest first, including this run's file so far.
Tape names
A tape name and a thread name are each one lowercase word: lowercase letters, digits, - and _, starting with a letter or digit, at most 64 characters. rick, research-2 and q3_notes are names; Rick, my tape and a:b are not.
The rule is strict because the name is spelled into a label that policy rules match exactly (.src:tape:<name>, .src:tape:thread:<name>, below), and a tape name is also a folder. On a disk that ignores case, RICK would write to rick's folder under a label that a rule on .src:tape:rick does not match. So a name outside the rule is refused, never rewritten to lowercase:
tape @notes = { name: "q3_notes" }
exe @lookup(city) = cmd { echo "weather in $city: sunny" }
const @paris = @lookup("Paris") with { tape: @notes, thread: "europe" }
show @notes.select({ type: "tool_call", thread: "europe" }).length
tape @alias = { name: "RICK" }
tape name 'RICK' is not allowed: use lowercase letters, digits, '-' and '_', at most 64 characters (it becomes the label .src:tape:RICK and a folder name)
A thread name outside the rule is refused the same way, when the call runs: with { tape: @notes, thread: "Europe" } stops with thread name 'Europe' is not allowed: ... (it becomes the label .src:tape:thread:Europe).
A name must also be a plain, non-secret string, and not one of the words tape labels already use:
| Name | Result |
|---|---|
run, thread, unverified |
tape name 'run' is reserved — these words already name tape labels (below) |
| a secret value | a tape name cannot be secret: it is written to disk as a folder name |
../x, a/b, .hidden |
tape name '../x' is not allowed: ..., the refusal above |
Only a value declared with tape is a tape. A hand-built object such as { name: "rick" } has no tape methods. A tape stored inside an object keeps its methods, so @holder.t.select({}) works.
Notes a script leaves
A script can write its own record into the run's tape with @mx.tape.note("decision", "picked B", { data: @choice, facts: { decision: "D12" } }), and find it again with .select. A note is stamped with the file that wrote it and is never treated as proof, an approval or a checkpoint. See tape-methods. @mx.tape.snapshot(@value, { key }) stores a value and returns a reference that @mx.tape.lookup gives back in the run, and that @t.lookup reads from a named tape in a later run, without its proof.
Where a value came from: provenance labels
Every value read back from a tape carries labels that say where it came from:
| Label | On |
|---|---|
.src:tape |
everything read from any tape |
.src:tape:<name> |
everything read from the named tape <name> |
.src:tape:run |
everything read from a run's own tape (@mx.tape) |
.src:tape:thread:<thread> |
events recorded under that thread |
.src:tape:unverified |
everything read from a tape with no verified seal |
A policy rule or guard on .src:tape covers all tape reads. Combine labels to narrow it, for example .src:tape:rick with .src:tape:thread:europe. These labels describe origin only. They never make a value trusted or unlock anything.
Values read back are untrusted
Values from a tape come back untrusted, and they keep the labels they were recorded with. Those recorded labels can block but never permit: they count toward every deny rule and every guard that denies on them, and never toward anything a label unlocks.
class .pii = { kind: "data", effect: "restrict", description: "Personal data about a real person." }
tape @notes = { name: "notes" }
llm @ask(prompt, config) = cmd { printf 'summary of: %s' "$prompt" }
const .pii @record = "Ada Lovelace, 12 Byron Street"
const @summary = @ask(@record, {}) with { tape: @notes, thread: "intake" }
const @back = @notes.select({ type: "tool_result", thread: "intake" })[0].payload.raw_value.data
show @back.mx.labels
show @back.mx.trust
@back.mx.labels lists .pii beside the tape labels, so a guard that denies .pii still denies the copy. @back.mx.trust is untrusted.
This example, and the next, also print a NON_IFC_RUNTIME_LABELED_DATA warning: a labelled value went into a cmd {} body, where mlld cannot keep its labels on what the command prints back. It is advice, not an error; Checkpoint & Resume explains it and how to turn it off for one call.
Because recorded labels appear in .mx.labels, a guard that allows on @input.mx.labels.includes(...) would also allow a value read back from a tape. An allow-guard tests .mx.proof instead. It lists the facts the value carries: fields a record checked when the value came in, such as the email a => contact lookup returned (see labels-facts). A value read from a tape has none.
record @contact [
email: string [ kind "email" ]
name: string
* { read: [email, name] }
]
tape @crm = { name: "crm" }
exe @lookup(name) = cmd { printf '{"email":"ada@example.com","name":"Ada"}' } => contact
exe @send(to) = cmd { echo "sent to $to" }
guard @provenRecipient = match [
@input[0].mx.proof.includes(".fact:@contact.email") => allow
* => deny "the recipient is not a proven contact email"
]
policy @recipients = { .op:named:send { before: @provenRecipient } }
const @ada = @lookup("Ada") with { tape: @crm }
show @send(@ada.email)
const @copy = @crm.select({ type: "tool_result" })[0].payload.raw_value.data | @parse
const @result = match [
denied => `denied: ${@mx.guard.reason}`
* => @send(@copy.email)
]
show @result
The live lookup is sent. The same email read back from the tape is denied:
sent to ada@example.com
denied: the recipient is not a proven contact email
Reading a tape is not a call: it never adds to @mx.history and is not recorded on the run's tape.
A person's answers are on the run's tape too, as answer events: the question and options as shown, the option picked, how the answer came in and, when the host said, who answered (see match-ask). A tape keeps no text of a question that carried a secret. Reading an answer back through a tape is reading data, not being answered: only a resumed run's own question is served its recorded answer (see checkpoint-resume).
Sealed tapes
A named tape is sealed the same way as the run's own tape, when the project's config lists signers (self_attestation.signers, see policy-signers). Most projects do not need it: Sealed tapes says when you do, how to turn it on, and what an unsealed tape does and does not protect against. Under a seal that verifies, a value's recorded labels can permit an action as well as block one when it comes back through .lookup, .recall, replay or resume; it still comes back untrusted. What .select() and .usage() return is held to the rule for another session's history (@mx.hydrate): its recorded labels only block, sealed or not.
A tape file that claims a seal and fails the check refuses the whole read, naming the file:
tape .select(): run tape .../.llm/tapes/rick/<run-id>.tape.jsonl refused: it claims a seal, and there is no signers root to verify it against
A symlinked .llm, .llm/tapes, .llm/runs, tape folder, tape file, payloads folder or .llm/tape.key is refused the same way, and nothing is recorded through it.
Sharing one key across machines
Some things on a tape are stored as fingerprints rather than as the values themselves: what a call was given, the key @mx.op.key hands to an outside service, and the checks a resume relies on. Each fingerprint is made with a secret key, 32 random bytes that mlld creates the first time a project records anything, at .llm/tape.key. A fingerprint made with one key never matches one made with another.
So each machine's tapes match only its own. When the same project runs on several machines and their tapes should be compared, or one machine should pick up another's run, give them one key:
-
On each machine, name the key's file in the project's
mlld-config.json:{ "tape": { "keyFile": "~/.config/mlld/team-tape.key" } }The path can be absolute, start with
~/for your home folder, or be relative to the project folder. -
Run something that records on one machine. mlld creates the key at that path, readable only by you.
-
Copy that file to the same path on the other machines by a private channel, such as a password manager or an encrypted copy. Never commit it to git or send it in plain text.
Only mlld-config.json can set this. A script, a policy, an imported module, an environment variable and a request through an SDK cannot, so the project's author decides which key the tapes use.
The key file follows the same rules as .llm/tape.key: a symlink is refused, and so is a file that is not exactly 32 bytes. A run that cannot use the key records no tape and names the file it could not use. It never falls back to .llm/tape.key, because fingerprints made with a different key would quietly stop matching.
Whoever has the key can forge fingerprints. Anyone holding it can write a tape whose fingerprints check out, so on a tape without a seal nothing tells their record from yours. Give the key only to machines you trust as much as your own. If others can write to your tapes, turn on sealing (see Sealed tapes): a sealed tape is signed through your ssh-agent, and the shared key alone cannot forge that signature.
Copying a tape folder does not copy the key. A run or a named tape copied to another machine keeps its fingerprints, but they match only where the same key is configured.
Tape Methods
A value declared with tape (see tapes) and the run's own tape, @mx.tape, have six methods that read: .select, .usage, .conversation, .fork, .compact and .recall. The run's own tape also has .note, which writes a note to it, and .snapshot, which stores a value on it; .lookup gets a stored value back. Any other method name errors with tape has no method `<name>` . An imported llm executable adds .continue, which carries a conversation read from a tape into a new call.
Every value these methods return is untrusted and labelled with where it came from (see tapes for the labels and what they allow). Calling a reading method is a read, not a call: it never adds to @mx.history and is not recorded on the run's tape.
.select(filter?): events
.select returns the tape's events, oldest run first, including this run's events so far. It takes the same filter as @mx.history.select (see builtins-ambient-mx), plus thread and run:
tape @rick = { name: "rick" }
exe @lookup(city) = cmd { echo "weather in $city: sunny" }
const @paris = @lookup("Paris") with { tape: @rick, thread: "europe" }
const @lima = @lookup("Lima") with { tape: @rick, thread: "americas" }
const @calls = @rick.select({ type: "tool_call", run: @mx.tape.run_id })
show @calls.length
show @rick.select({ type: "tool_result", thread: "europe" })[0].payload.raw_value.data
show @rick.select({ type: "tool_call", after: @calls[0].id }).length
It shows 2, weather in Paris: sunny and 1, on the first run and on every later one: run: @mx.tape.run_id counts only this run's calls, and [0] is the oldest Paris result.
| Key | Matches |
|---|---|
type |
the exact event type, such as tool_call, tool_result, conversation |
producer |
the exact producer string |
after, before |
events after or before the given event address (<run id>/<event id>), event id or sequence number |
fact |
events whose own facts entry matches kind, and value when given |
tool |
events about a tool, by name; * stands for any run of characters |
path |
events a host recorded a path on, by exact text |
limit |
at most this many of the matching events, the oldest first |
last |
with limit, keep the newest instead (last: true) |
thread |
events recorded under that thread |
run |
only the events of one run, named by its run id |
host, session |
only one host session's files, oldest first, read as one stream; give both (see below) |
A thread, run, host or session that is not a string selects nothing, and so does host or session without the other. A sequence number counts positions within one run, so a numeric after or before on a tape with more than one run selects nothing: use an event's address, or add run.
An event's address is its run id and its event id, <run id>/<event id>: the event's own session_id and id, joined by /. It is unique across every file of a tape, and it is what a host's tape:record and mlld tape record return as event. Sequence numbers stay per file: a sealed line is never renumbered, so there is no sequence number across files.
A host session as one stream. A host session can span several files: a later process that takes the session up continues the same file, but a restart after close, or a file that could not be continued, starts a new one. { host, session } reads just that session's files, in order, as one list: host is the host's id and session its id for the session, as given to tape:open or mlld tape open. An after address continues into later files:
tape @t = { name: "harness" }
const @stream = @t.select({ host: "og", session: "sess-1" })
const @next = @t.select({ host: "og", session: "sess-1", after: "20261113T204752Z-1a2b3c4d/9f8e7d6c", type: "tool_call" })
show @next.length
A judge keeps the address of the last event it read, built from that event's session_id and id, and passes it as after next time. Each run writes the tape under the same run id as its own tape, so run: @mx.tape.run_id selects what this run recorded.
tool, path, limit and last work the same way on @mx.history.select; see builtins-ambient-mx for exactly what each matches. limit counts after every other key, thread included, and the events still come back oldest first. It makes the result smaller, not the read faster: .select loads and checks every file of the tape before it matches anything.
A key
.selectdoes not know is ignored, not refused.{ tools: "Bash" }(with ans) constrains nothing and returns every event. Check the spelling of each key against the table.
Judging a tape step by step
A judge that reads a long session does not need to read it all every time. Write it as a step: it takes the state it returned last time and the events since then, and returns the next state. Whoever runs the judge keeps the state between calls. The place to resume from is a run id and a sequence number, { run, after: seq }, or, for a host session that spans files, the address of the last event seen, { host, session, after: "<run id>/<event id>" }: a sequence number counts within one run.
exe @judge(state, events) = [
if @events.length == 0 [
=> @state
]
let @edits = @events.filter(@item.payload.tool == "harness:claude/Edit")
=> {
run: @state.run,
cursor: @events.at(-1).seq,
edits: @state.edits + @edits.length
}
]
exe @step(tape, state) = @judge(@state, @tape.select({ run: @state.run, after: @state.cursor, type: "tool_call", limit: 500 }))
The first call starts from { run: "<run id>", cursor: -1, edits: 0 }, and each later call passes the state the one before returned. limit bounds the work one step does; the next step picks up after the last event this one saw. The same judge runs on @mx.history by selecting from @mx.history.select without run.
To record which tape format a verdict judged, read it from the tape's first event: @tape.select({ type: "session_start", run: @state.run })[0].payload.config_version. Each run's file has its own session_start. Every tape written by a released 2.x mlld verifies under every later 2.x; a new major version may drop old formats, with a tool to migrate them. Tapes written before the first released mlld are not covered.
An event has the same shape as a @mx.history event: shared fields such as id, type and ts at the top, the type-specific fields under payload. A recorded result's value is payload.raw_value.data. On a result a host recorded, payload.recorded_content is the content hash mlld's tape door writes for clearing a source across sessions (see builtins-ambient-mx, "Clearing a source in every session that read it"): mlld writes it, replaces it on every read, and it is never authority.
Stored and pruned bodies
A host that records its own sessions can keep each event's body (what the person typed, a tool's arguments or result, a note's text and data, the data of an event type the host defines) in the tape's payloads/ folder instead of in the event, so the bodies can be deleted later while the tape still checks out. The event keeps its small fields (source, host_fields, facts, author, occurred_at, labels, why a call was denied) and names its body under payload.body. Anything that must stay checkable after the body is deleted, such as an author's signature over an event, belongs in those small fields, not in data. .select puts a body that is still there back into the event, and says what it found in payload.body.state:
state |
Meaning |
|---|---|
stored |
The body was found and matches; its fields are back in the event. |
pruned |
The body's file was deleted. Only the small fields are left. |
uncheckable |
The body is named with a key the host holds and this reader does not, so it cannot be checked and is not returned. |
The file holds the body's fields as one JSON object in the RFC 8785 canonical form (keys sorted, no spaces, numbers and strings written one fixed way), and its name is sha256- and the SHA-256 of those bytes in hex, or with a host key hmac-sha256-<key id>- and the HMAC-SHA256. A host can compute the same name before it hands the event over, with any RFC 8785 library; mlld's test vectors are in crates/mlld-interp/tests/fixtures/body-hash-vectors.json.
A body whose file was changed stops the read with an error. To find what was pruned: @t.select({ type: "message" }).filter(@item.payload.body.state == "pruned").
.note(kind, text, { data, facts }?): leave a note on the run's tape
@mx.tape.note writes one note to this run's tape, for a later reader to find by kind or fact:
const @choice = { option: "B", reason: "cheaper" }
@mx.tape.note("decision", "picked B for D12", { data: @choice, facts: { decision: "D12" } })
const @found = @mx.tape.select({ fact: { kind: "decision", value: "D12" } })
show @found[0].payload.text
It shows picked B for D12 when the run records a tape. kind is any non-empty string and text a one-line summary. data is any value. facts is a list of { kind, value } objects, each a non-empty string kind and a string value, that .select({ fact }) matches; an object of strings such as { decision: "D12" } is shorthand for one fact per kind. Only the list holds two facts of one kind:
@mx.tape.note("merge", "folded D12 into D13", { facts: [{ kind: "decision", value: "D12" }, { kind: "decision", value: "D13" }] })
.select({ fact: { kind: "decision", value: "D12" } }) and the same with D13 each find that note. The call returns nothing.
- The note is an
annotationevent whose producer isscript:followed by the file that made the call (its path from the project root, or@author/name@versionfor a registry module) and#with 12 hex digits of that file's source hash, so a note always says which code wrote it. - A note is never authority. Its facts are what the script claimed, not proof: a parameter or record that needs a fact proven is not satisfied by one. A note is never a resume point (a note of kind
checkpointis not a checkpoint), an approval or a user turn. - A note keeps the labels of its kind,
text,dataand facts. If any of them is secret, the note is written with its labels and its words, data and facts withheld (and its kind too, when the kind is the secret), so it reads back labelled secret and nothing secret reaches disk. - Each note takes the next
note#<n>position, apart from calls, so a note moves no call's position. A resumed run does not write again the notes of statements it restores; the statement that was running when the earlier run stopped runs again, and its notes are written again with it. - A run that records no tape writes nothing, and the call still succeeds.
.noteis refused on a declared tape, on another run's tape, and inside a guard.
.snapshot(value, { key }?) and .lookup(ref): store a value, get it back
@mx.tape.snapshot stores a value with its labels on this run's tape and returns a reference to it, a string like snap:20261020T101500Z-3f9a2c1b/8e41d0a7. @mx.tape.lookup gives the value back from the reference, or from the key you stored it under:
const @result = { id: 7, status: "paid" }
const @r = @mx.tape.snapshot(@result, { key: "cref-1" })
const @again = @mx.tape.lookup(@r)
const @same = @mx.tape.lookup("cref-1")
show @same.status
This shows paid.
To read a snapshot in a later run, store it while attached to a named tape (with { tape: @t }, see tapes), and look it up on that tape:
tape @handles = { name: "handles" }
exe @mint(value, ref) = @mx.tape.snapshot(@value, { key: @ref })
const @r = @mint(@result, "cref-1") with { tape: @handles }
>> later, in another run
tape @handles = { name: "handles" }
const @result = @handles.lookup("cref-1")
What comes back depends on where it is read from:
- In the same run (
@mx.tape.lookup, or@t.lookupon the tape the run is writing to), the value comes back exactly as stored, with its proof: a fact it carried still satisfies a record or parameter that needs one. Any code holding the reference or the key can get it back, as with@mx.history.resolve. A reference is as hard to guess as a value handle; a key only as hard as you make it. - From a named tape in a later run (
@t.lookup), the value comes back as every tape value does (seetapes): untrusted, without its facts, and labelled with where it came from, including.src:tape:unverified. Its recorded labels still block. When the tape is sealed by a signer your config lists, they can also count toward allowing. A tape that claims a seal that fails to verify is refused, not read. - A secret is never written to disk. A value carrying
.secretanywhere is written as withheld; the same run still gets it back, and a later run's lookup is an error saying the value was secret. - A lookup that finds nothing returns
null.@mx.tape.lookupreads only this run; read another run's snapshots through the named tape it wrote them to.
A key names one value per tape. Storing the same value under the same key again returns the first reference; a different value under a key that is taken is refused. A key may not be secret (it is written in clear) and may not start with snap:. If a tape was edited so that two snapshots share a key, the oldest wins.
- Each snapshot is an
annotationevent, stamped like a note and at the nextsnapshot#<n>position. A note of kindsnapshotis never read as one. - A resumed run does not store again the snapshots of statements it restores. A reference bound before the restart still resolves, but a resumed run is a new run reading the tape, so the value comes back without proof, as from a later run. A statement that touched a secret always runs again on resume, so a secret is stored again rather than read back. The statement that was running when the earlier run stopped also runs again, and stores its value again.
- In a run that records no tape, references look like
snap:mem/0and resolve only in that run. .snapshotis refused on a declared tape, on another run's tape, and inside a guard.
.usage(): size per event
.usage() returns one row per event, { id, run, type, thread?, bytes, tokens? }:
tape @rick = { name: "rick" }
exe @lookup(city) = cmd { echo "weather in $city: sunny" }
const @paris = @lookup("Paris") with { tape: @rick, thread: "europe" }
const @rows = @rick.usage()
show @rows.filter(@item.type == "tool_result")
The first run shows one row; each later run adds one, since the tape keeps every run's events.
bytes counts the stored line plus any payload files it names. tokens is the token count the event recorded; for a conversation event it is summed over the whole conversation. .usage() takes no arguments (tape .usage() takes no arguments); filter its rows instead.
.conversation(call, { run }?): an agent's turns
When an llm call runs an agent, its module can say where the agent's own log lives, through an @conversation adapter it exports beside the executable. The tape then keeps that conversation, and .conversation(call) returns it as { session_id, provider, events }.
A module with an adapter:
>> agent.mld: a stand-in agent that writes its session log where the adapter finds it
llm @ask(prompt, config) = sh {
mkdir -p .llm/sessions/demo
printf '%s\n' '{"type":"session","session_id":"s1"}' \
'{"id":"e1","seq":0,"ts":"2026-09-25T00:00:00Z","type":"message","payload":{"role":"user","text":"Name a prime"}}' \
'{"id":"e2","parent_id":"e1","seq":1,"ts":"2026-09-25T00:00:01Z","type":"assistant_turn","payload":{"text":"7"}}' \
> .llm/sessions/demo/s1.jsonl
printf '{"value":"7","_mlld":{"sessionId":"s1","provider":"demo"}}'
}
exe @locate(sessionId, cwd) = js { return cwd + "/.llm/sessions/demo/" + sessionId + ".jsonl" }
exe @ingest(text) = js {
const lines = text.split("\n").filter(l => l.trim()).map(l => JSON.parse(l))
return { header: lines[0], events: lines.slice(1) }
}
exe @emit(events, at) = js {
return events.slice(0, at + 1).map(e => e.type + ": " + ((e.payload && e.payload.text) || "")).join("\n")
}
const @conversation = { provider: "demo", locate: @locate, ingest: @ingest, emit: @emit }
export { @ask, @conversation }
locate(sessionId, cwd) returns the path of the agent's log, which must sit under .llm/sessions/<provider>/. The provider must be one plain folder name, and not host, sdk or a name starting mlld: a recorded conversation's events are marked with their provider, and those names mark events mlld itself writes, so a conversation under one is refused and not recorded. mlld makes that folder before the call, and the agent may write inside it while the call runs, though nowhere else under .llm/ (see enforcement-planes). If the folder cannot be given safely, the call still runs, with a warning, and its conversation is not recorded. ingest(text) turns the log into { header, events }. provider and emit are used by .continue (below).
The stand-in agent is a shell script, and sh blocks are off by default, so the scripts that import it switch them on with a policy line.
Reading the conversation back:
import { @ask } from "./agent.mld"
policy @allow_sh = { * { capabilities: { sh: true } } }
tape @chat = { name: "chat" }
const @answer = @ask("Name a prime", {}) with { tape: @chat, thread: "primes" }
const @call = @chat.select({ type: "tool_call", thread: "primes" })[0]
const @conv = @chat.conversation(@call)
show @conv.provider
show @conv.events.map(@item.type)
show @conv.events[2].mx.labels
call is a tool_call event from .select() or its event id; add { run: "<run id>" } when a bare id could name calls in more than one run. The result is null when the call recorded no conversation (a command, or a module without an adapter). Events carry the call's tape and thread labels, and the agent's own output also carries .src:llm.
| Error | When |
|---|---|
tape .conversation(): tape '<name>' has no tool_call <id> |
the id names no call on this tape |
the conversation of <id> was withheld because it carried a secret |
the call handled a secret, so its conversation was never written |
tape .conversation(): <id>'s conversation_ref '...' is not a conversation file of run <run> on tape '<name>' |
the event points outside its own run's files |
.fork(at, { name, run? }): a new tape from a point
.fork writes a new named tape holding the history up to and including the event at, and returns it. Earlier runs are copied whole; at's run is copied through at. The payload and conversation files those events name come along. Calls attached to the fork later in the same run continue from the copied history:
tape @plan = { name: "plan" }
exe @step(n) = cmd { echo "step $n" }
const @a = @step(1) with { tape: @plan }
const @b = @step(2) with { tape: @plan }
const @c = @step(3) with { tape: @plan }
const @second = @plan.select({ type: "tool_result" })[1]
const @alt = @plan.fork(@second, { name: "plan-alt" })
const @d = @step(4) with { tape: @alt }
show @alt.select({ type: "tool_result" }).map(@item.payload.raw_value.data)
This shows step 1, step 2, step 4. @plan is unchanged.
A fork writes a new tape, so a second run of the same script stops at .fork because plan-alt exists now:
mlld: tape 'plan-alt' already exists; fork writes a new tape at line 8, column 14
Give each fork a name that is new, or delete .llm/tapes/plan-alt/ before running it again.
at is an event from .select() or an event id; run picks the run for a bare id. A fork never signs anything. It keeps the source's seals only up to at, and a seal written after a call also covers that call's result, so forking at a call drops it. To keep a sealed stretch sealed, fork at a seal event or later.
| Error | When |
|---|---|
tape '<name>' already exists; fork writes a new tape |
the name is taken |
tape .fork(): expected { name: "<new tape>" } as the second argument |
no name |
tape .fork(): tape '<name>' has no event <id> |
at names nothing on this tape |
tape .fork(): <id> names a <type> in more than one run of tape '<name>'; add { run: "<run id>" } |
a bare id names events in two runs |
A reserved, secret or unusable name gets the same error as the tape declaration (see tapes).
.compact({ over, with, name }): a smaller copy
.compact writes a new named tape in which every recorded result larger than over bytes is replaced by a summary your own executable with produces. The original stays in the new tape's payload store, and the summary's payload.summary_of names it:
tape @research = { name: "research" }
exe @fetch(page) = node { return "page " + page + ": " + "x".repeat(3000) }
const @p1 = @fetch("one") with { tape: @research, thread: "pages" }
const @p2 = @fetch("two") with { tape: @research, thread: "pages" }
exe @brief(text) = `${@text.length} bytes, starting "${@text.slice(0, 8)}"`
const @small = @research.compact({ over: 2000, with: @brief, name: "research-brief" })
const @results = @small.select({ type: "tool_result" })
show @results[0].payload.raw_value.data
show @results[0].payload.summary_of
Everything else is copied as recorded, and the source tape is unchanged. A summary keeps the original's labels (and .src:llm when with is an llm executable) but carries no proof. A summary that is secret is written withheld. A compacted tape is never sealed, so everything read from it is untrusted. Each large result it keeps, whole or as a summary's original, records which run and event of the source tape it came from, so .recall can check that source later. Replay and resume never answer a call with a summary in place of what the call returned.
Every with call runs before anything is written, so a summarizer that fails leaves no tape behind. Like .fork, .compact writes a new tape, so running this example a second time stops with tape 'research-brief' already exists; compact writes a new tape.
| Error | When |
|---|---|
tape .compact(): expected { over, with, name } as the argument |
no options, or no name |
tape .compact(): `with` is required: the executable that summarizes a result |
no with |
tape .compact(): `with` must be an executable taking the original value |
with is not an executable |
tape .compact(): `over` must be a positive whole number of bytes |
over missing, zero, negative or fractional |
tape .compact(): unknown option `<key>`; the options are over, with and name |
any other key |
tape '<name>' already exists; compact writes a new tape |
the name is taken |
.recall: the original behind a summary
@t.recall(hash) returns the original a summary names, or any large result the tape holds, when an event of that tape references the hash:
tape @research = { name: "research" }
exe @fetch(page) = node { return "page " + page + ": " + "x".repeat(3000) }
const @p1 = @fetch("one") with { tape: @research }
exe @brief(text) = `${@text.length} bytes, starting "${@text.slice(0, 8)}"`
const @small = @research.compact({ over: 2000, with: @brief, name: "research-recall" })
const @hash = @small.select({ type: "tool_result" })[0].payload.summary_of
const @original = @small.recall(@hash)
show @original.length
show @original.mx.trust
Read as a field, without a call, @t.recall is a tool of one hash parameter, so an agent that sees summaries can ask for the full text. Put it in a tool collection:
tape @research = { name: "research" }
tools @kit = { recall: { mlld: @research.recall, description: "Fetch the full text a summary stands for" } }
The recalled value carries the tape's labels and is untrusted. From an unsealed tape its recorded labels can block but never permit. A tape whose seal fails is refused. A compacted tape is never sealed, but a recall from one re-opens the tape the original came from: when that source run was sealed, its seal still verifies and its event is unchanged, the recalled original's labels can permit, as a recall from the sealed source would. If the source was edited, is gone, or was never sealed, you get the same value with labels that can only block. Sealed tapes covers what sealing changes and whether you need it.
| Error | When |
|---|---|
tape .recall(): expected a payload hash like sha256-<64 hex> |
not a hash |
tape .recall(): expected one payload hash |
more than one argument |
tape .recall(): <hash> is not a payload of tape '<name>' |
no event of this tape references it |
tape .recall(): tape '<name>' no longer holds <hash> |
the payload file is gone |
.continue(conv, { at?, prompt }): carry a conversation into a new call
An imported llm executable whose module exports an @conversation adapter has a .continue method. It takes a conversation from a tape's .conversation() and a new prompt:
import { @ask } from "./agent.mld"
policy @allow_sh = { * { capabilities: { sh: true } } }
tape @chat = { name: "chat" }
const @answer = @ask("Name a prime", {}) with { tape: @chat }
const @conv = @chat.conversation(@chat.select({ type: "tool_call" })[0])
const @next = @ask.continue(@conv, { prompt: "Name a bigger one" })
show @next._mlld.carried
const @retold = @ask.continue(@conv, { at: 1, prompt: "Name an even one" })
show @retold._mlld.carried
show @retold.value
It shows native, transcript and 7, after a NON_IFC_RUNTIME_LABELED_DATA warning: the conversation's labels cannot follow it into the stand-in agent's shell code (see Checkpoint & Resume for what the warning means).
It returns { value, _mlld: { carried } }. carried says how the conversation reached the new call:
native: the adapter'sprovidermatches the conversation's and it continues from the last event, so the agent resumes a fork of its recorded session. The recorded log is left as it was.transcript: anything else, such as an earlierat(a 0-based event index) or a module for another provider. The adapter'semit(events, at)turns the events into text that goes before the prompt in a fresh call.
continue reads the conversation again from the tape it came from and uses only that read, so editing the value's fields changes nothing. The value must be the one .conversation() returned (passing it as a parameter or keeping it in an object is fine). A resumed run restores @conv without that mark, so call .conversation() again after --resume.
The answer carries the prompt's labels and the conversation's (the original call's input labels, .src:llm, and the tape labels), and no proof. Links that came from the resumed turns count as of unknown origin.
| Error | When |
|---|---|
continue needs an llm exe from a module with a @conversation adapter |
the executable is not llm, or its module has no adapter |
continue needs a conversation from a tape's .conversation(); a value restored by --resume or built by hand is not one, so read it again with .conversation() |
conv did not come from .conversation() in this run: an object with the same fields, a copy made with ..., or a value a resumed run restored |
@<exe>.continue: `prompt` must be text: @<exe>.continue(@conv, { prompt: "..." }) |
prompt missing or not text |
@<exe>.continue: `at` must be an event index: a whole number from 0 |
at is not a whole number from 0 |
@<exe>.continue: `at` must be an event index from 0 to <n> (the conversation has <count> events) |
at out of range |
<module>'s @conversation adapter has no emit, so this conversation cannot be carried as a transcript |
a transcript is needed and the adapter has no emit |
Services
A service is a node process that mlld starts on the first call, keeps running for the rest of the run, and calls declared methods on. Use one when a piece of work needs state that outlives a single call: a database connection, a browser, a loaded model. A node { … } block, by contrast, starts fresh every time it runs.
service @counter [
.op:store:r get(key)
add(key, amount)
close()
] = node {
const counts = new Map();
return {
get: (key) => counts.get(key) ?? 0,
add: (key, amount) => { counts.set(key, (counts.get(key) ?? 0) + amount); return counts.get(key); },
close: () => { counts.clear(); },
};
}
exe @bump(key) = @counter.add(@key, 1)
const @a = @bump("visits")
const @b = @bump("visits")
show @counter.get("visits")
This prints 2: both calls reached the same process, which kept its counts between them.
The declaration
- The method list in
[ … ]is written in mlld. Separate entries with a new line or;, never a comma. - The body runs once, when the process starts, and returns an object whose keys are exactly the declared methods. A body that returns other keys refuses at the first call, naming both lists.
- A method line may carry labels (
.op:store:r get(key)) and an input record (exec(sql, params) with { inputs: @writeArgs }), as anexecan. - Some names cannot be methods:
__proto__,constructor,then,prototype,mx,filter,find,some,everyandmap. - One
serviceper name per program. - Nothing starts until the first call. A service the program never calls never runs.
mlld validatechecks calls before anything runs: a method the service does not declare, the wrong number of arguments, a method name built at run time, a call policy would refuse, and two services with one name.with { timeout: 5000 }limits each call to that many milliseconds, and also the body's start: its run up to returning the method object. Node starting up does not count, so a limit sized for calls holds on a slow machine. There is no limit unless you set one. A call that runs past it fails the run; a start that runs past it fails like any start that fails.
What crosses into and out of the process
Arguments go in as JSON data, and only a method's returned value is its result. What the process prints (console.log, console.error) goes to mlld's stderr and is never part of a result.
undefined comes back as "no value", which is not null. A function, symbol, BigInt, Map, Set, Promise or stream cannot cross, and refuses naming the method. An Error object crosses as {}, a class instance as its own fields, and NaN or Infinity as null.
Credentials and environment values
secret @db = { from: "env:DB_URL", as: "DB_URL" }
const @region = "eu-west"
service @store [ query(sql) ] using { secret: "db", env: { REGION: @region } } = node {
const client = connect(secret.DB_URL, env.REGION);
return { query: (sql) => client.query(sql) };
}
using secret:db, orusing { secret: ["db", "cache"] }for several, gives the bodysecret.<name>, where the name is each credential'sasname.using { env: { NAME: @value } }gives the bodyenv.<NAME>.- Both objects are always present (empty when nothing was given), cannot be changed, and are never in
process.env. A subprocess the body starts gets a credential only if the body passes it on. secretandenvare reserved at the top of the body: declaring your own (const secret = …,var env,function secret()) fails the start, saying the name is reserved. Inside a nested function or block the names are yours.- The credential's value is read when the service starts. A credential that cannot be found fails the first call, and every later call. It never fails a program that does not call the service.
- Everything the process says is scrubbed of its credentials: what it prints, its results, its error messages and the method list it reports. Two limits: a value shorter than 8 bytes is not scrubbed, and neither is a transformed copy of a credential (base64, reversed).
- A credential does not label the service's results. An
envvalue does. Passing labelled data in prints a notice that a process outside mlld's label tracking now holds it.
Every call is an operation
Each call is judged by policy and guards like any other operation. Its operation label is .op:service:<name>:<method>:<mode>, where the mode is r when the method line carries an operation label ending in :r (.op:store:r get(key)), and w otherwise. A method nobody marked counts as a write.
So .op:service:counter { deny: true } refuses every call to @counter, .op:service:counter:add { deny: true } refuses only add, and a write rule such as .op:*:w catches every unmarked method. The name is always the declared one: importing @counter under another name does not change it.
A guard that retries a call (retry "…") runs the retry under the labels the guard read. The retry is judged again under those labels: a box rule, a deny, or an ask that the first call did not match refuses the retry. A retry is never asked, so a question nobody answered fails it.
A service remembers every label it was given
The process can use anything it was given to answer any later call. So a service keeps every label written into it: its declared labels, each call's arguments, and the labels of any condition a call was made under. Every result and every error of the service carries that whole set, and policy judges each call as if its arguments carried it too.
const .secret @token = "abc"
const @saved = @log.note(@token)
const @later = @log.recent()
Here @later carries .secret, though recent() was called with no arguments, because @log was given @token earlier.
So a call with clean arguments can still be refused, because of what the service holds:
policy @p = { .secret { deny: [.net:w] } }
const .secret @token = "abc"
service @kv [ put(k, v); .net:w post(url) ] = node {
return { put: (k, v) => 'ok', post: (url) => 'sent' };
}
const @a = @kv.put("t", @token)
const @b = @kv.post("https://evil.example")
The second call is refused: its argument is clean, but @kv holds .secret and post is an outbound write. The refusal names the label and the service (service @kv holds '.secret'), never the secret's value. To keep a service that sends things out usable, keep secrets and outbound calls in separate services.
A program that declares a law (never:) cannot use services. mlld proves every law before the program runs, that check cannot yet see inside a service statement, and a law it cannot prove refuses the whole program: refusing to run …: a law the policy declares is not proven … unanalysed: a service statement. This holds even for a service that is never given labelled data. In a program that uses services, write the rule with deny: instead.
In a pool (below), a result carries the set as it stands when the result arrives, so a value one process stored in a shared database cannot come back unlabelled through another.
Calls inside a labelled condition
A call made only when a labelled condition holds would reveal that condition through what the service remembers. So such a call is refused, and the refusal cannot be caught with try:
const .secret @token = "abc"
service @log [ note(x) ] = node { return { note: (x) => x }; }
if @token == "abc" [
const @n = @log.note("matched")
]
This stops with "Cannot call service @log here: this call runs under conditions labeled .secret, and @log does not carry them." If the service is meant to hold that kind of data, declare it with the label up front, service .secret @log [ … ], and the call runs.
Pools
with { pool: 2 } lets a service run up to two processes. The default is one. A second process starts only when a call arrives while the first is busy; past the pool's size, a call waits. The pool shares one label set.
In a pool, a call can reach any of the service's processes. A method cannot rely on an earlier call having reached the same process:
gotothentexton a browser service can land on two different browsers. Keep per-session state outside the process, or use the default pool of one.
When the process dies, and the end of the run
- A process that crashes, breaks its protocol or runs past its time limit fails the run. Nothing restarts it, and
trycannot catch it. - At the end of a run, whether it succeeded or failed, and on Ctrl-C, mlld calls the service's
close()if it declares one, waits up to 2 seconds (1.5 seconds after Ctrl-C), then stops the process. close()is skipped, and the process simply stopped, when policy denies or would ask about theclosecall, when node is denied, or when a call was cut off mid-reply.- A
close()that throws or runs out of time is reported on stderr and does not change whether the run succeeded. - A process the body starts is stopped when the run ends, including one started with node's
detached: true. A daemon that forks twice can still outlive the run; seerun-basics("Processes a command leaves running").
The sandbox
A service runs in a sandbox, fixed when the service is declared. It is the narrowest of four things: the sandbox a node { … } block would get, the box configuration named by using box:@b on the declaration, every policy box rule on .op:service:<name>:* that the service's labels and credentials match, and what its methods declare (below). Every process of a pool runs in it. When a policy rule narrows it, mlld prints a note naming the rule at the first start.
Method declarations are enforced. A method's .fs: and .net: labels, together with any on the service itself, declare what the method's code may do, as an exe's do (see labels-overview): no .net: label means no network, and no .fs:w or .fs:rw label means no file writes. Every method runs in the same process, so the process gets the widest of their declarations, and only when every method is declared. A single method with no .fs: or .net: label leaves the whole service undeclared, and it runs as before.
service @kv [ .fs:r get(key); .net:w post(url) ] = node { … }
Here post declares the network, so the process has it, for get as well; neither method declares writes, so the process cannot write files. service .fs:r @kv [ get(key) ] = node { … } declares every method .fs:r: no network and no writes. A declaration only narrows the sandbox above it, never widens it. If the computer cannot fence what a declaration takes away, a declared service is refused while a policy is in force, and otherwise runs as an undeclared one would.
- On a service,
using box:@bnames a box configuration such asconst @b = { net: "none" }. On anexeor a call,using box:nameselects a profile of the box already running. - A later call whose rules need a stricter sandbox than the service runs in is refused, naming the rule. So is a call that needs a box of its own: one service is shared by the whole run.
- A call made inside a
boxblock is refused unless the service can reach no more of the network, and write to no more places, than that box allows. - With the sandbox switched off in
mlld-config.json, the service runs with open files and network, plus its connection to mlld. Box rules andusing boxstill narrow it, and a rule that only asks for "some box" refuses. - If the computer cannot start any sandbox, the service refuses at its first call and says why.
- On Linux,
net: "none"refuses every network socket, TCP and UDP alike. A service still connects to mlld over a unix socket, and Linux cannot limit that to one path, so a service there can open any unix socket on the machine (such as/var/run/docker.sock).
Resuming a run
A statement that called a service is run again on resume, not restored: a resumed run starts its services fresh, so their calls must be made again. A resumed service also keeps the labels recorded for it before the point resume restarts from. A write method called before the resume point runs twice. In a loop, only the rounds that called a service run again.
Service calls are recorded on the run tape for audit, as service:<name>.<method>, and never answered from it. Replay always makes them live, and --other and --live do not apply to them. See Checkpoints and resume.
Services under mlld mcp
A module served with mlld mcp can declare and call services. A service starts at the first tool call that uses it (or while the module loads, if the module calls it at the top level) and lives until the server stops. All tool calls share it, so its labels carry from one tool call to the next.
- A crash fails the tool call it happens in, as a tool error, and the server keeps serving. The crash is also reported once by the next call to any service of that module. The crashed service stays down until the server restarts; its later calls fail.
- When the server's input ends, or on Ctrl-C or SIGTERM, mlld runs
close()and stops the process as at the end of a run. - Labels from every tool result also carry into later tool calls, and they count as the condition each later call runs under. So once any tool has returned
.secretdata, every later call to a service not declared.secret, and not already holding.secret, is refused for the rest of the server's life (see "Calls inside a labelled condition" above). Declare the service.secretif it is meant to be used after secret data has passed through the server.
Services under mlld serve live
Under mlld serve live, a service lives for one request, as state does: it starts at its first call in the request and is closed when the request ends, including on cancel. Nothing it holds, labels included, carries to the next request, and requests running at the same time each get their own process. A crash fails only the request it happens in.
Not supported yet
- Windows: a service refuses, saying so.
- A
pythonbody refuses with a "not yet" error.
Builtins
Ambient @mx Accessors
mx is the mlld execution context — ambient @mx is the context you're standing in, per-value .mx is the context of the value you're holding. Ambient @mx is runtime state for the current execution; @someValue.mx is the execution context attached to a specific value.
mx is a reserved variable, so it cannot be used as a free identifier inside js/node code blocks.
The whole-object read
A bare @mx read (show @mx, const @dump = @mx, or @mx in a template) returns one object holding the context that can be read safely at that point, so a debugging dump is a single read. Its keys are profile, actors, handles, with, llm, tools, denied, denial, ask, for, loop, while, errors, history and warnings. Two things about the dump are deliberate:
- Some frames are left out, not null.
op/operation,guardandsessionnever appear in the dump. If you bind it and read through it (@dump.op.metadata), the read is an error, the same error the named read gives — it does not answer null, because a null there could let a labeled value reach a sink a guard should have blocked. Ask@mx.op.typeby name instead; that works. - Omission is not evidence of absence. A program that tests
@dump.guardover the dump refuses; a program that needs a frame must use the named read. There is no key in the dump whose presence or absence means "an operation is (not) running".
The dump's members are the same views the named reads produce, live at the moment of the read. js bodies receive a different curated mx param — the pipeline frame (input, try, tries, hint, stage, isPipeline, lastOutput, with, pass) — because a code body always runs inside an invocation; the mlld-level dump is the session ambient. The two surfaces are curated on purpose and differ on purpose.
Use @mx.* when you want to inspect the current execution context:
@mx.llm.config,@mx.llm.allowed,@mx.llm.native,@mx.llm.inBox@mx.llm.sessionId@mx.llm.read@mx.llm.resume@mx.actors@mx.handles@mx.handles.unfiltered@mx.history@mx.hydrate(history, config?)@mx.tape@mx.op.key@mx.moduleDigest(path?)@mx.bindPending(toolCatalog)@mx.warnings
With-clause metadata
Data a caller passes along with a call goes under with { pass: { ... } }, and the callee reads it as @mx.pass:
exe @tagged() = @mx.pass.requestId
show @tagged() with { pass: { requestId: "req-42" } }
Reserved keys such as format, pipeline, stream and trace configure the call and are not copied into @mx.pass. A key mlld does not read is an error rather than call data, so data always goes under pass. Reading @mx.with is an error that names the @mx.pass read to use instead.
A labelled value passed in pass keeps its label: @mx.pass.<key> reads back with the value's security descriptor attached, so a policy that denies that label denies it at every downstream sink — the same value passed as an ordinary argument is already governed this way.
Warnings
@mx.warnings is the runtime warning buffer for the current invocation. Runtime advisories — the warnings printed to stderr, such as the non-IFC boundary advisory — are recorded there while still using the existing warning output path.
show @mx.warnings
show @mx.warnings[0].code
Each entry has message and may include code, suggestion, and location.
Values from a resumed run
A value that a resumed run took from its tape carries the .src:tape label; test its labels to tell it apart from one computed live.
The run's tape
@mx.tape is the current run's own tape (see Checkpoint & Resume) as a tape value, { script, run_id }. It has the tape methods (see tape-methods), and reads what this run has recorded so far:
exe @greet() = cmd { echo hello }
const @g = @greet()
show @mx.tape.run_id
show @mx.tape.select({ type: "tool_call" }).length
show @mx.tape.select({ type: "tool_call" })[0].mx.labels
Events read from it carry .src:tape and .src:tape:run, and are untrusted like every tape read (see tapes). A run started with --no-checkpoint records no tape, and @mx.tape errors with @mx.tape: this run records no tape. @mx.tape is not part of the bare @mx dump.
@mx.hydrate accepts events from a tape's .select(). Its call record then names the tape file's run_id and head_hash beside the event count. When a verified seal covers every event the read returned (see tapes), the history is sealed, and the record also names the signer in sealed_by (see What counts as proof after hydration).
@mx.history or @mx.tape?
A run keeps two logs, and they record different things:
@mx.historyis the session history that guards and policy read: the executables the script called, plus messages, asks and verdicts.@mx.hydrateloads an outside history into it. It lives in memory for this run.@mx.tapeis the run tape on disk: the outside commands and model calls those executables made, plus snapshots.--resumeand replay read it.
So one call appears in both, under different names and ids:
exe @greet(name) = cmd { echo "hi $name" }
const @g = @greet("Ada")
show @mx.history.toolcall[0].payload.tool
show @mx.tape.select({ type: "tool_call" })[0].payload.tool
This shows greet (the executable) and then cmd (the command it ran). Read @mx.history when a guard or decision needs what the script did in this session; read @mx.tape to look at what the run sent to the outside world, or at an earlier run.
A key for each outside call
@mx.op.key is a key for the place in an executable call where it is read. Many services that take payments, send messages or start deploys support idempotency keys. Send @mx.op.key as that key, so that service can deduplicate the retry when --resume makes the call again after a crash (see Checkpoint & Resume). The key alone prevents nothing; where a repeat must be prevented here, label the executable .once instead. Sending the key:
exe @post(key, card, amount) = cmd { curl -X POST https://api.example/charges -H "Idempotency-Key: $key" -d "card=$card&amount=$amount" }
exe @charge(card, amount) = [
let @key = @mx.op.key
=> @post(@key, @card, @amount)
]
The key is the same for this call in the run that made it, in every --resume of that run, and in every --replay of it. It is different for every other call: a second call to @charge, a call in another loop iteration, and the same call in a fresh run all get their own. Inside one call, each loop iteration and each parallel branch has its own key, so a loop that makes one outside call per item sends each item its own key:
exe @post(key, card, amount) = cmd { curl -X POST https://api.example/charges -H "Idempotency-Key: $key" -d "card=$card&amount=$amount" }
exe @chargeAll(cards) = for @card in @cards => [
let @key = @mx.op.key
=> @post(@key, @card, 10)
]
Two reads in the executable's own body, outside any loop, get the same key. It is made from where the call is in the script and which run it belongs to, not from the arguments, so a resumed call whose arguments changed sends the same key; a service that sees the same key with a different request usually refuses it, which is the safe outcome. The key is 64 hex characters and says nothing about the call's arguments.
Read it in the executable, at the place that makes the outside call or passes the key to it, as @charge passes it to @post. Outside any executable, @mx.op.key errors with @mx.op.key is read inside the exe that makes the outside call: it names that exe call. A run started with --no-checkpoint records no tape, and the read errors with @mx.op.key: this run records no tape, so it has no per-call key.
Editing the script before a resume can change a key: adding another call to the same executable earlier in the same executable or statement moves this call to a new place. Resume already runs again from the first edited statement (see When the script changed).
A digest of the code that ran
@mx.moduleDigest() returns { digest, mlldVersion }: a fingerprint of the program's main file and every module its imports reach. The same code gives the same digest on any machine, wherever the files sit on disk, so two parties can compare digests to show they ran the same judge. Changing any file in it changes the digest. @mx.moduleDigest("./judge.mld") digests another module instead, with the path read from the calling file's directory; a program that was not run from a file must name one. mlld module digest <path> prints the same digest from the command line.
const @ran = @mx.moduleDigest()
show `judged by ${@ran.digest} on mlld ${@ran.mlldVersion}`
The digest is of the files as they are when it is asked for. It is never written on the run's tape: a plain fingerprint can confirm a guess at what a file holds, so the tape keeps only fingerprints made with the project's secret key (see tapes). A script that wants the digest in its record writes it there itself. A registry module counts by the hash of its published files; an import mlld cannot read, such as a URL, counts by its reference only. The mlld version sits beside the digest, not inside it.
Serialized Session Hydration
@mx.history is serialized event-history context. It is separate from state session state and from @mx.llm.sessionId provider metadata.
A decision script loads a history with @mx.hydrate and then queries it:
const @history = [
{ id: "e0", parent_id: null, seq: 0, session_id: "s1", ts: "2026-09-26T00:00:00Z", producer: "hook", type: "session_start", payload: { config_version: "1" } },
{ id: "e1", parent_id: "e0", seq: 1, session_id: "s1", ts: "2026-09-26T00:00:01Z", producer: "hook", type: "message", payload: { role: "user", text: "Please approve sending to Ada" } }
]
const @loaded = @mx.hydrate(@history)
show @mx.history.user.values
show @mx.history.user.includes("approve sending to Ada")
show @mx.history.facts("contact").includes("ada@example.com")
This shows ["Please approve sending to Ada"], false, and false. The message is in the history, but a history built in the script is not sealed, so it proves nothing: .includes asks whether the user's words are known, and they are not, and no fact is established (see What counts as proof after hydration). In a run that has hydrated nothing and made no calls, every view below is empty.
Event-specific views are available:
show @mx.history.session_start
show @mx.history.thread_start
show @mx.history.toolcall
show @mx.history.toolresult
show @mx.history.ask
show @mx.history.verdict
show @mx.history.error
show @mx.history.meta
@mx.history.meta holds annotations folded last-wins per kind — the session and thread names that render as headers.
Values read back from history keep their security labels. A secret passed to any function comes back from @mx.history.toolcall still labelled secret, and a guard or policy rule that blocks the original blocks the copy too. Each tool_call event records its arguments' labels in a payload.args_mx field, a tool_result that recorded a value keeps its labels on payload.raw_value (a call a script makes to its own executable records no value; see What counts as proof after hydration), and any other event whose content was labelled (a message added with @mx.history.addevent.user, an ask payload) records them in its labels field. The lists built from event text, @mx.history.user.values, @mx.history.llm, @mx.history.meta and @mx.history.facts(kind).values, carry the labels of the events they came from.
The labels come back as labels that can block but never permit. They count toward every deny rule and every guard that denies on them, and never toward anything a label unlocks: an accepts list, a :not(.reviewed) exception, a trust check, a grant, a guard's allow. So a draft labelled .pii and .reviewed, read back from history, is still refused by a .pii:not(.reviewed) rule until it is reviewed again in this run. The labels also cover a whole argument: if one field of an object argument is secret, every field read back from that argument counts as secret.
Event shape
Every event has the same two parts. The fields every event shares sit at the top level: id, parent_id, seq, session_id, user_id, ts, producer, type, and, when present, payload_hash, facts, labels and prev_hash. Everything specific to the event's type sits under payload:
{
"id": "a1b2c3d4", "parent_id": "0f0e0d0c", "seq": 3, "session_id": "s1",
"ts": "2026-09-23T12:00:00.000Z", "producer": "record", "type": "message",
"payload": { "role": "user", "text": "Please send this to Ada" }
}
So a script reads a message's text as .payload.text, and a tool call's tool as .payload.tool. The views, select, @mx.hydrate's input and the run tape's lines all use this shape. @mx.hydrate refuses an event with a type-specific field at the top level.
@mx.history.llm lists assistant text. Assistant output may be recorded as assistant_turn events or as assistant message events; when both appear with the same text, the text is listed once.
Querying events in order
@mx.history.select(filter) returns matching events ordered by sequence. Every filter key is optional, so an empty filter returns the whole history:
show @mx.history.select({ type: "tool_call" })
show @mx.history.select({ type: "tool_call", after: "evt-123" })
show @mx.history.select({ producer: "record" })
show @mx.history.select({ fact: { kind: "path", value: "/etc/hosts" } })
| Key | Matches |
|---|---|
type |
the exact event type, including types this version does not recognize |
producer |
the exact producer string |
after |
events after the given event id or sequence number |
before |
events before the given event id or sequence number |
fact |
events whose own facts entry matches kind, and value when given |
tool |
events about a tool whose name matches; * stands for any run of characters |
path |
events whose host-recorded host_fields name the path, by exact text |
limit |
at most this many of the matching events, the oldest first |
last |
with limit, keep the newest instead (last: true) |
show @mx.history.select({ tool: "harness:claude/*", type: "tool_call" })
show @mx.history.select({ path: "src/main.rs" })
show @mx.history.select({ type: "tool_call", limit: 10, last: true })
tool reads the event's own tool name: payload.tool, or payload.tool_name on a tool_failed. An event that names only a call's tool_use_id takes the tool of the latest tool_call with that id at or before it. So { tool: "Bash" } finds a call, its result, its failure, and a verdict or ask about it; add type to narrow. Without * the name must match exactly: a host tool recorded as harness:claude/Edit is not matched by { tool: "Edit" }; use { tool: "*/Edit" } or { tool: "harness:claude/*" }. * follows the policy's tool patterns: harness:claude/* matches every tool under that prefix.
path matches payload.host_fields.path when it is a string, or any string in payload.host_fields.paths. A host writes those fields when it records a tool call or result. The text must match exactly: src/main.rs does not match ./src/main.rs, and there is no prefix or pattern matching.
limit takes a whole number from 0, and counts after every other key. With last: true it keeps the newest of the matches; either way they come back ordered by sequence. last without limit changes nothing.
A tool or path that is an object or array, a limit that is not a whole number from 0, or a last that is not true or false returns no events.
A key
selectdoes not know is ignored, not refused. A misspelled key such astoolsconstrains nothing, so the query returns every event the other keys allow. Check each key's spelling against the table.
The fact filter matches what an event claims. It is a query, not a permission check — @mx.history.facts(kind).includes(value) remains the only view that answers whether something is proven.
An after or before that names no event, or names an id that appears more than once, returns no events rather than ignoring the bound, so a guard asking for "tool calls after the approval" never widens to every tool call. The same holds for a bound that is neither an event id nor a number.
Calls to @mx.history methods such as facts, select and resolve, and the @mx.hydrate call itself, are recorded as tool calls. They appear in later select results (a select call is never in its own result). Their producer is record, which is also the producer of every event in a history mlld recorded itself, so producer cannot separate them. To get only the hydrated events, bound the query by position with before or after and an event id.
Unrecognized event types
History may contain event types this version of mlld does not know. They are recorded, appear in @mx.history.events, and are selectable by name, but they contribute nothing to the security posture. New event types can therefore be added without breaking existing scripts.
Trusted framework code can append decision-local events:
const @userEvent = @mx.history.addevent.user("Please send this to Ada")
const @llmEvent = @mx.history.addevent.llm("I will prepare the message")
const @askEvent = @mx.history.addevent.ask({
ask_id: "ask-001",
tool: "send_email",
question: "Send to Ada?"
})
const @verdictEvent = @mx.history.addevent.verdict({
tool: "send_email",
verdict: "allow",
reason: "recipient matched session fact"
})
@mx.hydrate(history, config?) validates ordered event history, folds it into @mx.history, and optionally registers serialized records, declarations, policy, and tools from a serialized Session config.
Labels a recorder attaches
A program that records an agent session mlld did not run, such as an agent harness, can label each tool result: on the event's labels field, or on the result's raw_value. When the session is hydrated, those labels only restrict. They count toward every deny rule and guard, and never toward anything a label unlocks: a guard arm @input.any is .reviewed => allow does not match when the only .reviewed is a recorder's, and @input.any is not .reviewed => deny "…" does. A recorded .trusted, .fact:* or .src:user:intent:* label earns no trust, no fact and no proof, and a seal does not change that: a seal proves who recorded the labels, not that they are authority.
A recorder's label is added to what every hydrated value already carries, and never replaces it. A result labelled .src:web still reads back untrusted, and an unsealed one keeps .src:tape and .src:tape:unverified. Each result's labels stay on that result: a WebFetch result labelled .src:net does not label the Read result beside it.
A recorder should label results by where they came from:
| Tool | Label |
|---|---|
| WebFetch | .src:net |
| Read | .src:file |
| Bash | .src:cmd |
an MCP tool on server <server> |
.src:mcp:<server> |
The standard policy (@standard from @mlld/policy) marks .src:net and .src:mcp:* data .untrusted, and a policy can deny by source directly:
policy @noNetWrites = { .src:net { deny: [.op:tool:w] } }
With that rule, a WebFetch result read back from a hydrated session cannot be passed to a tool labelled .op:tool:w.
Influence after hydration
A hydrated history can be an agent session mlld did not run, such as a host's harness session. Once an untrusted tool result enters that session, the model has read it, so every later model output in the session is .influenced: assistant turns and messages, thinking, and the tool calls it proposes, with their arguments, as D68 holds for mlld's own llm calls. The pending call @mx.bindPending binds is the model's own proposal, so @pending is influenced too when its session is. @pending names no session, so it is judged against the sessions that recorded a call with its tool_use_id, and against every session in the history when none did. Nothing before the result is influenced, and influence stays in its own session.
policy @influence = { * { llm: { influence_from: [".src:net"] } } }
const @history = [
{ id: "e0", parent_id: null, seq: 0, session_id: "s1", ts: "t", producer: "host", type: "session_start", payload: { config_version: "1" } },
{ id: "e1", parent_id: "e0", seq: 1, session_id: "s1", ts: "t", producer: "host", type: "message", payload: { role: "assistant", text: "Let me look that up" } },
{ id: "e2", parent_id: "e0", seq: 2, session_id: "s1", ts: "t", producer: "host", type: "tool_result", labels: [".src:net"], payload: { tool: "fetch", tool_use_id: "u1", raw_value: { "__coerced": true, type: "text", data: "page text", mx: { labels: [], taint: [], sources: [] } } } },
{ id: "e3", parent_id: "e0", seq: 3, session_id: "s1", ts: "t", producer: "host", type: "message", payload: { role: "assistant", text: "I will send it" } }
]
const @loaded = @mx.hydrate(@history)
const @said = @mx.history.select({ type: "message" })
show `before: ${@said[0].mx.influenced}, after: ${@said[1].mx.influenced}`
show @mx.history.influence[0].description
This shows before: false, after: true, then fetch, turn 1, labels .src:net. A result counts when the labels the history recorded on it make it untrusted under the policy in force, through the same rules as a live call: @standard turns .src:net and .src:mcp:* into untrusted input, and untrusted-llms-get-influenced or llm.influence_from decide what influences a model. Every value read back from a tape or a history is marked untrusted, so that mark is not counted, or every result would. What counts is whether the result was untrusted as recorded, before it was read back, and this holds for a history read from a tape with @t.select as much as for one written inline. The labels the value you hand to @mx.hydrate carries count too, so a result whose data is an .untrusted value is untrusted. A sealed and an unsealed history are judged alike. Influence is judged when @mx.hydrate runs, under the policy in force then, so declare the policy before hydrating. A result the model never saw does not count: a tool_result_withheld, or one a host recorded with tool_result_shown and shown_withheld. Where the host recorded what it showed, with labels of its own, those labels decide. A tool_result_shown describes the latest result with its call id recorded before it, so a harness that reuses an id cannot have a later result's record change an earlier one.
A message handed to the agent as its prompt enters its context the same way. A host records it as a user message (role user); when the labels recorded on it, on its labels field or as the host's asserted_labels, make it untrusted under the policy in force, it is a cause like an untrusted result, and every later model output in the session is .influenced. A host can also say who sent the message, with its sender kind (senderKind on tape:record, sender_kind in most SDKs): agent or person. A message from another agent, recorded with sender kind agent, is a cause whether or not it carries labels, and the turns after it are influenced until the session ends or a person clears it (below). mlld adds .src:agent and .untrusted to its labels, keeping the ones it carried. .src:agent comes only from the sender kind: a host cannot record it as a label itself. A person's clear of an agent's message counts when the config's clear.sources lists .src:agent and every other source label the message carried (see policy-basics); without .src:agent listed, the clear does not count (source_not_clearable). The label grants nothing. A person's message is judged by who sent it as well. A host that records the person's identity on the turn (its principal), or gives it sender kind person, marks it as a person's: it is trusted as the words of the person the run works for only when the project config lets the host claim user intent (intent in the host row of self_attestation, see security-policies) and the turn carries a .src:user:intent:* label. Any other person's message is untrusted and influences the turns after it, whatever its labels. Sender kind person alone never makes a message trusted. A message with no principal and no sender kind does not say who sent it, so only its labels decide, and one with no untrusted labels counts for nothing: a host should give each delivered message its sender kind. Recording a sender kind grants nothing.
.influenced only restricts. A guard or rule that refuses influenced input refuses the pending call, and nothing becomes allowed because of it.
@mx.history.influence lists every influence cause: each untrusted tool result the model saw, and each untrusted message it was handed as a prompt, in every hydrated session, in the order they arrived. A session stays influenced from its first cause on, and every later untrusted result is listed too. Each entry holds:
ref:<session_id>/<event_id>. For a session a host recorded through mlld, this is the same reference the host got back when it recorded the result.session_id,event_id,seq: where the result is in the history.toolandtool_use_id: the call the result answered; bothnullfor a message.labels: the labels that made it count.turn: the model turn it arrived in, counted from 1. When the host numbered its turns (turn_id, counted from 0), that number plus one; otherwise how many model turns came before it.nullwhen none did.description: the tool, the turn and the labels, for a person:fetch, turn 1, labels .src:net, ora message delivered as a prompt, turn 1, labels .src:netfor a message (a message from another agent delivered as a prompt, ...ora message from a person delivered as a prompt, ...when the host gave its sender kind). mlld writes it from those fields alone, never from the result's or message's content or who sent it.
When a session carries .secret anywhere (in any of its events, at any depth, or in the whole history), its entries are still listed in full here, and each carries .secret, so policy restricts whatever reads them. The run's tape and mlld why record such a session only as a count of its causes. The list is empty when nothing in the hydrated history was influenced. It explains and grants nothing. Each entry carries the labels of the result it names, so whatever reads it is restricted the way a read of the result would be. The same causes are written to the run's tape, where mlld why reads them to explain a refusal (see why).
A cause a person cleared stays in the list with cleared: { by, login?, roles, event, reason? }, the principal who cleared it, the roles that let them, the clear event's ref and the reason they gave. When the clear was recorded in another session (see "Clearing a source in every session that read it" below), cleared also has from_session and from_tape, naming where it was recorded. A cause a clear named that did not count has clear_ignored instead, saying why (see below).
Clearing a source
A person who has looked at a cause and judged it safe can clear it, so the agent's retry goes through. The program that embeds mlld records the clear on the session's tape, as a clear event naming the causes by ref with the person's principal (tape:record kind clear, see config-live-stdio). The next @mx.hydrate of that session reads the tape again without that cause: model output that only the cleared cause influenced is no longer .influenced, and a pending call proposed after it is judged again. A host's check of its own session counts the clear the same way (see config-live-stdio). Every other cause in the session still counts from where it arrived.
A clear counts only when all of these hold, and otherwise the cause gets clear_ignored:
| Check | clear_ignored |
|---|---|
| the clear is in the same session as the cause (a clear from another session counts only as described below) | wrong_session |
| it was recorded after the cause | before_cause |
a verified seal covers the history (see checkpoint-resume, Sealed tapes); anyone who can write an unsealed tape could write a clear on it |
unsealed |
the config's host row grants clear and principal (see policy-basics) |
no_grant |
labeling.principals, as configured now, maps the person to a role clear.by lists |
no_role |
the cause has a .src:* label, and each one matches clear.sources |
source_not_clearable |
no rule on .influenced in the policy in force has a never: law |
law |
no rule on .influenced is locked |
locked |
A clear is only as trustworthy as the host's recording channel, the same as an approval the host records: anything that can write through the host's tape:record calls, or reach the key that seals its tape, can record a clear. Agents must not be able to reach either (see Clears a program records for you).
A clear removes influence and nothing else. The result itself keeps its .untrusted and .src:* labels, so a rule on those still applies. A never: law or a locked rule on .influenced still treats what the cleared source influenced as influenced, whenever that rule comes into force, including one declared after the hydrate, one in a using { policy }, and one that reaches .influenced through a label alias; ordinary rules and guards see it as not influenced. Nothing already done is undone: a call refused before the clear stays refused, and the tape is not changed. A clear only counts in the hydrates that read it.
Clearing a source in every session that read it
With across_sessions: true in the config's host.clear block (see policy-basics), a clear also counts in other sessions that read the same content. "The same content" means the tool result holds exactly the same value as it was recorded: mlld compares a hash of the value, never its labels. A copy that differs anywhere, including one reformatted, trimmed or quoted differently, has a different hash and stays influenced. A result the host withheld as secret, or one mlld saved to a separate payload file, has no content to compare and is never cleared this way.
When the host records a clear, mlld also adds a line to the project's clear index, .llm/clears/index.jsonl, naming the tape and event of the clear and the hashes of the results it names. When another session is hydrated, mlld looks up each cause's hash in that index, then opens the tape the line names and checks it under the config's signers. The line counts only when that tape's seal verifies, the event is a host's clear under that seal, and the results it names, hashed from the tape itself, include this content. The hashes in the index only say where to look.
The clear must then pass every check in the table above except being in the same session, judged against the current config and policy, with these reasons when it does not:
| Check | clear_ignored |
|---|---|
the clear's tape is there and verifies under a seal of the config's signers, and covers the clear |
other_session_unverified |
| the results the clear names, hashed from its tape, include this content | content_differs |
the history being hydrated was read from a sealed tape (@t.select); a history handed in any other way, such as through a signed SDK envelope, cannot have a clear from another session |
not_a_tape_read |
| a verified seal covers the history being hydrated | unsealed |
every config policy that writes host.clear sets across_sessions: true |
across_sessions_off |
no_grant, no_role, source_not_clearable, law and locked apply as above, to the cause being cleared. A cause that a clear in its own session already named keeps that clear's reason when nothing from another session counts.
The index grants nothing by itself, but it is a plain file and it is not rollback-proof. Removing a line, rolling the file back to an earlier copy, or deleting it takes those clears back in every other session: their causes count again at the next hydrate. That direction fails closed. A clear in its own session is read from that session's tape and does not depend on the index. Nothing written to the index can make a clear count that its own tape does not prove.
What counts as proof after hydration
Only a tool_result this run recorded itself, still carrying its value, can establish a fact. @mx.history.facts(kind).includes(value) answers yes only for those.
Only a call an agent makes into one of the script's tools records its value. A call the script makes itself, such as const @ada = @lookup("Ada"), records its tool_call and a tool_result with no value, so @mx.history.facts("contact") never includes the facts that call returned, whether or not the result was read. The value carries them itself: @ada.email.mx.proof lists .fact:@contact.email.
A history loaded by @mx.hydrate proves nothing unless it is sealed. A script can build a history, or read one from a file anything could have written, so an unsealed history's events are claims like any other:
- a
tool_resultestablishes no fact. Itsfactslist stays searchable throughselect, its value comes back untrusted with its fact labels and proof removed, and a durable reference on it resolves to the value without fact kinds; - a user message is not the user's known words. It is in
@mx.history.user.values, but@mx.history.user.includes(...)does not find it, and@castdoes not admit an argument because the message named it; - every event, messages as well as tool calls, can make a guard deny but never allow, so a guard whose
allowarm readselector any other view of a hydrated history blocks instead.
A seal proves who certified a history, not that what it records is true. A sealed history's user messages are known to @cast and to @mx.history.user.includes, and a guard may allow on its events. Its tool_result values come back as the seal's admission left them: untrusted, without the signer's fact records, with the signer's labels able to block but not permit, and stamped with the issuer that sealed them. So its facts count no more than an unsealed history's. A history is sealed when it reaches the script through a verified seal, and is handed to @mx.hydrate as it arrived:
- a field of an SDK payload sent as an envelope signed by an issuer the project's config policy trusts (see
policy-envelopes).@mx.hydrate(@input.sdk.history)folds it sealed; - a tape read (
@t.select(...)) that a verified seal covers from its first event to its last (seetapes).
The @mx.hydrate call record names the signer in sealed_by. Binding it to a variable first (const @h = @input.sdk.history) keeps it sealed; a history the script rebuilt from a sealed one, by editing or selecting its events (.slice(), a for loop, a js step), is not. A sealed envelope that was altered, lost its signature, or was signed by a key the policy does not list is refused before @mx.hydrate sees it. Every argument and result in a hydrated history comes back untrusted, and keeps the labels of the value you handed to @mx.hydrate: a history labelled secret, or read from a file, reads back with those labels, which can block an action but never permit one, whatever the events themselves claim.
A tool_call whose arguments were withheld, with args left out and args_withheld set to secret, credential, too-large or not-kept (a call a judged module call kept only the name, id and outcome of; see live-stdio), makes @mx.hydrate refuse the whole history (history[1]: tool_call "x" arguments were withheld (secret); @mx.hydrate cannot decide without them): the call had arguments the history does not hold, so no decision can be rebuilt from it. args: {} means the call had no arguments, and hydrates.
Facts listed on any other event — an annotation, a commit, a tool call, an event type mlld does not recognize — are claims by whatever wrote them, with nothing backing them. The same is true of a tool_result whose stored value was later dropped to save space. Those claims stay searchable through select, but they never grant permission to anything. Otherwise anything able to append to a history file could grant itself access simply by writing down the fact it wanted.
@mx.bindPending(toolCatalog) rebinds visible @pending as a structured value whose data is the pending args and whose mx metadata includes tool, toolName, and toolUseId.
const @history = [
{ id: "e0", parent_id: null, seq: 0, session_id: "s1", ts: "2026-09-26T00:00:00Z", producer: "hook", type: "session_start", payload: { config_version: "1" } },
{ id: "e1", parent_id: "e0", seq: 1, session_id: "s1", ts: "2026-09-26T00:00:01Z", producer: "hook", type: "message", payload: { role: "user", text: "Send the report to ada@example.com" } }
]
const @toolCatalog = { send: { record: { name: "send_inputs", rootMode: "object", validate: "strict", direction: "input", read: { kind: "open" }, fields: [
{ name: "to", classification: "fact", valueType: "string", optional: false, factAccepts: [".src:user:intent:literal"] }
] } } }
const @pending = { tool: "send", args: { to: "ada@example.com" }, tool_use_id: "toolu_1" }
const @hydrated = @mx.hydrate(@history)
const @bound = @mx.bindPending(@toolCatalog)
const @valid = @cast(@pending, @pending.mx.tool.record)
match [
@valid => show "allow"
* => show @valid.mx.error.message
]
@pending is the call the agent wants to make, and @toolCatalog gives each tool's input record. The catalog is written here in the serialized form a host passes in, not in the record syntax a script uses. to is a fact field that accepts .src:user:intent:literal: a value the user wrote in one of their messages. Built in the script as here, the history is not sealed, so the user's message does not count and this shows why the cast failed:
Tool 'send_inputs' input 'to' must carry an accepted proof kind: .src:user:intent:literal
When the same history arrives sealed, for example as @input.sdk.history from a trusted issuer, the user named ada@example.com and this shows allow; with to: "eve@example.com" it still fails.
The history path is expected to be preselected by the caller. mlld folds the provided linear path by seq; it does not traverse an event tree.
Handle introspection
@mx.actors exposes the read-projection inspector for the current execution actor only. In a read-scoped context, @mx.actors[".role:planner"].records.<recordName> maps visible field names to their effective read modes; omitted fields are filtered out. Outside an actor-scoped context, @mx.actors is empty.
@mx.handles returns the handles visible in the current LLM bridge session, grouped by record instance. The accessor is scope-filtered on read, so sibling calls do not see each other's handles. The active read mode shapes which fields appear; @mx.handles.unfiltered exposes the full grouped view.
show @mx.handles
show @mx.handles.unfiltered
Example shape:
[
{
"record": "@contact",
"instance": {
"email": {
"value": "alice@example.com",
"handle": "h_a7x9k2",
"address": "contact:44d1c1cc"
},
"name": {
"value": "Alice",
"handle": "h_k91m4p",
"address": "contact:44d1c1cc"
}
}
}
]
For masked fields, the grouped view uses { preview, handle, address }. For handle-only fields, it uses { handle, address }. @mx.handles.unfiltered always uses { value, handle, address } for every available record-backed field.
Minting, resolving and searching handles from code (@mx.handles.mint, .resolve, .find) is not available in mlld 2.2.0.
Field-provenance predicates
.mx.allFields(pattern) and .mx.anyField(pattern) quantify a descriptor pattern across every leaf field of a structured value. They are value methods — usable in record refine blocks, in guard conditions, and anywhere an expression is (assignment, show, templates, pipeline stages). The boolean carries the receiver's labels: a predicate over secret content is itself secret, and an exfil gate treats it accordingly.
>> Every leaf field is user-originated, fact-backed, or handle-backed
@input.mx.allFields({ source: ["user", "fact", "handle"] })
>> Any leaf field is untrusted AND influenced
@input.mx.anyField({ trust: "untrusted", influenced: true })
Pattern shape — all constraints ANDed:
| Key | Type | Matches when |
|---|---|---|
trust |
"trusted" | "untrusted" | null or array |
field's mx.trust equals (or is one of) |
influenced |
boolean | field's mx.influenced equals |
factsource |
boolean | field has at least one factsource entry |
labels |
string or array of label patterns | field's mx.labels contains a match (hierarchical) |
source |
source class or array | field's synthesized source class is (one of): "user", "fact", "handle", "value" |
The source synthetic derives at evaluation time from the actual mx state:
"user"— field carries any.src:user[*]label"fact"— field has proof-bearing fact provenance"handle"— field's variable is a handle ref to a grounded record"value"— otherwise (literal with unknown origin)
A field may satisfy multiple source classes simultaneously. source: ["user", "fact"] matches if any one is true.
Field iteration. Both predicates walk the input recursively. Each non-object leaf (or any value with its own mx) is evaluated against the pattern. Arrays iterate as element-fields. Cycles are skipped.
Use in refine:
class .review:bounded = { kind: "data", effect: "describe", description: "Output whose fields all have a known origin" }
record @worker_extraction [
body: string
note: string
refine [
@input.mx.allFields({ source: ["user", "fact", "handle"] }) => labels += [.review:bounded]
]
validate "strict"
]
Use in guards:
A guard reads the operation's arguments through @input. Reach one positionally (@input[0]) and call the predicate on its .mx:
class .payload = { kind: "data", effect: "restrict", description: "Request bodies sent to other services" }
guard @noTaintedPayload = match [
@input[0].mx.anyField({ trust: "untrusted" }) => deny "payload contains untrusted fields"
* => allow
]
policy @payloads = { .payload+.op:cmd { before: @noTaintedPayload } }
exe @send(body) = cmd { echo "sent $body" }
const .untrusted @external = "reply text from outside"
const .payload @req = { id: "42", note: @external }
show @send(@req)
The call is denied: the note field carries .untrusted trust, so anyField matches and the guard blocks the command. A payload whose fields are all clean passes.
Value-local handle accessors
@someValue.mx is per-value metadata. Record-coerced objects expose identity metadata there:
.mx.keyis an opaque record identity used for stateupsert, fact correlation, and read-handle grouping. For object iteration,.mx.keyis also the current object key on each iterated value..mx.addressis{ record, key, string }for record-coerced values andnullotherwise. The string form is<record>:<mx.key>..mx.hashis a deterministic record content fingerprint for change detection..mx.appliedActionsis field-local audit/dedup metadata for record field actions. Each entry records{ actionFingerprint, inputHash, outputHash, coercionId, appliedAt? }so materialization can skip an already-applied action on unchanged content. It stays on the field value and is not promoted into aggregate object summaries.
.mx.handles returns the read-shaped handle view for a structured record value. (The single-value .mx.handle is not available in mlld 2.2.0.)
record @contact [
email: string [ kind "email" ]
name: string
* { read: [name, { value: email }] }
]
const @ada = { email: "ada@example.com", name: "Ada" } as record @contact
show @ada.mx.handles
This shows each field with its value and handle:
{
"email": { "value": "ada@example.com", "handle": null },
"name": { "value": "Ada", "handle": null }
}
Outside an active LLM call, as here, every handle is null; inside one, each field gets a live handle. This makes tests and debug code deterministic without minting live handles when no resolver scope exists.
LLM call metadata
@mx.llm.sessionId is the current bridge call session id, or null when no LLM call is active.
This is bridge or provider metadata, not state session state. Session state is read through its declared name:
state session @planner = {
count: number?
}
show @mx.llm.sessionId
show @planner.count
@mx.llm.read is the active read mode for the current call, or null.
@mx.llm.resume is null outside resumed calls. During resume it exposes:
{
"sessionId": "resume-session",
"provider": "openai",
"continuationOf": "resume-session",
"attempt": 2
}
State metadata
A record slot's .mx.version (for example @book.contact.mx.version) is the count of writes applied to that slot. Any other value has no version, so its .mx.version is null: a slot whose type is not a record, a string, a number, an array, a plain object or one of its fields, and a field of a stored record. Code walking a state's slots can tell record slots from the rest this way, and gets null rather than an error when handed a plain object. On a state itself, @s.mx is its metadata view as on any value, so @s.mx.labels lists its labels, and mx cannot name a slot. A state's @s.mx.id names that state: every read of it in a run gives the same id, including through the state, one of its slots, or @s.readonly() passed to an exe, and two states never share one. A slot read directly (@s.items.mx.id) or a read-only view held in a variable reads it as null. A state declared inside an exe gets a new id each call, and a state session a new one in each LLM call it is attached to. The id is opaque: compare ids, but do not parse one. Any value that is not a state reads .mx.id as null. A state's own @s.mx.slots, @s.mx.slotEntries and @s.mx.version are not available in mlld 2.2.0: reading one is an error. Read a slot by name (@s.label) to get its contents; see State.
Active policies
@mx.policy.active lists every policy in force where it is read, as { name, source } entries in the order they came into force. source says how the policy got there:
"file": apolicy @name = …in the running file."import":import policy @alias from …, or a policy declared in a module this file imports."config": an entry ofpolicy.importinmlld-config.json."call": theusing { policy }of a call orfor/matchthat is running now. An inline policy object hasname: null.
name is the policy's name without @ (the alias, for an import). A policy reached by two routes is listed once, under the first. Inside a call with using { policy, replace: true }, a policy from outside stays listed only while one of its rules is still in force there: a locked rule, or a rule another file declared.
policy @base = { .op:cmd:rm { deny: true } }
const @strict = { deny: ["cmd:curl:*"] }
exe @inside() = [ => @mx.policy.active ]
show @inside() using { policy: @strict }
shows base with source: "file", then strict with source: "call". @mx.policy.activePolicies has been removed; reading it is an error that points here.
As With
as / with Overloads
The keywords as and with each have several meanings across mlld syntax, and
using sits next to with on calls and definitions. Each meaning is listed here
so you can read any as/using/with and know which rule applies. The set is
closed (see A closed set): no new as meanings will be added,
and future with features take object payloads rather than new bare keywords.
as overloads
| Form | Meaning |
|---|---|
import { @foo as @bar } |
Alias a selected import. The alias takes the @-form. |
import "path" as @ns |
Namespace alias — bind a whole imported module under one name. |
export { @foo as @bar } |
Alias on export — importers see @bar, not @foo. The alias takes the @-form. |
<file.md # Heading> as "New Title" |
Section rename — replace a loaded section's heading. See file-loading-basics. |
<docs/*.md> as `- ${@item.mx.relative}` |
Load template — render each loaded section, selected code record or file, with @item bound to it. Works wherever a load is a value: const, let, show and an exe body. See file-loading-basics. |
@value as record @schema |
Record coercion — shape a value to a record's fields. An executable can do the same on its result with => record @schema. See records-basics. |
output @x to "out.csv" as csv |
Output format — how the written file is serialized: json (pretty-printed JSON) or csv (an array of objects as a header row plus one row per object, or an array of arrays as one row each). text writes the value unchanged. Any other name is refused when the file loads. |
These as forms are not available in mlld 2.2.0: an alias on a data value (@value as alias), a heading level (show @doc as ##), renaming the heading of a variable (show @doc as "Title") and applying a template held in a variable to loaded files (<files.md> as @template).
using and with
A call or a definition can carry two clauses. They answer different questions:
usinglends authority: what the call may reach. Credentials, a policy
fragment, a box, a grant, guards, the tools an LLM may call, what a role may
read, a session, environment variables.withsays how it runs and how it describes itself: streaming,
pipelines, parallelism, output format, timeouts, passthrough data, a
description.
When both appear, using comes first. On a definition, clauses go between the
signature and =. On a call or statement, they go after it. A clause attaches
to the call or statement it follows; it cannot go inside an argument
(@f("x" with { … }) is a parse error).
const @token = "t-123"
exe @whoami() using { env: { TOKEN: @token } } = cmd { echo "$TOKEN" }
show @whoami()
const @frag = policy { .secret { deny: [.op:cmd] } }
exe @shout(x) = js { return x.toUpperCase() }
show @shout("hi") using { policy: @frag }
const @loud = "abc" with { pipeline: [@shout] }
show @loud
using keys:
| Key | Meaning |
|---|---|
secret |
Credentials to inject. Short form using secret:anthropic, or using { secret: "anthropic" }. |
grant |
A grant that widens what the call may do. |
policy |
A policy fragment in force for this call only. |
box |
Select a box profile on a box block (box @cfg using box:readonly [ … ]), or, inside a running box, for one call from that box's declared profiles (@f() using box:full). See box-directive. |
guards |
using { guards: false } turns guards off for one call. It is refused unless a .priv.sss policy sets allow_guard_disable: true. |
tools |
The tools an LLM function may use. On a call to an llm function, @ask("…", {}) using { tools: @tools } serves them to that call, as the config's tools would; naming tools in both places is an error. On a call to any other executable it is not available in mlld 2.2.0. |
harness |
Where an llm definition's own command keeps its state, what else it may write, and its network tier: using { harness: { home: "~/.agents/planner", write: ["./tmp"], net: "open" } }. It replaces the llm.harness profile in mlld-config.json for that definition. A harness module also lists the hosts its harness needs in egress, such as its model API: egress: ["api.anthropic.com"]. Only on an llm definition, and only as an object written there. See config-files. |
read |
The role whose read view applies: using { read: .role:worker }. |
session, seed, override |
Attach a session and its starting values. |
env |
Environment variables for a code body: using { env: { NAME: @value } }. |
A single key has a short form, using key:value. Everything else uses the
object form using { … }.
with keys: pipeline, parallel, delay, format, stream,
stream_format, stdin, trace, timeout, lifecycle, mode,
description, warnings, tape, thread, pass, inputs. Keys are
snake_case. Not every key applies everywhere: on a call to an executable
(@f() with { … }), delay, stdin, mode and a standalone format are not
available in mlld 2.2.0, while stdin works on run cmd { … } with { stdin: … }. The
full key-by-surface table is in docs/dev/WITH-CLAUSE.md.
Passthrough data goes under with { pass: { … } }, and the callee reads it
as @mx.pass.
Time limits. with { timeout: … } on a call limits how long it may run.
Write milliseconds (timeout: 600000) or a duration (timeout: 10m, or the
string "30s"). At the deadline mlld stops every process the call started,
their children included, and the call fails with the code CALL_TIMEOUT,
which try catches. In a for parallel loop that item fails like any other
failed item, and the others carry on. There is no limit unless you write one.
exe @slow() = cmd { sleep 5 }
const @r = try @slow() with { timeout: 100ms }
show @r.error.code >> CALL_TIMEOUT
The limit covers sh, cmd, node, py and llm bodies, and any
executable that calls them. @http reads it as its request timeout (30
seconds unless you set one). Three callees refuse it, because mlld cannot stop
their work part-way: a js { … } body, which runs inside mlld (write it as
node { … } instead), an MCP tool call, and a service method (a service sets
its limit on its definition, see services-basics).
with has one more meaning: the bare method name on sign, as in
sign @doc with sha256.
Labels and trust do not go in a clause
Labels are written before the name: const .pii @email = …, or
exe .pii @f() = … on a definition. with { labels: … } on a definition is a
parse error that shows the label slot. Trust works the same way:
const .untrusted @name = …; with { trust: … } does not mark anything
untrusted.
A closed set
The as/with overload set is closed:
- No new
asmeanings will be added. The forms above are the complete set. - Future
withclauses take object payloads. New runtime behavior is configured by adding a key insidewith { ... }orusing { ... }, never by introducing a new bare-identifierwithform. sign … with <method>is the one bare-identifier form. It does not authorize new bare-keywordwithforms.
This keeps the keyword surface small enough to teach completely on one page. If you need a new behavior that feels like it wants an as/with keyword, model it as a key in with { ... } or using { ... } instead.