---
name: help-how-to-workflow
description: Author and maintain Po workflow graphs, validate commands and artifacts, and scaffold definitions in Help mode.
---

# Workflow authoring and maintenance

`@agimon-ai/po-workflow` owns persisted YAML execution and the `workflow` and `dynamicWorkflow` code-mode namespaces. Select the workflow layer in presets.yaml. There is no workflow mode. Load `codemode-how-to-workflow` for launching, monitoring and recovery.

In Help mode, use `workflowAdmin.scaffold` in `exec` to create a YAML skeleton (main agent only). Choose an explicit skeleton with `preset`; omitting it preserves the existing `dag` skeleton. Existing files require `force: true`, which asks the person's approval before overwriting. Where the session has stored sets (Po Cloud's `org` and `personal`, or a self-hosted Worker's `host`), pass `source` with a plain file name to create the skeleton there instead of in the repository; stored workflows cannot use imports or relative tools and instructions paths. Scaffolding writes a definition, it does not launch agents or run commands. Review and customize the generated file before running it.

## Choose a workflow type

| Preset           | Use when                                                                                         | Completion authority                                                            |
| ---------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
| `dag`            | Jobs and their dependencies are known before launch.                                             | Job/step outcomes and declared artifacts.                                       |
| `child-review`   | One producer owns the work and repairs, while independent child jobs attest acceptance criteria. | Current immutable artifact checks from the authorized child verifiers.          |
| `dynamic-fanout` | A step discovers a bounded item list at runtime and needs tracked per-item work.                 | The enclosing step's outcome and persisted results, not independent acceptance. |

Call `workflowAdmin.scaffold` with one of these inputs. It uses the effective `workflows` set from Settings > Templates. If the set is off, scaffolding is unavailable.

```ts
await workflowAdmin.scaffold({ path: 'automations/check.workflow.yaml' });
await workflowAdmin.scaffold({ path: 'automations/produce.workflow.yaml', preset: 'child-review' });
await workflowAdmin.scaffold({ path: 'automations/items.workflow.yaml', preset: 'dynamic-fanout' });
```

Do not turn independent acceptance into ordinary Team fan-out: a producer's summary of another agent's opinion is not an authorized criterion report. Conversely, use the simpler `dag` or `dynamic-fanout` contract when independent attestation is not required. Managed agent skeletons require the Po server; they are not shell/CLI-only workflows. Replace the example brief and set `runConfig.preset` to an existing preset with the workflow layer. A `dynamic-fanout` skeleton also needs Team in that preset. Pin available models under the producer/reviewer job `runConfig` when the task requires distinct models, never invent model IDs.

## Author Po workflows

Create a `*.workflow.yml` file and keep its graph explicit:

```yaml
name: verify

jobs:
  test:
    steps:
      - name: Run tests
        run: pnpm test

  summarize:
    needs: test
    steps:
      - name: Record result
        run: node scripts/write-verification-summary.mjs
```

`needs` expresses job ordering. Keep steps small enough that failure evidence identifies the command that needs attention. Use runner-specific `interactiveRun` configuration when a command genuinely requires a TTY.

For an agent step, declare the command once under `commands` (usually in an imported file) and let the step name it. A command is a Liquid template; `inProcess: true` lets the Po server run it as a child session instead of spawning a shell command:

```yaml
imports: [commands.yml]
choices:
  default: { model: openai-codex/gpt-6-sol, thinking: medium }
jobs:
  develop:
    steps:
      - name: Develop
        runConfig: { preset: dev, domains: [engineering] }
        systemPrompt: ${{ env.JOB_SYSTEM_PROMPT }}
        prompt: ${{ env.WORKFLOW_CONTEXT }}
        interactiveRun: [{ command: po }, { command: terminal }]
```

`po` and `terminal` are the commands `commands.yml` declares; a step can only name a declared command. `runConfig` takes `preset`, `modes`, `profile`, `domains`, `model`, and `thinking`, plus any key the template reads; any other key fails the step, so a typo such as `prest` never runs on workspace defaults. `choices` compose model and thinking, with per-command overrides such as `terminal: { model: openai-codex/gpt-6-luna }`; a step can pin `choice:`, and a launch picks `command=` and `choice=` for the rest. Templates must quote prompts with `{{ prompt | shell }}`.

A command that only the Po server should run, such as `po: { inProcess: true }`, leaves out `run`. Hosts without an in-process agent runner reject it instead of starting an agent outside Po.

After scaffolding and before launch, use `workflow.validate({ workflowPath, inputs, env, command, choice, runner, profile, job })` in code mode with the intended launch settings. Omit optional settings you do not need. Read diagnostic codes, locations and corrective messages; fix errors, then revalidate after edits. This checks the imported/extended graph and actual command binding resolution, not just the YAML schema. It checks required/default inputs and declared options/types, missing injected references, command/choice settings, effective runConfig and interpolation phases. Workflow env and runConfig values are literal where execution leaves them literal; a prompt cannot read a step-only env override that is installed later.

Read the separate `deferred` entries too. Run identities, assembled job prompts, child invocation inputs and conditional context files are not fabricated during validation. Preset/model/profile admission, authentication, shell behavior and produced artifacts still need runtime verification. `valid: true` means no errors detected by the available checks, not guaranteed successful execution. Reports/cards omit binding values; validation does not load secret files or execute steps. Secret availability may remain deferred.

Without code mode, use `workflow_tools { action: 'validate', ... }` for the same diagnostics. Fix every error validation reports; the Po server refuses to launch a definition with errors.

An agent step ends by recording its outcome with the native workflow tools: `workflow.complete({ summary })`, `workflow.fix({ restartFrom, reason })` or `workflow.fail({ reason })` in code mode, or `workflow_step_complete`, `workflow_step_fix` and `workflow_step_fail` as direct tools. `workflow.context()` shows the step and what it recorded. The engine binds these tools to the step's own session, puts the instructions in its system prompt, and sends an agent that stops without deciding back until it does. Write repair contracts in those terms, not as `fix.md`.

What a step or job must leave is held the same way. A step's `artifacts` must be written during the step. A job must be the last to have written each run-directory entry it produces (`produced-by`): an entry an earlier job wrote must be written again, while a retry or a job that skips work it already did keeps its own output, and removing a file counts. Each write is sealed as an immutable version in the run database, recording which job and step wrote it; its bytes stay under `.workflow/versions` in the run directory. An agent step that ends its job is sent back until those entries are written, and the job fails when one was not. List a job under `produced-by` only when it writes the entry in every run. Write a `description` for every entry: the reminder tells the agent what the file holds from it.

Put independent checks in a `parallel` group. A `run:` check with `restart-from: <job>` turns a failure into a fix request, and every fix request of the job merges into one repair, so one loop back fixes all of them. Keep steps that edit files out of a group: its steps share the checkout.

Every `run` command executes on the workflow host with that process's environment and privileges. There is no VM, container, or sandbox. Review workflow changes as executable code, avoid embedding secrets, and make retry-sensitive external side effects explicit.

Before relying on the graph, discover it with `workflow.list`, validate the exact intended settings with `workflow.validate`, then launch an authorized disposable run with `workflow.launch` and inspect job/step status with `workflow.status`. Test a failure path when recovery behavior matters. Validation alone is not runtime acceptance.

## Fix, steer, or rewind a run in Help mode

A run executes its saved definition by default. Roleless runs launched from this checkout adopt an edited YAML once on `workflow.recover` even outside Help mode; live reloads, role-bound runs, handed-off runs, budget resets, live steering, and job rewinds require Help mode.

- **Adopt YAML edits:** Edit the YAML, run `workflow.validate`, then `workflow.recover`. If a later job reports `"No authoritative accepted criteria ledger exists for this job."`, inspect with `workflow.inspectRun` and run `workflow.helpRepair({ runKey, workspace, stage: 'error', revision, reason, recomputeRevision: true })`, then recover again and verify with `workflow.status`. Pass `fixLoopCycle` or `continuations: { <lead job>: <spent count> }` to the same `helpRepair` call to lower spent budgets.
- **Rewind to a chosen job:** Call `workflow.recover({ runKey, workspace?, expectedRunId?, restartFrom: '<job>' })` (or `workflow_tools { action: 'recover', restartFrom }`). Refused outside Help mode, on pinned durable hosts, on parked runs, when `activeRepair` is active, or for unknown jobs. From the 4th recovery, the approval card displays `Restart from`.
- **Steer a live agent step:** Call `workflow.steer({ runKey, workspace?, expectedRunId, step?, message })` (or `workflow_run { action: 'steer', ... }`). Main-agent owner only, running runs only, agent-session steps only, and refused on identity- or secret-bound runs (`admission`, `allocation`, `identities`, `profile`, `secretFile`). Delivered text is prefixed with `[Guidance from owner agent (Help mode)] `. Use `workflow.inspectStep` before and after to observe progress.

## Author one producer with independent child reviews

Start with `preset: child-review`. Keep exactly one main job under `jobs` when one producer is required. Define reusable reviewers separately under top-level `child-jobs`, not as root jobs connected with `needs`.

1. Declare the deliverable as a file under `run-directory.entries`, with a description and `produced-by: [producer]`. The producer's managed step declares that file in `artifacts` and writes it in `WORKFLOW_RUN_DIR`.
2. The producer's `children` lists allowed child definition names. Its `acceptance-criteria` maps stable criterion keys to descriptions, `verified-by` child names and explicit `artifacts` paths. Do not let assignment text, launch inputs or a producer-generated PASS file define acceptance authority.
3. The producer explicitly calls `workflow.spawnChild({ job, prompt })` after preparing evidence. Children are not scheduled automatically, and `children` is not a fixed chain. If `inputs` are needed, declare their primitive types/requirements on the child before passing them in the spawn call. Jobs execute from the runtime root; definition-relative imports/tools and step `working-directory` have separate meanings.
4. Each reviewer calls `workflow.reviewArtifacts()` and assesses the immutable snapshot for only its authorized keys. It calls `workflow.reportCriteria({ results: { accurate: { status: 'checked', feedback: 'Evidence verified...' } } })` or reports `not-met` with concrete findings. It must not rewrite the producer's evidence or certify the producer's assertions. Reports commit only after successful child settlement.
5. The producer inspects `workflow.children()` and `workflow.childStatus({ invocationId })`, makes repairs itself, and requests fresh checks after changing reviewed artifacts. Do not edit shared evidence while children are reviewing it. All children must settle and all criteria must be checked against current bytes before completion.

Explicit criterion artifacts keep unrelated files from invalidating a review. For media, a text snapshot containing a filename does not attest the MP4, image or audio bytes: include immutable manifests/hashes, have reviewers verify the referenced files, and inspect the actual rendered/audio evidence. Distinguish source checks, deterministic measurements, rendered inspection and listening. Never claim a kind of review that was not performed.

`completion.max-continuations: 3` permits three additional settled attempts in the same lead session after its initial attempt, not three total attempts or a fresh root-job retry budget. Child waits consume the lead step's timeout, not continuation prompts. A child job counts its own failures: `max-failures` on the child (default 3) failed invocations in a row fail the lead with the last error; a recovery starts the count again. `not-met` is successful review feedback; execution/auth/environment failures are failures, not editorial verdicts. Exhaustion fails with outstanding criteria. A person's stop stays stopped. Load `codemode-how-to-workflow` for role-scoped methods, settlement and restart behavior.

An agent step that runs again in the same run directory (a re-spawned child, a fix-loop replay, a retry or a recovery) continues its previous conversation by default. Set `session: fresh` on a job, or a child job, whose agents must start clean each time, for example when an earlier conversation would bias a fresh review.

## Job-specific tools

Use a workflow-owned tools folder when a managed Po agent step needs task-specific methods. Reuse
code mode, not a new direct tool or external CLI bridge:

```yaml
tools: ./tools/shared
runConfig: { preset: copilot }
jobs:
  summarize:
    tools: ./tools/report
    steps:
      - name: Summarize
        customRun:
          prompt: Read workflow-job-tools, discover jobTools, then summarize this job.
```

Workflow `tools` is the default. A job override applies to its main steps, `preJob` and `postJob`;
repair triage uses `repair.tools` or the default. Global phases use the default. Paths resolve against
the declaring YAML before imports and template inheritance, never step `cwd` or environment values.
Each session uses its captured config.
Parsing, listing and inspection do not execute the tools module.

The folder must contain `index.mjs` and non-empty `SKILL.md`. Default-export a factory receiving
`{ sessionId, cwd, workflow, fs, shell, signal, context }`, where `workflow` is the trusted workflow
context and `context` is the call context `fs` and `shell` methods take (aborted with `signal`).
Return a `PoCodemodeNamespace` named `jobTools`, with a one-line `summary`, TypeScript `declarations`
and `bind(run)` returning flat named async methods with JSON arguments and results. Keep per-session
state inside the factory, validate method inputs, honour `run.signal`, pass `run.context` to `fs` and
`shell` calls made from a method so they stop with the exec, and register exec-owned cleanup
with `run.onDispose`. Optional approval policies must name returned methods and use the existing
code-mode approval flow. Put judgement, ordering and effect rules in the skill, not signatures.
The package README's **Job-specific tools** section has a runnable module and skill example.

Only managed Po `customRun` and in-process `interactiveRun` sessions receive the namespace and pinned
`workflow-job-tools` skill. Ordinary sessions, shell steps and external Claude/Codex runners do not.
These modules are trusted host code, not sandboxed code or directly loaded TypeScript. Native import
caches by file URL: restart the host after same-path module edits; there is no hot reload.

An authorized downstream consumer's trusted factory can receive `acceptedArtifacts({ job })`, which rechecks the runtime ledger and current revision and returns immutable bytes; fail closed when absent or stale. Inside `bind(run)`, use `run.runJson({ command, args, input? })` for shell-free argv plus JSON stdin/stdout (15s timeout, cancels with exec/session, returns `{ exitCode, output, stderr }`). Never interpolate input JSON into shell commands or treat PASS files / env flags as acceptance authority.

Verify a disposable managed step can read the skill, `discover({ namespace: 'jobTools' })`, and call
its methods through `exec`. Check invalid input and cancellation before relying on effects. Missing
files or malformed selected tools fail the managed session before its first prompt. Namespace and
skill dispose together without stopping the owning workflow or changing recovery ownership. Load
`codemode-how-to-workflow` for agent-side usage and safety rules.

## Step instructions

Top-level `instructions: ./AGENTS.md` gives the workflow's managed Po agent steps their own instructions
file in place of the AGENTS.md files they would discover from their working directory. It resolves and
inherits through imports like `tools`; the importing workflow's own value wins. A missing or unreadable
file fails the step session before its first prompt. Shell steps and external CLI runners ignore it.

## Dynamic fan-out inside a step

Start with `preset: dynamic-fanout` when one step needs work whose shape is only known at runtime (one agent per file, finding or page). Keep the YAML graph fixed and let a `customRun` step's agent run a `dynamicWorkflow` script through `exec({ code, background: true })`. The generated prompt includes a runnable `createStep` / committed item workflow / `.foreach(item, { concurrency: 3 })` example. Replace its sample items and read-only task with the real discovered list before running. The step session has code mode in every preset; child agents (`team.run`) need the Team layer in the step's `runConfig.preset`.

Keep concurrency bounded and inspect every child's terminal status. A failed child must not become a success just because its error was returned as data. The runs appear under that step in Activity, but the YAML step still settles on its agent and declared artifacts: persist actual outcomes to the generated `results.md`, not just an exec return value. Item findings do not attest managed acceptance criteria.

Create and commit nested workflows within the same exec binding. Use the supplied `z` (Zod 3 API), `createStep` and `createWorkflow`, not raw package imports. Supported composition: `.then(step)`, `.parallel([step, ...])`, `.branch([[predicate, step], ...])`, and `.foreach(committedItemWorkflow, { concurrency: positiveInteger })`. Unsupported: bare-step foreach, dynamic concurrency callbacks, raw Mastra instances, custom engines/storage, streams, Mastra suspend/resume, time travel, workflow retries, `startAsync`, or private methods. Return `null` (not `undefined`) when a step intentionally has no output; successful step outputs must be JSON-serializable for replay. On cloud (QuickJS guest), callbacks/schemas never cross the JSON membrane, child `team.run`/`dynamicWorkflow.agent` links to a phase only when one phase is running, and resuming submits the saved source in the armed binding rather than using `import()`. Code outside steps runs again on replay, and a step interrupted mid-effect is refused until `resume(recordId, { retryUncertain: true })` acknowledges it. Prefer read-only item tasks and make any required writes idempotent.

## Native execution contract

Agent steps require an effective `runConfig.preset`; delegated workflows require top-level `runConfig.preset` before their owner child is created. Selection projects preset, modes, profile and domains, without adding a workflow mode. `subagentModel` and `subagentThinking` set Team preferences independently of the step model.

The host inspects execution state before creating agent steps and waits for idle with no pending messages or active holds before checking step decisions. Unknown ownership waits closed without consuming reminders; stops interrupt reads and retry delays.

An approved call still in flight keeps its step waiting. While any approval is undecided, a step cannot record `complete` or `fix`. A regular job step left idle with only undecided approvals parks its run (`wait` in `run.json`), releases the step session, skips `post:`, and waits for a decision instead of restarting on boot. Lead, child, `pre:`, and `post:` steps keep their live session open until the person decides; a recorded fail, Stop, error, or timeout withdraws undecided requests. When the person approves or denies a parked step's request, the owner session resumes the parked run automatically (strict recovery, Help off). A finished step withdraws any undecided requests its session left open.

A delegated success is informational in the workflow owner and wakes the launcher to continue its playbook. Errors wake the workflow owner through durable message admission; the launcher receives an error notification rather than a competing recovery turn. A parked run posts a waiting notice (never an error or completion notice) and exposes `waitingEntries` (`[{ stepName, approvalId, title? }]`) in `workflow.status` and `workflow.inspectRun`. A Po restart or session release resumes interrupted runs automatically, re-running the interrupted job while keeping earlier jobs finished. A person's stop never resumes automatically, a person-paused run stays interrupted, and a parked run waits for the person's decision. User-requested stops do not trigger diagnosis or automatic restart.

## Proposal contract

Before applying or proposing a Help-mode change (YAML edits, `repairRun`, `helpRepair`, `recover({ restartFrom })`, `workflow.steer`, `workflowAdmin.set`, or `workflowAdmin.scaffold`), state four facts briefly so the person can review or approve from a phone without rereading the chat:

- **What changes:** the exact file, field, job target, or setting diff.
- **Reach:** `run`, `workspace`, or `host`.
- **Undo:** the exact reversal command or `none (irreversible)`.
- **Verify:** the exact check that confirms the change worked (for example `workflow.validate`, `workflow.status`, or `workflow.inspectStep`).
