# ultra workflow spec — canonical reference A workflow is a single JSON object. `parseWorkflow` (the same validator the runtime uses) checks it structurally and rejects anything malformed. This file is the authoritative format reference; the extension `README.md` links here rather than restating it. ## Top-level fields | Field | Required | Type | Meaning | | ------------- | -------- | --------------------------- | -------------------------------------------------------------- | | `name` | yes | string (non-empty) | Workflow id. The file is invoked as `/ultra run `. | | `description` | no | string | One line shown in the picker. | | `args` | no | object (`{ hint?, ... }`) | Declares run inputs; `hint` is the usage shown after the name. | | `schemas` | no | record | Named, reusable output schemas referenced by steps. | | `phases` | yes | array (≥1) of phases | The ordered stages. Each is `single` or `fanout`. | | `return` | no | string (one selector token) | Selects the workflow's final value from phase results. | `args` may also declare `params`: an ordered list of input names. A bare `/ultra run tokA tokB` maps tokens onto them positionally; the last declared parameter absorbs all remaining tokens so it can carry free text. Values are exposed as `{args.NAME}`. Without `params`, pass inputs as a trailing JSON object: `/ultra run {"k": "v"}`. A missing `{args.NAME}` renders to the empty string. ## Phases A phase has an `id` (referenced by interpolation and `return`), a `kind`, a `step`, an optional `concurrency` cap, an optional `when` selector, and optional fan-out `writeIsolation`. Phase IDs must be unique identifiers matching `[A-Za-z_][A-Za-z0-9_]*`; the reserved phase ID `args` is forbidden because it belongs to the workflow-input namespace. - **`single`** — runs the step exactly once, for one synthesis / judge / aggregation pass over prior results. (`over` is accepted by the schema but **ignored** in v1; for per-item parallelism use `fanout`.) - **`fanout`** — runs the step once per element of `over`, concurrently (capped by `concurrency` and the engine's global pool). `over` is **required**. `when` uses the existing single-selector grammar. If it resolves to `false`, `null`, `undefined`, an empty string, or an empty array, the phase is skipped and records `{ ran: 0, ok: 0, dropped: 0 }` with empty results. Any other value runs the phase. A skipped phase may still be referenced later through empty `{PHASE.results}` and `{PHASE.failures}` arrays. There are no loops or arbitrary expressions. `over` is either a literal array or a single interpolation token string (e.g. `"{review.results[].findings[]}"`). ### Fan-out mutation ownership Without `writeIsolation`, a `fanout` step's initial tools must stay within Pi's core set: `read`, `grep`, `find`, `ls`, `bash`. The prompt must instruct the agent not to mutate anything. With `writeIsolation`, mutating tools are allowed and the non-empty rationale plus prompt must assign disjoint ownership to every item. Ultra trusts that declaration; it does not constrain paths or arbitrary custom mutators. Loaded extensions remain trusted to activate additional tools. Every listed tool must be available to sub-agents or Ultra refuses to start the workflow. ## Steps | Field | Required | Type | Meaning | | --------------- | -------- | --------------------- | ------------------------------------------------------------------------------------------------- | | `summary` | yes | string | One short progress-UI sentence describing the task; interpolates `{...}` tokens. | | `prompt` | yes | string | The exact agent instruction; interpolates `{...}` tokens (see below). | | `tools` | no | string[] | Initial tool set. Omit when the agent needs only the injected result-submission tool. | | `model` | no | string | `provider/id` override, or configured tier `small`/`medium`/`big`; defaults to the session model. | | `thinkingLevel` | no | off…max | Reasoning budget for this step. | | `dynamicExtensions` | no | string[] \| selector | Stable catalog names, or one selector resolving to names, loaded in declared order. | | `schema` | no | string \| JSON Schema | A `schemas` name, or an inline schema that validates structured output. | `summary` is rendered on tool and overlay agent rows. Keep it concise and concrete; use the same interpolation grammar as `prompt` so fan-out rows can identify their item. The overlay separately shows the exact resolved `prompt` as the first user message in that agent's transcript. Every step returns a JSON object through the terminating `structured_output` tool. Ultra requests provider-side strict schema sampling when supported and always validates the submitted object locally. When an agent stops without submitting, Ultra sends up to `ultra.maxRetries` focused reminders in the same session. Without `schema`, any JSON object is accepted. A `schema` validates that object and is required when downstream phases depend on a stable shape. A string `schema` is a **name reference** and must resolve in the spec's `schemas` map, or validation fails. Configured model tiers live in Pi settings under `ultra.modelTiers`. If a step sets `model` to `small`, `medium`, or `big`, ultra resolves it through that map; an unset tier falls back to the session model. Tier values may include a thinking suffix like `openai/gpt-5-mini:low`, used only when the step omits `thinkingLevel`. ### Dynamic extensions and builders `dynamicExtensions` names stable catalog identities, never hashes. Immediately before child creation, Ultra resolves each name to one validated hash and a run-local source snapshot; name and hash participate in the checkpoint key. Normal configured extensions load first, then dynamic extensions in declared order. `subagentExtensions: "none"` suppresses normal extensions only. Generated tools activate during `session_start`. Dynamic extensions may declare exact qualified normal-registration overrides, but Ultra's workflow and builder tool names remain reserved. A builder step selects all four tools or none: `search_dynamic_extensions`, `create_dynamic_extension`, `checkout_dynamic_extension`, and `validate_dynamic_extension`. Builders receive every available child tool except `run_workflow` plus a versioned authoring contract. A builder failure blocks every later phase with typed `u008_builder_failure_blocker` outcomes; no normal-tool fallback exists. Known canonical names may load directly, but discovery, creation, improvement, stale validation, and repair require a builder. ### Model tier and thinking rubric Set both `model` and `thinkingLevel` on every authored step. Choose them from the work that step performs, not by copying another phase: | Work | Tier | | ---------------------------------------------------------- | -------- | | Planning, specification, architecture, critique, synthesis | `big` | | Coding, testing, editing, routine implementation | `medium` | | Scouting, extraction, classification, easy text work | `small` | Choose `big` models that gather context and knowledge. Choose `medium` models when context and knowledge has already been gathered in previous steps. Choose thinking independently from the tier and relative to that step's difficulty: - `off` / `minimal` — deterministic extraction, transcription, or formatting with negligible ambiguity. - `low` / `medium` — routine decisions with bounded context and cheap mistakes and when context has been prepared beforehand. - `high` / `xhigh` / `max` — ambiguous, multi-constraint reasoning where a wrong decision is costly downstream. `max` is the highest opt-in budget and requires model support. If every phase has the same model/thinking pair, re-evaluate each assignment before saving. Uniform settings are valid only when the phases genuinely perform equally difficult work of the same kind. Examples: - Repository inventory: `medium` + `low`. - Implement a well-specified edit: `big` + `medium`. - Design architecture from conflicting requirements: `big` + `high`. - Adversarially critique a risky plan: `big` + `xhigh`. ## Interpolation grammar A closed mini-syntax — not an expression evaluator, no `eval`. Tokens (braces are literal here, shown without JSON quoting): ```text {args.NAME} workflow input value {item} current fanout item (string verbatim; else compact JSON) {PHASE.results} a prior phase's results array (nulls retained positionally) {PHASE.failures} a prior phase's typed failure array {PHASE.results[].FIELD[]} flatten: concat each result's FIELD array (nulls/missing skipped) {EXPR | where FIELD} keep elements whose boolean FIELD is truthy ``` Anything outside this grammar raises a validation error at run time. In a step `prompt`, the only literal braces allowed are these tokens — do not put raw `{`/`}` (e.g. an inline JSON example) in a prompt; describe the shape in words and use a `schema` instead. ### Explicit linear recovery A dropped step appears in `{PHASE.failures}` with `agentId`, `index`, optional original `item`, `code`, `message`, `retryable`, `attempts`, optional `model`, optional `thinkingLevel`, optional accumulated `usage`, and an optional 2,000-character `transcriptTail`. Failure codes are `auth`, `transport`, `schema`, `missing-output`, `aborted`, or `session`. Use the non-empty failure array to condition and fan out one later recovery phase: ```json { "id": "recover", "kind": "fanout", "when": "{work.failures}", "over": "{work.failures}", "step": { "summary": "Recover failed task {item}", "prompt": "Recover this failed task and return the required result. Failure: {item}", "model": "big", "thinkingLevel": "high" } } ``` Ultra has no timeout, automatic rerun, loop, or back-edge. `ultra.maxRetries` sends result-submission reminders only after an agent turn ends without output; it never reruns the work in a fresh session. Workflow authors explicitly place any recovery phase after the failed phase. ### Schema join-keys When one phase fans out over another's findings, give the producer schema and the consumer schema a shared field (a "join key") and instruct the consumer to echo it. In the worked example below, `Findings.file` is echoed into `Verdict.file`, so each verdict ties back to the finding it judges. ## Worked example — minimal single fan-out Every `fanout` agent reads one path and returns a structured summary. Tools are read-only; the prompt forbids mutation. ```json { "name": "summarize-paths", "description": "Summarize each input path in parallel.", "args": { "hint": "" }, "phases": [ { "id": "summarize", "kind": "fanout", "over": "{args.paths}", "step": { "summary": "Summarize {item}", "prompt": "Read the file at {item} and return JSON with two string fields: path (the file path you were given) and summary (one sentence). Do not modify anything.", "tools": ["read"], "model": "small", "thinkingLevel": "low", "schema": { "type": "object", "properties": { "path": { "type": "string" }, "summary": { "type": "string" } }, "required": ["path", "summary"] } } } ], "return": "{summarize.results}" } ``` ## Worked example — two phases with a join key Fan out a review across dimensions, then fan out verification over the flattened findings. `Findings.file` → `Verdict.file` is the join key; `return` filters to the verdicts the verifier judged `real`. The single `params` entry lets a bare `/ultra run review main` maps `main` to `{args.base}` (a missing arg renders empty, so the diff falls back to the working tree). ```json { "name": "review", "description": "Review the diff across dimensions, then adversarially verify each finding.", "args": { "hint": "[base-ref]", "params": ["base"] }, "schemas": { "Findings": { "type": "object", "properties": { "findings": { "type": "array", "items": { "type": "object", "properties": { "title": { "type": "string" }, "file": { "type": "string" }, "detail": { "type": "string" } }, "required": ["title", "file"] } } }, "required": ["findings"] }, "Verdict": { "type": "object", "properties": { "title": { "type": "string" }, "real": { "type": "boolean" }, "why": { "type": "string" }, "file": { "type": "string", "description": "echo of the reviewed finding's file, for correlation" } }, "required": ["title", "real", "file"] } }, "phases": [ { "id": "review", "kind": "fanout", "over": ["correctness", "security", "performance"], "step": { "summary": "Review diff for {item} issues", "prompt": "Review the diff for {item} issues. Inspect it with `git diff {args.base}` (no base ref → the working tree; a base ref → everything since that ref), plus read/grep as needed; do not modify any files. Return JSON matching the Findings schema, and set each finding's file to the path it concerns.", "tools": ["read", "bash", "grep", "find", "ls"], "model": "small", "thinkingLevel": "medium", "schema": "Findings" } }, { "id": "verify", "kind": "fanout", "over": "{review.results[].findings[]}", "step": { "summary": "Verify one candidate finding", "prompt": "Adversarially try to refute this finding. Default to real=false if uncertain. Echo the finding's file verbatim in your verdict's file field so the verdict ties back to its finding. Finding: {item}", "model": "big", "thinkingLevel": "high", "schema": "Verdict" } } ], "return": "{verify.results | where real}" } ``` ## Where workflows live Discovery merges three locations, lowest-to-highest precedence — a later source overrides a bundled name: 1. **bundled** — `/workflows/*.json` (ships with ultra) 2. **global** — `~/.pi/agent/workflows/*.json` 3. **project** — `/.pi/workflows/*.json` Save an authored workflow as `.json` (filename should match the spec's `name`) in the project dir for repo-scoped workflows, or the global dir for personal ones.