---
name: orchestration
description: Execute or review the full SDD flow across any provider/model and client, including CLI, Codex, Claude Code, opencode, Cursor, Devin, Antigravity and Trae. Use when the user asks for SDD, orchestration, orchestrator, discover, PRD, Tech Spec, tasks, execution, ADR, review or memory.
---

# SDD Orchestration

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

## Canonical CLI

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

## Resolve Input First

Before initializing the store or running any stage, resolve the unified context skeleton:

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

It detects whether the entry is a card ID (`TEXT-NUMBER`), a resume (an existing `docs/<slug>/`) or a new orchestration, and returns the canonical `--name`, the suggested next stage and the already-materialized artifacts. Reuse that `--name` across every stage and `sdd` command, start from the suggested next stage without skipping stages, build each stage context with `sdd context build --name "<name>" --stage <stage>`, and do not regenerate approved stages. This keeps the context skeleton identical whether the entry came from a card ID, the bot or free text.

## CLI Resolution

Resolve the CLI once before inspecting repository internals or searching for alternate entrypoints:

1. If `command -v sdd` succeeds, run `sdd ...`.
2. If `sdd` is not in `PATH` and the current checkout is the `sdd-layer` source repo (`Cargo.toml` declares package `sdd-layer` and bin `sdd`), run `cargo run --bin sdd -- ...` from the repo root.
3. If both paths fail, report that the SDD CLI is unavailable and include the exact command the harness should retry after installing the binary or adding `$HOME/.cargo/bin` to `PATH`.

Editor and agent shells may not inherit the user's interactive shell `PATH`; do not spend time searching for another CLI implementation before this preflight.

The CLI is the deterministic harness for state, risk, artifact store, validation and hooks. Agent/editor surfaces must call the CLI instead of duplicating logic in prompt text.

## Provider Compatibility

The SDD contract must be provider-neutral. OpenAI-compatible, Anthropic, Google, local CLI, offline and future providers should all be able to consume the same Markdown skills and produce the same artifacts. Treat tool calling, browser access, screenshots, MCP and subagents as optional client capabilities with fallbacks.

## 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.

## Agentic SDD Loop

Use `agentic-sdd-loop` when a demand should enter the durable loop from free text, card, bot or webhook input:

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

This workflow resolves input, runs the durable planning motor through `standard-sdd`, persists workflow status and pauses at the PRD checkpoint. After human approval, continue with the canonical SDD engine:

```bash
sdd auto run --real
sdd auto run --real --through review
sdd auto run --real --through memory
sdd auto run --real --unattended
```

Use `--unattended` only when the operator explicitly wants a fully automatic run without human gates. It auto-accepts PRD, Tech Spec and Refinement with `channel: automation`, records `gate_auto_accept` events, defaults to `--through memory` when `--through` is omitted, and must not be represented as human approval. Do not autoapprove merge, release or deploy. Treat Execution, ADR, Review and Memory as supervised post-planning stages unless the client has an authorized workspace-execution adapter (Codex, Claude Code, opencode, Cursor Agent, Devin, Trae or Antigravity) or `--unattended` was explicitly requested. If a loop repeats the same error, diff, command or search without new hypothesis, source, narrower scope or evidence, stop and produce a human handoff instead of retrying blindly.

Primary documentation: `docs/AGENTIC-SDD-LOOP.md`.

## Design And Diagrams

Always trigger the design subflow when the feature involves UI, UX, CLI/TUI, design system, journey, navigation, screen, form, dashboard, visual state or interface copy.

- PRD: use `design-interview` and `experience-design`.
- Tech Spec: use `information-architecture`, `design-tokens` and `artifact-diagrams`.
- Tasks or Refinement: use `design-to-tasks`.
- Execution: use `frontend-design` or the stack-appropriate experience handoff.
- Review, checkpoint or merge: use `visual-review` with visual evidence or a documented fallback.

Use `artifact-diagrams` in planning when flow, architecture, states, contracts or dependencies are clearer visually. IDEA may include `## Diagramas` when useful. Every materialized PRD and Tech Spec must include `## Diagramas`: add useful Mermaid/Excalidraw references, or write `Não aplicável` with a short reason when a diagram would be noise. Keep Mermaid in Markdown for versioned artifacts, save Excalidraw canvases in `docs/<orchestration-slug>/assets/`, and use `diagram-design` only as an HTML/SVG companion in `docs/<orchestration-slug>/assets/diagrams/`. Attach companions with `sdd diagram attach`.

## Task Agent Prompts

Tasks must include `## Prompts Agent` with one standalone prompt per task. Each prompt must be precise enough for any LLM/client to execute without conversation memory.

Each prompt must include:

- Task ID and title using the executable format `T-01` or `TSK-01`.
- Origin artifacts: PRD, Tech Spec, Tasks, diagrams and relevant assets.
- Verifiable objective.
- In scope and out of scope.
- Probable files and ownership boundaries.
- Business rules, technical contracts, states, data constraints and design references needed to execute.
- Implementation steps or investigation sequence.
- Validation commands/checks or instructions to discover them in the repo.
- Definition of Done and expected final report.

Do not require a specific provider, model, browser, MCP, subagent or tool-calling capability inside the prompt. Express optional capabilities with fallbacks.

## Flow

0. Project Discovery: stack, commands, paths, CI, risks and adapters.
0. Risk Classification: rigor, Refinement, Agent Teams, checkpoints and evidence.
1. Idea: product discovery.
2. PRD: requirements, rules and acceptance criteria. Checkpoint.
3. Tech Spec: codebase-grounded architecture. Checkpoint.
4. Tasks: atomic backlog with Gherkin.
5. Refinement: optional but formal grooming; record when skipped.
6. Execution: one task at a time, after reading the execution Context Pack and code-intelligence handoff.
6a. ADR: create or update Architecture Decision Records from execution evidence.
7. Review: diff, tests, security and acceptance criteria. Checkpoint.
8. Memory: compact decisions, links and learnings.

## Rules

- Do not skip required stages.
- Do not skip Refinement when risk is medium, high or critical.
- Stop for explicit human decisions at checkpoints.
- Before creating stage artifacts, initialize the local artifact store with `sdd init "<orchestration-name>"`.
- Use `docs/<orchestration-slug>/` and `traceability-map.yaml` as the local source of truth when external integrations are absent or partial.
- Use `sdd artifact save` for every approved or recorded artifact, with `approved` only after the human checkpoint.
- Validate materialized Markdown with `sdd validate-artifact`.
- When generating PT-BR artifacts or human-facing content, preserve accents and diacritics. Use ASCII-only text only for slugs, paths, branches, code identifiers, commands, schemas, API fields or literal external contracts.
- Use `provider-compatibility` when a workflow must run across all providers/models.
- 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.
- Use `artifact-diagrams` in planning with Mermaid and Excalidraw when the visual map improves shared understanding; use `diagram-design` only for companion HTML/SVG assets attached through `sdd diagram attach`.
- After Execution, run `sdd adr` when a technical or architectural decision was made or changed.
- Keep traceability from idea to code, tests and memory.
- After `/discover`, use the generated recommendations to propose technology-specific skills, rules, `AGENTS.md` sections and `CLAUDE.md` deltas.
- Before broad repo or artifact reads, prefer `sdd health --json` for global readiness and `sdd context build --name "<orchestration>" --stage <stage> --json --metadata-only` for low-token handoff metadata.
- Before `/execution`, generate or read `sdd context build --name "<orchestration>" --stage execution --write`; use `code-intelligence` when CodeGraph/Lexa are available, otherwise use `rg --files`, `rg` and focused reads.
- During `/execution`, use `execution-discipline`: tracer bullet vertical slices, failing tests when a seam exists, reproducible diagnosis loops for bugs/performance and fresh verification evidence.

## Formato de saída por etapa

Use o mesmo contrato de saída dos subagents `.codex/agents` e `.claude/agents` em qualquer cliente:

- `idea`: visão geral da ideia, problema, público-alvo, proposta de valor, jornada principal, MVP, fora do MVP, hipóteses, riscos, perguntas em aberto e `Diagramas` opcional quando o visual melhorar entendimento.
- `prd`: resumo executivo, contexto, objetivos, não objetivos, personas, casos de uso, fluxos, requisitos funcionais e não funcionais, regras de negócio, estados, critérios de aceite, métricas, riscos, dependências, escopo do MVP e `Diagramas` com Mermaid/Excalidraw ou justificativa de `Não aplicável`; companion `diagram-design` entra como referência `assets/diagrams/*.html|*.svg`.
- `techspec`: visão técnica, arquitetura, stack, estrutura de pastas, modelagem de dados, contratos de API, fluxos técnicos, estados/eventos, autenticação/autorização, validação, erros, observabilidade, segurança, performance, testes, riscos, decisões arquiteturais, plano de implementação e `Diagramas` técnicos com Mermaid/Excalidraw ou justificativa de `Não aplicável`; companion `diagram-design` entra como derivado visual.
- `tasks`: épicos, histórias técnicas, tarefas atômicas em formato executável (`T-01` ou `TSK-01`), ordem sugerida, dependências, critérios de aceite em Gherkin, DoD, estratégia de testes, arquivos prováveis e `Prompts Agent` standalone por tarefa.
- `refinement`: documento único e enxuto com `Resumo`, `Solução proposta`, `Pontos de observação`, `Checklist macro`, `Subtasks` com estimativas em múltiplos de 0.5h, `Definition of Done` e `Flags, Remote Configs e Configurações`.
- `execution`: resumo do implementado, arquivos criados/alterados, decisões técnicas, como testar, impactos e pendências.
- `adr`: rastreabilidade, status, contexto, problema, decisão, alternativas, consequências, impactos/riscos, plano de adoção, plano de reversão, evidências e histórico de revisão.
- `review`: veredito `Aprovado | Aprovado com ressalvas | Reprovado`, pontos positivos, problemas, severidade, sugestões, testes recomendados e checklist de qualidade.
- `memory`: estado atual, funcionalidades implementadas, arquitetura atual, decisões, padrões, comandos úteis, variáveis de ambiente, testes, pendências, próximos passos e contexto resumido.

Todo artefato materializado deve ter `Rastreabilidade`, apontar para o artefato anterior e ser salvo em `docs/<slug-da-orquestracao>/` com `sdd artifact save`. Use `recorded` para etapas informativas e `approved` somente depois de checkpoint humano.
