@luanpdd/kit-mcp 1.9.0 → 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.
@@ -151,4 +151,58 @@ Gate executável: `gates/omm-no-regression.md`.
151
151
  Skill consultada: [`observability-maturity-model`](../skills/observability-maturity-model/SKILL.md).
152
152
 
153
153
  **REQ:** INT-FW-05.
154
- </observability_integration>
154
+ </observability_integration>
155
+
156
+ <sre_integration>
157
+ **PRR gate opcional para features production-bound (v1.10 — INT-FW-V2-02):**
158
+
159
+ Quando `workflow.complete_milestone_prr_gate = true` (default `false` — opt-in até maturidade SRE Engagement do projeto), o workflow inclui passo PRR coverage check **antes de arquivar** o milestone:
160
+
161
+ 1. Listar features production-bound do milestone (heurística: features com Edge Functions deployed, features com SLO definido em `.planning/slos/`, features marcadas explicitamente `production: true` em ROADMAP.md ou em `.planning/phases/<N>-CONTEXT.md`)
162
+ 2. Para cada feature production-bound, procurar `.planning/prr/<feature-id>-PRR-REPORT.md` (cross-ref [prr-conductor](../agents/prr-conductor.md) — agent que produz o relatório scored em 6 axes do cap 32)
163
+ 3. Verificar status do PRR-REPORT.md:
164
+ - Se ausente: BLOQUEAR conclusion — sugerir `/prr --feature "<descrição>"` ou `/sre prr --feature "..."` antes de re-rodar `/concluir-marco`
165
+ - Se presente mas status `failed` (≥ 1 axe P0 reprovado): BLOQUEAR conclusion — listar axes P0 reprovados e exigir remediation
166
+ - Se presente com status `passed`: incluir `PRR-REPORT.md` como anexo no `.planning/milestones/v<version>-MILESTONE.md` (audit trail)
167
+ 4. Quando todos os PRRs de features production-bound forem `passed`: prosseguir para passo 7 (commit + tag) do workflow `complete-milestone.md`
168
+
169
+ **Distinção `passed` vs `failed`:**
170
+
171
+ | Status | Definição | Resultado em /concluir-marco |
172
+ |---|---|---|
173
+ | `passed` | Todos os 6 axes scored ≥ 3/5 (cap 32 — System Architecture / Instrumentation / Emergency Response / Capacity Planning / Change Management / Performance) | Milestone arquivável (gate aprova) |
174
+ | `passed-with-warnings` | 6/6 axes ≥ 3/5 mas ≥ 1 axe com action items P1 não resolvidos | Milestone arquivável; warnings explícitos no archive |
175
+ | `failed` | ≥ 1 axe < 3/5 OU ≥ 1 action item P0 não resolvido | Gate BLOQUEIA — exige remediation antes de arquivar |
176
+
177
+ **Default `false` por design:**
178
+
179
+ `workflow.complete_milestone_prr_gate` default `false` (≠ `complete_milestone_omm_gate` que é `true`) — PRR Engagement Model do livro Google SRE assume **maturidade organizacional** (SRE team, on-call rotation, incident response). Para projetos em early stage / dogfooding, gate `false` é o correto. Quando o projeto atinge tier-1 (production-user-facing, paid tier, SLA contratual), user explicitamente liga setando `workflow.complete_milestone_prr_gate=true` no config.
180
+
181
+ **Quando ligar gate:**
182
+
183
+ - Projeto tem feature user-facing pagante (≥ 1 jornada crítica monetizada)
184
+ - Projeto tem SLO definido em `.planning/slos/` com error budget tracking
185
+ - Projeto tem on-call rotation documentada em runbook
186
+ - Projeto tem postmortem culture estabelecida (≥ 1 postmortem blameless escrito em `.planning/postmortems/`)
187
+ - **Pelo menos 2 dos 4 acima** = liga gate (sinal de production maturity)
188
+
189
+ **Quando manter gate desligado:**
190
+
191
+ - Projeto early stage / dogfooding interno (sem usuário pagante)
192
+ - Solo developer side project sem on-call
193
+ - Pesquisa / POC / experimento (não production-bound por design)
194
+ - Equipe ainda construindo SRE muscle (PRR vira teatro se não há cultura de remediation)
195
+
196
+ **Skill consultada:** [production-readiness-review](../skills/production-readiness-review/SKILL.md) (cap 32 livro Google SRE — *Evolving SRE Engagement Model* — define os 6 axes + 3 engagement models: Simple, Early Engagement, Frameworks/SRE Platform).
197
+
198
+ **Gate executável:** `gates/prr-checklist-coverage.md` (criado em Phase 41 — QA-SRE-03). Workflow `.claude/framework/workflows/complete-milestone.md` consulta esse gate quando flag `true`.
199
+
200
+ **Anti-patterns prevenidos:**
201
+
202
+ - "Marcar feature como production-bound mas pular PRR" → gate exige PRR-REPORT.md presente
203
+ - "PRR-REPORT.md gerado mas status `failed`" → gate exige `passed` (não basta existir)
204
+ - "Auto-PRR pelo time dev" → cross-ref [prr-conductor](../agents/prr-conductor.md) reforça que `prr-conductor` agent é par externo (não o mesmo agent que escreveu a feature)
205
+ - "Gate ligado em projeto early stage" → bloco "Quando ligar gate" exige ≥ 2 sinais de production maturity
206
+
207
+ **REQ:** INT-FW-V2-02.
208
+ </sre_integration>
@@ -72,4 +72,67 @@ Cada anomalia detectada vira hipótese com query de validação:
72
72
  **Skill consultada explicitamente:** abrir o arquivo `kit/skills/core-analysis-loop/SKILL.md` para padrão "documentação da trilha (formato canônico)" — o relatório forense em `.planning/forensics/report-<ts>.md` segue esse formato com cada hipótese tendo "Query / Resultado / Status (VALIDATED / REFUTED / INCONCLUSIVE)".
73
73
 
74
74
  **REQ:** INT-FW-06.
75
- </observability_integration>
75
+ </observability_integration>
76
+
77
+ <sre_integration>
78
+ **Chain `/postmortem` após Core Analysis Loop (v1.10 — INT-FW-V2-01):**
79
+
80
+ Forense é diagnóstico evidence-based read-only — identifica o **o que** e o **como** via método científico (sintoma → hipótese → query → status `VALIDATED | REFUTED | INCONCLUSIVE`). Quando o Core Analysis Loop fecha com pelo menos uma hipótese `VALIDATED` apontando para root cause, o próximo passo canônico é **postmortem blameless** (cap 15 livro Google SRE — *Postmortem Culture: Learning from Failure*).
81
+
82
+ Distinção fundamental:
83
+
84
+ | Etapa | Pergunta respondida | Output | Audiência |
85
+ |---|---|---|---|
86
+ | Forense | "O que aconteceu? Onde está a evidência?" | `.planning/forensics/report-<ts>.md` | Investigador (você) |
87
+ | Postmortem | "O que aprendemos? O que mudaremos?" | `.planning/postmortems/<id>.md` | Organização inteira (no postmortem left unreviewed) |
88
+
89
+ Forense **diagnostica**; postmortem **transforma diagnóstico em aprendizado durável**. Pular postmortem = perder aprendizado organizacional (anti-pattern hero culture: "fixei o bug, vamos seguir").
90
+
91
+ **Trigger automático sugerido (não-bloqueante):**
92
+
93
+ Quando o relatório forense conclui com:
94
+ - ≥ 1 hipótese `VALIDATED` apontando root cause acionável, OU
95
+ - Incident impactou usuário (não apenas dev experience), OU
96
+ - Workflow framework crashou em produção (não dogfooding)
97
+
98
+ O comando `/forense` **sugere ao usuário** ao final do relatório:
99
+
100
+ ```text
101
+ Próximo passo recomendado:
102
+ /postmortem --incident "<one-liner derivado do relatório forense>"
103
+ Continua o blameless write-up com Summary + Impact + Root Causes + Action Items.
104
+ Cross-ref canônico: [blameless-postmortems](../skills/blameless-postmortems/SKILL.md) skill + [postmortem-writer](../agents/postmortem-writer.md) agent.
105
+
106
+ Nota: para incidents de produção SRE com investigação completa via /investigar-producao
107
+ (que produz .planning/investigations/<id>.md), use `/postmortem --from-investigation <id>`.
108
+ ```
109
+
110
+ **Chain de fluxo canônico:**
111
+
112
+ ```text
113
+ Falha detectada
114
+
115
+ /forense "<descrição>" ← diagnóstico evidence-based (este comando, output: .planning/forensics/report-<ts>.md)
116
+ ↓ (Core Analysis Loop fecha com VALIDATED)
117
+ /postmortem --incident "<one-liner>" ← blameless write-up (chain sugerido — modo standalone)
118
+
119
+ Action Items P0/P1 viram tarefas em milestone atual ou próximo
120
+
121
+ Wheel of Misfortune: postmortem vira treino de novos engineers (cap 15)
122
+ ```
123
+
124
+ **Distinção `/forense` vs `/investigar-producao`:**
125
+
126
+ - `/forense` — diagnóstico de workflows framework com falha (post-mortem de processo). Output: `.planning/forensics/report-<ts>.md`. Chain: `--incident "<one-liner>"`.
127
+ - `/investigar-producao` (v1.9) — Core Analysis Loop em incident produção SRE com MCP Supabase. Output: `.planning/investigations/<id>.md`. Chain: `--from-investigation <id>`.
128
+
129
+ **Quando NÃO sugerir chain `/postmortem`:**
130
+
131
+ - Forense `INCONCLUSIVE` em todas as hipóteses (root cause não identificada — sugerir nova investigação ao invés)
132
+ - Falha trivial documentada (typo em `.gitignore`) sem impacto a usuário
133
+ - Investigação cancelada pelo user antes do Core Analysis Loop fechar
134
+
135
+ **Cultura blameless é não-negociável:** o postmortem foca em **sistema** (controles ausentes, signals não monitorados, escalation paths frágeis), nunca em **pessoas** ("dev X esqueceu de testar"). Anti-pattern blame culture é explicitamente prevenido pelo template de `postmortem-writer` (cap 15 — *No postmortem left unreviewed*).
136
+
137
+ **REQ:** INT-FW-V2-01.
138
+ </sre_integration>
@@ -0,0 +1,142 @@
1
+ ---
2
+ name: golden-signals
3
+ description: Invoca golden-signals-instrumenter para serviço/Edge Function/fase — instrumenta 4 golden signals OTel (Latency histogram, Traffic counter, Errors counter, Saturation gauge).
4
+ argument-hint: "<target> [--service <name>] [--saturation <resource>] [--runtime <node|deno|python>]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+
15
+ <objective>
16
+ Instrumentar um serviço/Edge Function/fase com os **4 golden signals** do cap 6 do livro Google SRE — Latency (histogram bucketed), Traffic (counter), Errors (counter por `error.type`), Saturation (gauge resource-specific). Invoca o agente [`golden-signals-instrumenter`](../agents/golden-signals-instrumenter.md) que aplica a skill [`four-golden-signals`](../skills/four-golden-signals/SKILL.md).
17
+
18
+ **Cria/Atualiza:**
19
+ - Patches OTel nos arquivos do `<target>` (Latency + Traffic + Errors + Saturation)
20
+ - `GOLDEN-SIGNALS.md` por target com tabela de instrumentação aplicada (output do agent)
21
+
22
+ **Após:** os 4 signals estão instrumentados e o user pode rodar smoke local para verificar histogram/counter/gauge no backend OTel.
23
+ </objective>
24
+
25
+ <context>
26
+ **Argumentos:** `$ARGUMENTS` — primeiro token é o `<target>` (path de arquivo, diretório de service, ou número de fase como `38`); restante são flags.
27
+
28
+ **Flags:**
29
+ - `--service <name>` — nome canônico do serviço (default: deriva de `package.json#name` ou diretório)
30
+ - `--saturation <resource>` — recurso de saturation (`db_connection_pool` | `cache_memory` | `queue_depth` | `concurrency_limit` | `cpu_load` | `egress_bandwidth`); se omitido, agent infere via heurística
31
+ - `--runtime <node|deno|python>` — runtime; se omitido, detecta via `package.json`/`deno.json`/`pyproject.toml`
32
+
33
+ **Exemplos:**
34
+ ```
35
+ /golden-signals src/orders/handler.ts # 1 arquivo
36
+ /golden-signals supabase/functions/process-emails # 1 Edge Function
37
+ /golden-signals 38 # todos os arquivos modificados pela Phase 38
38
+ /golden-signals src/api --service orders-api --saturation db_connection_pool
39
+ ```
40
+
41
+ **Pré-requisito:** OTel SDK pode estar ausente — agent flagga deps necessárias no output. Caller decide instalar.
42
+ </context>
43
+
44
+ <process>
45
+
46
+ ## 1. Parsear argumentos
47
+
48
+ ```bash
49
+ TARGET=$(echo "$ARGUMENTS" | awk '{print $1}')
50
+ SERVICE=$(echo "$ARGUMENTS" | grep -oE -- '--service [^ ]+' | awk '{print $2}')
51
+ SATURATION=$(echo "$ARGUMENTS" | grep -oE -- '--saturation [^ ]+' | awk '{print $2}')
52
+ RUNTIME=$(echo "$ARGUMENTS" | grep -oE -- '--runtime [^ ]+' | awk '{print $2}')
53
+
54
+ if [ -z "$TARGET" ]; then
55
+ echo "Uso: /golden-signals <target> [--service N] [--saturation R] [--runtime RT]"
56
+ echo "Exemplos:"
57
+ echo " /golden-signals src/orders/handler.ts"
58
+ echo " /golden-signals supabase/functions/process-emails"
59
+ echo " /golden-signals 38 # todos arquivos da Phase 38"
60
+ exit 1
61
+ fi
62
+ ```
63
+
64
+ ## 2. Resolver target → lista de target_files
65
+
66
+ ```bash
67
+ # PT-BR: 3 modos de resolução
68
+ if [[ "$TARGET" =~ ^[0-9]+$ ]]; then
69
+ # Modo fase — extrai files_modified de PLAN.md(s) da Phase $TARGET
70
+ PHASE_STATE=$(node "./.claude/framework/bin/tools.cjs" init phase-op "$TARGET")
71
+ PHASE_DIR=$(echo "$PHASE_STATE" | jq -r .phase_dir)
72
+ if [ "$PHASE_DIR" = "null" ] || [ ! -d "$PHASE_DIR" ]; then
73
+ echo "Fase $TARGET ainda não foi planejada."
74
+ exit 1
75
+ fi
76
+ TARGET_FILES=$(grep -rh "^ - " "$PHASE_DIR"/*-PLAN-*.md | grep -oE '[a-zA-Z0-9_/.-]+\.(ts|js|py|deno|sql)' | sort -u | tr '\n' ' ')
77
+ elif [ -d "$TARGET" ]; then
78
+ # Modo diretório — todos arquivos relevantes (.ts, .js, .py)
79
+ TARGET_FILES=$(find "$TARGET" -type f \( -name "*.ts" -o -name "*.js" -o -name "*.py" \) | tr '\n' ' ')
80
+ elif [ -f "$TARGET" ]; then
81
+ # Modo arquivo único
82
+ TARGET_FILES="$TARGET"
83
+ else
84
+ echo "Erro: target '$TARGET' não é arquivo, diretório ou número de fase válido."
85
+ exit 1
86
+ fi
87
+
88
+ if [ -z "$TARGET_FILES" ]; then
89
+ echo "Nenhum arquivo encontrado para target '$TARGET'."
90
+ exit 0
91
+ fi
92
+ ```
93
+
94
+ ## 3. Dispatch para `golden-signals-instrumenter`
95
+
96
+ ```text
97
+ Task(
98
+ subagent_type="golden-signals-instrumenter",
99
+ prompt="
100
+ target_files: ${TARGET_FILES}
101
+ ${SERVICE:+service_name: ${SERVICE}}
102
+ ${RUNTIME:+runtime: ${RUNTIME}}
103
+ ${SATURATION:+saturation_resource: ${SATURATION}}
104
+
105
+ Aplicar skill four-golden-signals. Gerar patches OTel para os 4 signals em cada arquivo:
106
+ 1. Latency: histogram com explicitBucketBoundaries exponencial, dimension result=success|error
107
+ 2. Traffic: counter incrementado antes de processar request
108
+ 3. Errors: counter por error_type enum (5-15 valores; NÃO error.message)
109
+ 4. Saturation: ObservableGauge do recurso mais escasso (callback lê estado real)
110
+
111
+ Validar 6 checks no Step 3 do agent (latency separado success/error, error_type enum, etc.).
112
+ Output: tabela de patches gerados + GOLDEN-SIGNALS.md por target.
113
+ "
114
+ )
115
+ ```
116
+
117
+ ## 4. Pós-output
118
+
119
+ ```
120
+ ═══════════════════════════════════════════════════════════
121
+ framework ► GOLDEN-SIGNALS ▸ ${TARGET}
122
+ ═══════════════════════════════════════════════════════════
123
+
124
+ [output do golden-signals-instrumenter — ver Step 4 do agent]
125
+
126
+ ## Próximos passos
127
+ 1. Smoke local — enviar request e verificar histogram/counter/gauge no backend OTel
128
+ 2. Cross-ref: rodar `/instrumentar-fase ${TARGET}` se spans/wide events ainda ausentes (complementar)
129
+ 3. Após validar baseline, definir SLO event-based: `/observabilidade slo <feature>`
130
+ 4. PRR antes de production: `/prr --service ${SERVICE:-<name>}`
131
+ ```
132
+
133
+ </process>
134
+
135
+ <success_criteria>
136
+ - [ ] `<target>` parseado de $ARGUMENTS (arquivo, diretório, ou número de fase)
137
+ - [ ] `target_files` resolvido para lista não-vazia (3 modos suportados)
138
+ - [ ] `golden-signals-instrumenter` invocado via `Task(subagent_type=...)`
139
+ - [ ] Patches aplicados em todos os arquivos do target (4 signals cada)
140
+ - [ ] Output forwarded transparentemente do agent (sem post-processing)
141
+ - [ ] Próximos passos sugerem cross-ref para `/instrumentar-fase`, `/observabilidade slo`, `/prr`
142
+ </success_criteria>
@@ -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>
@@ -0,0 +1,205 @@
1
+ ---
2
+ name: prr
3
+ description: Invoca prr-conductor — Production Readiness Review scored em 6 axes (cap 32); modos --service <name> ou --feature <desc>; offline fallback se MCP ausente.
4
+ argument-hint: "(--service <name> | --feature \"<desc>\") [--engagement simple|early|platform] [--reviewer @sre]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ - AskUserQuestion
13
+ ---
14
+
15
+ <objective>
16
+ Conduzir **Production Readiness Review** (PRR — cap 32 do livro Google SRE) para serviço/feature antes de production. Invoca o agente [`prr-conductor`](../agents/prr-conductor.md) que aplica a skill [`production-readiness-review`](../skills/production-readiness-review/SKILL.md) — checklist canônico **6 axes** + **3 engagement models** + handoff dev→SRE.
17
+
18
+ **6 axes obrigatórios** (pular um = aprovação inválida):
19
+ 1. System Architecture — design, dependencies, blast radius, isolation
20
+ 2. Instrumentation/Metrics/Monitoring — 4 golden signals, SLOs, alerting
21
+ 3. Emergency Response — runbooks, on-call, rollback, communication
22
+ 4. Capacity Planning — load testing, scaling, headroom
23
+ 5. Change Management — canary, feature flags, rollback < 60s
24
+ 6. Performance — latency budgets, throughput, optimization
25
+
26
+ **Cria/Atualiza:**
27
+ - `.planning/prr/<service>.md` (Modo A) OR `.planning/prr/feature-<slug>.md` (Modo B) — PRR-REPORT.md scored
28
+
29
+ **Após:** o user tem decisão `Approved` / `Approved with conditions` / `Blocked` + lista canônica de P0 items por axe + reviewer signature. Phase 40 INT-FW-V2-02 integra `/concluir-marco` com gate PRR opcional.
30
+ </objective>
31
+
32
+ <context>
33
+ **Argumentos:** `$ARGUMENTS` — comando suporta **2 modos mutuamente exclusivos**.
34
+
35
+ **Modo A: `--service <name>` (audit de serviço existente)**
36
+
37
+ Para serviços já em production OU prestes a entrar — agent lê schema (Supabase MCP), Edge Functions code, SLOs definidos (`.planning/slos/`), advisors. Output: `.planning/prr/<service>.md`.
38
+
39
+ **Modo B: `--feature <description>` (audit pré-launch)**
40
+
41
+ Para feature em design/dev — agent lê design docs, SLOs propostos, código WIP. Output: `.planning/prr/feature-<slug>.md`.
42
+
43
+ **Engagement models (cap 32):**
44
+ - `simple` — outage cost < $1k/min OR internal tool — 4-8h, 1 sessão
45
+ - `early` — outage cost $1k-100k/min OR customer-facing — semanas, SRE no design
46
+ - `platform` — outage cost > $100k/min OR built on Frameworks/SRE Platform — PRR é confirmação
47
+
48
+ **Flags:**
49
+ - `--engagement <simple|early|platform>` — engagement model (default: AskUserQuestion baseado em outage cost)
50
+ - `--reviewer <@handle>` — handle do reviewer SRE (default: AskUserQuestion — **NUNCA pode ser team dev**, anti-pattern auto-PRR)
51
+ - `--outage-cost <usd>` — custo de outage por minuto (default: AskUserQuestion para escolher engagement)
52
+ - `--output <path>` — caminho do output (override de default canônico)
53
+
54
+ **Exemplos:**
55
+ ```
56
+ /prr --service orders-api # Modo A — defaults
57
+ /prr --service orders-api --engagement early --reviewer @ops-lead # Modo A com config
58
+ /prr --feature "RAG sobre documentos privados" --reviewer @sre # Modo B
59
+ /prr --service edge-process-emails --engagement simple # Edge Function simples
60
+ ```
61
+
62
+ **Pré-requisito (Full mode):** projeto Supabase configurado, `mcp__supabase__*` disponível. Modo offline funciona com fallback graceful (filesystem only — itens MCP-dependentes ficam `EVIDENCE_PENDING_MCP`).
63
+ </context>
64
+
65
+ <process>
66
+
67
+ ## 1. Parsear argumentos (2 modos)
68
+
69
+ ```bash
70
+ SERVICE=$(echo "$ARGUMENTS" | grep -oE -- '--service [^ ]+' | awk '{print $2}')
71
+ FEATURE=$(echo "$ARGUMENTS" | grep -oE -- '--feature "[^"]+"' | sed 's/--feature //; s/^"//; s/"$//')
72
+ ENGAGEMENT=$(echo "$ARGUMENTS" | grep -oE -- '--engagement [^ ]+' | awk '{print $2}')
73
+ REVIEWER=$(echo "$ARGUMENTS" | grep -oE -- '--reviewer [^ ]+' | awk '{print $2}')
74
+ OUTAGE_COST=$(echo "$ARGUMENTS" | grep -oE -- '--outage-cost [^ ]+' | awk '{print $2}')
75
+ OUTPUT_PATH=$(echo "$ARGUMENTS" | grep -oE -- '--output [^ ]+' | awk '{print $2}')
76
+
77
+ # PT-BR: validar mutuamente exclusivos
78
+ if [ -n "$SERVICE" ] && [ -n "$FEATURE" ]; then
79
+ echo "✗ Erro: --service e --feature são mutuamente exclusivos. Escolha um."
80
+ exit 1
81
+ fi
82
+
83
+ # PT-BR: nenhum dos 2 → erro com sugestão
84
+ if [ -z "$SERVICE" ] && [ -z "$FEATURE" ]; then
85
+ echo "✗ Forneça --service <name> OU --feature \"<descrição>\""
86
+ echo " Exemplos:"
87
+ echo " /prr --service orders-api"
88
+ echo " /prr --feature \"RAG sobre documentos privados\""
89
+ exit 1
90
+ fi
91
+ ```
92
+
93
+ ## 2. Resolver output_path + idempotência
94
+
95
+ ```bash
96
+ if [ -n "$SERVICE" ]; then
97
+ [ -z "$OUTPUT_PATH" ] && OUTPUT_PATH=".planning/prr/${SERVICE}.md"
98
+ else
99
+ SLUG=$(echo "$FEATURE" | tr ' ' '-' | tr -cd 'a-zA-Z0-9-' | head -c 30 | sed 's/-$//')
100
+ [ -z "$OUTPUT_PATH" ] && OUTPUT_PATH=".planning/prr/feature-${SLUG}.md"
101
+ fi
102
+ mkdir -p "$(dirname "$OUTPUT_PATH")"
103
+
104
+ # PT-BR: PRR pode ser re-PRR (após mudança grande) — informar mas permitir
105
+ if [ -f "$OUTPUT_PATH" ]; then
106
+ LAST_DATE=$(grep -m1 '**Date:**' "$OUTPUT_PATH" 2>/dev/null | sed 's/.*Date:\*\* //' || echo "?")
107
+ echo "ℹ PRR-REPORT.md anterior detectado ($LAST_DATE) em $OUTPUT_PATH."
108
+ echo " Re-PRR válido (após mudança grande, incident, ou anual). Continuando — vai sobrescrever."
109
+ fi
110
+ ```
111
+
112
+ ## 3. Detectar `supabase/config.toml` (Full mode)
113
+
114
+ ```bash
115
+ PROJECT_ID=""
116
+ if [ -f supabase/config.toml ]; then
117
+ PROJECT_ID=$(grep -E '^project_id\s*=' supabase/config.toml | sed 's/.*= *"\(.*\)".*/\1/' | head -1)
118
+ echo "✓ project_id detectado: $PROJECT_ID (Full mode com MCP Supabase)"
119
+ else
120
+ echo "ℹ Sem supabase/config.toml — agent pode rodar em modo offline (fallback graceful)"
121
+ fi
122
+ ```
123
+
124
+ ## 4. AskUserQuestion — engagement model + reviewer
125
+
126
+ Se `--engagement` não fornecido E `--outage-cost` ausente:
127
+
128
+ > **AskUserQuestion**
129
+ > header: "PRR Engagement Model"
130
+ > question: "Qual custo estimado de outage para este target?"
131
+ > options:
132
+ > - "< $1k/min OR internal tool → Simple PRR (4-8h, 1 sessão)"
133
+ > - "$1k-100k/min OR customer-facing → Early Engagement (semanas, SRE no design)"
134
+ > - "> $100k/min OR built on platform → Frameworks/Platform (PRR é confirmação)"
135
+
136
+ Se `--reviewer` não fornecido (anti-pattern auto-PRR):
137
+
138
+ > **AskUserQuestion**
139
+ > header: "PRR Reviewer (anti auto-PRR)"
140
+ > question: "Quem é o reviewer? Reviewer DEVE ser SRE OU par externo ao time dev (anti-pattern: time dev faz auto-PRR — confirmation bias)."
141
+ > options: (texto livre — handle/email)
142
+
143
+ ## 5. Dispatch para `prr-conductor`
144
+
145
+ ```text
146
+ Task(
147
+ subagent_type="prr-conductor",
148
+ prompt="
149
+ ${SERVICE:+service_name: ${SERVICE}}
150
+ ${FEATURE:+feature_description: ${FEATURE}}
151
+ output_path: ${OUTPUT_PATH}
152
+ ${ENGAGEMENT:+engagement_model: ${ENGAGEMENT}}
153
+ ${REVIEWER:+reviewer: ${REVIEWER}}
154
+ ${OUTAGE_COST:+outage_cost_per_min: ${OUTAGE_COST}}
155
+ ${PROJECT_ID:+project_id: ${PROJECT_ID}}
156
+
157
+ Aplicar skill production-readiness-review. Audit em 6 axes (todos obrigatórios — pular = inválido):
158
+ 1. System Architecture — design, dependencies, blast radius, isolation, single points of failure
159
+ 2. Instrumentation/Metrics/Monitoring — 4 golden signals, SLOs definidos, alerting com burn rates
160
+ 3. Emergency Response — runbooks atualizados, on-call rotation, rollback < 60s, communication plan
161
+ 4. Capacity Planning — load testing recente, scaling docs, headroom % atual vs peak
162
+ 5. Change Management — canary deployment, feature flags, rollback drills
163
+ 6. Performance — latency p50/p95/p99 vs budget, throughput vs target, optimization headroom
164
+
165
+ Padrão obrigatório: cada item evidence-based (NÃO 'acreditamos que está pronto' — exigir query/log/runbook/test).
166
+ Modo offline: se MCP ausente, declarar [MODO OFFLINE] e marcar items MCP-dependentes EVIDENCE_PENDING_MCP.
167
+ Output: PRR-REPORT.md com scoring 0-5 por axe + status Pass/Pass with gaps/Fail + decisão Approved/Approved with conditions/Blocked + reviewer signature + Re-PRR triggers.
168
+ "
169
+ )
170
+ ```
171
+
172
+ ## 6. Pós-output
173
+
174
+ ```
175
+ ═══════════════════════════════════════════════════════════
176
+ framework ► PRR ▸ ${SERVICE:-feature-${SLUG}}
177
+ ═══════════════════════════════════════════════════════════
178
+
179
+ [output do prr-conductor — ver Step 3 do agent]
180
+
181
+ ## Estado salvo
182
+ ${OUTPUT_PATH}
183
+
184
+ ## Próximos passos
185
+ 1. Reviewer (`${REVIEWER}`) precisa assinar — anti-pattern: rubber stamp sem ler evidence
186
+ 2. P0 items são bloqueadores; P1 items são conditions; P2 items são monitoramento
187
+ 3. Re-PRR triggers (anual, mudança arquitetural grande, incident SEV1+) — agendar
188
+ 4. Se status `Approved` → liberar para production; se `Blocked` → fechar P0s antes de re-submit
189
+ 5. Cross-ref OMM: PRR alimenta Capacidade 4 (Production Readiness) — `/observabilidade omm`
190
+ 6. Phase 40 INT-FW-V2-02: `/concluir-marco` pode exigir PRR `Approved` se `workflow.complete_milestone_prr_gate=true`
191
+ ```
192
+
193
+ </process>
194
+
195
+ <success_criteria>
196
+ - [ ] `--service <name>` E `--feature "<desc>"` parseados (mutuamente exclusivos)
197
+ - [ ] Modo A: output canônico `.planning/prr/<service>.md` (override via `--output`)
198
+ - [ ] Modo B: output canônico `.planning/prr/feature-<slug>.md` (slug auto-gerado)
199
+ - [ ] Re-PRR não-bloqueante (informa mas permite — re-PRR é válido após mudança grande)
200
+ - [ ] `supabase/config.toml` detectado para passar `project_id` (Full mode)
201
+ - [ ] AskUserQuestion para engagement model (se ausente) E reviewer (se ausente — anti auto-PRR)
202
+ - [ ] `prr-conductor` invocado via `Task(subagent_type=...)` com prompt completo (6 axes literalmente + modo offline)
203
+ - [ ] Output forwarded transparentemente do agent
204
+ - [ ] Próximos passos sugerem cross-ref para `/observabilidade omm`, `/concluir-marco`, P0/P1/P2 priorização
205
+ </success_criteria>