@luanpdd/kit-mcp 1.7.0 → 1.9.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 (70) hide show
  1. package/CHANGELOG.md +101 -0
  2. package/README.md +39 -1
  3. package/gates/agent-no-recursive-dispatch.md +48 -0
  4. package/gates/budget-description.md +68 -0
  5. package/gates/no-personal-uuid.md +72 -0
  6. package/gates/obs-agents-mcp-supabase.md +86 -0
  7. package/gates/obs-skills-frontmatter.md +76 -0
  8. package/gates/omm-no-regression.md +83 -0
  9. package/gates/skill-must-include.md +71 -0
  10. package/gates/sync-idempotent.md +62 -0
  11. package/kit/agents/burn-rate-forecaster.md +160 -0
  12. package/kit/agents/codebase-mapper.md +1 -1
  13. package/kit/agents/executor.md +17 -0
  14. package/kit/agents/incident-investigator.md +245 -0
  15. package/kit/agents/observability-instrumenter.md +200 -0
  16. package/kit/agents/omm-auditor.md +199 -0
  17. package/kit/agents/planner.md +35 -0
  18. package/kit/agents/project-researcher.md +1 -1
  19. package/kit/agents/schema-checker.md +4 -4
  20. package/kit/agents/slo-engineer.md +224 -0
  21. package/kit/agents/supabase-architect.md +166 -0
  22. package/kit/agents/supabase-auth-bootstrapper.md +315 -0
  23. package/kit/agents/supabase-edge-fn-writer.md +207 -0
  24. package/kit/agents/supabase-migration-writer.md +174 -0
  25. package/kit/agents/supabase-realtime-implementer.md +275 -0
  26. package/kit/agents/supabase-rls-writer.md +235 -0
  27. package/kit/agents/supabase-storage-implementer.md +258 -0
  28. package/kit/agents/user-profiler.md +1 -1
  29. package/kit/agents/verifier.md +1 -1
  30. package/kit/commands/auditar-marco.md +22 -1
  31. package/kit/commands/auditar-observabilidade.md +103 -0
  32. package/kit/commands/burn-rate-status.md +140 -0
  33. package/kit/commands/concluir-marco.md +19 -1
  34. package/kit/commands/definir-slo.md +108 -0
  35. package/kit/commands/depurar.md +17 -0
  36. package/kit/commands/discutir-fase.md +26 -0
  37. package/kit/commands/fazer.md +15 -0
  38. package/kit/commands/forense.md +20 -1
  39. package/kit/commands/instrumentar-fase.md +200 -0
  40. package/kit/commands/investigar-producao.md +162 -0
  41. package/kit/commands/observabilidade.md +116 -0
  42. package/kit/commands/planejar-fase.md +20 -0
  43. package/kit/commands/supabase.md +148 -0
  44. package/kit/commands/verificar-trabalho.md +26 -0
  45. package/kit/framework/workflows/discuss-phase.md +19 -0
  46. package/kit/framework/workflows/plan-phase.md +25 -0
  47. package/kit/skills/_shared-observability/glossary.md +396 -0
  48. package/kit/skills/_shared-supabase/glossary.md +180 -0
  49. package/kit/skills/burn-rate-alerting/SKILL.md +258 -0
  50. package/kit/skills/core-analysis-loop/SKILL.md +352 -0
  51. package/kit/skills/distributed-tracing/SKILL.md +362 -0
  52. package/kit/skills/event-based-slos/SKILL.md +274 -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/structured-events/SKILL.md +265 -0
  57. package/kit/skills/supabase-auth-ssr/SKILL.md +260 -0
  58. package/kit/skills/supabase-cron-queues/SKILL.md +266 -0
  59. package/kit/skills/supabase-database-functions/SKILL.md +247 -0
  60. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -0
  61. package/kit/skills/supabase-edge-functions/SKILL.md +242 -0
  62. package/kit/skills/supabase-migrations/SKILL.md +175 -0
  63. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -0
  64. package/kit/skills/supabase-postgres-style/SKILL.md +138 -0
  65. package/kit/skills/supabase-realtime/SKILL.md +236 -0
  66. package/kit/skills/supabase-rls-policies/SKILL.md +185 -0
  67. package/kit/skills/supabase-storage/SKILL.md +234 -0
  68. package/kit/skills/telemetry-pipelines/SKILL.md +259 -0
  69. package/kit/skills/telemetry-sampling/SKILL.md +256 -0
  70. package/package.json +1 -1
@@ -20,8 +20,25 @@ Depurar problemas usando o método científico com isolamento de subagente.
20
20
  <available_agent_types>
21
21
  Tipos de subagente framework válidos (usar nomes exatos — não usar 'general-purpose'):
22
22
  - debugger — Diagnostica e corrige problemas
23
+ - schema-checker — Pré-validação de SQL (FK, JOIN, INSERT) contra schema real via Supabase MCP. Use quando o bug envolve migration que falhou em apply ou suspeita de drift entre comentário do dev e schema real.
23
24
  </available_agent_types>
24
25
 
26
+ <supabase_pre_check>
27
+ ## Triagem rápida — bug envolve SQL/Supabase?
28
+
29
+ Se o $ARGUMENTS ou sintomas mencionam algum destes patterns, faça **pre-validação com `schema-checker`** ANTES de invocar o `debugger` genérico:
30
+
31
+ | Sintoma | Razão |
32
+ |---|---|
33
+ | "migration falhou em apply" | `schema-checker` valida FKs/colunas/tabelas — sintoma comum é referência a coluna/tabela inexistente |
34
+ | "RLS quebrou query" ou "query lenta após RLS" | Provavelmente `auth.uid()` sem `(select)` wrapper; veja skill `supabase-rls-policies` |
35
+ | "Edge Function quebrou em deploy" | Provavelmente bare specifier ou import sem versão; veja skill `supabase-edge-functions` |
36
+ | "user_metadata em policy" | Privilege escalation; veja skill `supabase-rls-policies` (REGRA absoluta) |
37
+ | "service_role exposto" | Vazamento via `NEXT_PUBLIC_*`; veja skill `supabase-auth-ssr` |
38
+
39
+ Se aplicável: invoque `Task(subagent_type=schema-checker, prompt=...)` primeiro. Se schema-checker retorna GO mas o bug persiste, então invoque o `debugger`.
40
+ </supabase_pre_check>
41
+
25
42
  <context>
26
43
  Problema do usuário: $ARGUMENTS
27
44
 
@@ -62,3 +62,29 @@ Se `DISCUSS_MODE` for `"discuss"` (ou não definido, ou qualquer outro valor): L
62
62
  - CONTEXT.md captura decisões, não visão vaga
63
63
  - Usuário conhece os próximos passos
64
64
  </success_criteria>
65
+
66
+ <observability_integration>
67
+ **Integração com Observability-Driven Development (v1.9):**
68
+
69
+ Quando o workflow.observability_phase_questions = true (default), o workflow inclui pergunta canônica de ODD na sessão de discussão:
70
+
71
+ > "Quais SLIs essa fase impacta? O que precisa ser instrumentado para responder às 4 perguntas pré-PR?"
72
+
73
+ A pergunta é resolvida consultando a skill [`observability-driven-development`](../skills/observability-driven-development/SKILL.md) e o resultado é registrado na seção `<observability>` do CONTEXT.md gerado:
74
+
75
+ ```markdown
76
+ <observability>
77
+ ## SLIs impactados
78
+ - [SLI ou "nenhum — fase puramente interna"]
79
+
80
+ ## Instrumentação necessária
81
+ - Spans novos: [lista]
82
+ - Atributos canônicos: [user.id, tenant_id, ...]
83
+ - error.type enum esperado: [validation, timeout, ...]
84
+ </observability>
85
+ ```
86
+
87
+ O `plan-checker` invocado pelo `/planejar-fase` (Phase 33 — INT-FW-02) lê esta seção e bloqueia o plano se ODD ausente para fases voltadas ao usuário (skip silenciosamente para fases de infraestrutura — ver detecção em `discuss-phase.md`).
88
+
89
+ **REQ:** INT-FW-01.
90
+ </observability_integration>
@@ -19,10 +19,25 @@ allowed-tools:
19
19
  | Tarefa **trivial** (rename, ajuste pontual) | **`/rapido`** | Sem necessidade de plano formal; commit atômico, sem subagentes |
20
20
  | Tarefa **rápida com garantias** (commit limpo, rastreamento de estado) | **`/expresso`** | Algo concreto mas pequeno; pula agentes opcionais mas mantém disciplina |
21
21
  | Trabalho **estruturado** (multi-arquivo, requer planejamento) | **`/discutir-fase` → `/planejar-fase` → `/executar-fase`** | Fase real de milestone; usa agentes completos |
22
+ | **Tarefa Supabase** (DB/Auth/Realtime/Edge/Storage/RLS/migration) | **`/supabase <subcomando>`** | Roteia para agent especializado: arquiteto / migration / rls / edge / realtime / auth / storage / rag / cron / check |
22
23
  | **Próximo passo** ambíguo no fluxo atual | **`/proximo`** | Avança no roadmap automaticamente |
23
24
  | **Capturar ideia** sem agir agora | **`/nota`** ou **`/adicionar-tarefa`** | Salva pra depois sem interromper o foco |
24
25
  | **Investigar bug** com método científico | **`/depurar`** | Hipótese → teste → fix com checkpoints |
25
26
 
27
+ ## Detecção de intenção Supabase
28
+
29
+ Se a descrição do user menciona qualquer destes termos, considere rotear para `/supabase` em vez de `/discutir-fase` ou `/expresso`:
30
+
31
+ - **DB:** "migration", "RLS", "policy", "schema", "tabela Postgres", "supabase/migrations", "supabase/schemas"
32
+ - **Auth:** "Supabase auth", "Next.js auth", "@supabase/ssr", "magic link", "OAuth", "MFA TOTP"
33
+ - **Realtime:** "broadcast Supabase", "presence", "postgres_changes", "channel"
34
+ - **Edge Functions:** "Edge Function", "Deno + Supabase", "supabase/functions"
35
+ - **Storage:** "bucket", "signed URL", "upload Supabase"
36
+ - **AI/RAG:** "pgvector", "embeddings + Supabase", "RAG with permissions"
37
+ - **Background:** "pg_cron", "pgmq", "scheduled job Supabase"
38
+
39
+ Para contexto sobre o que cada subcomando faz, leia [`/supabase`](./supabase.md) ou as 11 skills em `kit/skills/supabase-*/`.
40
+
26
41
  ## Aliases (continuam funcionando)
27
42
 
28
43
  `/rapido`, `/expresso`, `/proximo`, `/depurar`, `/discutir-fase`, `/planejar-fase`, `/executar-fase` — todos continuam executando direto, sem passar pelo `/fazer`. Use `/fazer` quando estiver em dúvida sobre qual escolher.
@@ -53,4 +53,23 @@ Ler e executar o workflow forensics de @./.claude/framework/workflows/forensics.
53
53
  - **Redigir dados sensíveis:** Remover caminhos absolutos, chaves de API, tokens de relatórios e issues.
54
54
  - **Fundamentar descobertas em evidências:** Toda anomalia deve citar commits, arquivos ou dados de estado específicos.
55
55
  - **Sem especulação sem evidência:** Se os dados forem insuficientes, diga isso — não fabrique causas raiz.
56
- </critical_rules>
56
+ </critical_rules>
57
+
58
+ <observability_integration>
59
+ **Integração com Core Analysis Loop (v1.9):**
60
+
61
+ Forense usa skill [`core-analysis-loop`](../skills/core-analysis-loop/SKILL.md) — método científico iterativo (sintoma → hipótese de dados → validação → próxima iteração) em vez de inspeção ad hoc.
62
+
63
+ Cada anomalia detectada vira hipótese com query de validação:
64
+
65
+ | Tipo de anomalia | Hipótese formada | Query de validação |
66
+ |---|---|---|
67
+ | Loop travado | "phase X stuck há Yh" | `git log --since="Yh ago" --grep=phase` para confirmar zero commits |
68
+ | Artefatos ausentes | "PLAN.md ausente em phase X" | `ls .planning/phases/X-*/X-PLAN-*.md` |
69
+ | Trabalho abandonado | "branch sem merge nem commit recente" | `git log -1 <branch>` + `git status` |
70
+ | Crash/interrupção | "executor falhou em meio a fase" | grep no STATE.md por "in_progress" sem update recente |
71
+
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
+
74
+ **REQ:** INT-FW-06.
75
+ </observability_integration>
@@ -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>