---
name: ultracode
description: >
Execute one deliverable through a multi-agent workflow with explicit dependencies,
parallel investigations, bounded repair, and a complete result handoff. Use when
requested by the user or selected by multitask for dependent stages within one task.
userInvocable: true
argumentHint: "[task description or /ultracode]"
---
# Ultracode: Multi-Agent Workflow Orchestration
Use the **Workflow** tool through `ToolSearch` and `ToolInvoke`.
Main owns the business task and its current contract; the run owns its stage graph.
When multitask is active, a single-role task uses one fresh Agent and a task with
ordered multi-agent stages uses one Workflow. Do not nest a coordinator agent or
manually dispatch stages that the run already owns.
An explicit workflow request takes precedence even for a small task. If the tool is
unavailable, explain the concrete blocker before substituting another requested method.
Without that requirement, a simple task does not need a workflow. Do not add planning,
verification, or a summarizer just because those roles exist: use the task's actual
risk, unresolved design, and explicit acceptance requirements.
## Capability preflight
Read each target definition, including mandatory instructions and tool policy, before
writing a script. Use the available resource reader, such as `mcp_read_resource`, for
`agent://builtin/plan/agent.md`; discover the reader if it is not exposed. There is no
capability-query API. `available_agents` is a scheduling hint, not a tool list.
Omitted definition `tools` inherits; `tools: []` grants none; a list or `*` is an allowlist;
`disallowedTools` always removes tools. Workflow `allowedTools` can only narrow inherited
permissions. In the current workflow API, `allowedTools: []` means no additional narrowing,
unlike definition `tools: []`. Use a nonempty allowlist to restrict a stage.
| target | runs commands | why |
| --- | --- | --- |
| `coder` | yes | Inherits tools; excludes Agent |
| `explorer` | yes | Inherits tools; excludes Agent; role uses only read-only local and Web tools and returns evidence inline |
| `general-purpose` | yes | Inherits tools |
| `plan` | yes | Inherits tools; excludes Agent; brief remains read-only |
| `verification` | yes | Inherits tools; excludes Agent; do not modify the implementation |
This table describes shipped definitions, not the current parent's complete permissions.
It is checked against those definitions by `resources/builtin_skill_capability_test.rs`.
Runtime filtering can remove more tools. Record each brief's required tools against its
effective target. A command stage needs `Bash`; file inspection commonly needs `Read`
and `Grep`. Fail fast with one required-tool probe; a missing tool ends that stage.
Do not widen permissions or claim unrun checks succeeded.
Each assignment has one role and a fresh instance. Execution includes locating code,
local decisions, test code, and self-checks. Independent verification uses a fresh
verifier when risk or the user requires it. Planner and explorer are not implementers.
Assign a local, web or mixed read-only investigation to one explorer. Provide the question and the evidence needed. Use a command-capable execution stage for measurements or file delivery.
A pure investigation or acceptance-only request does not require implementation.
## Task, resource, and version boundaries
Keep independently deliverable business outcomes as separate tasks. The investigation,
implementation, combined acceptance, performance checks required for that implementation,
and its release notes normally remain stages of one deliverable. An independent benchmark
or training document may remain a separate task with explicit artifact dependencies.
Mechanical aggregation belongs in the script or Main, not an additional agent.
For a multi-part build, plan one independently checkable outcome per assignment.
Name its owner, entry points and writable paths, direct inputs and their versions,
local acceptance, and the evidence its consumer needs. Identify the first ready
packages. A phase is a progress label and may contain several packages. Keep
tightly coupled diagnosis, edits and local tests with one owner when handing them
off would require reconstructing the same investigation. Keep a small change small.
Start independent, resource-compatible work together. For similar packages with
local successors, use `pipeline(items, ...stages)`. For different dependency
chains, put each successor inside the branch that produces its input. Await all
branches together only where the consumer actually needs all their results.
Use the codemode `tool()` hook for repeatable collection, filtering and checks.
Bound scripted tool batches to the downstream resource limit; `maxConcurrency`
limits agents. Send only work that needs judgment to an agent. Keep a result
for every required input, including failures.
Before dispatching a consumer, match its input ID, exact expected revision and
artifact identity to the producer's evidence. At a batch join, require exactly
one matching result for every expected ID. Conflicting or duplicate verdicts
leave that item unresolved. Taking the first match can turn a failed check into
a pass. Keep valid siblings and block overall acceptance until every required
item has a current, unambiguous result.
Before launch, trace the generated script with one fast package and one still
building. The fast package's local check must already be callable. In particular,
`const builds = await parallel(allBuilds)` followed by any loop over `builds`
forces every check to wait for the slowest build. This holds for a local
`tool()` command as well as a verifier. Keep the build and its check inside the
same branch, or put them in successive stages of one per-item pipeline. A
dashboard's Build and Check labels describe progress. Only a consumer of all
outputs, such as the release decision, needs the final join. Compute a shared
frozen prerequisite once and pass its result into each branch.
Use new evidence to decide when to replan. Keep the existing owner for a live
reproduction or running check. If calls repeat without changing any evidence,
reuse the recorded result or change the approach. Hand back current artifacts,
checks, blockers and remaining work when the scope changes; replan only affected
packages. A tool-call count alone does not establish a useful split.
A shared worktree, index/HEAD, repository-wide baseline, mutable fixture, or port can
conflict even for different files. The `isolation` option does not currently prove that
a separate worktree/cwd was created. Serialize conflicting work unless actual isolation
is established. Keep independent read-only branches parallel when their inputs are stable.
A dependent write or acceptance stage waits for relevant writes to settle. Do not turn
an unsettled scope into a blanket pause: stable-input planning, contract preparation, and
independent tasks can continue. A retained preview needs a real owner-transfer receipt
and cleanup responsibility. A URL or a terminal agent message does not prove settlement.
Track the business task, goal revision, run_id, stage assignment, artifact version,
required evidence, resource owner, budget and stop conditions. Clarifications that do not
invalidate the current work update the contract without an automatic cancel/restart.
For a real goal change, cancel only affected execution and confirm it stopped before
fresh replacement. Old results cannot close the new goal. Repair new artifact versions
within budget while retaining valid upstream work; do not reopen finished agent threads.
On `scope-close-incomplete`, the host fences the entire affected Workflow run and
cancels its remaining assignments before allowing an engine retry to execute. It cannot
identify a smaller resource-conflict subgraph. Other runs and independent stable-input
work may continue. Do not restart the fenced run until its outstanding resources settle.
## Discover and launch
```
ToolSearch("workflow")
ToolInvoke({
"name": "Workflow",
"arguments": {
"script": "...workflow script...",
"args": {},
"maxConcurrency": 3,
"writeIntent": { "kind": "read_only" }
}
})
```
Declare the actual `writeIntent`; a writing workflow must use the write form with the
real `repo_root`, `cwd`, and `path_allowlist`. Do not claim read_only to bypass the post-condition.
Inspect the exposed tool schema for current parameters and limits. A missing intent or
baseline can leave an otherwise completed run blocked. Limits are enforced by the host;
do not increase them silently after a failure.
The tool returns a run_id asynchronously. Bind it to the task immediately. A launch
acknowledgment is not completion. After a timeout or compaction, reconcile the current
run from available bindings/results; do not assume absence from a lookup means it never
started. Do not launch duplicate work or resume an old worker to query its status.
## Script API
Scripts use the engine's ESM-like format with `export const meta = { name, description }`
and a top-level `return`. Both metadata fields are required.
- `agent(prompt, options?)` runs a fresh assignment and returns its output. Options include
agentType, allowedTools, label, model, schema, maxTokens, isolation, and phase.
- `parallel([...factories])` accepts zero-argument factories such as `() => agent(...)`,
not already-started promises. Check every required branch before using its result.
- `pipeline(items, ...stages)` calls each stage as `(prev, item, index)` for each item;
its return becomes the next stage's prev. Failed entries can be null.
- `phase(title)` marks subsequent agents; it does not take a callback and returns undefined.
- `log(message)` emits progress. Never log credentials.
- `workflow(nameOrScriptPath, args?)` invokes a child workflow, with a one-level nesting limit.
Use it only for a reusable workflow boundary, not another coordinator around ordinary stages.
Required outputs that are null, missing, failed, blocked, or inconsistent with the current
artifact must not feed a dependent stage or be reported as success. The engine can return
null for dead/skipped agents and failed parallel branches; process exit/completed alone is
not business acceptance. Preserve a concrete blocker and available evidence.
### Build example
A single independently acceptable change needs one coder brief with its local
check. For a larger deliverable, pass one self-contained brief per package. This
example assumes nonempty packages with unique IDs, stable input revisions and
exclusive output paths. Each brief names its entry points, write scope and local
checks. Set `independentCheck` only when the acceptance or risk calls for it.
```javascript
export const meta = { name: 'build-packages', description: 'Build and check ready packages' }
async function runPackage(role, pkg, brief) {
const raw = await agent(
`${brief}\nAcceptance: ${pkg.acceptance}\nTarget: ${pkg.id} at ${pkg.revision}, output ${pkg.artifact}.\n` +
'Return JSON with id, revision, artifact, status (passed or blocked), evidence (references to actual checks), and reason if blocked.',
{ agentType: role, label: `${role}/${pkg.id}` }
)
let receipt = raw
if (typeof raw === 'string') {
try { receipt = JSON.parse(raw) } catch { receipt = null }
}
if (receipt?.id === pkg.id && receipt.revision === pkg.revision &&
receipt.artifact === pkg.artifact && receipt.status === 'passed' &&
Array.isArray(receipt.evidence) && receipt.evidence.some(ref => typeof ref === 'string' && ref.trim())) {
return receipt
}
return { id: pkg.id, status: 'blocked', reason: receipt?.reason || 'Missing current acceptance evidence' }
}
phase('Build')
const packages = args.packages
if (!Array.isArray(packages) || !packages.length) throw new Error('Expected at least one build package')
if (new Set(packages.map(pkg => pkg.id)).size !== packages.length) {
throw new Error('Expected unique package IDs')
}
const rows = await pipeline(packages,
pkg => runPackage('coder', pkg, pkg.brief),
async (build, pkg) => {
if (build?.status !== 'passed' || !pkg.independentCheck) return build
const verdict = await runPackage('verification', pkg,
`Independently check the delivered artifact. Build evidence: ${JSON.stringify(build)}`)
return { ...verdict, build }
}
)
const results = packages.map((pkg, i) =>
rows[i] ?? { id: pkg.id, status: 'blocked', reason: 'No usable branch result' })
return {
taskId: args.taskId, goalRevision: args.goalRevision,
status: results.every(r => r.status === 'passed') ? 'passed' : 'blocked', results
}
```
Match receipts against the original acceptance and the actual artifact before
delivery. A worker's reported local checks are self-checks. The verification
assignment supplies independent evidence only for the package it inspected.
### Validate a saved script
For an existing nontrivial script, validate with the pinned CLI version:
```bash
npx -y @peri-code/workflow@0.3.0 validate scripts/task.mjs --json
```
The explicit version prevents reuse of an incompatible globally installed binary.
Do not create a file just to validate a small inline script. Avoid `Date.now()`,
`new Date()`, random values, and other nondeterministic globals in scripts; inject
needed external values through args. Follow the actual engine restrictions.
## Formal handoff and one completion summary
Workflow agents receive a host handoff instruction: put the final assignment output
in an entire assistant message enclosed in `` and ``.
The host selects the latest complete block, so later cleanup-only text does not replace
it. A corrected result needs a new complete block. With a schema, the block body must be
valid JSON without fences. Legacy unmarked output falls back to the last nonempty
assistant message. The marker identifies output; it does not certify acceptance.
The workflow script owns the final deliverable. Return a concise summary with actual
status, task/goal/artifact identities, evidence, verification basis, blockers and next
steps. Aggregate existing results without spawning an agent just to rephrase them.
Keep execution, business acceptance, resource settlement and external delivery separate.
If a required external delivery is only accepted/pending, verify its actual outcome;
retry a known retryable failure with the original message identity rather than rerunning work.
Completion notifications include a bounded reported-result preview (up to 8192 UTF-8
bytes before envelope escaping), with safe external references expanded when available.
Use a complete preview directly when it contains the necessary evidence. A partial
preview is not a complete result and may not be valid JSON. Read the saved aggregate
report for missing details, without restarting agents or polling unchanged state.
Engine acceptance `unknown` is expected unless an external acceptance layer supplies a
verdict; it does not itself require another verifier. Blocked delivery still needs its
specific reason even if execution completed.
Full results remain under `.claude/workflow-runs//`. Object string fields over
200 bytes are stored as `${label}` references to `outputs/