---
name: orchestration
description: Execute or review the full SDD flow in Trae 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.

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"
```

For demand intake from card, bot, webhook or external agent, prefer:

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

Read `docs/AGENTIC-SDD-LOOP.md` before moving into supervised execution/review/memory. 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.

If Trae's shell cannot find `sdd`, do not search for another entrypoint yet. Check `command -v sdd`; in the `sdd-layer` source checkout, run the same command through `cargo run --bin sdd -- orchestration "$ARGUMENTS"`. Outside the source repo, report that the binary is not installed or `$HOME/.cargo/bin` is missing from `PATH`.

The CLI owns deterministic state, risk, artifact persistence, validation and hooks.

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

Before creating stage artifacts, initialize the local artifact store:

```bash
sdd init "<nome-da-orquestracao>"
```

All stage artifacts must live in `docs/<slug-da-orquestracao>/` when external integrations are absent or partial. Use `sdd artifact save` with `recorded` for informational stages and `approved` only after explicit human checkpoints.

Required checkpoints:

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

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

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

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