Proven patterns for tool orchestration, data pipelines, conditional workflows, agent definitions, lifecycle hooks for observability, and checkpoint/resume for long-running LLM workflows.

Ralph Loop Pattern

Autonomous coding loop based on the Ralph Wiggum technique by Geoff Huntley. Each iteration: reload context from disk, pick one task, execute it, test, commit on green. The loop is the outer process; the LLM decides what to work on.

@commit and @checkTask are small shell scripts (&&, if … then), so the script switches sh blocks on with its policy line: they are off by default, because policy rules can't see inside them. Everything else uses cmd, which the policy can check.

>> ralph.mld - autonomous coding agent loop

import { @agent } from @mlld/multi-harness
policy @allow_sh = { * { capabilities: { sh: true } } }
const @tools = ["Read", "Write", "Edit", "Glob", "Grep", "Bash(git:*)", "Bash(npm:*)"]
exe @mkdirp(dir) = cmd { mkdir -p "$dir" }
run @mkdirp("runs/ralph")

>> Cheap model picks the most important task from current plan.
>> Model names are per tool, so the call names the tool too.
llm @pickTask(plan, specs) = [
  let @outPath = "runs/ralph/pick.json"
  let @prompt = `Given this plan and these specs, identify the SINGLE most
important next task. Search before assuming something isn't implemented.
Return JSON: { "task": "...", "type": "implement|fix|test", "files": [...] }

<plan>
${@plan}
</plan>

<specs>
${@specs}
</specs>

IMPORTANT: Write your JSON response to ${@outPath} using the Write tool.`
  @agent(@prompt, {
    harness: "claude",
    model: "haiku",
    tools: ["Read", "Glob", "Grep", "Write"]
  })
  => <@outPath>? | @parse.llm
]

>> Worker executes the task with full agent capabilities
llm @doTask(task, specs) = [
  let @outPath = "runs/ralph/work.json"
  let @prompt = `# Task
${@task.task}

## Specs
${@specs}

Implement this task. Search the codebase before assuming anything is
not implemented. After implementing, run tests for just this change.

IMPORTANT: Write your result JSON to ${@outPath} using the Write tool.`
  @agent(@prompt, {
    harness: "claude",
    model: "sonnet",
    tools: @tools
  })
  => <@outPath>?
]

>> Commit and push; sh bodies read parameters as shell variables
exe @commit(message) = sh { git commit -am "$message" && git push }

>> Validate with tests; the full test log goes to a file
exe @checkTask() = [
  let @out = sh { if npm test > runs/ralph/test.log 2>&1; then echo pass; else echo fail; fi }
  let @pass = @out.trim() == "pass"
  => { pass: @pass }
]

>> The loop
loop(endless) [
  >> Fresh context every iteration — the context IS the history
  let @plan = <fix_plan.md>
  if @plan.trim() == "" => done "complete"
  let @specs = <specs/*.md>

  >> One task per loop — trust the LLM to pick what matters
  let @task = @pickTask(@plan, @specs)
  let @result = @doTask(@task, @specs)

  >> Test backpressure — only commit what passes
  let @check = @checkTask()
  if @check.pass => run @commit(@task.task)

  continue
]

Core principles:

  • One task per loop — Each iteration picks a single task and executes it. Narrowing scope keeps context usage low and outcomes predictable.
  • Fresh context from disk — Plan and specs reload every iteration. No chat history carried forward. The filesystem is the state.
  • Test backpressure — Tests gate commits. Failing iterations aren't fatal; the next iteration sees the current state and adapts.
  • LLM picks the work — The cheap classifier decides priority. The orchestrator doesn't encode task selection logic.

Crash recovery — Every mlld run records a run tape, and defining @pickTask and @doTask with llm puts their model calls on it. If the loop crashes mid-iteration, --resume continues the run and answers calls it already made from the tape. See Checkpoint & Resume.

mlld run ralph                     # start a run
mlld run ralph --resume            # continue the latest run
mlld run ralph --new               # start from the top

Hook telemetry — Log every function call as it finishes. log writes to stderr, so it stays out of the script's output:

hook @progress after .op:exe = [
  log `finished ${@mx.op.name}`
]

With pacing — Add a delay between iterations to avoid hammering APIs:

loop(endless, 5s) [
  ...
]

With a cap — Limit total iterations:

loop(50) [
  ...
]

Guarded Tool Export

Expose mlld functions as MCP tools with fixed context parameters and security guards. The tool catalog is the tools collection itself: one declaration carries the surfaced name, input contract, labels, binds, and prompt metadata.

Define the function, guard, and tool collection:

record @search_issues_inputs [
  query: string
  validate "strict"
]
exe @searchIssues(org: string, repo: string, query: string) = cmd {
  gh issue list -R "$org/$repo" --search "$query" --json number,title
}

guard @noSecrets = match [
  @input.any is .secret => deny "Secret data cannot flow to tools"
  * => allow
]
policy @toolRules = { .op:exe { before: @noSecrets } }

tools @agentTools = {
  searchIssues: {
    call: @searchIssues,
    inputs: @search_issues_inputs,
    bind: { org: "mlld-lang", repo: "mlld" },
    labels: [.op:tool:r],
    description: "Search mlld issues by keyword"
  }
}

export { @searchIssues, @agentTools }

The agent sees one parameter (query) because inputs: @search_issues_inputs defines the surfaced contract. The bound org and repo are invisible and fixed. A guard has no trigger of its own: the policy line binds @noSecrets to run before every function call, and the guard blocks any call that carries .secret data.

Serve it:

mlld mcp tools.mld --tools-collection @agentTools

The --tools-collection flag tells the MCP server to use the reshaped tool definitions instead of raw exports.

Give it to an agent:

Point any MCP client at the command. For Claude Code:

{
  "mcpServers": {
    "my-tools": {
      "command": "mlld",
      "args": ["mcp", "tools.mld", "--tools-collection", "@agentTools"]
    }
  }
}

Add operation labels for policy:

@createIssue and @create_issue_inputs are defined the same way as @searchIssues / @search_issues_inputs:

record @search_issues_inputs [
  query: string
  validate "strict"
]
exe @searchIssues(org: string, repo: string, query: string) = cmd {
  gh issue list -R "$org/$repo" --search "$query" --json number,title
}
record @create_issue_inputs [
  title: string
  body: string
  validate "strict"
]
exe @createIssue(org: string, repo: string, title: string, body: string) = cmd {
  gh issue create -R "$org/$repo" -t "$title" -b "$body"
}

guard @needsApproval = match [
  * => deny "Creating issues needs a human"
]
policy @writeRules = { .risk:destructive { before: @needsApproval } }

tools @agentTools = {
  searchIssues: {
    call: @searchIssues,
    inputs: @search_issues_inputs,
    bind: { org: "mlld-lang", repo: "mlld" },
    labels: [.op:tool:r],
    description: "Search mlld issues"
  },
  createIssue: {
    call: @createIssue,
    inputs: @create_issue_inputs,
    bind: { org: "mlld-lang", repo: "mlld" },
    labels: [.risk:destructive],
    description: "Create an mlld issue"
  }
}

A catalog's labels join the operation's labels when the tool is called, so policy patterns match them. Here .risk:destructive binds @needsApproval, which blocks every createIssue call while searchIssues runs freely. See mcp-guards for after-guard patterns that validate tool outputs.

Planner-Worker Authorization

The planner-worker pattern splits agent execution into two phases: a planner that decides what to do and authorizes specific tools and values, and a worker that executes under those constraints.

Why split?

An LLM agent that both decides and executes has one shot to get everything right. If it reads untrusted content (an email with injection), the same LLM that's now influenced also controls tool dispatch.

Splitting creates a security boundary:

  • The planner runs with callable read/dispatch tools, sees projected handles, and receives separate authorization docs for any write tools its role may authorize
  • The worker runs under that authorization, can read untrusted content, but can only call tools the planner pre-approved with pre-approved values

The worker can be tricked into wanting to send to attacker@evil.com. It can't actually do it because the planner never authorized that recipient.

Phase-shaped tools

The planner-worker split works best when tools are designed for specific security phases:

  • Resolve tools find and ground targets — search, list, metadata lookup. Use with read: .role:planner. Return facts + handles, not raw content.
  • Extract tools read grounded content by ID — get_email_by_id, not search_emails. Use with read: .role:worker. Content is visible, facts are masked.
  • Execute tools do one concrete write — single tool, handle-backed control args, step-scoped policy.

When tools mix phases (search + read content in one call), the planner sees untrusted content it shouldn't, and the orchestrator needs repair logic. Phase-shaped tools make the security boundaries clean: resolve discovers, extract reads, execute writes.

Multi-write tasks become multiple execute steps, each with its own grant. One write per step keeps authorization, state, and failure recovery simple.

Workers receive typed inputs, not state blobs

A common mistake is to pass a worker everything the program holds in state and rely on prompt instructions to narrow it:

>> Wrong: worker sees everything, prompt tries to filter
exe @executeWorker(slotState, request) = [
  ...prompt says "use only the referenced inputs"
]

The worker drifts. It sees all the stored content and copies nearby prose instead of the exact values the request referenced. The fix isn't better prompt discipline — it's a different interface. The orchestration should resolve slot references into concrete values before calling the worker:

>> Right: orchestration resolves references, worker receives typed inputs
>> @lookup is your own helper that finds the named entry, e.g. with @find from @mlld/shelf
let @target = @lookup(@request.target_slot, @request.target_name)
let @inputs = for @ref in @request.input_refs => {
  name: @ref.name,
  value: @lookup(@ref.slot, @ref.name)
}
let @result = @executeWorker(@target, @inputs, @request, @policy)

The worker signature becomes:

exe @executeWorker(target, inputs, request, policy) = [
  >> worker body with typed, bounded parameters
]

Now the worker has semantic arguments, not raw state. It cannot accidentally access slots it wasn't given. If the worker is an LLM call, the record's read list still governs what it sees at that boundary. The orchestration does the slot access; the worker does the semantic work.

The rule: the worker's interface should describe what it needs, not the state it operates on. Structural narrowing (the worker literally cannot see what it wasn't passed) beats prompt discipline every time.

Structure

record @contact [
  email: string [ kind "email" ]
  name: string [ kind "name" ]
  notes: string?
  * { read: [name, { value: email }] }
]
exe @searchContacts(query) = run cmd {
  contacts-cli search "$query" --format json
} => contact

record @send_email_inputs [
  recipient: string [ kind "email" ]
  subject: string?
  body: string?
  validate "strict"
]
exe .risk:exfil:send, .op:tool:w @sendEmail(recipient, subject, body) = run cmd {
  email-cli send --to "$recipient" --subject "$subject" --body "$body"
}
tools @writeTools = {
  send_email: {
    call: @sendEmail,
    inputs: @send_email_inputs,
    labels: [.risk:exfil:send, .op:comm:w]
  }
}

The input record marks recipient as a security-relevant parameter because it has a kind (kind "email"). A field with a kind carries proof; subject and body have none, so they are ordinary payload. They are optional in the record so that a grant can leave them out (see "The tool contract only cares about facts" below). The { value: email } entry in the read list means the LLM sees the value AND gets a handle — it can read the email for reasoning and reference it by handle for tool calls.

Planner phase

The planner looks up contacts and receives a projected result with value handles:

{
  "name": "Mark Davies",
  "email": { "value": "mark@example.com", "handle": "h_a7x9k2" }
}

Base policy declares which planner role can authorize which write tools. can_authorize goes on the role's pattern block; tools that can never be authorized are listed in the global * block:

exe .risk:exfil:send, .op:tool:w @sendEmail(recipient, subject, body) = `sent to ${@recipient}`

policy @workspace = {
  * { authorizations: { deny: ["update_password"] } }
  .role:planner { can_authorize: [@sendEmail] }
}

The planner then produces a request — which tool to call and, per argument, either a reference to a field of a record it resolved (a {ref}) or a verbatim quote from the user's task:

{
  "write_tool": "send_email",
  "args": {
    "recipient": { "ref": { "address": "contact:ab12", "field": "email" } },
    "subject": "the Q4 report"
  }
}

A request is not proof. The orchestrator compiles it into proof-carrying values with @compileArgs from @mlld/authorize: a {ref} is resolved against the state that holds the records (keeping its fact proof), a verbatim string is cited against the user's task with @cite.user.intent.literal, and anything it cannot prove is left bare so the grant refuses it by name. It then mints a grant that pins the control arg to the compiled value, and dispatches under it, passing each argument in its own position:

import { @compileArgs } from @mlld/authorize
const @plannerResult = @plan(@task) | @parse
const @compiled = @compileArgs(@plannerResult.args, @task, @found)
const @grant = { args: { recipient: @compiled.recipient } } as grant for @sendEmail
const @result = @sendEmail(@compiled.recipient, @compiled.subject, @body) using grant:@grant

Pass the arguments one by one. @sendEmail(@compiled) would hand the whole object to the first parameter, and the grant refuses it (argument 'recipient' factsource does not match its pin).

@compileArgs never substitutes a value it could not prove, so the grant never sees an attacker-chosen literal wearing a proof label. If a request arg can't be proven, the grant refuses it — a guard on the planner exe can retry with that refusal as feedback. See security-grants and security-citations.

Planner prompt assembly

Explicit planner prompts should usually include generated tool docs from the same write collection the request will be compiled against. @fyi.tools(@writeTools) renders them (see tool-docs):

const @plannerToolDocs = @fyi.tools(@writeTools)
const @plannerPrompt = `
You are the planning phase.

${@plannerToolDocs}

Return JSON with:
- write_tool
- args
`

@fyi.tools renders each tool with its parameter list, control args flagged, and read/write classification derived from the active policy. The planner returns a request: the tool to call and, per argument, a {ref} to a field of a record it resolved or a verbatim quote from the user's task. The orchestrator turns that request into proof with @compileArgs.

@fyi.tools, <fyi_tools>, and <fyi_authorizations> share the same base rendering and classification path. Use @fyi.tools when you're assembling a prompt template by hand and want explicit control. Let auto-injection handle the default text form when you're calling an llm function such as @agent(...): <fyi_tools> covers callable tools, <fyi_authorizations> covers tools the current role can authorize but not call directly.

Worker phase

The worker executes under the combined base policy plus validated authorization:

import { @noSendToUnknown, @noUntrustedDestructive } from @mlld/policy
exe .risk:exfil:send, .op:tool:w @sendEmail(recipient, subject, body) = `sent to ${@recipient}`

const @workspacePolicy = policy {
  * { authorizations: { deny: ["update_password"] } }
  .role:planner { can_authorize: [@sendEmail] }
}

policy @basePolicy = union(@noSendToUnknown, @noUntrustedDestructive, @workspacePolicy)

policy { … } written as a value builds a policy without putting it in force; union() combines it with the imported policies, and the policy directive puts the result in force.

At dispatch time:

  1. The grant pins recipient to the compiled value's proof carrier (the contact's factsource).
  2. The dispatch guard checks: does the dispatched recipient match the grant's pin? Yes.
  3. The base policy's positive check runs: does recipient carry fact proof or .src:user:intent:literal? Yes — the compiled value kept its .fact:@contact.email proof.
  4. @noUntrustedDestructive scopes to control args. Tainted data args (subject, body) are not checked.
  5. The call proceeds.

If injection tricks the worker into calling sendEmail(recipient: "attacker@evil.com"):

  1. "attacker@evil.com" was never compiled, so it carries no proof and matches no pin.
  2. The grant has no consent for that value — GRANT_DENIED.
  3. Call denied.

Because the grant pins the unforgeable proof carrier and not a label, an attacker cannot get through by copying a .fact:* label onto a fabricated address.

Key properties

Control args are mandatory

Declare surfaced write-tool control args with inputs: @record and give every security-relevant field a kind. Built-in send/destroy checks key off those fields.

The tool contract only cares about facts

The planner doesn't need to know which args are security-relevant. The tool's input record does: fields with a kind are the ones to pin in the grant, and they are checked for proof. Fields without one (subject, body) stay out of the grant, so any value may flow there. @compileArgs proves what it can and the grant enforces the facts. See tool-definition.

Two conditions hold every grant to this shape. Every entry in a grant's args must carry proof: a payload value such as a free-text body is refused (args entry 'body' carries no proof). And when a tools collection gives the tool an input record, the grant's args must satisfy that record, so a required field the grant leaves out is refused (Missing required field 'body'). Mark payload fields optional (body: string?) and pin only the fields with a kind.

Grants and positive checks compose

A grant is not the only gate. Even with consent, positive checks from the base policy still apply:

  • @noSendToUnknown requires fact proof or .src:user:intent:literal on destination args
  • @noDestroyUnknown requires fact proof or .src:user:intent:literal on target args

Because the compiled value keeps its proof (a factsource from the stored record, or a citation from the task), it clears both the grant's pin and the base policy's positive check. A proofless literal clears neither — the grant refuses it by name, and the positive check would deny it anyway.

Consent, not payload rewriting

A grant pins the specific consented values. The runtime does not rewrite arbitrary payloads or tool schemas; it checks that the dispatched fact args match what the grant consented to.

Locked policies

* { locked: true } in the base policy makes its denials terminal — a denied grant refusal inside a locked rule cannot be caught. Use this when you want a floor that no denied handler can route around.

Validation

mlld validate catches input-record contract mistakes on surfaced tools before execution. It does not check that tools named in can_authorize or deny resolve to a known tool: that needs mlld validate --context, which refuses to run.

See policy-authorizations for the validation codes.

Worker returns with handle field type

Workers that pass security-critical values across phases should return handle-bearing structures. The handle field type enforces this:

import { @agent } from @mlld/multi-harness
exe @readChannel(name) = `channel ${@name}`
tools @readerTools = { read_channel: { call: @readChannel } }

record @reader_result [
  channel: handle [ kind "channel" ]
  needs_reply: boolean
  summary: string
  * { read: [{ value: channel }, needs_reply, summary] }
  validate "strict"
]
exe @readWorker(task) = @agent(@task, { tools: @readerTools }) => reader_result

The handle type requires a resolvable handle — under validate "strict", plain strings fail validation. If the LLM returns "general" instead of copying the handle from the tool result, => record validation fails and a guard can retry.

Named read modes

Different agents need different visibility. Use named modes and box config:

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

The named modes are then selected per box, or per call:

box using { read: .role:worker } [...]
box using { read: .role:planner } [...]

>> Or per call-site without boxes:
const @readResult = @agent(@prompt, { tools: @readTools }) using { read: .role:worker }
const @plan = @agent(@prompt, { tools: @plannerTools }) using { read: .role:planner }

Call-site using { read } overrides box-level read selection.
If no explicit read is set, a matching llm label such as .role:planner also selects the corresponding read key by default. The exe's .role:* label remains the authorization identity; using { read } only filters what the LLM sees.

Worker sees subject and body (its job), from is masked. Planner sees from and message_id in value mode, sees needs_reply, and sees unlisted fields as protected schema-only fields.

Full example

import { @agent } from @mlld/multi-harness
import { @compileArgs } from @mlld/authorize
import { @noSendToUnknown, @noUntrustedDestructive } from @mlld/policy

record @contact [
  key id
  id: string [ kind "contact_id" ]
  email: string [ kind "email" ]
  name: string [ kind "name" ]
  notes: string?
  * { read: [name, { value: email }] }
  .role:planner { write: { state: [upsert] } }
]
exe @searchContacts(query) = run cmd {
  contacts-cli search "$query" --format json
} => contact

record @send_email_inputs [
  recipient: string [ kind "email" ]
  subject: string?
  body: string?
  validate "strict"
]
exe .risk:exfil:send, .op:tool:w @sendEmail(recipient, subject, body) = run cmd {
  email-cli send --to "$recipient" --subject "$subject" --body "$body"
}
tools @writeTools = {
  send_email: {
    call: @sendEmail,
    inputs: @send_email_inputs,
    labels: [.risk:exfil:send, .op:comm:w]
  }
}

const @workspacePolicy = policy {
  .role:planner { can_authorize: [@sendEmail] }
}
policy @basePolicy = union(@noSendToUnknown, @noUntrustedDestructive, @workspacePolicy)

state @found = { contact: contact[] }
const @task = "Send Mark the Q4 report summary."

>> Step 1: Resolve. Search results go into state, so a request can refer to them
exe .role:planner @findContacts(query) = [
  let @hits = @searchContacts(@query)
  for @c in @hits [ @found.upsert("contact", @c) ]
  => for @c in @hits => { name: @c.name, address: @c.mx.address.string }
]
const @candidates = @findContacts("Mark")

>> Step 2: The planner produces a request: tool name plus per-arg refs/quotes
llm @plan(task, candidates) = @agent(`Plan this task. Return JSON with write_tool and args. For a contact's email, give { "ref": { "address": <address>, "field": "email" } }. Quote any other value verbatim from the task.
Task: ${@task}
Contacts: ${@candidates}`)
const @plannerResult = @plan(@task, @candidates) | @parse

>> Step 3: Compile the request into proof-carrying values (refs resolved in @found,
>> task quotes cited, unprovable entries left bare)
const @compiled = @compileArgs(@plannerResult.args, @task, @found)

>> Step 4: Mint a grant that pins the control arg, then dispatch with the
>> arguments spread out
const @grant = { args: { recipient: @compiled.recipient } } as grant for @sendEmail
const @body = "Q4 revenue grew 12% over Q3."
show @sendEmail(@compiled.recipient, @compiled.subject, @body) using grant:@grant

The grant binds @sendEmail by its definition site, so aliasing the tool to another name cannot escape the consent. Every fact arg the grant names must have been proven by @compileArgs; anything it could not prove stays bare and the grant refuses it.

An allow-only step — a tool with no security-relevant arguments — uses an empty grant:

exe .op:tool:w @createFile(path) = `created:${@path}`
policy @basePolicy = { .role:planner { can_authorize: [@createFile] } }

const @grant = {} as grant for @createFile
show @createFile("notes.md") using grant:@grant

An empty grant consents to the tool's shape but pins no argument values. A tool that declares fact fields still requires those to carry proof.

Persistent-session variant: workers as tools via -> and canonical record return

The stateless variant above dispatches each phase as a separate @agent call and threads prior-step context through orchestration code. That works, but each iteration re-pays the full prompt assembly cost and the planner has to reconstruct its situational awareness from primitives like stored state and prior-step summaries.

The persistent-session variant runs the planner as a single long-running @agent call with workers exposed directly as tools. A worker tool can use either of the two sanctioned planner boundaries:

  • canonical record return when the planner should see the normal projected domain result
  • -> when the planner-facing tool result should intentionally differ from the canonical return, for example by adding count/status/summary fields or returning an attestation envelope

The planner's conversation history naturally accumulates progress across tool calls.

import { @agent } from @mlld/multi-harness
import { @noSendToUnknown, @noUntrustedDestructive } from @mlld/policy

record @contact [
  email: string [ kind "email" ]
  name: string [ kind "name" ]
  * { read: [name, { value: email }] }
]
record @email_msg [
  from: string [ kind "email" ]
  message_id: string [ kind "message_id" ]
  subject: string
  body: string
  .role:planner { read: [{ value: from }, { value: message_id }, subject] }
]

>> Worker exes are tools the planner can call. Use canonical record return
>> when the planner should see the normal projected domain result. Use ->
>> when the planner-facing result should intentionally differ.
exe @searchContacts(query) = [
  let @results = run cmd { contacts-cli search "$query" --format json }
  let @parsed = @results | @parse as record @contact[]
  >> Differentiated planner-facing envelope: count + contacts + summary
  >> rather than the plain contact array alone.
  -> { found: @parsed.length, contacts: @parsed, summary: "Found matching contacts" }
  => @parsed
]
exe .risk:exfil:send, .op:tool:w @sendEmail(recipient, subject, body) = [
  let @sent = run cmd {
    email-cli send --to "$recipient" --subject "$subject" --body "$body"
  }
  -> { status: "sent", recipient: @recipient }
  => { ok: true, message_id: @sent.id, full_response: @sent }
]
exe @getEmailById(id) = [
  let @email = run cmd { email-cli get "$id" --format json }
  let @parsed = @email | @parse as record @email_msg
  => @parsed
]

record @send_email_inputs [
  recipient: string [ kind "email" ]
  subject: string
  body: string
  validate "strict"
]
record @search_contacts_inputs [
  query: string
  validate "strict"
]
record @get_email_by_id_inputs [
  id: string [ kind "message_id" ]
  validate "strict"
]
tools @plannerTools = {
  search_contacts: {
    call: @searchContacts,
    inputs: @search_contacts_inputs,
    labels: [.op:tool:r]
  },
  get_email_by_id: {
    call: @getEmailById,
    inputs: @get_email_by_id_inputs,
    labels: [.op:tool:r]
  },
  send_email: {
    call: @sendEmail,
    inputs: @send_email_inputs,
    labels: [.risk:exfil:send, .op:comm:w]
  }
}

const @workspacePolicy = policy {
  .role:planner { can_authorize: [@sendEmail] }
}
policy @basePolicy = union(@noSendToUnknown, @noUntrustedDestructive, @workspacePolicy)
const @task = "Find Mark's address and send him the Q4 report summary."
exe @plannerPrompt(task) = `You are the planner. Use the tools to finish this task: ${@task}`

>> The "planner" is a single @agent call with the workers as its tool set.
>> Its conversation history IS the execution log — no prior-step threading
>> needed, no stateless re-rendering, no cumulative summary primitive.
const @agentResult = @agent(@plannerPrompt(@task), {
  tools: @plannerTools
}) using {
  read: .role:planner,
  policy: @basePolicy
}

The planner naturally accumulates progress via its own conversation history. When it sees the {status: "sent", recipient: ...} tool result from @sendEmail, it knows the email was sent and can compose a final answer without re-issuing the write. When it calls @getEmailById, it sees the canonical projected @email_msg result because that worker does not need a differentiated planner-facing envelope. No "prior step" threading, no cumulative execution log, no separate compose dispatch step.

Which variant to use:

  • Stateless variant — when you want deterministic per-phase authorization gates, explicit phase boundaries, or framework-level orchestration control. Each phase is a separate @agent call with explicit state threading.
  • Persistent-session variant — when you want the simplest possible orchestration, natural progress accumulation via conversation history, and the shortest path from "define your tool exes" to "call @agent(prompt, {tools})". Works well for open-ended agent tasks where the planner decides the flow.

Both variants are equally secure because the security model (-> strict mode, consumer-side untrusted tagging, grant enforcement at dispatch) is identical. They differ only in orchestration shape.

See exe-tool-return for the full -> and =-> semantics, strict mode, and multi-reach polymorphism rules.

See facts-and-handles for how records, facts, projections, and handles work. See security-grants for per-step consent, security-citations for proving the user's words, and policy-authorizations for the can_authorize / deny law.

Schema Validation with Records and Guards

LLM exes produce unpredictable output. Records validate the shape. Guards retry on failure with a correction hint.

The pattern

import { @agent } from @mlld/multi-harness

record @task_result [
  status: string
  summary: string
  items: array?
]
exe @analyzeTask(input) = @agent(`
  Analyze this and return JSON: { status, summary, items }
  Input: ${@input}
`) => task_result

guard @checkShape = match [
  @output.mx.schema.valid == false && @mx.guard.try < 2
    => retry "Return JSON with a string status, a string summary and an optional items array"
  @output.mx.schema.valid == false => deny "Schema invalid after retries"
  * => allow
]
policy @shapeRules = { .op:named:analyzeTask { after: @checkShape } }

Four pieces:

  1. Record defines the expected shape — field names, types, optionality
  2. => record on the exe applies coercion automatically on every call
  3. Guard checks @output.mx.schema.valid and asks for another attempt with a correction hint
  4. Policy binds the guard: .op:named:analyzeTask names this one exe, and after: runs the guard on its result. A guard has no trigger of its own; nothing runs it until a policy binds it.

A verdict message is a plain quoted string: it cannot quote the value's errors. Write a hint that restates the shape you want. The errors themselves stay available on @output.mx.schema.errors for logging and for the guard's own conditions.

The same coercion engine is also available inline for ordinary values:

record @task_result [
  status: string
  summary: string
  items: array?
]
const @raw = { status: "done" }
const @checked = @raw as record @task_result
show @checked.mx.schema.valid

This prints false: summary is missing.

Use => record when the coercion belongs to the exe's return contract. Use as record @schema when you need to validate or re-coerce a value inside a larger expression.

resume vs retry for tool-calling exes

If the exe calls write tools, use resume instead of retry. retry re-executes the entire exe — including tool calls. That means double-sending emails, double-creating events. resume continues the existing LLM conversation without re-executing tools or exposing new ones:

import { @agent } from @mlld/multi-harness

record @worker_result [
  status: string
  summary: string
]
exe @executeWorker(prompt) = @agent(@prompt) => worker_result

guard @fixShape = match [
  @output.mx.schema.valid == false && @mx.guard.try < 2
    => resume "Return valid JSON with a string status and a string summary"
  @output.mx.schema.valid == false => deny "Still invalid after resume"
  * => allow
]
policy @workerRules = { .op:named:executeWorker { after: @fixShape } }

The LLM sees its prior tool calls and results, plus the correction message. It reformats. => record coercion runs on the new response. No tools re-fire, and the bridge tool list is forced empty. See security-guards-basics for the full resume invariants discussion.

Use retry for exes without side effects (read-only tools, template exes, JS exes). Use resume for exes with write tools.

The LLM gets the hint and tries again, and => record checks the new answer. Make the hint name the fields and types you expect, since it is all the model is told.

Supported field types

Type Accepts Rejects
string strings numbers, booleans, arrays, objects, null
number numbers, numeric strings ("42" → 42) non-numeric strings, booleans, arrays, objects
boolean booleans, "true"/"false" other strings, numbers, arrays, objects
array arrays strings, numbers, objects
object plain objects strings, numbers, arrays, null
handle resolvable handle strings/wrappers plain strings, numbers

Append ? for optional: items: array? means the field can be missing or null.

Validation modes

Records support three validation modes via validate:

record @strict_result [
  status: string
  count: number
  validate "strict"
]
Mode Behavior
demote (default) Any validation error means no fact labels are minted for the record. Schema metadata is attached. Guards can inspect and retry.
strict Any invalid field throws a hard error. Guards do NOT fire — the error propagates before the after-guard evaluates.
drop Invalid fields are silently dropped; valid fields keep their classification. Schema metadata is attached.

For LLM output validation with guard retry, use demote (default) or drop. Do NOT use strict — it throws before the guard fires, making retry impossible. demote is the right choice for most LLM output validation: the value is accessible (for debugging), schema errors are available (for the guard's conditions and for logging), and the guard controls what happens next.

Schema metadata

After => record coercion, the output carries:

  • @output.mx.schema.valid — boolean
  • @output.mx.schema.errors — array of { path, code, message }
  • @output.mx.schema.mode — which validation mode was used

Guards and ordinary code read these directly:

record @count_result [
  status: string
  count: number
]
const @checked = { status: "ok" } as record @count_result
show @checked.mx.schema.errors

Output:

[
  {
    "code": "required",
    "expected": "number",
    "message": "Missing required field 'count'",
    "path": "count"
  }
]

Inline as record @schema attaches the same mx.schema metadata, so grouped expressions like (@value as record @schema).mx.schema.errors work the same way.

Nested output validation

For outputs with nested structure:

record @worker_output [
  worker: string
  summary: string?
  state_patch: object
]

object validates that state_patch is a plain object. It doesn't validate internal structure. For deeper validation:

Option A: flatten. Move important nested fields to the top level:

record @worker_output [
  worker: string
  summary: string?
  results: array
  created_refs: object?
]

Option B: two-stage coercion. Validate the outer shape with the exe record, validate inner structure in the guard:

import { @agent } from @mlld/multi-harness

record @outer [
  worker: string
  state_patch: object
]
record @result_entry [
  tool: string
  status: string
  details: string?
]
exe @worker(input) = @agent(@input) => outer

guard @checkInner = match [
  @output.mx.schema.valid == false && @mx.guard.try < 2
    => retry "Return an object with a string worker and an object state_patch"
  @output.state_patch is not @result_entry && @mx.guard.try < 2
    => retry "state_patch needs a string tool, a string status and an optional details string"
  * => allow
]
policy @innerRules = { .op:named:worker { after: @checkInner } }

Start with object for nested fields. Add deeper validation only if the simple version isn't catching enough.

Proof in validated output

A record field carries proof (it can be used where a tool needs an authoritative value) exactly when it has a kind. For LLM output validation, most fields should have no kind — the LLM's output isn't authoritative:

record @extraction_result [
  category: string
  urgency: string
  summary: string
]

Give a field a kind only when the exe returns data from an authoritative source (a tool result, a database query) — not for LLM-generated classifications:

record @contact [
  id: string [ kind "contact_id" ]
  email: string [ kind "email" ]
  name: string [ kind "name" ]
  notes: string?
]
exe @searchContacts(query) = run cmd {
  contacts-cli search "$query" --format json
} => contact

LLM output parsing

=> record handles messy LLM output automatically:

  1. Strips prose and markdown fences
  2. Parses JSON, then falls back to YAML if the text is not JSON
  3. Coerces types ("42" → 42 for number fields)
  4. Validates required fields
  5. Reports errors on @output.mx.schema

No @parse.llm step needed when using => record. The record IS the parser + validator.

Because step 2 already decodes YAML, => record doubles as a YAML-to-record path.
Use it when you are coercing to a schema; use the @yaml pipe transformer (see
Transformers) when you just want the
parsed value.

Worker validation pattern

For agents with phase-shaped workers (resolve, extract, execute, compose), each worker gets its own record:

import { @agent } from @mlld/multi-harness

record @resolve_output [
  worker: string
  summary: string?
  state_patch: object
]
record @extract_output [
  worker: string
  summary: string?
  state_patch: object
]
record @execute_output [
  worker: string
  summary: string?
  state_patch: object
]
exe @resolveWorker(prompt) = @agent(@prompt) => resolve_output
exe @extractWorker(prompt) = @agent(@prompt) => extract_output
exe @executeWorker(prompt) = @agent(@prompt) => execute_output

guard @checkWorkerShape = match [
  @output.mx.schema.valid == false && @mx.guard.try < 2
    => retry "Return an object with a string worker, an optional summary and an object state_patch"
  * => allow
]
policy @workerRules = {
  .op:named:resolveWorker { after: @checkWorkerShape }
  .op:named:extractWorker { after: @checkWorkerShape }
  .op:named:executeWorker { after: @checkWorkerShape }
}

Same pattern for every worker, and one guard serves them all: the policy binds it after each worker. The record defines the contract. The guard enforces it with retry. No JS validation functions.

Extract-to-write contracts

When an extract phase produces data that feeds a downstream write tool, the record schema is the contract between them. Shape the extract record's fields to match the write tool's parameter names exactly — then the planner can pass extracted values through without renaming, and wrong field names fail coercion.

The wrong shape causes drift. Consider an extract step that produces email_subject and email_recipient, followed by a planner that synthesizes a send_email(recipients, subject, body) call. The rename step is where values drift — the planner reconstructs field names and often copies nearby prose instead of the extracted literals.

The right shape is to define a record whose fields match send_email's parameters:

import { @agent } from @mlld/multi-harness

record @sendEmailInput [
  subject: string
  body: string
  recipients: string
]
exe @extractSendEmailInput(source_content) = [
  >> LLM extracts the data, shaped to match the record
  => @agent(`Extract subject, body, and recipients from: ${@source_content}`)
] => sendEmailInput

guard @checkExtract = match [
  @output.mx.schema.valid == false && @mx.guard.try < 2
    => retry "Wrong shape. Required fields: subject, body, recipients."
  * => allow
]
policy @extractRules = { .op:named:extractSendEmailInput { after: @checkExtract } }

If the LLM returns email_subject instead of subject, => record coercion fails and the guard retries with a hint that names the required fields. The record's field names ARE the contract — there's nothing for the next phase to rename.

None of these fields has a kind, so none carries proof, and each keeps whatever trust the source content had. recipients in particular needs resolution through the contacts directory before it can be used as a control arg in send_email. This is phase discipline: extract doesn't resolve. If the source gives you a name but not an email, extract produces person_name, not recipients. A separate resolve step turns person_name into a handle.

When possible, define the extraction record once per write tool shape (one record for email inputs, one for calendar inputs, etc.) so the contract is visible and reusable. The downstream write tool's parameter list is the source of truth — the record mirrors it.

Dynamic coercion for framework-driven contracts

When a framework takes contracts as configuration (e.g., @framework.build({ contracts: { email: @emailPayload } })), the extract worker needs to coerce output against a record that was passed in, not one referenced statically by name. Use => record @schema:

import { @agent } from @mlld/multi-harness

>> The extract worker takes the contract as a parameter
exe @extractWorker(source, target, contract) = @agent(`
    Extract data matching this shape from: ${@source}
    Target: ${@target}
  `) => record @contract

guard @checkExtract = match [
  @output.mx.schema.valid == false && @mx.guard.try < 2
    => retry "Your output does not match the requested contract; return exactly its fields"
  * => allow
]
policy @extractRules = { .op:named:extractWorker { after: @checkExtract } }

The orchestration layer picks the right contract from a configured map:

import { @emailPayload, @assignmentRows } from "./domain/contracts.mld"
const @contracts = {
  email_task_payload: @emailPayload,
  assignment_rows: @assignmentRows
}

>> The planner requested contract_name: "email_task_payload"
const @contract = @contracts[@request.contract_name]
const @result = @extractWorker(@source, @target, @contract)

The record definitions live in the domain layer. The framework takes them as configuration and coerces extract output against the chosen one. Wrong field names still fail coercion, the guard still retries — same enforcement, but the framework doesn't need to know about email_task_payload or assignment_rows specifically. The developer's domain records are the contract.

This is the pattern that makes framework-driven capability agents possible. The framework owns orchestration, phases, guards, and policy integration. The developer owns records, tools, and contracts. Dynamic coercion is the interface between them.

What this replaces

JS shape validators like:

exe @isValidResult(result) = js {
  return Boolean(
    result
    && typeof result === "object"
    && !Array.isArray(result)
    && result.worker === "execute_capability"
    && result.state_patch
    && typeof result.state_patch === "object"
  );
}

become:

import { @agent } from @mlld/multi-harness

record @execute_output [
  worker: string
  summary: string?
  state_patch: object
]
exe @worker(prompt) = @agent(@prompt) => execute_output

The record validates. The guard retries. The JS is deleted.