Workflow Schema
Deprecated. Workflows are removed in 0.11, when tasks take over ordered steps. See STABILITY.md.
This is the authoritative reference for a workflow asset's exact frontmatter
and body syntax — every key, its shape, and the validation rules enforced by
the published JSON Schema (schemas/akm-workflow.json) and
akm lint --type workflows. Other pages link here instead of reproducing this
detail.
- For a task-oriented walkthrough of writing your first workflow, see the Author's Guide.
- For how a frozen plan actually executes — persistence, dispatch, resume — see Architecture: The Workflow Engine.
- For operating a run day to day (
run,status,resume,abandon), see Running Workflows.
Source format
A workflow is a Markdown .md asset. Nothing else is a workflow source: the
GitHub-shaped .yml workflow format was removed in 0.10, and a stray .yml file
under workflows/ is skipped at index time with a message saying it must use
.md. The shipped schemas/akm-workflow.json frontmatter schema
validates the source.
A Markdown workflow is an ordinary AKM asset — the same envelope as every other Markdown type, OKF-conformant frontmatter plus a body — whose frontmatter carries the orchestration graph (params, and how each step dispatches, fans out, and gates). Its body carries each step's instructions and gate rubric under plain headings, joined to the frontmatter by step id. The remainder of this page's frontmatter/body sections document that authoring format.
Child workflows
Experimental. Child workflows are part of the Deprecated
akm workflowsurface (seeSTABILITY.md) and are removed with it in 0.11.
A step can run another workflow as a child run. It declares the child in
its unit: bag:
steps:
- id: investigate
unit:
workflow: workflows/research # canonical ref, or <bundle>//workflows/<name>
with:
topic: { from: params.topic } # a child param: a literal or { from: <reference> }
- id: report
inputs: [steps.investigate.output] # the child's last step output
The step needs a ## investigate body section like any other step (it is
documentation for a human; the child's own steps carry the instructions).
workflownames the child. A workflow unit runs no model of its own and the child carries its own environment, soexec,connection,harness,model,llmandenvbesideworkfloware lint errors.workflowis not allowed insidemap.unit.with:binds the child's declaredparams:(a workflow has noinputs:). Each value is a literal (validated against the param's declared type at freeze) or{from: "steps.<id>.output(.<segment>)*"}or{from: "params.<name>"}, resolved just before the unit dispatches. A child param the step leaves out takes the child's owndefault:. An unknown key or an invalid reference fails at freeze withUsageErrorcodeINPUT_BINDING_INVALID.- The child's result is its last step's output, exactly what
steps.<child-step>.outputwould be for that step inside the child. A later step reads it assteps.<composing-step>.output(sub-paths legal). A workflow has no separateoutputs:key.
Frozen before publication
Composing a child workflow is a freeze-time resolution. When the parent
workflow's plan is frozen, AKM loads the child's source, compiles it,
validates it, and freezes the child's complete plan before the parent run is
published. The result is embedded whole inside the parent step's frozen target
(kind: "child-workflow"); nothing about the child is re-read at dispatch
time. Editing the child's source after the parent run has started has no effect
on that run.
A workflow that reaches itself through any chain of children fails at freeze
with UsageError code COMPOSITION_INVALID (exit 2), naming the cycle path.
The same workflow reached twice through disjoint branches (a diamond) is not a
cycle; each occurrence embeds its own copy. A workflow: ref that does not
resolve fails with the ordinary asset-resolution error.
Child execution
Running a step whose own target is kind: "child-workflow" publishes (or
finds, if one already exists — see "Identity and retries" below) a child
run and drives it to completion, or as far as it gets, before the parent
step is finalized. The drive happens inline, in the parent's own
process: it is the same engine akm run uses on the child's
frozen plan, not a separately scheduled job. Consequently, whatever aborts
the parent's own dispatch — Ctrl-C, a --timeout, or a budget ceiling —
also aborts the child drive; both runs are left resumable, never partially
torn down.
The child's final status maps onto the composing step and the parent run:
| Child status | Composing step | Parent run |
|---|---|---|
completed |
completes; its output is the child's last step output | continues |
failed |
failed |
failed |
blocked |
blocked |
blocked |
| aborted mid-drive (parent cancelled/timed out) | left unfinished, not finalized | active and resumable |
the child could not be published (its params do not satisfy the child's declared params:) |
failed |
failed |
| another process already holds the child's run lock | failed |
failed |
Blocked-child recovery. A blocked child blocks its composing step —
akm does not resume a child for you, because a gate is a gate for a
child workflow too. The step's notes name the exact three-command
sequence: resume the child first, then resume and re-run the
parent — re-driving the parent is what advances it, because that is
what re-enters the composing step and drives the now-resumed child:
akm workflow resume <childRunId>
akm workflow resume <parentRunId>
akm run <parentRunId>
Nested blocks. The three-command sequence above clears a block exactly one level deep. With a grandchild block (root composes child, child composes grandchild, grandchild blocks), resume every blocked run in the chain, deepest first, then re-run only the root:
akm workflow resume <grandchildRunId>
akm workflow resume <childRunId>
akm workflow resume <rootRunId>
akm run <rootRunId>
Identity and retries. A child run's identity is keyed by the parent run,
the parent unit, and that unit's input hash — publishing is idempotent, so
re-driving the composing step (an explicit akm workflow resume +
akm run) finds and continues the same child run rather than
starting a new one. Only a change to the composing step's own inputs (params,
upstream step outputs it reads, or gate feedback from a rejected verification
loop) produces a different child.
Visibility. akm workflow status on a run that composes children
renders a children: tree — every descendant run's ref, status, and, for a
blocked child, its resume command. Child runs are excluded from akm workflow list by default; pass --children to include them. A child run
id always works directly with akm workflow status/resume/abandon/run,
listed or not. See
Running Workflows: Child runs for a
worked example, and
Architecture: The Workflow Engine
for the dispatch seam.
Frontmatter keys
Frontmatter is the standard AKM asset envelope (type, description, tags,
when_to_use, xrefs, updated/timestamp, and the OKF v0.2 trust/lifecycle
families) plus the orchestration keys:
params— name →{ type, description, default }(JSON-Schema-typed, unlike a bare description string). A param the run does not supply takes itsdefault:; an explicit value wins. Params are never required.defaults— run-level dispatch defaults (connection,harness,model,llm,timeout,on_error), overridable per unit. A step with neither runs on the default harness, else akm's own runtime over the default connection.llm:tuning (temperature,max_tokens,enable_thinking,reasoning_effort) reaches every step, and a document-levelllm:reaches EVERY step. A connection and akm's own runtime send it; a harness reports it as anuntranslated-fieldnotice on that step (see Settings a call asks for). There is no per-step opt-out (llm: {}is a no-op andllm: nullis a parse error), so in a mixed document putllm:on theunit:of each step it is meant for instead of indefaults:.budget— run-lifetime ceilings (max_units,max_tokens; see Budget ceilings below).steps— an ordered list. Each step has anid([A-Za-z_][A-Za-z0-9_-]*— no dots) and at most one ofunitormap. A step with neither is still a unit step — bare- id: validateis the complete minimal declaration.unit:is the optional dispatch-override bag (exec,connection,harness,model,llm,timeout,retry,on_error,output,env; see Exec (shell) units and Failure policy). Dispatch settings live underunit:(map.unit:on a map step), not on the step itself;unit.outputtypes that unit's result, so a solo step puts its schema there.inputs— on aunit/mapstep, the prior-step artifacts this step consumes, as bare reference strings (sub-paths legal:steps.x.output.issues, not juststeps.x.output). This is how a step's attached context sees upstream data, and how replay hashing gets its exact input set — a step re-dispatches only when the slice it actually consumes changes.output— a JSON Schema for the step's promoted artifact. On amapstep it checks the reducer's result. On any other step that is not a child-workflowunit and whoseunit:declares nooutputof its own, it is also the unit'soutputschema, so the reply is parsed and checked as JSON;unit.outputis the explicit form.gate— optional validation-loop configuration:max_loopsbounds evaluator-optimizer retries (see Gates and verification). The rubric itself lives in the body's### gatesection. Without non-empty rubric text, the configuration is inert.
No version:/name: keys — identity is the ref, and the frozen plan already
versions execution semantics — and no step titles anywhere: a step is its id,
and the asset's human name is its description and H1 like any other asset
type.
Body structure and rules
Checked by akm lint --type workflows:
- Every level-2 heading must be
## <step-id>for a step declared in frontmatter, exactly — no titles, noStep:/Step ID:lines, no# Workflow:prefix on the H1. (Fenced code blocks are skipped when scanning for headings.) - Every step must have a body section — its instructions,
or its per-item template for a map step, byte-exact to the next H2 or
EOF. Everything before the first H2 is free preamble —
indexed for search, shown in
akm show, never dispatched. - Inside a step's section, an optional
### gatesub-heading starts that step's gate rubric, running to the section end — the format's single reserved marker. The judge that evaluates the step receives this whole section byte-exact. An omitted or empty### gatesection needs no verification. A non-empty rubric enables mandatory verification; frontmattergate:only tunes its retry bound.
Prose is never templated — see The reference grammar for how a step's instructions refer to run params, upstream artifacts, and a map unit's item.
Minimal example
---
type: workflow
description: Ship a tagged release to production
params:
version: { type: string, description: The semver version string to release }
steps:
- id: validate
- id: build
inputs: [steps.validate.output]
---
# Ship Release
## validate
Check that the `version` parameter follows semver and the tag does not
already exist.
### gate
- `git tag v<version>` does not already exist.
- The version string matches `^\d+\.\d+\.\d+$`.
## build
Run `npm run build && npm test`, using the validation from `validate`,
attached to this unit as input. Fix any failures before proceeding.
Richer example
Fan-out, retries, gates, and a run budget:
---
type: workflow
description: Review changed files and give an overall verdict
params:
changed_files: { type: array, description: Files to review }
defaults: { harness: claude, model: balanced, timeout: 10m, on_error: fail }
budget: { max_units: 40, max_tokens: 200000 }
steps:
- id: discover
unit:
output: { type: object, properties: { files: { type: array } }, required: [files] }
- id: review
map:
over: steps.discover.output.files
concurrency: 8
unit:
harness: claude
model: reasoning
timeout: 5m
retry: { max: 1, on: [timeout, llm_rate_limit] }
on_error: continue
output: { type: object, properties: { file: { type: string }, verdict: { type: string } }, required: [file, verdict] }
# `output` here describes the REDUCER RESULT, not one unit's result: the
# default `collect` reducer folds per-item unit results into an array.
output: { type: array }
gate: { max_loops: 2 }
- id: aggregate
inputs: [steps.review.output]
unit:
output: { type: object, properties: { verdict: { type: string } }, required: [verdict] }
---
# Review Changes
## discover
List the files that need review, drawn from the `changed_files` parameter.
### gate
Every file named by `changed_files` is listed in the reported result.
## review
This section is the **map unit template** — the engine attaches each unit's
item (the file to review) and its index as context; instructions refer to
"the file you were given," never a template expression.
Review the file you were given for correctness bugs.
### gate
Every changed file has a verdict of `pass` or `fail`.
## aggregate
Combine the per-file review verdicts — attached to this unit as input via
`inputs: [steps.review.output]` above — into one overall verdict, `pass` or
`fail`.
The reference grammar
Workflow prose is never templated — there is no ${{ … }}/{{ … }}
interpolation anywhere in a workflow's body, and no escape syntax to learn,
because there are no delimiters in prose to escape.
Bare reference strings appear in exactly two frontmatter positions, each an unquoted-style YAML string:
| Position | What it names |
|---|---|
map.over |
The list a map step fans out over. |
inputs (each entry) |
A prior step's artifact this step consumes. |
Every reference resolves against exactly two roots:
| Reference | Meaning |
|---|---|
params.<name> |
A run parameter, by name. |
steps.<id>.output( .<ident> | [<int>] )* |
A prior step's artifact, addressed by producer step id; the path walks properties (.name) and array indexes ([0]). |
Nothing else parses: no functions, no clock, no randomness, no ambient
lookup. item and item_index are not part of the language — a map
unit's item and its index are never referenced from anywhere in frontmatter
or body. They arrive as attached context instead, the same way as
everything else a unit needs.
Context attachment, not string splicing. Each dispatched unit receives, alongside its byte-exact instructions, structured context:
- every run param (params are run-scoped — see Params are not secret below);
- for a map unit, its item and item index;
- the artifacts named by its step's
inputs:.
Instructions refer to this context in plain language — "clone the repository
named by the repo parameter," "review the file you were given," "using the
intake step's artifact attached to this unit" — never by splicing a value
into the instruction string.
akm lint --type workflows still checks every bare reference statically —
unknown step, unknown param, bad path — at lint time.
Params are not secret
Run params are copied verbatim into every unit's dispatched instructions and
are stored on the run row and shown by akm workflow status, so params are
declared non-secret: secrets belong in env: refs instead, which carry
by name only through the plan and are resolved from akm's env/secret store
at dispatch (see Reference: Env & Secrets).
As a best-effort guardrail, akm run scans a new run's params for
values that look like credentials — secret-suggesting key names (token,
password, apikey, credential, …) or long, high-entropy strings matching
known token prefixes — and surfaces a warning naming the param path and
recommending an env: ref instead. This is advisory only: it never blocks a
run and never mutates params, and false positives/negatives are expected. The
same heuristic feeds the dispatch redaction set, so a unit result or
diagnostic that echoes such a value is scrubbed before it is journaled.
What a step's output is
steps.<id>.output resolves to the value the step's execution produced:
- a
unitstep → the unit's structured result (when the unit declaresoutput) or its text; - a
mapstep → the collected array of per-item results, in item order (underon_error: continue, a failed item's slot isnull), unless the step's ownoutputschema describes a reduced, single-value shape instead; - an exec unit → its stdout (trailing newlines stripped),
or the JSON value stdout parsed to when the unit declares an
outputschema.
An empty successful free-text output is treated as no output. When a
schemaless unit (one that declares no output schema) succeeds but returns
the empty string, akm normalizes it to absent: nothing is journaled for its
result, and its contribution to the step artifact is null — a null slot
in a collected array, or output = null for a solo step. This absence is
deliberate, so a live run and a resumed run promote the identical artifact.
The practical consequence: a downstream step that declares an empty upstream
result in its inputs: gets nothing meaningful attached for it — akm
surfaces this loudly rather than silently attaching an empty string. A unit
that declares an output schema is unaffected — an empty response is not
valid JSON, so it fails as a parse error and can never satisfy a schema as a
silent null. A prose unit whose agent ends with no reply has not succeeded
either: it fails with parse_error, which retry.on: can name.
When a step declares no output: schema
A step-level output: schema is optional, and omitting it is a supported
mode, not a deficiency. The step artifact is then exactly the value described
above — the unit's result for a solo step, the collected array for a map
step — carried untyped and never validated.
The shape is stable either way: it does not depend on whether a schema is
present, and it does not vary between a live run and a resume. steps.<id>.output
resolves the same in both cases, so downstream references work with or without
a schema.
What a schema adds is enforcement, not shape. With one, the promoted
artifact is checked against it and the step fails on mismatch; without one, a
downstream reference to a field the artifact happens not to carry surfaces at
resolution time instead (steps.X.output is not an object — cannot resolve property "y"). Declare output: when you want that mismatch caught at the
producing step rather than at the consuming one.
akm does not warn about a missing step output: schema; leaving it off is
legitimate.
Typed step artifacts
When a step declares output, the promoted step artifact (the unit's
structured result, the collected array, or a reduced single value — see
What a step's output is above) is validated
against that schema before the step can complete. A mismatch fails the
step with the validation errors in its summary. This is fail-fast on purpose:
a bounded gate loop (see Gates and verification)
can re-run the step with those errors as corrective feedback.
The enforced JSON Schema subset
output and params schemas are validated as schemas at parse time
(akm lint --type workflows, akm workflow create), because the runtime
enforces only a subset of JSON Schema:
type, enum, properties, required, items, additionalProperties: false, minItems, maxItems, minLength, maxLength, minimum,
maximum, allOf, anyOf, oneOf, not.
Anything outside it is an authoring error, not a silent no-op. A typo'd
type name (type: strig) and a recognized-but-unenforced keyword ($ref,
$defs, const, pattern, format, patternProperties, if/then/else,
uniqueItems, multipleOf, exclusiveMinimum/exclusiveMaximum,
tuple-form items, schema-form additionalProperties, …) both fail with the
offending keyword named, a suggested replacement where one exists (const →
a single-value enum; $ref → inline the schema), and the location anchored
to the line. A gate that depends on a schema constraining nothing is worse
than a loud failure. Annotation keywords (description, title, default,
examples) constrain nothing in full JSON Schema either, so they pass through
untouched.
pattern is among the unsupported keywords. Matching an author-supplied regex
inside a synchronous gate decision would have to be bounded before the match
starts — a static safety analysis — and any such analysis also refuses regexes
authors legitimately write. Rather than carry machinery that fails authoring
for no benefit, the subset does not evaluate pattern at all and says so at
the point of authoring. Where a string's shape matters, list the allowed values
with enum, bound its size with minLength/maxLength, or check the shape in
the step's gate rubric, which can explain a mismatch in a way a regex cannot.
Evaluation is bounded: schema nesting is capped at 64 levels and one validation may make at most 100 000 checks. Exhausting either is reported as an error — a truncated evaluation never reports a value as valid.
Bounds
These are enforced identically by the parser, the published JSON Schema, and
the frozen-plan decoder (they share one set of constants in
src/workflows/resource-limits.ts), so a document that lints clean cannot
fail later at akm run:
| Field | Bound |
|---|---|
gate.max_loops |
1 – 100 |
map.concurrency |
1 – 64 |
retry.max |
0 – 100 |
timeout |
≤ 2147483647 ms (~24.8 days), or none |
connection and harness names |
^[a-z][a-z0-9]*(-[a-z0-9]+)*$, ≤ 63 chars |
timeout is resolved once, at freeze time, and the frozen value is what
dispatch applies — there is no separate ceiling on top of it. The
first of these that is set wins: the unit's timeout, then the document's
defaults.timeout, then the selected connection's or harness's timeoutMs,
then the default — none for agent work, whether it runs on a harness or on
akm's runtime over a connection, and 10m for model work. Writing timeout: none is an explicit opt
out and leaves the unit genuinely unbounded; nothing later re-imposes a cap.
Exec (shell) units
A step whose unit: block declares exec: runs a shell command instead of
dispatching a model. Deterministic work — running the test suite, building,
linting, copying a file, invoking a script — is a command, not a prompt, and
paying for an LLM or agent dispatch to get it done buys nondeterminism, latency,
and tokens in exchange for nothing.
steps:
- id: test
unit:
exec:
command: ["bun", "run", "test:unit"]
cwd: packages/core # optional: relative to the workflow's bundle root, or absolute
timeout: "10m"
retry: { max: 1, on: [timeout] }
An exec unit names no connection or harness. It carries no connection,
harness, model, or llm (the parser rejects those alongside exec:), it
consumes no tokens, and a workflow made only of exec steps freezes and runs on an
install with no connection or harness configured at all. Everything else about a unit still applies unchanged: timeout, retry,
on_error, output, env, map fan-out and its concurrency, the
unit journal, budget accounting, and replay/reuse.
The step's body prose is still required (it is the step's section, like any other unit step) and is not passed to the command — it documents what the command does, for the human reading the workflow.
command is an argv array
command is a non-empty list of non-empty strings; there is no shell-string
spelling. The program is spawned directly, so ;, |, &&, $(…),
backticks, > and * inside an argument are literal characters. For a
pipeline or a shell builtin, name the interpreter yourself:
command: ["bash", "-lc", "bun run build | tee build.log"]
cwd
Optional: a non-empty string, relative or absolute, and free to carry
${ref} tokens (see ${ref} in argv and cwd). It is
the only static check; there is no containment.
An exec unit's working directory is the root of the bundle that owns the
workflow. akm finds that bundle again for each step, by the run's workflow
ref, so a bundle update that moves the bundle to a new revision directory
between two steps of a running workflow is harmless: the next step runs from
the new directory. cwd is joined onto that root once: cwd: sub runs in
<bundle>/sub, and an absolute cwd replaces the root. Agent and SDK units
get the same directory as their workspace, and so does a step's gate judge. If the workflow's bundle no longer
resolves, the step fails with a message naming the ref; a step with a gate is
blocked by its judge first, for akm workflow resume, because the judge is built
before anything is dispatched. akm never falls back to its own working
directory.
The exec contract
What a command can rely on, in one place. The sections below give each point in full.
| Working directory | The owner root of the run's workflow, found at each step's dispatch. cwd joins it once and may be absolute. |
| Argv | Spawned directly, never shell-interpreted. A ${ref} token in an entry is replaced at dispatch. |
| Environment | akm's own, with the directories this akm resolved set over it, then the unit's env: bindings, then the engine's AKM_* context. |
${ref} tokens |
In argv, cwd and env-asset values. ${secrets/name} becomes the secret's value, any other asset ref the asset's absolute path. A ref no bundle owns fails the unit before it spawns. Prompts are not substituted. |
| Redaction | Only values akm knows are secret are scrubbed from stdout, stderr, diagnostics and the journal: values substituted from secrets/ refs, secret-shaped run params, connection keys, and the values of credential-named variables the command inherited from akm's environment (names such as *_API_KEY, *_TOKEN, *_SECRET and *_PASSWORD, eight characters or more). Configuration, such as a URL bound through an env asset or an ordinary inherited variable, is not. |
What is frozen, and what is found at dispatch
The frozen plan records the identities the engine itself dereferences: the
workflow ref, each unit's env: refs qualified with their bundle
(team//env/prod), and child workflow refs, plus the argv, cwd and
pass_env names as authored. It records no directory or file location. The
bundle root, the env files, the secrets and the paths behind ${ref} tokens are
all looked up when the unit dispatches, through the same ref lookup akm show
uses. Plans frozen by earlier releases (irVersion 5 and 6) also carry a frozen
cwdIdentity and the env asset's owner paths; they decode, those fields are
ignored, and such a run dispatches by ref like any other.
${ref} in argv and cwd
An argv entry or cwd can name an asset in any bundle with the same
${[bundle//]conceptId} token env assets use:
- id: status
unit:
env: [team//env/discord]
exec:
command: ["bun", "${homelab//scripts/lab-status/fetch-status.ts}"]
A secrets/ ref gives the secret's value, trimmed of surrounding whitespace,
and joins the redaction set; any other asset ref gives the asset's absolute
path. Putting a secret in argv is the author's choice (it shows up in the
process list); prefer an env: binding. A ${...} body that is not an akm ref
(${HOME}) is left as text. A ref no bundle owns fails the unit, naming it,
before anything is spawned.
The output rule
-
No
output:schema → the artifact is the command's stdout, with trailing newlines stripped (exactly like shell$(…)). Empty stdout follows the ordinary empty-output rule: it is treated as no output. -
With an
output:schema on the unit → stdout must be exactly one JSON value (surrounding whitespace tolerated, nothing else), which is parsed and validated against the schema. This is a strict parse, unlike the forgiving embedded-JSON scan used for model output: a command that claims a schema prints JSON, and log noise that happens to contain a JSON object must never be promoted as the artifact. Non-JSON stdout fails asparse_error; JSON that misses the schema fails asvalidation_error. -
stderr is never part of the artifact. It is a diagnostic channel: the tail of a failed command's stderr is included (clipped, redacted) in the unit's failure diagnostic and its journal row. Because a failing command's stderr is frequently the only explanation of the failure, that diagnostic is durable — it survives to
akm workflow status --unitsand to the step's summary in the run output, not just to the in-memory result. It is clipped to 2000 characters and goes through the same redaction contract as everything else journaled. -
Retained output is bounded at 8 MiB per stream. akm keeps at most that much of stdout and of stderr; past the cap it keeps reading and discards, so the command still runs to completion and its exit code still decides the unit. See Output limits — the artifact is then explicitly marked truncated, never silently shortened, and only a unit with a declared
output:schema fails for it. -
An incomplete STDOUT capture is a failure, not a partial artifact. Exiting 0 is not on its own proof that stdout was fully read: a pipe can error, and a background descendant that started its own session (
setsid) can keep the stdout handle open after the command leader exits, past the drain deadline. Either way the captured text is a prefix of the real output, so the unit failsexec_capture_incompleterather than promoting the prefix. That reason is deliberately outsideretry.on: the command already RAN, and re-dispatching identical argv to fix a capture problem would run its side effects again. If you hit this, have the command wait for its children or redirect their output.A background process the command leaves in its own process group (a server started with
&ornohup) is not a capture failure: when the command exits, akm gives the pipes a short grace, then stops what is left in the group (SIGINT, SIGTERM, SIGKILL) and the unit succeeds with the command's own result and the output read. Redirecting the child's output does not keep it alive; a process that must outlive the unit starts its own session and redirects its output (setsid server >server.log 2>&1 &). Either alone fails: without its own session it is stopped, and without the redirect the capture failsexec_capture_incomplete.Only stdout is fatal here. stderr never contributes to the artifact, so a stderr drain that did not finish leaves the unit's actual result — a completed command, a fully captured stdout — intact and the unit succeeds; failing it would discard a valid artifact over a lost log tail. akm warns when that happens, naming the unit, so stderr shown for it is never mistaken for the whole of it.
The drain deadline itself starts when nothing living owns the pipe any more — the command's exit, or for a unit with a declared
timeoutthe earlier of that and the budget expiring — plus a short grace. A unit does not sit until its wholetimeoutbecause a descendant outlived the command.
Note that a schema failure is not retried by the corrective-feedback loop
that model units use. Re-prompting is meaningless to a fixed argv — the same
command cannot produce different output — but re-running it can deploy twice.
A declared retry: still applies, because that is a policy you opted into per
failure reason.
Exit codes and failure reasons
| Outcome | failure_reason |
In retry.on? |
|---|---|---|
| exit 0 | — (unit succeeds) | — |
| non-zero exit | non_zero_exit |
yes |
exceeded timeout |
timeout |
yes |
run cancelled (Ctrl-C, --timeout, budget) |
aborted |
yes |
| binary missing / working directory missing | spawn_failed |
yes |
| stdout capture never completed | exec_capture_incomplete |
no (the command already ran) |
| stderr capture never completed | — (unit succeeds; a warning says the stderr tail may be missing) | — |
stdout past the retention limit, and the unit declares output: |
exec_output_limit |
no (deterministic) |
stdout past the retention limit, no output: schema |
— (unit succeeds; artifact marked truncated) | — |
AKM_* context too large for this platform to spawn |
exec_context_too_large |
no (an authoring/data problem) |
non_zero_exit in retry.on re-runs a command that already ran, and a
command's exit is usually deterministic, so the retry mostly repeats the
failure and any side effects. For exec steps prefer
retry: { max: 1, on: [timeout, spawn_failed] }.
A non-zero exit is an ordinary unit failure, so it flows through the ordinary
policy: with the default on_error: fail it fails the step and the run — which
is exactly what makes a test step a gate. With on_error: continue the
failure is recorded in the step's evidence and the completion gate decides.
On timeout or cancellation the child's whole process group gets a SIGINT→SIGTERM→SIGKILL ladder (each signal after a grace period of 5 seconds, for a command still running), so a command that spawned its own children does not leave them orphaned. Windows has no process group; there the first signal ends the command itself.
Output limits
akm captures the command's stdout and stderr into memory — stdout is the artifact — so it retains at most 8 MiB of each stream.
This is a cap on akm's memory, not on your command. Past the cap akm keeps reading the pipe and throws the extra bytes away, so the command never blocks on a full pipe: it runs to completion and its exit code is what decides the unit. A chatty-but-passing test suite is not failed for its log volume.
What overflow does cost is honesty about the artifact, and that depends on what the unit promised:
| The unit declares… | On overflow |
|---|---|
no output: schema |
the unit succeeds (given exit 0). Its artifact is the retained first 8 MiB with a __akm_exec_output_truncated__ block appended, naming the bytes written and the bytes retained. |
an output: schema |
the unit fails exec_output_limit and nothing is promoted. |
Nothing is ever truncated silently. The marker block is the last thing in the
artifact, so a downstream steps.<id>.output reference, a completion gate's
judge, and a human reading akm workflow status all see plainly that the text is
incomplete. Truncated data can never be mistaken for complete data — that is the
rule, and the marker is how it is kept.
The schema case stays a failure because a truncated prefix is not a JSON value:
with output: declared, stdout must parse as exactly one JSON value, so there is
nothing to validate and nothing safe to promote. exec_output_limit is therefore
still outside the retry.on vocabulary — the command is deterministic, so
re-dispatching it can only spend the budget to produce the same oversized output
again.
stderr overflow never fails anything. stderr is a diagnostic channel; the journal already clips and marks what it keeps.
The cap is generous (8× the 1 MiB evidence-persistence cap), so an ordinary build or test log is nowhere near it. If a command legitimately produces more and you want the whole thing, have it write to a file and print the path:
command: ["bash", "-lc", "bun run build > build.log 2>&1; echo build.log"]
Context reaching the command
A frozen argv never carries run data (this format has no substitution language
for params or step output; the only substitution is a ${ref} token
naming an asset), so data reaches an exec unit as environment, the argv
analogue of the context blocks a model unit gets in its prompt:
| Variable | Value |
|---|---|
AKM_RUN_ID, AKM_STEP_ID, AKM_UNIT_ID |
ids of this dispatch |
AKM_PARAMS |
the run params, canonical JSON |
AKM_ITEM, AKM_ITEM_INDEX |
a map unit's item (canonical JSON) and 0-based index |
AKM_INPUTS |
the step's declared inputs: artifacts, keyed by reference string |
These are applied after your env: bindings, so a binding can never shadow
them.
Context size limits
An environment variable is an operating-system object with a hard ceiling, and a workflow artifact has no comparable bound — so a perfectly legitimate declared input can grow past what process creation itself accepts. akm therefore bounds what it puts in the child's environment, against the ceiling of the platform the run is actually on:
| Bound | Linux / macOS / BSD | Windows |
|---|---|---|
One AKM_* context variable |
98 304 bytes (96 KiB) | 32 767 bytes |
All AKM_* context variables combined |
131 072 bytes (128 KiB) | 64 000 bytes |
Where those numbers come from:
- Linux caps a single
argv/environstring atMAX_ARG_STRLEN, defined as32 * PAGE_SIZE— 131 072 bytes. The 96 KiB bound leaves 32 KiB of margin for the variable's name, the=, theNUL, and the kernel's own accounting. - macOS has no per-string cap; its binding constraint is
ARG_MAX(262 144 bytes) overargv+environcombined. The 128 KiB total keeps akm's own contribution to half of that, leaving the rest for the argv, the rest of the environment and yourenv:bindings. - Windows caps a single user-defined environment variable at 32 767
characters (
SetEnvironmentVariable), and the environment block has limits of the same order.
Crossing either bound fails the unit exec_context_too_large before anything
is spawned, with an error naming the variable, its actual size, this platform's
limit and where that number comes from. That translation is the check's only
job: without it the same workflow dies inside the spawn syscall with a bare
E2BIG ("argument list too long") that names neither the variable nor the step
that produced the data.
Because that is its only job, the check uses this platform's ceiling rather than the smallest supported one. A guard that applied Windows' 32 767-byte limit on Linux would refuse spawns the kernel would happily have accepted — inventing a failure instead of explaining an inevitable one.
Portability guidance (not enforcement). If a workflow is meant to run on Windows as well, keep
AKM_*context under 32 767 bytes per variable. akm will not fail your Linux or macOS run for exceeding that — but a Windows runner will. The fix in both cases is the same: emit a reference instead of bulk data.
If you hit this, have the producing step emit a reference — a file path, an id, a key — instead of inline bulk data:
- id: extract
unit:
exec:
command: ["bash", "-lc", "./extract.sh > /tmp/rows.json; echo /tmp/rows.json"]
- id: load
inputs: [steps.extract.output] # a PATH, not the rows
unit:
exec:
command: ["./load.sh"]
akm deliberately does not transparently spill an oversized context to a file
and pass a path instead. That would make the AKM_INPUTS contract conditional
on the size of the data — sometimes JSON, sometimes a filename — so every
command would have to handle both shapes, and the spill file would have to be
placed and cleaned up. A stable contract plus
an explicit error is the smaller, more predictable surface.
The child's environment
An exec unit's command inherits the environment akm runs in, as a command typed in
your shell would, and nothing is filtered out of it: PATH, HOME, locale and
toolchain variables, and any credential or proxy setting of the process that ran
akm run reach the command. It is built in three layers, in this order:
- akm's own environment, with the directories this akm resolved set over it;
- the unit's resolved
env:bindings; - the engine-authored
AKM_*context — last, so a binding can never shadow it.
The directories are AKM_CONFIG_DIR, AKM_DATA_DIR, AKM_CACHE_DIR and
AKM_STATE_DIR, set to the ones the akm that started the command resolved (from
AKM_*_DIR, XDG_*_HOME or the platform default), and AKM_BUNDLE_DIR when that
akm had one. A step that runs akm therefore uses the same bundle, config, data,
cache and state. Binding one of them in env: overrides it. When a scheduled
task runs the workflow, AKM_EVENT_SOURCE is set (when the environment has
none), so a command that calls akm records machine traffic, not user demand; a
direct akm run leaves it as it found it.
Reach a fixed value or a secret with an exact named env: binding; what is
redacted from what the command prints is in the Redaction row of the exec
contract.
pass_env: — frozen, and it selects nothing
unit:
exec:
command: ["cargo", "build", "--release"]
pass_env: [CARGO_HOME, SCCACHE_DIR]
pass_env: was the list of variable names an earlier release copied into a child
that started empty. A workflow that has it keeps loading, and the names are kept
in the frozen plan and in the unit's input hash, but they select nothing now: the
command already has the environment. Names only, matching
^[A-Za-z_][A-Za-z0-9_]*$.
Binding a secret to a unit
A unit's env: lists env assets by ref. A value inside an env asset can be a
${ref} token, which akm replaces with the secret's value when the unit is
dispatched. Say the bundle team holds env/discord.env:
DISCORD_BOT_TOKEN=${team//secrets/discord_bot_token}
and the secret beside it, set with
akm secret set secrets/discord_bot_token --bundle team. The unit names the
env asset:
- id: announce
inputs: [steps.draft.output]
unit:
env: [team//env/discord]
exec:
command: ["node", "announce.mjs"]
- The token body is an akm ref,
[bundle//]conceptId, resolved with the one ref walk:${team//secrets/discord_bot_token}reads that secret from theteambundle whichever bundle holds the env asset, and an unqualified${secrets/discord_bot_token}resolves by the default bundle then installation priority. Asecrets/...ref gives the secret's value, trimmed of surrounding whitespace; any other asset ref (${scripts/x.sh}) gives the asset's absolute path. A${...}body that is not an akm ref (${HOME}) is left as text. - It is the same token
akm exec --envresolves.akm env exportdoes not resolve it; it writes the token verbatim. - Freezing records the env ref, never a value. At each dispatch the unit's env
assets are read live with
resolveEnvBinding, the same functionakm exec --envuses, so an edit to the env file, or to a secret, after the run started is picked up by the next dispatch; there is no key-set check against the frozen plan. A ref no bundle owns fails the step at dispatch ("frozen environment preflight failed") and nothing is injected. - Each dispatch that reads the env asset records an
env_accessevent with the ref and key names, never values. - Redaction covers secrets, not configuration. A value substituted from a
secrets/ref is treated as sensitive and redacted out of stdout, stderr and diagnostics before they are journaled. The rest of an env asset, such as a URL or a channel id, reaches the journal and the next step unredacted. A credential typed straight into an env file is not redacted, so keep credentials insecrets/and bind them with a${secrets/name}token. env:needs a child process: it works on exec units and on every unit that runs an agent, whether on a harness or on akm's own runtime. A model call that runs no agent cannot take a per-unit environment and failsenv_unsupported.
Durable v4 (irVersion: 8) forbids inherit_env
Every new workflow start freezes the durable plan v4 family's current
executable format (irVersion: 8; a plan frozen earlier decodes when it holds no
model step). It rejects
inherit_env: true, which is not needed: the command inherits akm's
environment. Exact named env: bindings are dispatch-significant and form part
of the unit's input hash.
What akm show reports for an exec step
akm show <workflow> --format json summarizes each step under
steps[].orchestration. For an exec step that summary carries an exec object
and no engine/model — an exec unit runs on no connection or harness, so
reporting the workflow's defaults there would describe a dispatch that never
happens. Field presence is the discriminator, the same way fanOut marks a
map step:
{
"id": "test",
"title": "test",
"instructions": "Run the unit tests.",
"orchestration": {
"timeoutMs": 600000,
"exec": {
"command": ["bun", "run", "test:unit"],
"cwd": "packages/core",
"passEnv": ["CARGO_HOME"]
}
}
}
commandis the argv in full, never clipped — the point of the field is that whatshowprints is what runs, and a truncated argv would be the same misdescription in miniature. It is safe to print because it is authored literally in the asset: this format has no substitution language, so no part of it is resolved from your environment, from a secret ref, or from a prior step's output. Every byte is already visible in the workflow file (and stored verbatim inplan_json) — which is also why you never inline a secret there.cwdandpassEnvappear only when the unit declares them.passEnvis a list of variable names that select nothing; no value is ever projected. New v4 plans never carryinheritEnv.timeoutMsis still reported, because an exec unit really does inheritdefaults.timeout— that number is true for it.
Everything else in the summary is unchanged: a map of exec units carries both
fanOut and exec, and hasSchema/env mean what they mean for any unit.
Security
Exec units sit inside the existing workflow trust model — see Security: workflow sources are executed code. They do not widen it, and they do not narrow it:
- The child inherits akm's environment. The command runs with your environment, as if you had typed it in your shell, so a credential the shell or CI job exported reaches it, and a value it inherited is not redacted from what it prints. That is the same trust a workflow source already has: a command that runs at all can read the same credentials off disk. Operators who need a boundary scope the akm process (dedicated account, ephemeral working directory, external network/filesystem policy); that is the boundary that actually holds.
- Secrets come from
env:bindings by name. The frozen plan carries only the ref names, the replay hash carries only the ref names, and the resolved values are collected and scrubbed out of stdout, stderr, and the failure diagnostic by the same redaction contract every other dispatch uses — before anything is journaled. Never inline a secret value intocommand:; argv is stored as authored inplan_json. A${secrets/name}token in argv is stored as the token and replaced only when the unit dispatches. - Read a workflow before you run it.
exec:makes what a workflow will run explicit and auditable in one place, which is a real improvement over instructing a model to "run the tests" — but a bundle you do not trust is still a stranger's script.
Fan-out and concurrency
A map step is a fan-out: it expands over: into one unit per item, runs
those units, and folds the results with its reducer. The units are
independent by construction — no unit can read another's result — so they run
in parallel by default.
The default
A map step that declares no concurrency: freezes a width of 4. The
width is a fixed number rather than "as wide as the machine allows", so an
author can reason about it without knowing which host the run lands on.
Three ways to change it:
| You want | Write |
|---|---|
| A specific width for one step | map.concurrency: <n> in that step |
| Serial execution for one step | map.concurrency: 1 |
| A different default for every workflow on this machine | akm config set workflow.defaultMapConcurrency <n> |
concurrency: 1 is a real, honored opt-out, not the absence of a value: an
authored 1 is kept distinct from an unset field, and it always beats the
config default. Set workflow.defaultMapConcurrency to 1 to make every map step serial by
default.
A step with no map: is one unit, not a fan-out. It is unaffected by any of
this.
The four limits
The width a step really runs at is the minimum of four independent values. Raising one never raises the others:
| Limit | Set by | Default when unset |
|---|---|---|
map.concurrency |
the step | workflow.defaultMapConcurrency, else 4 |
execution.maxConcurrency |
workflow.maxConcurrency config |
CPU-derived min(16, max(1, cores − 2)) |
| the selected connection's concurrency | connections.<name>.concurrency |
1 for a loopback endpoint, 4 for a remote one |
| the host CPU safety cap | nothing — reapplied at dispatch | min(16, max(1, cores − 2)) |
The connection limit is per endpoint kind on purpose. A local model server (LM
Studio, Ollama) has one loaded model, and concurrent inference makes it reload
and return HTTP 500 — a hard failure, so loopback endpoints stay at 1 and a
map against a local model is still effectively serial unless you raise
connections.<name>.concurrency yourself. Remote providers fail softly (a
retryable 429), and four concurrent completions is well inside any hosted
provider's entry tier. A harness carries no concurrency limit of its own.
What counts as a loopback endpoint
The whole loopback space, not one address:
| Recognized | Examples |
|---|---|
all of 127.0.0.0/8 |
http://127.0.0.1:1234, http://127.0.0.2:11434 |
localhost and any *.localhost name |
http://localhost:1234, http://lmstudio.localhost |
IPv6 ::1, in any spelling |
http://[::1]:1234, http://[0:0:0:0:0:0:0:1]:1234 |
| the unspecified addresses (a client connecting there reaches loopback) | http://0.0.0.0:11434, http://[::]:11434 |
127.0.0.2 matters in practice: running a second LM Studio or Ollama on
another address inside the 127.0.0.0/8 block is ordinary, and that server is
exactly as single-model as one on 127.0.0.1.
IPv4-mapped IPv6 is recognized for 127.0.0.0/8 in both spellings —
[::ffff:127.0.0.1] and the hex [::ffff:7f00:1] — because the URL parser
re-serializes the dotted form to the hex one before the check ever sees it. A
mapped public address such as [::ffff:8.8.8.8] still reads as remote. The
deprecated IPv4-compatible form [::127.0.0.1] is not recognized; if you use
it, set connections.<name>.concurrency: 1.
The check is purely syntactic — it never resolves a name. A frozen plan has
to come out the same on your laptop, on CI, and on a machine with no network at
all, and a DNS lookup would make the frozen width depend on what a resolver
happened to answer. So a name that resolves to loopback (a hosts-file alias,
host.docker.internal, an internal DNS record) is treated as remote; point
the connection's endpoint at the address itself, or set
connections.<name>.concurrency: 1 explicitly. In the other direction the classification is deliberately
conservative: an endpoint akm cannot parse at all is treated as loopback, since
freezing 4 for a config it does not understand is the failure worth avoiding.
The host cap is re-derived from the CURRENT machine at every dispatch, not frozen. A plan frozen on a 32-core CI box narrows itself when it resumes on a 4-core laptop.
Frozen widths
Every one of these numbers except the host cap is resolved once, when the run starts, and stored in the run's plan. Editing config, upgrading akm, or changing the defaults above never alters a run that is already in flight or being resumed — it keeps the widths it froze. The new defaults apply only to runs started after the upgrade.
Going back
"Go back and fix it" is a gate. A failed gate
re-runs its own step with the judge's feedback, bounded by gate.max_loops
— and a declared output: schema the promoted artifact fails is specifically
the error a gate loop retries through. A workflow that wants to "loop back to an
earlier step until this passes" expresses that as a bounded gate on the step
doing the work.
Failure policy
Fail-fast is the default. Per unit (or via defaults.on_error):
on_error: fail— the first failed unit fails the step, which fails the run (akm workflow resumere-opens it;akm runre-dispatches only incomplete units).on_error: continue— failures are recorded in the step's results and the completion gate decides whether the step passes.retry: { max: <n>, on: [<failure_reason>…] }— re-dispatches a failed unit up tomaxextra times when its recordedfailure_reasonis listed (e.g.timeout,llm_rate_limit,spawn_failed,non_zero_exit); every attempt is journaled separately. For an exec unit a non-zero exit isnon_zero_exit, a wall-clock expiry istimeout, and a failure to start isspawn_failed.
A unit's output schema is validated on every runner; a validation miss
re-dispatches once with corrective feedback before the unit is recorded as
failed. Exec units are the one exception: a fixed argv cannot answer feedback,
so a schema miss fails immediately rather than re-running a side-effecting
command (see The output rule).
Gates and verification
Gates judge the artifact; max_loops bounds the retry. Under
akm run, a step with a body ### gate rubric is gated on its
artifact, not on engine prose: the judge receives the step's artifact as
canonical JSON (clipped at 4000 characters) alongside the ### gate section
byte-exact, so the gate evaluates real results rather than a machine summary
like "Executed 3 units". Each engine-driven gate evaluation is itself an LLM
call and is journaled as its own unit row.
gate.max_loops: <n> (frontmatter) turns the gate into a bounded
evaluator-optimizer loop: on a rejection (or a typed-artifact schema
mismatch) with loop budget left, the engine re-executes the step's units
with the gate feedback and the missing-criteria list appended as attached
context. The feedback changes each unit's inputs, so the re-run naturally
dispatches fresh units instead of replaying journaled results. When the loop
budget is spent, the rejection stands exactly as in the one-shot case.
An exec step is judged, but never looped. A gate loop
earns its re-dispatch by handing the judge's feedback to a unit that can answer
it, and an exec unit cannot: its argv is frozen and never interpolated, and the
AKM_* context carries no feedback variable. A second loop would re-run the
byte-identical command — deploying, publishing, or migrating twice — for a
verdict that cannot change. So a step whose unit is exec: still has its
artifact judged and can still be failed by the verdict; a rejection simply lands
on the first evaluation, carrying the same missing criteria and feedback the
one-shot case does. gate.max_loops on such a step is capped at 1 rather than
rejected, and a model step's declared max_loops is untouched. This is the
same reasoning that makes an exec unit's output: schema miss fail without a
corrective re-dispatch.
Verification. With no non-empty ### gate rubric, no
verification runs. When a rubric is present, the workflow requires a
connection or a harness to judge it before the plan can be frozen: the judge
runs where model work runs (the default connection, else the default harness; see
Where each process runs) — see
Author's Guide: Troubleshooting
if neither is configured yet. That verifier invocation is frozen into the run.
Only a well-formed complete: true verdict advances a criteria-bearing step.
A missing verifier, dispatch failure, or malformed result rejects the gate. A well-formed complete: false verdict
returns its missing criteria and feedback and can trigger another bounded
max_loops attempt.
Budget ceilings
The top-level budget: key declares run-lifetime ceilings: max_units
(total dispatched units) and max_tokens (total reported token usage). Both
counters are seeded from the unit journal, so they measure the whole run
across resumes, not just the current invocation. Hitting a ceiling aborts
the step's still-pending dispatches and fails the step with a
budget exceeded (<which> ceiling) summary — budget exhaustion is a hard
stop that ignores on_error: continue. Because the plan is frozen, raising a
budget means starting a new run. Only units that run on akm's own runtime
report token usage; a unit on a harness or a direct model call reports none
and adds nothing to max_tokens.
Model references
Reference semantic aliases in model: fields instead of exact model ids so a
workflow stays portable across machines. The standard aliases are fast,
balanced and reasoning; each connection and harness says which of its models
answers them (connections.<name>.models, harnesses.<name>.models; Claude Code
ships a map of its own):
defaults: { model: balanced }
steps:
- id: review
unit:
model: reasoning
Resolution looks the alias up on the connection or harness the step runs on. A string that is not an alias is an exact model name and is used as written. An alias the connection does not map answers with that connection's first model; a harness with no model for it passes none and uses its own default. See Aliases for the full rules and the author's guide for which tier to pick per step.
See also
- Running Workflows — operating a run day to day
- Author's Guide: Writing Workflows — a task-oriented walkthrough
- Architecture: The Workflow Engine — persistence, dispatch, and resume internals
- CLI Reference — full flag documentation for
workflowandlint