# Autonomous Workflow

`orchestra workflow run` executes a full story lifecycle as a governed multi-phase sequence without requiring manual step-by-step commands. Each phase creates a sub-task, generates handoff artifacts, and persists state in an append-only run log at `.agent-workflow/workflow-runs.jsonl`.

## End-To-End Lifecycle

Use the autonomous workflow when a task needs product framing, architecture,
implementation, QA evidence, and release readiness in one governed trace.

1. Register or sync the backlog item with a task ID, paths, owner, and
   acceptance criteria.
2. Record an estimate and an architect sizing decision before implementation
   work begins.
3. Start `orchestra workflow run --task <id> --gates phase`.
4. Review the PO to Architect gate. Approve it when the story is refined enough
   for technical design and implementation.
5. Let Architect, Developer, and QA phases produce handoffs, reviews, evidence,
   and any clarification records needed to finish the work.
6. Review the QA to Release gate. Approve it only when validation evidence,
   unresolved risks, release notes, and rollback expectations are acceptable.
7. Resume into Release, then run `orchestra benchmark --task <id>` to capture
   actual delivery data for future estimates.

The run state, gate artifacts, handoffs, evidence, reviews, decisions, and
clarifications are persisted under `.agent-workflow/` so the delivery story can
be audited after the fact.

## Task-Scoped Roles

Tasks can declare the roles that are required or optional for the workflow. When
a task is created with only an owner role, Open Orchestra treats that owner as
the implicit required role instead of falling back to the default delivery
workflow.

```bash
orchestra task add --id BUG-001 --title "Fix CLI bug" --owner developer
orchestra workflow run --task BUG-001 --gates phase
```

Use explicit roles when the task needs a broader lifecycle:

```bash
orchestra task add --id STORY-001 --title "Ship user-facing workflow" \
  --owner product_owner --required-roles product_owner,architect,developer,qa,release_manager
```

This keeps small developer or QA tasks scoped while still allowing full
PO-to-release delivery for stories that need it.

## Workspace Isolation

Workflow commands that operate on run state support `--target-dir` so callers
can launch work from another directory without writing `.agent-workflow/` state
to the wrong repo.

```bash
orchestra workflow run --task STORY-001 --target-dir /path/to/project
orchestra workflow list --target-dir /path/to/project
orchestra workflow gate-approve --run <run-id> --target-dir /path/to/project
```

Use `--target-dir` for temporary E2E projects, editor integrations, local web
console actions, and any parent process that coordinates more than one
workspace.

## Phase Graph

```
PM → PO [gate] → Architect [sizing gate] → Developer → QA [gate] → Release
```

| Phase       | Role            | Output                                                               | Human checkpoint                                          |
| ----------- | --------------- | -------------------------------------------------------------------- | --------------------------------------------------------- |
| `pm`        | product_manager | Product framing, trade-offs, sequencing, and success metrics         | None by default                                           |
| `po`        | product_owner   | User-validated scope, definitions, acceptance criteria, assumptions, non-goals, priority, and release value | `po→architect` when `--gates phase` or `--gates all`      |
| `architect` | architect       | Technical approach, affected boundaries, sizing decision, and risks  | Architect sizing gate is always required                  |
| `developer` | developer       | Code/docs changes, implementation notes, and Developer to QA handoff | Optional clarification to PO or Architect                 |
| `qa`        | qa              | Test plan, validation evidence, gaps, and QA recommendation          | `qa→release` when `--gates phase` or `--gates all`        |
| `release`   | release_manager | Release readiness, rollback notes, and final completion state        | Release approval is represented by the QA to Release gate |

## Gate Modes

```bash
orchestra workflow run --task <id> --gates none    # fully autonomous
orchestra workflow run --task <id> --gates phase   # gates at po→architect and qa→release
orchestra workflow run --task <id> --gates all     # gate at every transition
```

Loading a task and recording an estimate is not execution. Managed agent work
must start or resume a workflow run before implementation, handoff, QA, or
release work. If `orchestra validate --pre-run --task <id>` reports a missing
`workflowRun`, run `orchestra workflow run --task <id> --gates phase` or resume
the existing run before continuing.

| Mode    | Pauses at                       |
| ------- | ------------------------------- |
| `none`  | Never — fully autonomous        |
| `phase` | `po→architect` and `qa→release` |
| `all`   | Every phase transition          |

When a gate is reached, the run writes a review artifact to `.agent-workflow/approvals/` and prints the exact `--resume` command. The run resumes when a human approves and runs that command.

## Gates Versus Clarifications

Gates and clarifications solve different problems. A gate is a planned approval
checkpoint between phases. A clarification is a mid-phase question that prevents
the active role from continuing safely.

| Situation                                                           | Use           | Why                                                                   |
| ------------------------------------------------------------------- | ------------- | --------------------------------------------------------------------- |
| PO/BA stories, definitions, acceptance criteria, or assumptions need user confirmation before design starts | Gate          | This is a planned phase boundary                                      |
| QA evidence is complete but release risk needs sign-off             | Gate          | This determines whether Release may proceed                           |
| Developer needs to know whether empty input is valid                | Clarification | The active phase is blocked by a product or architecture question     |
| QA finds ambiguous expected behavior while writing tests            | Clarification | The answer should unblock QA without inventing a new phase boundary   |
| Architect chooses between two durable system approaches             | Decision      | This is an architecture record, not a pause by itself                 |
| Reviewer finds a defect after evidence is attached                  | Review        | This is a quality finding that can approve, block, or request changes |

Do not use gates for every question. Use `workflow clarify` when the question is
specific, answerable by PO or Architect, and the current Developer or QA phase
can continue after the answer is recorded.

## Provider-Backed Phase Execution

By default, workflow phases remain deterministic because the default provider is `none`. When a role or default provider route is configured to a non-`none` provider, each phase builds a prompt from task context, rendered skills, the active phase playbook, and prior handoff content, then writes the provider output to `.agent-workflow/runs/<task>/<phase>/`.

```bash
orchestra model set-role --role architect --provider fake --model fake-model
orchestra workflow run --task FEAT-001 --gates phase
orchestra model provenance list --task FEAT-001 --json
```

Provider execution records `MODEL_PROVENANCE_RECORDED` events. The benchmark layer uses those events to report token and cost signals.

When every configured provider fails, the workflow prints sanitized per-provider causes and stores them in the failed phase notes and `AUTONOMOUS_RUN_FAILED` event metadata. These diagnostics distinguish DNS/network failures, missing credentials, HTTP status errors, policy blocks, and exhausted fallbacks without exposing API keys, auth headers, or raw secret values. If the cause is still unclear, run that provider's smoke test with the same credential file or environment variables used by `.agent-workflow/config.json`.

## Runtime Tool Permission Policy

Runtime briefs and delegation packets include a `Tool Permission Policy` section. This is adapter metadata, not an instruction to bypass runtime safety by default.

Claude CLI is intentionally brief-only in Open Orchestra today. Direct non-interactive Claude execution must not use `claude --print <prompt>` alone for tool-using tasks, because the process can block waiting for tool approval. If direct Claude CLI execution is added later, it must require explicit user opt-in and choose permission flags from the adapter policy:

- `--gates none` / fully autonomous mode: only with explicit opt-in, use the adapter autonomy flags.
- `--gates phase` or `--gates all`: use read-only allowed tools by default and require separate approval for write or shell tools.
- Brief/delegation rendering remains the default path and does not grant tool permissions by itself.

## Phase Execution Mode

`workflow run` separates the phase role from the runtime that may execute that
phase. The parent agent remains the coordinator; phase work can be planned for
runtime-native subagents when the runtime supports them.

```bash
orchestra workflow run --task FEAT-001 --phase-execution auto
orchestra workflow run --task FEAT-001 --phase-execution subagents
orchestra workflow run --task FEAT-001 --phase-execution single-agent
```

- `auto` is the default. It renders role-scoped runtime-native delegation
  packets when the selected runtime supports subagents and guardrails allow the
  spawn. If not, it records an explicit parent-agent fallback.
- `subagents` requires runtime-native subagent support. Unsupported runtimes or
  delegation guardrail blocks stop the run instead of silently switching to
  provider APIs.
- `single-agent` keeps all phases on the parent-agent path and records that
  executor choice for auditability.

`--gates none` only disables human gate pauses. It does not request detached
runtime execution, parent actions, or subagent lifecycle reports; combine it
with `--phase-execution single-agent` when every phase should run inline.

Runtime subagent capacity is controlled by
`runtimePolicy.delegation.guardrails.maxConcurrentDelegates`,
`maxSpawnsPerTask`, and `limitAction`. When the limit action is `queue`, a phase
that exceeds capacity is paused as `queued-runtime-subagent` and can be resumed
after active delegation sessions complete or close. This prevents a parent
agent from launching more subagents than the local runtime or SaaS tenant can
handle.

Detached phase execution is full async. The workflow records the spawn request
and session metadata, then returns control to the parent agent. The parent can
continue conversation or other commands while child sessions run. Session
completion is reconciled through lifecycle events, runtime notifications, or an
explicit later `runtime sessions` check. Waiting is only appropriate when the
next parent action is truly blocked by that specific child result.

Phase executor provenance is written to `.agent-workflow/workflow-runs.jsonl`
and into handoff artifacts. It includes phase, role, runtime, executor type,
delegation packet artifact when rendered, session id when known, fallback
rationale, and `directProviderApiAllowed=false`.

## Phase Playbooks

`orchestra init` creates editable phase playbooks in `.agent-workflow/playbooks/`:

```text
.agent-workflow/playbooks/
  pm.md
  po.md
  architect.md
  developer.md
  qa.md
  release.md
```

Use playbooks for phase-specific guidance that should not live in always-loaded runtime instructions. Examples: QA evidence expectations, release go/no-go criteria, architecture decision format, or developer handoff requirements.

Playbooks are provider-agnostic. They are loaded into provider-backed phase prompts, `workflow render --phase <phase>`, runtime briefs, and runtime delegation packets. Only the active phase playbook is loaded.

### Authoring Playbooks

Write playbooks as concise phase instructions, not as a second root
`AGENTS.md`. A good playbook should include:

- Role objective for the phase.
- Inputs the role should read before acting.
- Required outputs and artifact names.
- Quality gates or review checks owned by that role.
- Evidence that must be recorded before handoff.
- Escalation rules for clarifications, decisions, reviews, or security checks.

Keep project-specific conventions in the project playbooks and keep stack-wide
policy in root instructions or neutral rule sources selected by Orchestra. If a
playbook starts duplicating all phases, split the shared rule into `rules/` and
leave only phase-specific work in the playbook.

Configuration is convention-over-config by default, with optional overrides:

```json
{
  "workflow": {
    "playbooksDir": ".agent-workflow/playbooks",
    "phasePlaybooks": {
      "developer": "custom-developer.md"
    }
  }
}
```

If a playbook file is missing, Orchestra uses deterministic fallback guidance and surfaces a warning in rendered content.

### Playbook Resolution

Resolution order is:

1. `workflow.phasePlaybooks[phase]` in `.agent-workflow/config.json`, when set.
2. `<playbooksDir>/<phase>.md`, where `playbooksDir` defaults to
   `.agent-workflow/playbooks`.
3. Deterministic fallback guidance built into Open Orchestra.

Use `orchestra workflow render --task <id> --phase <phase>` to inspect the exact
playbook content that a runtime brief or provider-backed phase will receive.
Use `orchestra health --json` to confirm the workflow state is readable before a
run.

## Architect Sizing Gate

Regardless of `--gates` mode, the architect phase always requires a valid sizing decision before the developer phase starts. Provider-backed architect phases record that decision from structured phase output. Deterministic architect phases record a conservative default (`m [3 points]`) when no architect sizing exists, so unattended local runs remain complete and auditable. If the provider returns an unsupported sizing label, Orchestra normalizes it back to the same default before recording the decision.

The developer phase also records implementation story points when no developer estimate exists. Provider-backed phases can return `developerPoints` in the structured output; deterministic phases use the architect point estimate when available, or `3 points` as a conservative fallback. Burndown uses developer points before architect points.

When manual correction is needed, record an accepted architect decision:

```bash
orchestra decision add \
  --task <id> \
  --owner architect \
  --title "Story sizing" \
  --decision "m [5 points]" \
  --context "Authentication story, moderate complexity" \
  --consequences "Fits in a two-day sprint slot" \
  --status accepted
```

Valid sizing labels: `xs`, `s`, `m`, `l`, `xl`. An optional numeric point estimate can be appended to the decision text.

## Usage

```bash
# Explain recommended phases from project signals and task risk
orchestra workflow phase-plan --task FEAT-001
orchestra workflow phase-plan --task FEAT-001 --json

# Inspect the phase graph without persisting state
orchestra workflow run --task FEAT-001 --dry-run --gates phase

# Fully autonomous run
orchestra workflow run --task FEAT-001 --gates none

# Run with human approval gates
orchestra workflow run --task FEAT-001 --gates phase

# Resume a paused run after approving a gate
orchestra workflow run --task FEAT-001 --resume <run-id>

# Start a fresh run from an already-claimed phase
orchestra workflow run --task FEAT-001 --from-phase developer

# Resume an existing run from an explicit phase when automatic resume needs an override
orchestra workflow run --task FEAT-001 --resume <run-id> --from-phase qa

# Render a runtime brief with the active phase playbook
orchestra workflow render --task FEAT-001 --phase developer

# Cap the number of QA→developer retry iterations (default: 5)
orchestra workflow run --task FEAT-001 --gates none --max-iterations 3

# List all runs
orchestra workflow runs
orchestra workflow runs --json
```

`workflow phase-plan` is advisory. It uses project detection, task text, risks,
and paths to recommend additional review phases such as `ux_review` for
frontend accessibility or responsive behavior, and `docs_review` for
documentation or public-site changes. If `.agent-workflow/config.json` already
defines `workflow.phaseSequence`, that manual sequence remains authoritative and
the recommendations are reported without silently changing the run.

## Web and Runtime Progress

Workflow progress is available from both CLI and web-supported surfaces:

```bash
orchestra workflow runs --json
orchestra web
```

The local web console reads `/api/workflow/progress` and shows the active phase,
role, provider/model, elapsed time, fallback state, failed reason, paused gates,
and resumable runs. This is a local web API contract; it does not execute
runtime agents or call provider APIs by itself.

Provider-backed phases also print progress in `workflow run` human output. The
default provider remains `none`, so deterministic workflow runs do not require
model credentials.

## Clarification Loop

Developers or QA engineers can surface blocking questions to the PO or architect mid-phase. The active phase is suspended until the answer is recorded, then resumed normally.

Clarification is only allowed from `developer` and `qa` phases. Questions can be directed to `po` (product_owner) or `architect`.

```bash
# Open a clarification — suspends the active developer or qa phase
orchestra workflow clarify \
  --run <run-id> \
  --from developer \
  --to po \
  --question "Should empty input return null or throw a validation error?"

# The PO or architect answers
orchestra workflow clarify-respond \
  --run <run-id> \
  --clarification <clarification-id> \
  --answer "Return null — downstream code handles it with a friendly message."

# Resume execution — picks up exactly where the phase left off
orchestra workflow run --task FEAT-001 --resume <run-id>

# List all clarifications for a run (open and answered)
orchestra workflow clarify-list --run <run-id>
orchestra workflow clarify-list --run <run-id> --json
```

Clarification records are persisted in `.agent-workflow/clarifications.jsonl` and are visible in `orchestra context --task <id>`.

## Run States

| Status    | Meaning                                                          |
| --------- | ---------------------------------------------------------------- |
| `running` | Execution in progress                                            |
| `paused`  | Waiting for human gate approval or clarification answer          |
| `done`    | All phases completed successfully                                |
| `failed`  | Run stopped due to a missing prerequisite (e.g. sizing decision) |

## Phase States

| Status                   | Meaning                                                      |
| ------------------------ | ------------------------------------------------------------ |
| `pending`                | Not yet started                                              |
| `running`                | Currently executing                                          |
| `done`                   | Completed and handed off                                     |
| `gate_paused`            | Completed; waiting for human gate approval before next phase |
| `awaiting_clarification` | Suspended; waiting for a clarification answer                |
| `qa_failed`              | QA found issues; developer phase will retry                  |
| `blocked`                | Blocked by an unresolvable condition                         |

## Gate Pause Notifications

When a workflow pauses at a gate, Orchestra can notify Slack and/or comment on the linked GitHub issue. Configure channels in `.agent-workflow/config.json`; Slack webhooks must reference an environment variable so secrets are not written to disk.

```json
{
  "notifications": {
    "slack": { "webhookUrl": "$SLACK_WEBHOOK_URL" },
    "github": { "issueComment": true }
  }
}
```

GitHub comments use the task `backlogItem` when it is a `#123` issue reference, otherwise Orchestra falls back to the numeric suffix in the task id.

## Persistent Files

```text
.agent-workflow/
  workflow-runs.jsonl       ← one JSON line per run state snapshot (append-only)
  clarifications.jsonl      ← one JSON line per clarification state snapshot (append-only)
  approvals/                ← gate review artifacts (Markdown)
  handoffs/                 ← inter-phase handoff artifacts (Markdown)
```

## Example: Full Lifecycle with gates=phase

```
$ orchestra workflow run --task FEAT-001 --gates phase
Started autonomous workflow wfrun-... for task FEAT-001 [gates=phase]
→ pm (product_manager) task=FEAT-001-pm
  ✓ handoff → product_owner (...)
→ po (product_owner) task=FEAT-001-po
  ✓ handoff → architect (...)
  ⏸ gate po→architect — review: .agent-workflow/approvals/FEAT-001-gate-po-to-architect-....md
  Approve: orchestra workflow gate-approve --run wfrun-... --gate "po->architect" --approver <name> --rationale "<text>"

$ orchestra workflow gate-approve --run wfrun-... --gate "po->architect" --approver "product-owner" --rationale "User validated scope, assumptions, non-goals, priority, acceptance criteria, and sizing context"
$ orchestra workflow run --task FEAT-001 --resume wfrun-...
Resuming run wfrun-... from phase architect
→ architect (architect) task=FEAT-001-architect
  ✓ sizing=m (5 pts)
  ✓ handoff → developer (...)
→ developer (developer) task=FEAT-001-developer
  ✓ handoff → qa (...)
→ qa (qa) task=FEAT-001-qa
  ✓ handoff → release_manager (...)
  ⏸ gate qa→release — review: .agent-workflow/approvals/FEAT-001-gate-qa-to-release-....md
  Approve: orchestra workflow gate-approve --run wfrun-... --gate "qa->release" --approver <name> --rationale "<text>"

$ orchestra workflow gate-approve --run wfrun-... --gate "qa->release" --approver "release-manager" --rationale "Implementation evidence, QA findings, BA/PO acceptance, and Architect review are recorded"
$ orchestra workflow run --task FEAT-001 --resume wfrun-...
Resuming run wfrun-... from phase release
→ release (release_manager) task=FEAT-001-release
Workflow complete [run=wfrun-...]
```

Gate ids should be quoted in shells. If a generated handoff says
`Acceptance Criteria: none`, do not approve release from that handoff alone.
Use the linked issue or task as the acceptance source, record the missing
handoff detail as a review finding, and continue only after the gap is fixed or
the Product Owner explicitly accepts the risk.
