---
name: orchestration
description: Execute or review the full SDD flow in Claude Code using the canonical `sdd orchestration` CLI harness. Use for SDD, orchestrator, Project Discovery, PRD, Tech Spec, Tasks, Execution, ADR, Review and Memory.
---

# SDD Orchestration

Use `orchestration` as the canonical command and skill name. Treat `orchestrator` as a legacy alias only.

## CLI preflight (obrigatório antes de qualquer etapa)

Verifique se `sdd` está disponível:

```bash
command -v sdd
```

- **Encontrado** → use `sdd ...` normalmente.
- **Não encontrado + projeto é o checkout fonte** (`Cargo.toml` com `name = "sdd-layer"`) → use `cargo run --bin sdd -- ...`.
- **Ambos falham (Helmor, CI, container sem cargo)** → **fallback manual obrigatório**: antes de iniciar qualquer etapa, crie os arquivos do Passo 0 manualmente:
  1. `mkdir -p docs/<slug>/`
  2. Crie `docs/<slug>/README.md` com `# SDD - <nome>\n\nArtefatos locais desta orquestração.`
  3. Crie `docs/<slug>/traceability-map.yaml` com o esqueleto canônico (orchestration + artifacts com todos os stages em `state: pending` + external_links vazios).
  4. Crie `docs/<slug>/00-project-discovery.md` com o contexto do projeto (stack, comandos, convenções, integrações).
  5. Crie `docs/<slug>/00-risk-classification.md` com nível de risco, decisões de processo e evidências mínimas.
  6. Só então inicie `01-idea.md` e as etapas seguintes.

  > **Nunca pule o Passo 0.** Os 5 arquivos acima são pré-condição para rastreabilidade completa, independente do CLI estar disponível.

## Fluxo principal

First, resolve the unified context skeleton (works for card ID, bot or free text):

```bash
sdd resolve-input "$ARGUMENTS"
```

Reuse the canonical `--name` it returns across every stage and `sdd` command, start from the suggested next stage, build each stage context with `sdd context build --name "<name>" --stage <stage>`, and do not regenerate approved stages.

Then run:

```bash
sdd orchestration "$ARGUMENTS"
```

Then conduct the full SDD flow with subagents and human checkpoints. The CLI owns deterministic state, risk, artifact persistence, validation and hooks.

## Agentic SDD Loop

For demand intake from a card, bot, webhook or external agent, prefer the durable loop recipe:

```bash
sdd workflow run agentic-sdd-loop --input "$ARGUMENTS" --max-iterations 3 --json
```

It resolves input, runs the planning loop through `standard-sdd`, persists workflow status and pauses at the PRD checkpoint. After human approval, continue with `sdd auto run --real`, `sdd auto run --real --through review` or `sdd auto run --real --through memory` according to the authorized boundary. For a fully automatic run without human gates, use `sdd auto run --real --unattended`; it records PRD, Tech Spec and Refinement acceptances as `channel: automation`, defaults to `--through memory`, and must not be represented as human approval.

Stop instead of retrying when the same error, diff, command or search repeats without a new hypothesis, source, narrower scope or evidence. Full guide: `docs/AGENTIC-SDD-LOOP.md`.

## Runtime-agnostic contract

The SDD core owns the SDLC contract: stages, artifact store, checkpoints, validation, traceability, provider registry and deterministic CLI behavior. Runtime engines such as Rig, Flue, LangGraph, Agno or future frameworks are optional adapters for execution, routing, tools or composition. They must not replace `.agents` as the canonical contract, `docs/<slug>/traceability-map.yaml` as the local source of truth, or MCP/trace as read-only observability. If a runtime adapter is unavailable, continue with Markdown, `sdd` CLI commands and local artifact persistence.

## Quality Gates And Observability

Before autonomous execution, review or memory, run:

```bash
sdd eval stage --name "<orchestration>" --stage <stage> --json
sdd eval orchestration --name "<orchestration>" --json
sdd quality report --name "<orchestration>" --json
sdd trace summary --orchestration "<orchestration>" --json
```

Evaluations validate required sections, traceability, diagrams, `Prompts Agent`, Context Pack freshness and `traceability-map.yaml` state. Critical findings block automatic advancement. `sdd quality report` records optional tools and fallbacks in `.sdd/evaluations.jsonl`.

Events must preserve `agent`, `selected_model`, `observed_model` when the provider/CLI reports trustworthy metadata and `confidence`. Do not infer `observed_model` from configuration.

When an adapter/editor has real token usage, call `sdd <stage>` or `sdd artifact save` with `SDD_USAGE_INPUT_TOKENS`, `SDD_USAGE_CACHED_INPUT_TOKENS`, `SDD_USAGE_OUTPUT_TOKENS`, `SDD_USAGE_REASONING_OUTPUT_TOKENS` and `SDD_USAGE_TOTAL_TOKENS`; artifacts record `Tokens source: provider-reported`. For real generation timing, pass `SDD_GENERATION_STARTED_AT`, `SDD_GENERATION_EXECUTION_STARTED_AT`, `SDD_GENERATION_FINISHED_AT`, `SDD_GENERATION_DURATION_MS`, `SDD_GENERATION_REASONING_DURATION_MS` and `SDD_GENERATION_EXECUTION_DURATION_MS`; artifacts record `Tempo source: provider-reported`. Without those env vars, the CLI records a local token estimate and local CLI timing with explicit source.

After Execution, create or update ADRs with `sdd adr` when the implementation introduced, confirmed or changed an architectural decision.

IDEA may include `## Diagramas` when the visual improves understanding. PRD and Tech Spec artifacts must include `## Diagramas` with useful Mermaid/Excalidraw references, `assets/diagrams/*.html|*.svg` visual companions, or `Não aplicável` with a short reason. Tasks must include `## Prompts Agent` with standalone provider-neutral prompts using executable IDs such as `T-01` or `TSK-01`.

Required checkpoints:

- PRD
- Tech Spec
- Refinement when risk requires it
- Review/merge
- Deploy when applicable

Save approved artifacts with:

```bash
sdd artifact save "<nome-da-orquestracao>" <stage> --file <arquivo> --state approved
```

Workspace execution must use an authorized adapter. In this version, providers without write support must fail explicitly before mutating files.
