---
name: codemode-how-to-workflow
description: Discover, launch, monitor and recover YAML workflows, use selected jobTools, or track dynamic script graphs and child transcripts in Activity.
pinned: true
---

# Workflows in code mode

Use `workflow` for persisted YAML runs and `dynamicWorkflow` for tracked script graphs. Managed steps may also receive `jobTools`. Call `discover({ namespace })` for current signatures. Available whenever `@agimon-ai/po-workflow` is selected, with no mode activation.

## Discover, launch, monitor

1. `workflow.list` discovers definitions, tags, and pages (not runs). Call `workflow.requirements({ workflowPath, job? })` for read-only role and eligible-profile discovery before choosing assignments; never pass product, workspace, profile, team, or assignments to discovery.
2. Call `workflow.validate({ workflowPath, inputs, env, runner, command, choice, profile, job })` with the exact settings you intend to launch. Fix every error and revalidate after edits. `valid: true` does not verify `deferred` runtime items (identities, secrets, prompts, shell behavior); never invent deferred values.
3. `workflow.launch` starts a run only when authorized. Prefer a declared in-process Pi command (for example `command: "pi"` when declared); `pi`, `po`, and `claude` are literal command names, never aliases, and `runner: "codex"` does not imply `command: "pi"`. An acknowledgement `{ message, run? }` is not completion; verify with `workflow.status({ runKey, workspace })` and terminal notices.
   - Launches run in your session; `sessionName` only names a workflow session opened to collect missing inputs from the UI.
   - Definitions with `isolation: 'checkout'` need an isolating launcher such as `po-git` `worktrees.startWorkflow`, not `workflow.launch` from a shared checkout.
4. Observe live or finished steps with `workflow.inspectStep({ runKey, workspace?, step?, tailBytes?, messageLimit? })`: returns bounded live agent messages or CLI screen, sealed artifacts, and criteria ledger. Identity- or secret-bound runs omit messages and CLI screens; non-owner callers receive `messagesState: 'other_owner'`, and released steps receive `messagesState: 'released'`.
5. Pause, resume, and stop only at the person's request or explicit launcher delegation. Pass `expectedRunId` from the inspected run with exact `runKey` and `workspace`. Launchers may stop handed-off runs; `pause` and `resume` stay owner-only. In Help mode only, `workflow.steer({ runKey, workspace?, expectedRunId, step?, message })` guides a live non-identity/secret-bound agent step you own.

Shell steps use `/bin/zsh` when available, otherwise `/bin/sh`. Dispatcher sessions may only `list`, `requirements`, `validate`, `inspectDefinition`, and `launch`. Closing an `exec` binding never stops a committed YAML workflow. Subagents may call read-only members only; mutating `workflow.*` calls require the main agent.

## Continue a workflow chain

A successful completion notice is a handoff, not a recovery prompt. Read the declared outputs using the notice's exact `runKey` and `workspace`, reconcile with the work state, and advance if authorized (or name the blocker). A skipped, parked, or user-stopped run is not a trigger to advance or recover.

On failure, the run's owner diagnoses with `workflow.recoveryEvidence` (and `workflow.inspectStep`), fixes what is within existing authority, and calls `workflow.recover`. The first `MAX_UNATTENDED_RECOVERIES` (3) recoveries run unattended; later ones ask the person, including in Help mode. Dry runs do not count. Verify progress with `workflow.status`. If a handed-off workflow session owns the run, let it diagnose and report once via `network.send({ to: launcher, text, terminal: true, outcome })`.

## Recover safely

Recovery resumes an existing failed, interrupted, or stale dead-PID run in its checkout, preserving completed work. `workflow.listFailed` and `workflow.listRuns` list runs without exposing environment values.

- **Held locks:** Plugin-launched runs keep their lock on failure so recovery reuses it. Never launch a duplicate. Use `workflow.abandon` (person-approved) to release the lock when giving up; abandoned runs can never be recovered.
- **Parked runs:** A regular agent step idle with undecided approvals parks (`waiting: true`, step session released, `post:` skipped). `workflow.status` and `workflow.inspectRun` expose `waitingEntries` (`[{ stepName, approvalId, title? }]`) so you can name the exact blocking card. Once decided, the owner resumes automatically. Do not recover while undecided; `workflow.stop` clears the wait and withdraws undecided requests.
- **YAML edits:** Every resume runs the saved definition. A `workflow.recover` started by the owner adopts an edited file once when the run is roleless and launched from this checkout; role-bound runs, handed-off runs, and live reloads require Help mode.
- **Safety rules:** Read `workflow.recoveryEvidence` before `workflow.recover`. Never edit `issue.md` or `repair.json`, manufacture a failed job, use `dryRun` for a real recovery, or retry an already-claimed recovery. User-requested stops never trigger diagnosis or auto-restart.

## Repair a stuck run

Use only when recovery cannot proceed (invalid `run.json`, hung PID, exhausted budget, or triage lock).

1. `workflow.inspectRun({ runKey, workspace })` returns every stage directory, raw files, `pidAlive`, `waitingEntries`, and `revision`.
2. `workflow.repairRun({ runKey, workspace, stage, revision, reason, record?, fix?, remove?, force? })` requires person approval outside Help mode, and inside Help mode whenever delegated, `force: true`, or touching `allocation`, `admission`, or `identities`. Outside Help mode, lowering budgets is refused. Replaced files are backed up under `repair-backups/`.
3. **Help mode only:** `workflow.helpRepair({ runKey, workspace, stage: 'error', revision, reason, fixLoopCycle?, continuations?, recomputeRevision? })` adjusts budgets or lead journal revisions without approval; `workflow.recover({ restartFrom })` rewinds directly to a chosen job. Load `help-how-to-workflow` for authoring, steering, rewind, and proposal rules.

## Managed child jobs & step outcomes

Inside managed sessions, call `discover({ namespace: 'workflow' })` for role-scoped methods:

- **Lead:** `spawnChild({ job, prompt, inputs, inputPaths })`, `children()`, `childStatus({ invocationId })`. Keep secrets out of assignments and feedback; `not-met` is feedback, not a step failure.
- **Child verifier:** `reviewArtifacts()` for the immutable snapshot, then `reportCriteria({ results })` for authorized keys only. Reopened verifiers must call `reviewArtifacts()` again before reporting.
- **Any child:** `assignment()` returns the sealed prompt, inputs, `inputManifest`, and writable outputs.
- **Step sessions:** `context()`, `complete({ summary? })`, `fail({ reason })`, `fix({ restartFrom, reason })`.

## Selected job tools & stored definitions

- **Job tools:** When `workflow-job-tools` is pinned, read it and call `discover({ namespace: 'jobTools' })` before calling its methods in `exec`. Follow its validation and approval rules. See `help-how-to-workflow` for authoring `jobTools` modules.
- **Delete stored definition:** Find `source` (`org`, `personal`, or `host`) and plain filename `key` via `workflow.list()`, then call `workflow.deleteDefinition({ source, key })` in foreground `exec` (always person-approved, SHA-256 pinned, irreversible).

## Hosts without code mode

Direct tools share the same operations and safety gates: `list_workflows`, `launch_workflow`, `workflow_requirements`, `workflow_run` (`status`, `pause`, `resume`, `stop`, Help-mode `steer`), `workflow_tools` (`list-failed`, `list-runs`, `inspect-definition`, `recovery-evidence`, `recover`, `validate`, `abandon`, `inspect-run`, `repair-run`, `help-repair`), `workflow_delete_definition`, and role-scoped child/step tools (`workflow_spawn_child`, `workflow_child_status`, `workflow_children`, `workflow_assignment`, `workflow_review_artifacts`, `workflow_report_criteria`, `workflow_context`, `workflow_step_complete`, `workflow_step_fail`, `workflow_step_fix`). All mutating direct tools are main-agent-only and withdrawn when code mode is bound.

# Dynamic script graphs

Use `dynamicWorkflow` for multi-step scripts or bounded item fan-out visible in Activity. Discover `dynamicWorkflow` for current signatures. Use its supplied `z`, `createStep`, and `createWorkflow` (never raw imports), commit nested workflows before `.then`/`.parallel`/`.branch`/`.foreach(item, { concurrency })`, and run long or agent-bearing graphs in `exec({ code, background: true })`.

- Use `dynamicWorkflow.agent({ task, systemPrompt?, preset?, modes?, profile?, domains?, model?, thinking?, cwd?, timeoutMs? })` inside a `createStep` execute callback (main agent only) when a step needs its own selection; inspect returned `status` explicitly.
- Return `null` (not `undefined`) for empty step outputs, keep step outputs JSON-serializable for replay, and resume interrupted runs with `await dynamicWorkflow.resume(recordId)` (add `{ retryUncertain: true }` only after verifying interrupted side effects).
- Load `help-how-to-workflow` for full `dynamicWorkflow` composition, cloud runtime, and replay authoring rules.
