@luanpdd/kit-mcp 1.8.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +97 -1
  3. package/gates/golden-signals-coverage.md +133 -0
  4. package/gates/obs-agents-mcp-supabase.md +86 -0
  5. package/gates/obs-skills-frontmatter.md +76 -0
  6. package/gates/omm-no-regression.md +83 -0
  7. package/gates/postmortem-template-required.md +127 -0
  8. package/gates/prr-checklist-coverage.md +128 -0
  9. package/gates/skill-must-include.md +21 -19
  10. package/kit/agents/burn-rate-forecaster.md +160 -0
  11. package/kit/agents/golden-signals-instrumenter.md +241 -0
  12. package/kit/agents/incident-investigator.md +245 -0
  13. package/kit/agents/observability-instrumenter.md +200 -0
  14. package/kit/agents/omm-auditor.md +251 -0
  15. package/kit/agents/postmortem-writer.md +282 -0
  16. package/kit/agents/prr-conductor.md +288 -0
  17. package/kit/agents/slo-engineer.md +224 -0
  18. package/kit/agents/supabase-architect.md +62 -0
  19. package/kit/agents/supabase-auth-bootstrapper.md +17 -0
  20. package/kit/agents/supabase-edge-fn-writer.md +124 -0
  21. package/kit/agents/supabase-migration-writer.md +98 -0
  22. package/kit/agents/supabase-realtime-implementer.md +23 -0
  23. package/kit/agents/supabase-rls-writer.md +17 -0
  24. package/kit/agents/supabase-storage-implementer.md +174 -0
  25. package/kit/agents/toil-auditor.md +277 -0
  26. package/kit/commands/auditar-marco.md +102 -1
  27. package/kit/commands/auditar-observabilidade.md +103 -0
  28. package/kit/commands/auditar-toil.md +129 -0
  29. package/kit/commands/burn-rate-status.md +140 -0
  30. package/kit/commands/concluir-marco.md +73 -1
  31. package/kit/commands/definir-slo.md +108 -0
  32. package/kit/commands/discutir-fase.md +26 -0
  33. package/kit/commands/forense.md +83 -1
  34. package/kit/commands/golden-signals.md +142 -0
  35. package/kit/commands/instrumentar-fase.md +200 -0
  36. package/kit/commands/investigar-producao.md +162 -0
  37. package/kit/commands/observabilidade.md +116 -0
  38. package/kit/commands/planejar-fase.md +20 -0
  39. package/kit/commands/postmortem.md +179 -0
  40. package/kit/commands/prr.md +205 -0
  41. package/kit/commands/risk-budget.md +220 -0
  42. package/kit/commands/sre.md +227 -0
  43. package/kit/commands/verificar-trabalho.md +26 -0
  44. package/kit/skills/_shared-observability/glossary.md +396 -0
  45. package/kit/skills/_shared-sre/glossary.md +573 -0
  46. package/kit/skills/blameless-postmortems/SKILL.md +340 -0
  47. package/kit/skills/burn-rate-alerting/SKILL.md +258 -0
  48. package/kit/skills/core-analysis-loop/SKILL.md +352 -0
  49. package/kit/skills/distributed-tracing/SKILL.md +362 -0
  50. package/kit/skills/eliminating-toil/SKILL.md +243 -0
  51. package/kit/skills/event-based-slos/SKILL.md +296 -0
  52. package/kit/skills/four-golden-signals/SKILL.md +297 -0
  53. package/kit/skills/observability-driven-development/SKILL.md +315 -0
  54. package/kit/skills/observability-maturity-model/SKILL.md +222 -0
  55. package/kit/skills/opentelemetry-standard/SKILL.md +351 -0
  56. package/kit/skills/production-readiness-review/SKILL.md +305 -0
  57. package/kit/skills/sre-risk-management/SKILL.md +221 -0
  58. package/kit/skills/structured-events/SKILL.md +265 -0
  59. package/kit/skills/telemetry-pipelines/SKILL.md +259 -0
  60. package/kit/skills/telemetry-sampling/SKILL.md +256 -0
  61. package/package.json +1 -1
@@ -0,0 +1,200 @@
1
+ ---
2
+ name: instrumentar-fase
3
+ description: Após /planejar-fase, gera INSTRUMENTATION.md por plano (spans, atributos canônicos, eventos, validação ODD). Aplica skill observability-driven-development.
4
+ argument-hint: "[fase] [plano]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ ---
13
+
14
+ <objective>
15
+ Após `/planejar-fase` produzir PLAN.md, este comando gera `INSTRUMENTATION.md` para cada plano da fase. Aplica a skill [observability-driven-development](../skills/observability-driven-development/SKILL.md) — bundle telemetria com a feature, valide as 4 perguntas pré-PR.
16
+
17
+ **Cria/Atualiza:**
18
+ - `.planning/phases/<N>/<padded>-PLAN-<NN>-INSTRUMENTATION.md` por plano
19
+
20
+ **Após:** o user tem o contrato de instrumentação que o `executor` (e o `observability-instrumenter`) devem cumprir durante `/executar-fase`.
21
+ </objective>
22
+
23
+ <context>
24
+ **Argumentos:** `$ARGUMENTS` — primeiro token é número da fase (ex.: `30`); segundo opcional é número do plano (ex.: `01`); se omitido, processa todos os planos da fase.
25
+
26
+ **Pré-requisito:** `/planejar-fase <N>` já rodou. Existem `<padded>-PLAN-<NN>-*.md` em `.planning/phases/<N>/`.
27
+
28
+ **Skill consultada:** [`observability-driven-development`](../skills/observability-driven-development/SKILL.md) — 4 perguntas pré-PR canônicas.
29
+ </context>
30
+
31
+ <process>
32
+
33
+ ## 1. Parsear argumentos
34
+
35
+ ```bash
36
+ PHASE_NUM=$(echo "$ARGUMENTS" | awk '{print $1}')
37
+ PLAN_NUM=$(echo "$ARGUMENTS" | awk '{print $2}')
38
+
39
+ if [ -z "$PHASE_NUM" ]; then
40
+ echo "Uso: /instrumentar-fase <N> [<NN>]"
41
+ echo "Ex.: /instrumentar-fase 30 # todos os planos da Phase 30"
42
+ echo "Ex.: /instrumentar-fase 30 01 # só Plano 01 da Phase 30"
43
+ exit 1
44
+ fi
45
+ ```
46
+
47
+ ## 2. Detectar phase_dir + planos
48
+
49
+ ```bash
50
+ PHASE_STATE=$(node "./.claude/framework/bin/tools.cjs" init phase-op "$PHASE_NUM")
51
+ PHASE_DIR=$(echo "$PHASE_STATE" | jq -r .phase_dir)
52
+
53
+ if [ "$PHASE_DIR" = "null" ] || [ ! -d "$PHASE_DIR" ]; then
54
+ echo "Fase $PHASE_NUM ainda não foi planejada. Rode /planejar-fase $PHASE_NUM primeiro."
55
+ exit 1
56
+ fi
57
+
58
+ # PT-BR: descobrir PLAN.md(s) — exclui já-instrumentados
59
+ if [ -n "$PLAN_NUM" ]; then
60
+ PLANS=("$PHASE_DIR"/*-PLAN-${PLAN_NUM}-*.md)
61
+ else
62
+ PLANS=("$PHASE_DIR"/*-PLAN-*.md)
63
+ fi
64
+ ```
65
+
66
+ ## 3. Para cada plano, gerar INSTRUMENTATION.md
67
+
68
+ Para cada `PLAN_FILE`:
69
+
70
+ ```bash
71
+ PADDED=$(basename "$PLAN_FILE" | grep -oE '^[0-9]+')
72
+ NN=$(basename "$PLAN_FILE" | grep -oE 'PLAN-[0-9]+' | grep -oE '[0-9]+')
73
+ OUT_FILE="$PHASE_DIR/${PADDED}-PLAN-${NN}-INSTRUMENTATION.md"
74
+
75
+ # PT-BR: não sobrescrever se já existe
76
+ if [ -f "$OUT_FILE" ]; then
77
+ echo "Já existe: $OUT_FILE — pulando"
78
+ continue
79
+ fi
80
+ ```
81
+
82
+ Ler `PLAN_FILE` para extrair:
83
+ - Goal/objetivo
84
+ - Tarefas (especialmente as que adicionam novos handlers/funções/endpoints)
85
+ - Componentes/serviços tocados
86
+
87
+ Gerar `INSTRUMENTATION.md` com seções canônicas (consultar [`observability-driven-development`](../skills/observability-driven-development/SKILL.md)):
88
+
89
+ ```markdown
90
+ ---
91
+ phase: {N}
92
+ plan: {NN}
93
+ title: Instrumentation Plan for Plan {NN}
94
+ status: pending
95
+ ---
96
+
97
+ # Instrumentation Plan — Phase {N}, Plan {NN}: {plan_title}
98
+
99
+ ## Spans
100
+
101
+ Spans a adicionar em arquivos modificados/criados pelo plano.
102
+
103
+ | Name | Kind | Service | Atributos canônicos | Notas |
104
+ |------|------|---------|---------------------|-------|
105
+ | `{handler_name}` | SERVER | `{service}` | `user.id`, `tenant_id`, `request.id`, `endpoint`, `http.method`, `result.success`, `error.type`, `build_id` | inbound HTTP |
106
+
107
+ ## Eventos críticos
108
+
109
+ Eventos com semantic significance que merecem `result.success` discreto.
110
+
111
+ | Event | Quando emitir | result.success | error.type enum (catch) |
112
+ |-------|---------------|----------------|--------------------------|
113
+ | `{event_name}` | {momento} | true se {happy path} | `validation` \| `auth` \| `rate_limit` \| `timeout` \| `unknown` |
114
+
115
+ ## Métricas (opcional, se há valores numéricos críticos)
116
+
117
+ | Name | Type | Unit | Labels |
118
+ |------|------|------|--------|
119
+ | `{metric_name}` | counter \| histogram | `ms` \| `bytes` \| `count` | `tenant_id`, `endpoint` |
120
+
121
+ ## Validação ODD — 4 perguntas pré-PR
122
+
123
+ | # | Pergunta | Como verificar |
124
+ |---|----------|----------------|
125
+ | 1 | **Faz o que esperei?** | Span tem `result.success = true` no happy path. Smoke: enviar request, query `WHERE result_success = true` retorna |
126
+ | 2 | **Compara à versão anterior?** | `build_id` setado em todo span. Query: `SELECT build_id, ..., AVG(duration_ms) GROUP BY build_id` |
127
+ | 3 | **Usuários estão usando?** | `user.id` ou `tenant_id` ou `customer.tier` em todo span. Query: `SELECT customer.tier, COUNT(*) GROUP BY 1` |
128
+ | 4 | **Anomalias emergem?** | Cada `catch` emite `error.type` enum (não message livre). Cada if/else significativo emite `branch_taken`. Query: `SELECT error.type, COUNT(*) GROUP BY 1` |
129
+
130
+ ## Sampling (head-based, default)
131
+
132
+ ```ts
133
+ // PT-BR: errors sempre, success sample 10% — ajuste conforme volume
134
+ const shouldSample = (event: SpanLike): boolean => {
135
+ if (event.attributes['result.success'] === false) return true // 100% errors
136
+ if (event.attributes['customer.tier'] === 'enterprise') return true // 100% enterprise
137
+ return Math.random() < 0.1 // 10% baseline
138
+ }
139
+ ```
140
+
141
+ ## Referências cruzadas
142
+
143
+ - Skill [`structured-events`](../../../../kit/skills/structured-events/SKILL.md) — campos canônicos
144
+ - Skill [`distributed-tracing`](../../../../kit/skills/distributed-tracing/SKILL.md) — propagação cross-service
145
+ - Skill [`opentelemetry-standard`](../../../../kit/skills/opentelemetry-standard/SKILL.md) — SDK setup
146
+ - Skill [`observability-driven-development`](../../../../kit/skills/observability-driven-development/SKILL.md) — 4 perguntas
147
+ - Agente [`observability-instrumenter`](../../../../kit/agents/observability-instrumenter.md) — gera os patches durante `/executar-fase`
148
+
149
+ ## Aceitação
150
+
151
+ - [ ] Cada handler do plano tem span com 8 atributos canônicos mínimos
152
+ - [ ] Cada `catch` emite `error.type` enum
153
+ - [ ] Cada branch significativo emite `branch_taken`
154
+ - [ ] Outbound calls propagam contexto via `propagation.inject`
155
+ - [ ] Smoke: 100 requests sintéticos → spans queryables com filtragem por `tenant_id`/`user.id`
156
+ ```
157
+
158
+ ## 4. Plan-checker hook
159
+
160
+ Se `plan-checker` está ativo no fluxo, este comando atualiza checkpoint do plan-checker:
161
+
162
+ ```bash
163
+ # PT-BR: registrar que plano agora tem ODD-spec acoplada
164
+ echo "instrumentation:$NN:ready" >> "$PHASE_DIR/.plan-checker-state"
165
+ ```
166
+
167
+ ## 5. Output
168
+
169
+ ```
170
+ ═══════════════════════════════════════════════════════════
171
+ framework ► INSTRUMENTAR-FASE ▸ Phase {N}
172
+ ═══════════════════════════════════════════════════════════
173
+
174
+ Planos processados: {count}
175
+ INSTRUMENTATION.md gerados:
176
+ - {padded}-PLAN-01-INSTRUMENTATION.md
177
+ - {padded}-PLAN-02-INSTRUMENTATION.md
178
+ ...
179
+
180
+ Próximo passo:
181
+ - `/executar-fase {N}` — executor invocará observability-instrumenter automaticamente para aplicar os spans descritos
182
+ - `/auditar-uat` antes do PR — valida que as 4 perguntas ODD têm resposta executável
183
+ ```
184
+
185
+ ## 6. Commit
186
+
187
+ ```bash
188
+ node "./.claude/framework/bin/tools.cjs" commit "docs(${PHASE_NUM}): instrumentation plans" --files "${PHASE_DIR}"/*-INSTRUMENTATION.md
189
+ ```
190
+
191
+ </process>
192
+
193
+ <success_criteria>
194
+ - [ ] Para cada `PLAN-NN-*.md` da fase, existe `PLAN-NN-INSTRUMENTATION.md`
195
+ - [ ] INSTRUMENTATION.md tem 4 seções: Spans, Eventos críticos, Métricas, Validação ODD
196
+ - [ ] Validação ODD com 4 perguntas explicitamente respondidas
197
+ - [ ] Cross-references para skills `structured-events`, `distributed-tracing`, `opentelemetry-standard`, `observability-driven-development`
198
+ - [ ] Não sobrescreve INSTRUMENTATION.md já existente (idempotente)
199
+ - [ ] Commit atômico após geração
200
+ </success_criteria>
@@ -0,0 +1,162 @@
1
+ ---
2
+ name: investigar-producao
3
+ description: Lança Core Analysis Loop guiado em incidente real — agente incident-investigator usa MCP Supabase, mantém estado em .planning/investigations/, retoma entre resets de contexto.
4
+ argument-hint: "<sintoma em texto livre> [--id <investigation_id>]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+
15
+ <objective>
16
+ Lança o agente [`incident-investigator`](../agents/incident-investigator.md) para aplicar o [Core Analysis Loop](../skills/core-analysis-loop/SKILL.md) sobre um incidente. Estado iterativo de hipóteses fica em `.planning/investigations/<id>.md` — permite retomar entre resets de contexto (precedente: `/depurar`).
17
+
18
+ **Cria/Atualiza:**
19
+ - `.planning/investigations/<investigation_id>.md` — trilha de hipóteses validadas/refutadas
20
+
21
+ **Após:** root cause documentado + action items + estado salvo para próxima sessão.
22
+ </objective>
23
+
24
+ <context>
25
+ **Argumentos:** `$ARGUMENTS` — texto livre do sintoma + flags opcionais.
26
+
27
+ **Flags:**
28
+ - `--id <investigation_id>` — retoma investigação existente (pula criação de novo arquivo)
29
+ - `--time-window <Nh|Nd>` — janela de busca (default: 1h)
30
+
31
+ **Exemplos:**
32
+ ```
33
+ /investigar-producao "checkout SLO burn rate = 8 às 14:32"
34
+ /investigar-producao --id incident-2026-05-06-1432-checkout-burn # retomar
35
+ /investigar-producao "tenant acme reportou erros 5xx" --time-window 6h
36
+ ```
37
+
38
+ **Pré-requisito (Full mode):** projeto Supabase configurado, `mcp__supabase__*` disponível.
39
+ </context>
40
+
41
+ <process>
42
+
43
+ ## 1. Parsear argumentos
44
+
45
+ ```bash
46
+ INV_ID=$(echo "$ARGUMENTS" | grep -oE -- '--id [^ ]+' | awk '{print $2}')
47
+ TIME_WINDOW=$(echo "$ARGUMENTS" | grep -oE -- '--time-window [^ ]+' | awk '{print $2}')
48
+ SYMPTOM=$(echo "$ARGUMENTS" | sed -E 's/--(id|time-window) [^ ]+//g' | xargs)
49
+
50
+ [ -z "$TIME_WINDOW" ] && TIME_WINDOW="1h"
51
+ ```
52
+
53
+ ## 2. Validar pré-requisitos
54
+
55
+ ```bash
56
+ mkdir -p .planning/investigations
57
+
58
+ # PT-BR: se --id fornecido, validar arquivo existe
59
+ if [ -n "$INV_ID" ]; then
60
+ INV_FILE=".planning/investigations/${INV_ID}.md"
61
+ if [ ! -f "$INV_FILE" ]; then
62
+ echo "Investigation $INV_ID não existe. Liste com: ls .planning/investigations/"
63
+ exit 1
64
+ fi
65
+ echo "Retomando investigação: $INV_ID"
66
+ fi
67
+
68
+ # PT-BR: se SYMPTOM vazio + sem --id → erro
69
+ if [ -z "$SYMPTOM" ] && [ -z "$INV_ID" ]; then
70
+ echo "Erro: forneça sintoma OU --id <investigation_id>"
71
+ echo "Exemplos:"
72
+ echo " /investigar-producao \"checkout SLO burn rate = 8\""
73
+ echo " /investigar-producao --id incident-2026-05-06-1432-foo"
74
+ exit 1
75
+ fi
76
+ ```
77
+
78
+ ## 3. Detectar `supabase/config.toml`
79
+
80
+ ```bash
81
+ PROJECT_ID=""
82
+ if [ -f supabase/config.toml ]; then
83
+ PROJECT_ID=$(grep -E '^project_id\s*=' supabase/config.toml | sed 's/.*= *"\(.*\)".*/\1/' | head -1)
84
+ fi
85
+ ```
86
+
87
+ ## 4. Listar investigações em aberto (UX)
88
+
89
+ Antes de lançar agente, mostrar contexto de investigações ativas:
90
+
91
+ ```bash
92
+ ls -t .planning/investigations/*.md 2>/dev/null | head -5 | while read f; do
93
+ ID=$(basename "$f" .md)
94
+ STARTED=$(grep '**Started:**' "$f" | head -1 | sed 's/.*Started:\*\* //')
95
+ STATUS=$(grep -E '^## (Root Cause|Status:)' "$f" | head -1)
96
+ printf " %s — %s — %s\n" "$ID" "$STARTED" "$STATUS"
97
+ done
98
+ ```
99
+
100
+ ## 5. Dispatch para `incident-investigator`
101
+
102
+ ```text
103
+ Task(
104
+ subagent_type="incident-investigator",
105
+ prompt="
106
+ ${SYMPTOM:-(retomando $INV_ID)}
107
+
108
+ ${INV_ID:+investigation_id: $INV_ID}
109
+ ${PROJECT_ID:+project_id: $PROJECT_ID}
110
+ time_window: ${TIME_WINDOW}
111
+
112
+ Aplicar Core Analysis Loop até root cause OU lacuna intransponível.
113
+ Salvar estado iterativo em .planning/investigations/{id}.md.
114
+ Documentar todas as hipóteses (validated/refuted/inconclusive) com query + resultado citado.
115
+ "
116
+ )
117
+ ```
118
+
119
+ ## 6. Após retorno do agente
120
+
121
+ Apresentar resumo curto + caminho do arquivo de estado:
122
+
123
+ ```
124
+ ═══════════════════════════════════════════════════════════
125
+ framework ► INVESTIGAR-PRODUCAO ▸ ${INV_ID}
126
+ ═══════════════════════════════════════════════════════════
127
+
128
+ [output do agente — ver agente incident-investigator Step 7]
129
+
130
+ ## Estado salvo
131
+ .planning/investigations/${INV_ID}.md
132
+
133
+ ## Próximos passos
134
+ - Action items listados no Root Cause acima
135
+ - Para abrir loop separado (ex.: "por que tenant acelerou?"):
136
+ /investigar-producao "<novo sintoma>"
137
+ - Para retomar mais tarde:
138
+ /investigar-producao --id ${INV_ID}
139
+ ```
140
+
141
+ ## 7. Pause AskUserQuestion (opcional)
142
+
143
+ Se agente reportou status `INCONCLUSIVE` ou `gaps_found`, perguntar via AskUserQuestion:
144
+
145
+ - header: "Próximo?"
146
+ - question: "Investigation incompleta. O que fazer?"
147
+ - options:
148
+ - "Continuar com hipótese específica" — pede texto livre da hipótese
149
+ - "Pausar — retomar depois" — sai mantendo state
150
+ - "Fechar como inconclusiva" — marca arquivo como `## Status: INCONCLUSIVE` e sai
151
+
152
+ </process>
153
+
154
+ <success_criteria>
155
+ - [ ] Sintoma + investigation_id (novo ou existente) parseados corretamente
156
+ - [ ] Arquivo `.planning/investigations/<id>.md` criado/atualizado
157
+ - [ ] `mcp__supabase__*` invocados em ≥ 1 hipótese (Full mode); ou modo offline declarado
158
+ - [ ] Cada hipótese documentada com Query + Resultado citado
159
+ - [ ] Root cause tem 4 dimensões (WHO/WHERE/WHEN/WHAT) OU status INCONCLUSIVE explícito
160
+ - [ ] Action items concretos listados
161
+ - [ ] Estado retomável: `/investigar-producao --id <id>` recarrega trilha
162
+ </success_criteria>
@@ -0,0 +1,116 @@
1
+ ---
2
+ name: observabilidade
3
+ description: Orquestrador da Suíte Observabilidade — dispatch para agents (instrumenter, investigator, slo-engineer, burn-rate-forecaster, omm-auditor) com sinônimos PT/EN.
4
+ argument-hint: "<subcomando> [args...]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+
15
+ <objective>
16
+ Orquestrador único da Suíte Observabilidade (v1.9). Recebe subcomando e args, faz dispatch via `Task(subagent_type=...)` para o agent especializado correto. **Único ponto de chain de agents observability** (precedente: `/supabase` em v1.8 — anti-pitfall A10 mantido).
17
+
18
+ **Cria/Atualiza:** o que cada agent invocado cria.
19
+
20
+ **Após:** o usuário tem o output do agent (patches, SLO.md, snapshot OMM, investigation trail, etc.).
21
+ </objective>
22
+
23
+ <execution_context>
24
+ Skills consultadas pelos agents: `kit/skills/_shared-observability/glossary.md` (Phase 29) + `kit/skills/observability-*/SKILL.md` + `kit/skills/structured-events/SKILL.md` + `kit/skills/distributed-tracing/SKILL.md` + `kit/skills/opentelemetry-standard/SKILL.md` + `kit/skills/core-analysis-loop/SKILL.md` + `kit/skills/event-based-slos/SKILL.md` + `kit/skills/burn-rate-alerting/SKILL.md` + `kit/skills/telemetry-sampling/SKILL.md` + `kit/skills/telemetry-pipelines/SKILL.md`.
25
+
26
+ Agents disponíveis: `kit/agents/observability-instrumenter.md` (Phase 30), `kit/agents/incident-investigator.md` (Phase 30), `kit/agents/slo-engineer.md` (Phase 32), `kit/agents/burn-rate-forecaster.md` (Phase 32), `kit/agents/omm-auditor.md` (Phase 34).
27
+ </execution_context>
28
+
29
+ <context>
30
+ **Argumentos:** `$ARGUMENTS` — primeiro token é o subcomando; restante é passado para o agent como prompt.
31
+
32
+ **Subcomandos suportados (sinônimos PT-BR/EN):**
33
+
34
+ | Subcomando | Sinônimos | Agent dispatched |
35
+ |---|---|---|
36
+ | `instrumentar` | `instrument`, `inst` | `observability-instrumenter` |
37
+ | `investigar` | `investigate`, `incident` | `incident-investigator` |
38
+ | `slo` | `definir-slo`, `slo-engineer` | `slo-engineer` |
39
+ | `burn-rate` | `burn`, `burn-rate-forecaster`, `forecast` | `burn-rate-forecaster` |
40
+ | `omm` | `auditar`, `audit`, `maturity` | `omm-auditor` |
41
+ | `help` | `ajuda`, `?` | exibe esta tabela inline |
42
+ </context>
43
+
44
+ <process>
45
+
46
+ ## 1. Parsear subcomando
47
+
48
+ ```bash
49
+ SUBCMD=$(echo "$ARGUMENTS" | awk '{print $1}')
50
+ ARGS=$(echo "$ARGUMENTS" | cut -d' ' -f2-)
51
+ ```
52
+
53
+ **Se `$ARGUMENTS` for vazio ou `SUBCMD` for `help`/`ajuda`/`?`:** exibir tabela de subcomandos inline + exemplo. Sair.
54
+
55
+ ## 2. Resolver sinônimos
56
+
57
+ ```text
58
+ instrumentar, instrument, inst → observability-instrumenter
59
+ investigar, investigate, incident → incident-investigator
60
+ slo, definir-slo, slo-engineer → slo-engineer
61
+ burn-rate, burn, burn-rate-forecaster, forecast → burn-rate-forecaster
62
+ omm, auditar, audit, maturity → omm-auditor
63
+ ```
64
+
65
+ **Se subcomando não resolve:** exibir erro inline com lista de subcomandos válidos. Sair.
66
+
67
+ ```
68
+ ✗ Subcomando desconhecido: '<SUBCMD>'
69
+
70
+ Subcomandos válidos:
71
+ instrumentar / instrument → instrumentar código com OTel + atributos canônicos
72
+ investigar / investigate → Core Analysis Loop em incident
73
+ slo / definir-slo → criar SLO.md + SQL materializar SLI
74
+ burn-rate / forecast → calcular burn rate atual + ETA exhaustão
75
+ omm / auditar → OMM scored 5 capacidades
76
+
77
+ Uso: /observabilidade <subcomando> <args...>
78
+ Exemplo: /observabilidade investigar "checkout SLO burn rate = 8 às 14:32"
79
+ ```
80
+
81
+ ## 3. Detectar `supabase/config.toml` (para agents que usam MCP Supabase)
82
+
83
+ ```bash
84
+ PROJECT_ID=""
85
+ if [ -f supabase/config.toml ]; then
86
+ PROJECT_ID=$(grep -E '^project_id\s*=' supabase/config.toml | sed 's/.*= *"\(.*\)".*/\1/' | head -1)
87
+ fi
88
+ ```
89
+
90
+ ## 4. Dispatch
91
+
92
+ Invocar `Task(subagent_type=<agent_name>, prompt=<built_prompt>)`.
93
+
94
+ **Prompt construído:**
95
+
96
+ ```
97
+ {ARGS}
98
+
99
+ {Se project_id detectado:}
100
+ project_id: {PROJECT_ID}
101
+ ```
102
+
103
+ ## 5. Output
104
+
105
+ Output do agent é o output do command. Sem post-processing — agent já formata estruturado.
106
+
107
+ </process>
108
+
109
+ <success_criteria>
110
+ - [ ] Subcomando resolvido para agent canônico (5 subcomandos × seus sinônimos)
111
+ - [ ] `project_id` extraído de `supabase/config.toml` se presente
112
+ - [ ] Dispatch via `Task(subagent_type=...)` — único ponto de chain
113
+ - [ ] Subcomando inválido → mensagem clara com lista
114
+ - [ ] Subcomando `help`/`ajuda`/`?` → exibe tabela inline
115
+ - [ ] Args após subcomando passam transparentemente para o agent
116
+ </success_criteria>
@@ -45,3 +45,23 @@ Normalizar entrada da fase no passo 2 antes de qualquer pesquisa de diretório.
45
45
  Execute o workflow plan-phase de @./.claude/framework/workflows/plan-phase.md do início ao fim.
46
46
  Preserve todos os checkpoints do workflow (validação, pesquisa, planejamento, loop de verificação, roteamento).
47
47
  </process>
48
+
49
+ <observability_integration>
50
+ **Integração com ODD plan-checker gate (v1.9):**
51
+
52
+ Quando `workflow.observability_plan_gate = true` (default para fases voltadas ao usuário), o `plan-checker` invocado neste workflow inclui uma checagem extra:
53
+
54
+ 1. Lê `<observability>` section do CONTEXT.md (criado por `/discutir-fase` ou `/instrumentar-fase`)
55
+ 2. Verifica que as 4 perguntas pré-PR estão respondidas (consulta skill [`observability-driven-development`](../skills/observability-driven-development/SKILL.md)):
56
+ - Faz o que esperei? → INSTRUMENTATION.md tem `result.success` documentado?
57
+ - Compara à versão anterior? → `build_id` em todo span planejado?
58
+ - Usuários estão usando? → identidade (`user.id`/`tenant_id`/`customer.tier`) presente?
59
+ - Anomalias emergem? → `error.type` enum + `branch_taken` planejados?
60
+ 3. Se alguma pergunta ausente: VERIFICATION.md status = `gaps_found`, sugerindo invocar `/instrumentar-fase` para gerar INSTRUMENTATION.md.
61
+
62
+ **Fases de infraestrutura pura** (skip discuss already detectou): pula gate silenciosamente.
63
+
64
+ **Quando há observability gate enabled e gap encontrado:** o user pode (a) `/instrumentar-fase` antes de prosseguir; ou (b) editar manualmente CONTEXT.md `<observability>` section; ou (c) override via `--skip-observability-gate`.
65
+
66
+ **REQ:** INT-FW-02.
67
+ </observability_integration>
@@ -0,0 +1,179 @@
1
+ ---
2
+ name: postmortem
3
+ description: Invoca postmortem-writer — modo --from-investigation <id> (lê v1.9 trail) ou --incident "<descrição>" standalone; produz postmortem blameless 9 seções.
4
+ argument-hint: "(--from-investigation <id> | --incident \"<descrição>\") [--severity SEV1|SEV2|SEV3]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+
15
+ <objective>
16
+ Gerar **postmortem blameless** de 9 seções (cap 15 do livro Google SRE) — Summary, Impact, Root Causes, Trigger, Resolution, Detection, Action Items, Lessons Learned, Timeline UTC. Invoca o agente [`postmortem-writer`](../agents/postmortem-writer.md) que aplica a skill [`blameless-postmortems`](../skills/blameless-postmortems/SKILL.md) — cultura blameless ("foco em sistema/processo, NÃO em pessoas"), action items SMART, "no postmortem left unreviewed".
17
+
18
+ **Cria/Atualiza:**
19
+ - `.planning/postmortems/<id>.md` — postmortem blameless completo
20
+
21
+ **Após:** o user tem postmortem revisável + action items concretos. Phase 40 INT-FW-V2-01 chained do `/forense` automaticamente após Core Analysis Loop fechar.
22
+ </objective>
23
+
24
+ <context>
25
+ **Argumentos:** `$ARGUMENTS` — comando suporta **2 modos mutuamente exclusivos**.
26
+
27
+ **Modo A: `--from-investigation <id>` (preferido — continuação de v1.9)**
28
+
29
+ Lê `.planning/investigations/<id>.md` produzido pelo [`incident-investigator`](../agents/incident-investigator.md) (v1.9 — Core Analysis Loop). Extrai automaticamente: trigger, root cause, hipóteses validadas, action items. Campos faltantes (impact quantificado, severity, autores) são perguntados via `AskUserQuestion`.
30
+
31
+ **Modo B: `--incident "<descrição>"` (standalone)**
32
+
33
+ Para postmortem sem investigation prévia (incident menor, near-miss, lições retrospectivas). Agent gera template e usa `AskUserQuestion` para 9 perguntas guiadas — uma por seção canônica.
34
+
35
+ **Flags adicionais:**
36
+ - `--severity <SEV1|SEV2|SEV3>` — severity do incident (default: AskUserQuestion)
37
+ - `--output <path>` — caminho do postmortem (default: `.planning/postmortems/<id>.md` — id auto-gerado)
38
+
39
+ **Exemplos:**
40
+ ```
41
+ /postmortem --from-investigation incident-2026-05-06-1432-checkout-burn # Modo A
42
+ /postmortem --incident "checkout SLO burn às 14:32 — RCA N+1 query orders" --severity SEV2 # Modo B
43
+ /postmortem --incident "near-miss: deploy bloqueou 2min antes do PR-1234" # near-miss
44
+ ```
45
+
46
+ **Pré-requisito (Modo A):** arquivo `.planning/investigations/<id>.md` existe (criado por `/investigar-producao` ou `/forense`).
47
+ </context>
48
+
49
+ <process>
50
+
51
+ ## 1. Parsear argumentos (2 modos)
52
+
53
+ ```bash
54
+ INV_ID=$(echo "$ARGUMENTS" | grep -oE -- '--from-investigation [^ ]+' | awk '{print $2}')
55
+ INCIDENT=$(echo "$ARGUMENTS" | grep -oE -- '--incident "[^"]+"' | sed 's/--incident //; s/^"//; s/"$//')
56
+ SEVERITY=$(echo "$ARGUMENTS" | grep -oE -- '--severity [^ ]+' | awk '{print $2}')
57
+ OUTPUT_PATH=$(echo "$ARGUMENTS" | grep -oE -- '--output [^ ]+' | awk '{print $2}')
58
+
59
+ # PT-BR: validar mutuamente exclusivos
60
+ if [ -n "$INV_ID" ] && [ -n "$INCIDENT" ]; then
61
+ echo "✗ Erro: --from-investigation e --incident são mutuamente exclusivos. Escolha um."
62
+ exit 1
63
+ fi
64
+
65
+ # PT-BR: se nenhum dos 2 → AskUserQuestion (Modo C — interativo)
66
+ if [ -z "$INV_ID" ] && [ -z "$INCIDENT" ]; then
67
+ # Listar investigations recentes para sugestão
68
+ RECENT_INVS=$(ls -t .planning/investigations/*.md 2>/dev/null | head -5 | while read f; do basename "$f" .md; done | tr '\n' ',')
69
+ # AskUserQuestion: "Modo? Continuar de investigation existente OU postmortem standalone?"
70
+ # Opções: Continuar de <ID> (uma por investigation recente) | Standalone (texto livre)
71
+ echo "ℹ Sem flag explícita. Use --from-investigation <id> ou --incident \"<descrição>\"."
72
+ [ -n "$RECENT_INVS" ] && echo " Investigations recentes: $RECENT_INVS"
73
+ exit 1
74
+ fi
75
+ ```
76
+
77
+ ## 2. Validar pré-requisitos por modo
78
+
79
+ ```bash
80
+ mkdir -p .planning/postmortems
81
+
82
+ # PT-BR: Modo A — investigation file precisa existir
83
+ if [ -n "$INV_ID" ]; then
84
+ INV_FILE=".planning/investigations/${INV_ID}.md"
85
+ if [ ! -f "$INV_FILE" ]; then
86
+ echo "✗ Investigation $INV_ID não existe. Liste com: ls .planning/investigations/"
87
+ echo " Para postmortem standalone: /postmortem --incident \"<descrição>\""
88
+ exit 1
89
+ fi
90
+ # PT-BR: derivar postmortem id do investigation_id
91
+ POSTMORTEM_ID="$INV_ID"
92
+ fi
93
+
94
+ # PT-BR: Modo B — gerar postmortem id automaticamente
95
+ if [ -n "$INCIDENT" ]; then
96
+ DATE=$(date -u +%Y-%m-%d-%H%M)
97
+ SLUG=$(echo "$INCIDENT" | tr ' ' '-' | tr -cd 'a-zA-Z0-9-' | head -c 30 | sed 's/-$//')
98
+ POSTMORTEM_ID="postmortem-${DATE}-${SLUG}"
99
+ fi
100
+
101
+ # PT-BR: default output_path (override via --output)
102
+ [ -z "$OUTPUT_PATH" ] && OUTPUT_PATH=".planning/postmortems/${POSTMORTEM_ID}.md"
103
+
104
+ # PT-BR: idempotência — não sobrescrever postmortem existente sem confirmar
105
+ if [ -f "$OUTPUT_PATH" ]; then
106
+ echo "⚠ Postmortem $OUTPUT_PATH já existe."
107
+ echo " Use --output <novo-path> ou rm $OUTPUT_PATH antes de re-rodar."
108
+ exit 1
109
+ fi
110
+ ```
111
+
112
+ ## 3. Listar postmortems recentes (UX)
113
+
114
+ ```bash
115
+ # PT-BR: contexto — postmortems anteriores para correlacionar lessons learned
116
+ ls -t .planning/postmortems/*.md 2>/dev/null | head -3 | while read f; do
117
+ ID=$(basename "$f" .md)
118
+ DATE=$(grep -m1 '\*\*Date:\*\*' "$f" 2>/dev/null | sed 's/.*Date:\*\* //' || echo "?")
119
+ printf " %s — %s\n" "$ID" "$DATE"
120
+ done
121
+ ```
122
+
123
+ ## 4. Dispatch para `postmortem-writer`
124
+
125
+ ```text
126
+ Task(
127
+ subagent_type="postmortem-writer",
128
+ prompt="
129
+ ${INV_ID:+investigation_id: ${INV_ID}}
130
+ ${INCIDENT:+incident_description: ${INCIDENT}}
131
+ ${SEVERITY:+severity: ${SEVERITY}}
132
+ output_path: ${OUTPUT_PATH}
133
+ postmortem_id: ${POSTMORTEM_ID}
134
+
135
+ Aplicar skill blameless-postmortems. Modo:
136
+ ${INV_ID:+- Modo A: ler .planning/investigations/${INV_ID}.md, extrair trigger/root_cause/hipóteses/action_items automaticamente; perguntar via AskUserQuestion apenas campos faltantes (impact quantificado, severity, autores).}
137
+ ${INCIDENT:+- Modo B: gerar template; perguntar via AskUserQuestion 9 questões guiadas — uma por seção canônica (Summary, Impact, Root Causes, Trigger, Resolution, Detection, Action Items, Lessons Learned, Timeline).}
138
+
139
+ Padrões obrigatórios:
140
+ - Foco em sistema/processo (NUNCA em pessoas) — anti-pattern blame culture
141
+ - Action items SMART (Specific, Measurable, Assignable, Realistic, Time-bound)
142
+ - Timeline em UTC sempre
143
+ - Impact quantificado (# usuários, duração, SLO budget consumido, revenue se aplicável)
144
+ - 9 seções canônicas obrigatórias (skip = inválido)
145
+ "
146
+ )
147
+ ```
148
+
149
+ ## 5. Pós-output
150
+
151
+ ```
152
+ ═══════════════════════════════════════════════════════════
153
+ framework ► POSTMORTEM ▸ ${POSTMORTEM_ID}
154
+ ═══════════════════════════════════════════════════════════
155
+
156
+ [output do postmortem-writer — ver Step 6 do agent]
157
+
158
+ ## Estado salvo
159
+ .planning/postmortems/${POSTMORTEM_ID}.md
160
+
161
+ ## Próximos passos
162
+ 1. Revisar o postmortem com o time — "no postmortem left unreviewed"
163
+ 2. Distribuir para reviewer SRE OU par externo (anti-pattern: auto-review)
164
+ 3. Action items entram no roadmap (`/adicionar-tarefa` ou `/adicionar-fase`)
165
+ 4. Se PRR for próximo passo de production-readiness: `/prr --service <name>`
166
+ 5. Cross-ref OMM: postmortems alimentam Capacidade 5 (Incident Response) — `/observabilidade omm`
167
+ ```
168
+
169
+ </process>
170
+
171
+ <success_criteria>
172
+ - [ ] `--from-investigation <id>` E `--incident "<text>"` parseados (mutuamente exclusivos)
173
+ - [ ] Modo A: arquivo `.planning/investigations/<id>.md` validado existe antes de dispatch
174
+ - [ ] Modo B: postmortem_id auto-gerado a partir de date + slug
175
+ - [ ] Idempotência: não sobrescreve postmortem existente sem `--output` explícito
176
+ - [ ] `postmortem-writer` invocado via `Task(subagent_type=...)` com prompt completo (modo + 9 seções + padrões)
177
+ - [ ] `.planning/postmortems/<id>.md` criado pelo agent
178
+ - [ ] Próximos passos sugerem cross-ref para `/prr`, `/observabilidade omm`, `/adicionar-tarefa`
179
+ </success_criteria>