@luanpdd/kit-mcp 1.35.0 → 1.36.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 (117) hide show
  1. package/bin/cli.js +2 -2
  2. package/bin/mcp.js +6 -6
  3. package/bin/ui.js +74 -74
  4. package/gates/ai-prompt-stability.md +120 -120
  5. package/gates/budget-description.md +68 -68
  6. package/gates/confidence.md +29 -29
  7. package/gates/dependency-check.md +33 -33
  8. package/gates/dept-cycle-prevention.md +179 -179
  9. package/gates/golden-signals-coverage.md +133 -133
  10. package/gates/legacy-refactor-safety.md +178 -178
  11. package/gates/multi-tenant-rls-coverage.md +102 -102
  12. package/gates/no-personal-uuid.md +72 -72
  13. package/gates/obs-agents-mcp-supabase.md +86 -86
  14. package/gates/obs-skills-frontmatter.md +76 -76
  15. package/gates/observability-coverage.md +151 -151
  16. package/gates/omm-no-regression.md +83 -83
  17. package/gates/postmortem-template-required.md +127 -127
  18. package/gates/prr-checklist-coverage.md +128 -128
  19. package/gates/regression.md +32 -32
  20. package/gates/release-pipeline-policy.md +132 -132
  21. package/gates/secrets-scan.md +33 -33
  22. package/gates/service-role-not-in-user-facing.md +113 -113
  23. package/gates/skill-must-include.md +71 -71
  24. package/gates/sync-idempotent.md +62 -62
  25. package/gates/verify-phase-goal.md +34 -34
  26. package/kit/agents/designer-ui.md +216 -216
  27. package/kit/agents/workflow-generator.md +537 -167
  28. package/kit/commands/adicionar-backlog.md +1 -1
  29. package/kit/commands/adicionar-fase.md +1 -1
  30. package/kit/commands/adicionar-tarefa.md +1 -1
  31. package/kit/commands/auditar-observabilidade.md +103 -103
  32. package/kit/commands/auditar-toil.md +129 -129
  33. package/kit/commands/caracterizar-prompt.md +195 -195
  34. package/kit/commands/criar-workflow.md +158 -158
  35. package/kit/commands/definir-perfil.md +1 -1
  36. package/kit/commands/definir-slo.md +108 -108
  37. package/kit/commands/fio.md +1 -1
  38. package/kit/commands/golden-signals.md +142 -142
  39. package/kit/commands/instrumentar-fase.md +200 -200
  40. package/kit/commands/investigar-producao.md +162 -162
  41. package/kit/commands/observabilidade.md +118 -118
  42. package/kit/commands/postmortem.md +179 -179
  43. package/kit/commands/prr.md +205 -205
  44. package/kit/commands/publicar-rapido.md +207 -207
  45. package/kit/commands/risk-budget.md +220 -220
  46. package/kit/commands/sre.md +230 -230
  47. package/kit/file-manifest.json +424 -424
  48. package/kit/framework/references/output-style.md +22 -22
  49. package/kit/hooks/post-apply-migration.js +199 -199
  50. package/kit/hooks/sidecar-tool-publisher.js +210 -210
  51. package/kit/skills/_shared-dados-distribuidos/glossary.md +224 -224
  52. package/kit/skills/_shared-legacy/glossary.md +389 -389
  53. package/kit/skills/_shared-multi-tenant/glossary.md +186 -186
  54. package/kit/skills/_shared-observability/glossary.md +396 -396
  55. package/kit/skills/_shared-sre/glossary.md +712 -712
  56. package/kit/skills/_shared-supabase/glossary.md +234 -234
  57. package/kit/skills/blameless-postmortems/SKILL.md +340 -340
  58. package/kit/skills/burn-rate-alerting/SKILL.md +258 -258
  59. package/kit/skills/cascading-failures/SKILL.md +311 -311
  60. package/kit/skills/core-analysis-loop/SKILL.md +352 -352
  61. package/kit/skills/distributed-tracing/SKILL.md +362 -362
  62. package/kit/skills/dynamic-workflow-authoring/SKILL.md +327 -223
  63. package/kit/skills/eliminating-toil/SKILL.md +243 -243
  64. package/kit/skills/event-based-slos/SKILL.md +296 -296
  65. package/kit/skills/four-golden-signals/SKILL.md +314 -314
  66. package/kit/skills/hermetic-builds/SKILL.md +323 -323
  67. package/kit/skills/legacy-monster-methods/SKILL.md +444 -444
  68. package/kit/skills/llm-as-dependency/SKILL.md +436 -436
  69. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -396
  70. package/kit/skills/observability-driven-development/SKILL.md +315 -315
  71. package/kit/skills/observability-maturity-model/SKILL.md +222 -222
  72. package/kit/skills/opentelemetry-standard/SKILL.md +351 -351
  73. package/kit/skills/production-readiness-review/SKILL.md +305 -305
  74. package/kit/skills/release-engineering/SKILL.md +367 -367
  75. package/kit/skills/retry-strategies/SKILL.md +372 -372
  76. package/kit/skills/sre-risk-management/SKILL.md +221 -221
  77. package/kit/skills/structured-events/SKILL.md +265 -265
  78. package/kit/skills/supabase-cron-queues/SKILL.md +275 -275
  79. package/kit/skills/supabase-database-functions/SKILL.md +332 -332
  80. package/kit/skills/supabase-declarative-schema/SKILL.md +183 -183
  81. package/kit/skills/supabase-pgvector-rag/SKILL.md +253 -253
  82. package/kit/skills/supabase-postgres-style/SKILL.md +138 -138
  83. package/kit/skills/supabase-storage/SKILL.md +234 -234
  84. package/kit/skills/telemetry-pipelines/SKILL.md +259 -259
  85. package/kit/skills/telemetry-sampling/SKILL.md +256 -256
  86. package/kit/skills/ui-anti-padroes-ia/SKILL.md +261 -261
  87. package/kit/skills/ui-contexto-produto/SKILL.md +248 -248
  88. package/kit/skills/ui-cor-estrategia/SKILL.md +213 -213
  89. package/kit/skills/ui-critica-auditoria/SKILL.md +260 -260
  90. package/kit/skills/ui-motion-funcional/SKILL.md +264 -264
  91. package/kit/skills/ui-ritmo-espacial/SKILL.md +259 -259
  92. package/kit/skills/ui-tipografia/SKILL.md +211 -211
  93. package/package.json +1 -1
  94. package/src/cli/index.js +1114 -1114
  95. package/src/cli/render.js +194 -194
  96. package/src/cli/upgrade-check.js +135 -135
  97. package/src/core/error-redaction.js +76 -76
  98. package/src/core/failures.js +153 -153
  99. package/src/core/gate-runner.js +205 -205
  100. package/src/core/gates.js +82 -82
  101. package/src/core/logger.js +170 -170
  102. package/src/core/manifest-verify.js +174 -174
  103. package/src/core/metrics.js +268 -268
  104. package/src/core/notify.js +60 -60
  105. package/src/core/path-safety.js +141 -141
  106. package/src/core/replays.js +120 -120
  107. package/src/core/ui.js +185 -185
  108. package/src/mcp-server/install.js +149 -149
  109. package/src/mcp-server/roots.js +124 -124
  110. package/src/ui/auto-spawn.js +113 -113
  111. package/src/ui/browser.js +78 -78
  112. package/src/ui/client.js +130 -130
  113. package/src/ui/events.js +65 -65
  114. package/src/ui/lockfile.js +191 -191
  115. package/src/ui/port.js +67 -67
  116. package/src/ui/server.js +547 -547
  117. package/src/ui/wrapper.js +129 -129
@@ -1,296 +1,296 @@
1
- ---
2
- name: event-based-slos
3
- description: Use ao definir SLO — SLI event-based (não time-based), sliding window 30d, decouple what/why. SLO-based alerts substituem thresholds brutos como CPU/memória.
4
- ---
5
-
6
- # Observabilidade — Event-Based SLOs
7
-
8
- ## Quando usar
9
-
10
- LLM carrega esta skill ao definir/avaliar SLOs ou substituir alertas threshold por SLO-based. Trigger phrases:
11
-
12
- - "definir SLO", "criar SLI"
13
- - "alertas confiáveis", "alert fatigue"
14
- - "error budget", "sliding window"
15
- - "como medir saúde do serviço"
16
- - "decouple what from why"
17
-
18
- ## Regras absolutas
19
-
20
- - **SLI sempre event-based, nunca time-based** — "% de eventos com `result.success=true` em 30d" > "% de janelas de 5min com p99 < 300ms"
21
- - **Sliding window 30d por default** — fixed window (calendário) gera comportamento perverso (cliente não esquece bug por causa de reset).
22
- - **Target ≤ 99.95%** — para SLO 99.99%+ você não tem tempo de reagir antes do budget acabar; use métricas/dashboards informativos em vez de SLO.
23
- - **Decouple "what" do "why"** — SLO alert diz que tem dor (sintoma); investigation descobre porquê (use [`core-analysis-loop`](../skills/core-analysis-loop/SKILL.md)). NUNCA misturar (anti-pattern: "alert se memória > 80% AND p99 > 300ms").
24
- - **Customer-facing journey, não system metric** — SLI mede o que o cliente sente ("login funcionou em < 800ms"), não estado interno ("threads ativas").
25
- - **Granular por endpoint/feature** — 1 SLO por jornada crítica do user. Não SLO global "site availability" — específico demais para ser ignorável.
26
- - **Owner explícito** — cada SLO tem dono nomeado. Sem owner = sem ação = sem valor.
27
- - **Substituir alertas threshold gradualmente** — após SLO comprovar valor (1+ incident detectado por SLO antes de threshold), DELETAR threshold antigo.
28
-
29
- ## Risk continuum — SLO target é decisão explícita
30
-
31
- > Cross-ref canônico: [sre-risk-management](../sre-risk-management/SKILL.md) (cap 3 do livro Google SRE — Embracing Risk).
32
-
33
- SLO target NÃO é meta arbitrária ("queremos 99.99% porque soa bom"). É uma escolha consciente no **continuum risk × innovation**: cada nove adicional **multiplica custo** mas **divide benefício marginal** percebido pelo cliente.
34
-
35
- | Target | Tolerância 30d | User-perceptible? | Quando faz sentido |
36
- |---|---|---|---|
37
- | 99% | 7.2 h | Sim, notável | Tier free, beta features, internal tools |
38
- | 99.5% | 3.6 h | Notável em paths críticos | Tier free de produção |
39
- | 99.9% | 43.2 min | Aceitável para maior parte de UX | Tier paid default |
40
- | 99.95% | 21.6 min | Quase imperceptível | Tier enterprise / mission-critical |
41
- | 99.99% | 4.3 min | Imperceptível em smartphone (~99% no canal do user) | Apenas se justificado por user perception (raro) |
42
-
43
- **Sabedoria 99.99%** — cliente final acessa via smartphone (~99% disponibilidade) com ISP residencial (~99%). Serviço 99.99% **não é distinguível** de 99.999% nesse contexto: ambos parecem "sempre funcionando". Esforço além de 99.95% para serviço user-facing é tipicamente desperdício.
44
-
45
- **Error budget é o instrumento contábil dessa decisão.** Para SLO 99.9% em 30d com 10M eventos: budget = `0.001 × 10M = 10k bad events`. Esse 10k é orçamento explícito para gastar em deploys arriscados, experimentos, refactors. Quando esgota, releases freezam até regenerar — não como punição, mas como **balanço explícito risk × innovation**.
46
-
47
- **Diferentes tiers, diferentes targets** — `customer.tier='enterprise'` pode justificar 99.95%; `tier='free'` pode operar em 99.5%. Tratar todos como tier-1 desperdiça budget; tratar todos como tier-3 frustra clientes pagantes. A skill `sre-risk-management` documenta o framework completo de decisão.
48
-
49
- > Em resumo: a regra `Target ≤ 99.95%` desta skill (acima) é **consequência** do risk continuum, não restrição arbitrária. Para 99.99%+ trate como métrica informativa (dashboard), NÃO como SLO acionável (alerts).
50
-
51
- ## Patterns canônicos
52
-
53
- ### Pattern: SLI event-based vs time-based
54
-
55
- ```sql
56
- -- PT-BR: BAD — SLI time-based (anti-pattern)
57
- -- "99% das janelas de 5 min têm p99 < 300ms"
58
- -- Problema: pre-aggregation perde fidelidade; janela com 1 outlier puxa p99.
59
-
60
- -- PT-BR: GOOD — SLI event-based
61
- -- "99.9% dos eventos individuais têm duration < 300ms e result_success = true"
62
- select
63
- count(*) filter (where duration_ms < 300 and result_success = true) as good,
64
- count(*) as total,
65
- count(*) filter (where duration_ms < 300 and result_success = true)::float / count(*) as compliance
66
- from observability.events
67
- where
68
- event_name = 'http_request'
69
- and endpoint = '/api/v1/orders'
70
- and timestamp > now() - interval '30 days';
71
- ```
72
-
73
- ### Pattern: SLO definition canônico
74
-
75
- ```yaml
76
- # PT-BR: SLO documentado em formato YAML — alimenta agent slo-engineer
77
- slo:
78
- name: checkout_success
79
- description: "Checkout completes successfully within 800ms (customer perception)"
80
- owner: orders-team@company.com # PT-BR: dono nomeado
81
-
82
- sli:
83
- type: event_based # PT-BR: NUNCA time-based
84
- event_filter:
85
- service: orders-api
86
- endpoint: /api/v1/checkout
87
- http_method: POST
88
- good_event: # PT-BR: predicate booleano
89
- result_success: true
90
- duration_ms: { lt: 800 }
91
- bad_event: # PT-BR: complemento
92
- operator: not_good # qualquer evento que não é "good"
93
-
94
- target: 0.999 # PT-BR: 99.9% — não 99.99%+ por design
95
- window: 30d_sliding # PT-BR: nunca fixed/calendar
96
-
97
- alerts: # PT-BR: ver skill burn-rate-alerting
98
- - name: page_short_term
99
- lookahead: 4h
100
- baseline: 1h
101
- severity: page
102
- - name: ticket_long_term
103
- lookahead: 3d
104
- baseline: 18h
105
- severity: ticket
106
- ```
107
-
108
- ### Pattern: SLI materialized view (Postgres)
109
-
110
- ```sql
111
- -- PT-BR: view materializa SLI events para queries baratas
112
- -- Refresh agendado (pg_cron) ou em tempo real (trigger)
113
- create materialized view obs.sli_checkout_success as
114
- select
115
- date_trunc('minute', timestamp) as bucket,
116
- count(*) filter (where result_success = true and duration_ms < 800) as good,
117
- count(*) filter (where not (result_success = true and duration_ms < 800)) as bad,
118
- count(*) as total
119
- from observability.events
120
- where
121
- service = 'orders-api'
122
- and endpoint = '/api/v1/checkout'
123
- and http_method = 'POST'
124
- and timestamp > now() - interval '35 days' -- 30d + buffer
125
- group by 1
126
- with no data;
127
-
128
- -- PT-BR: índice para queries de burn rate
129
- create index on obs.sli_checkout_success (bucket);
130
-
131
- -- PT-BR: refresh schedule via pg_cron — a cada 30s
132
- select cron.schedule(
133
- 'refresh_sli_checkout_success',
134
- '*/30 * * * * *',
135
- $$ refresh materialized view concurrently obs.sli_checkout_success $$
136
- );
137
- ```
138
-
139
- ### Pattern: SLO compliance query (atual e histórico)
140
-
141
- ```sql
142
- -- PT-BR: compliance atual — % good no último 30d
143
- select
144
- sum(good)::float / nullif(sum(total), 0) as compliance_30d,
145
- 0.999 as target,
146
- case
147
- when sum(good)::float / nullif(sum(total), 0) >= 0.999 then 'IN_BUDGET'
148
- else 'OUT_OF_BUDGET'
149
- end as status
150
- from obs.sli_checkout_success
151
- where bucket > now() - interval '30 days';
152
-
153
- -- PT-BR: error budget remaining
154
- -- Budget = (1 - target) × total_events
155
- -- Remaining = budget - bad_events_so_far
156
- select
157
- (1 - 0.999) * sum(total) as budget,
158
- sum(bad) as burned,
159
- (1 - 0.999) * sum(total) - sum(bad) as remaining,
160
- 100.0 * (1 - sum(bad) / nullif((1 - 0.999) * sum(total), 0)) as remaining_pct
161
- from obs.sli_checkout_success
162
- where bucket > now() - interval '30 days';
163
- ```
164
-
165
- ### Pattern: SLO replacing thresholds (case study Honeycomb)
166
-
167
- ```text
168
- ANTES (cap 12 do livro):
169
- - Alert: CPU > 80% (false positive: garbage collector)
170
- - Alert: memory > 90% (false positive: cache warming)
171
- - Alert: 5xx > 1% in 5min (false negative: 0.5% por 1h burns 60% do budget)
172
- - Alert: p99 latency > 500ms in 5min (false positive: 1 spike isolado)
173
-
174
- DEPOIS:
175
- - 1 SLO: checkout_success em 30d sliding
176
- - 1 alert preditivo: burn rate sustained 4h+
177
- - 1 alert ticket: burn rate sustained 3d+
178
-
179
- RESULTADO: 60% menos paginations, 100% dos incidents reais detectados.
180
- ```
181
-
182
- ### Pattern: customer-facing SLI dimensions
183
-
184
- | Dimensão | Valor | Por quê SLI deve incluir |
185
- |---|---|---|
186
- | `endpoint` | `/api/v1/checkout` | Granular — não SLO global |
187
- | `customer.tier` | `'enterprise'` | Diferentes targets por tier (Pro = 99.95% vs Free = 99.5%) |
188
- | `region` | `us-east-1` | Identificar problema regional vs global |
189
- | `feature_flag.<name>` | `true`/`false` | SLO durante rollout incremental |
190
- | `tenant_id` | `'acme'` | Big customers podem ter SLOs próprios |
191
-
192
- ## Anti-patterns
193
-
194
- ### ANTI: SLO 99.99% ou 99.999%
195
-
196
- ```text
197
- ANTI: target 99.99% em SLO de 30d sliding
198
- - 30d × 24h × 60min × (1-0.9999) = 4.3 minutos de tolerância
199
- - Sem tempo para reagir antes do budget esgotar
200
- - Burn rate alerts disparam após o budget acabar (zero-level)
201
-
202
- CERTO: target ≤ 99.95% para SLO real
203
- Para 99.99%+, use métricas/dashboards informativos (não alerta)
204
- ```
205
-
206
- ### ANTI: SLO global "site up"
207
-
208
- ```text
209
- ANTI: 1 SLO "site availability" para tudo
210
- - Falha em /api/v1/admin não conta para 99% dos clientes
211
- - Falha em /api/v1/checkout = catastrófico
212
- - Misturar = alarmes confusos, ações vagas
213
-
214
- CERTO: 1 SLO por jornada crítica do user
215
- - checkout_success: 99.9%
216
- - login_success: 99.95%
217
- - search_p95_latency: 99% < 200ms
218
- - admin_panel: SEM SLO (uso baixo, latência aceitável)
219
- ```
220
-
221
- ### ANTI: SLO sem owner
222
-
223
- ```text
224
- ANTI: SLO definido em retrospectiva, sem dono nomeado
225
- - Burn alert dispara → ninguém atende → escalation
226
- - Sem follow-up no fim do mês
227
-
228
- CERTO: SLO tem owner em arquivo (yaml ou tabela DB)
229
- owner = team email ou pessoa específica
230
- Burn alert roteia direto para owner antes de escalation
231
- ```
232
-
233
- ### ANTI: SLO == SLA externo
234
-
235
- ```text
236
- ANTI: usar SLA do contrato (99.9% uptime) como SLO interno
237
-
238
- PROBLEMA: 0 margem de segurança. Atinge SLA mínimo no fio = 1 incident e quebra.
239
-
240
- CERTO: SLO interno mais rígido que SLA externo
241
- SLA externo: 99.9% (compromisso com cliente)
242
- SLO interno: 99.95% (margem de 5× para reagir)
243
- ```
244
-
245
- ### ANTI: alterar SLI quando burn ocorre
246
-
247
- ```text
248
- ANTI: SLO está queimando → "vamos relaxar SLI para reduzir false positives"
249
- (definir bad_event mais frouxo)
250
-
251
- PROBLEMA: você está mascarando dor real. Próximo incident similar passa silencioso.
252
-
253
- CERTO: SLI é compromisso com customer experience. Se está queimando, fixar
254
- o problema (root cause via core-analysis-loop), não o SLI.
255
- Se SLI sistematicamente errado (mede coisa errada): substituir, não relaxar.
256
- ```
257
-
258
- ### ANTI: fixed window (mensal/calendário)
259
-
260
- ```text
261
- ANTI: error budget reseta dia 1 do mês
262
-
263
- PROBLEMA:
264
- - "Tivemos outage dia 31, reseta amanhã" — cliente NÃO esquece
265
- - Pressão para postergar fixes para "depois do reset"
266
- - Behavioral hazard: deploy arriscado dia 30
267
-
268
- CERTO: sliding window 30d
269
- Outage dia 31 fica no budget até dia 30 do mês seguinte (sai gradualmente)
270
- Sem incentivo perverso, comportamento humano realista
271
- ```
272
-
273
- ## Verificação
274
-
275
- Antes de marcar SLO como produção-pronto:
276
-
277
- 1. **Owner nomeado** — email/team em `slo.owner`
278
- 2. **SLI event-based** — pred boolean, não time-bucket
279
- 3. **Target ≤ 99.95%** — > 99.95% sinaliza informativo, não SLO
280
- 4. **Window 30d sliding** — não fixed
281
- 5. **Customer-facing journey** — SLI mede o que o cliente sente
282
- 6. **Materialized view** existe e é refreshable (pg_cron)
283
- 7. **Burn alerts** configurados (ver skill `burn-rate-alerting`)
284
- 8. **Quero SLO ou metric?** — se a resposta é "informativo", crie metric, não SLO
285
-
286
- ---
287
-
288
- ## Ver também
289
-
290
- - `kit/skills/_shared-observability/glossary.md` — termos canônicos SLI/SLO/error budget
291
- - `kit/skills/structured-events/SKILL.md` — eventos canônicos para alimentar SLI
292
- - `kit/skills/burn-rate-alerting/SKILL.md` — lookahead/baseline windows
293
- - `kit/skills/core-analysis-loop/SKILL.md` — investigar quando SLO queima
294
- - `kit/agents/slo-engineer.md` — gera SLO.md + SQL para materializar SLI
295
-
296
- *Material-fonte: Observability Engineering (O'Reilly, 2022) — Cap 12: "Using Service-Level Objectives for Reliability".*
1
+ ---
2
+ name: event-based-slos
3
+ description: Use ao definir SLO — SLI event-based (não time-based), sliding window 30d, decouple what/why. SLO-based alerts substituem thresholds brutos como CPU/memória.
4
+ ---
5
+
6
+ # Observabilidade — Event-Based SLOs
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao definir/avaliar SLOs ou substituir alertas threshold por SLO-based. Trigger phrases:
11
+
12
+ - "definir SLO", "criar SLI"
13
+ - "alertas confiáveis", "alert fatigue"
14
+ - "error budget", "sliding window"
15
+ - "como medir saúde do serviço"
16
+ - "decouple what from why"
17
+
18
+ ## Regras absolutas
19
+
20
+ - **SLI sempre event-based, nunca time-based** — "% de eventos com `result.success=true` em 30d" > "% de janelas de 5min com p99 < 300ms"
21
+ - **Sliding window 30d por default** — fixed window (calendário) gera comportamento perverso (cliente não esquece bug por causa de reset).
22
+ - **Target ≤ 99.95%** — para SLO 99.99%+ você não tem tempo de reagir antes do budget acabar; use métricas/dashboards informativos em vez de SLO.
23
+ - **Decouple "what" do "why"** — SLO alert diz que tem dor (sintoma); investigation descobre porquê (use [`core-analysis-loop`](../skills/core-analysis-loop/SKILL.md)). NUNCA misturar (anti-pattern: "alert se memória > 80% AND p99 > 300ms").
24
+ - **Customer-facing journey, não system metric** — SLI mede o que o cliente sente ("login funcionou em < 800ms"), não estado interno ("threads ativas").
25
+ - **Granular por endpoint/feature** — 1 SLO por jornada crítica do user. Não SLO global "site availability" — específico demais para ser ignorável.
26
+ - **Owner explícito** — cada SLO tem dono nomeado. Sem owner = sem ação = sem valor.
27
+ - **Substituir alertas threshold gradualmente** — após SLO comprovar valor (1+ incident detectado por SLO antes de threshold), DELETAR threshold antigo.
28
+
29
+ ## Risk continuum — SLO target é decisão explícita
30
+
31
+ > Cross-ref canônico: [sre-risk-management](../sre-risk-management/SKILL.md) (cap 3 do livro Google SRE — Embracing Risk).
32
+
33
+ SLO target NÃO é meta arbitrária ("queremos 99.99% porque soa bom"). É uma escolha consciente no **continuum risk × innovation**: cada nove adicional **multiplica custo** mas **divide benefício marginal** percebido pelo cliente.
34
+
35
+ | Target | Tolerância 30d | User-perceptible? | Quando faz sentido |
36
+ |---|---|---|---|
37
+ | 99% | 7.2 h | Sim, notável | Tier free, beta features, internal tools |
38
+ | 99.5% | 3.6 h | Notável em paths críticos | Tier free de produção |
39
+ | 99.9% | 43.2 min | Aceitável para maior parte de UX | Tier paid default |
40
+ | 99.95% | 21.6 min | Quase imperceptível | Tier enterprise / mission-critical |
41
+ | 99.99% | 4.3 min | Imperceptível em smartphone (~99% no canal do user) | Apenas se justificado por user perception (raro) |
42
+
43
+ **Sabedoria 99.99%** — cliente final acessa via smartphone (~99% disponibilidade) com ISP residencial (~99%). Serviço 99.99% **não é distinguível** de 99.999% nesse contexto: ambos parecem "sempre funcionando". Esforço além de 99.95% para serviço user-facing é tipicamente desperdício.
44
+
45
+ **Error budget é o instrumento contábil dessa decisão.** Para SLO 99.9% em 30d com 10M eventos: budget = `0.001 × 10M = 10k bad events`. Esse 10k é orçamento explícito para gastar em deploys arriscados, experimentos, refactors. Quando esgota, releases freezam até regenerar — não como punição, mas como **balanço explícito risk × innovation**.
46
+
47
+ **Diferentes tiers, diferentes targets** — `customer.tier='enterprise'` pode justificar 99.95%; `tier='free'` pode operar em 99.5%. Tratar todos como tier-1 desperdiça budget; tratar todos como tier-3 frustra clientes pagantes. A skill `sre-risk-management` documenta o framework completo de decisão.
48
+
49
+ > Em resumo: a regra `Target ≤ 99.95%` desta skill (acima) é **consequência** do risk continuum, não restrição arbitrária. Para 99.99%+ trate como métrica informativa (dashboard), NÃO como SLO acionável (alerts).
50
+
51
+ ## Patterns canônicos
52
+
53
+ ### Pattern: SLI event-based vs time-based
54
+
55
+ ```sql
56
+ -- PT-BR: BAD — SLI time-based (anti-pattern)
57
+ -- "99% das janelas de 5 min têm p99 < 300ms"
58
+ -- Problema: pre-aggregation perde fidelidade; janela com 1 outlier puxa p99.
59
+
60
+ -- PT-BR: GOOD — SLI event-based
61
+ -- "99.9% dos eventos individuais têm duration < 300ms e result_success = true"
62
+ select
63
+ count(*) filter (where duration_ms < 300 and result_success = true) as good,
64
+ count(*) as total,
65
+ count(*) filter (where duration_ms < 300 and result_success = true)::float / count(*) as compliance
66
+ from observability.events
67
+ where
68
+ event_name = 'http_request'
69
+ and endpoint = '/api/v1/orders'
70
+ and timestamp > now() - interval '30 days';
71
+ ```
72
+
73
+ ### Pattern: SLO definition canônico
74
+
75
+ ```yaml
76
+ # PT-BR: SLO documentado em formato YAML — alimenta agent slo-engineer
77
+ slo:
78
+ name: checkout_success
79
+ description: "Checkout completes successfully within 800ms (customer perception)"
80
+ owner: orders-team@company.com # PT-BR: dono nomeado
81
+
82
+ sli:
83
+ type: event_based # PT-BR: NUNCA time-based
84
+ event_filter:
85
+ service: orders-api
86
+ endpoint: /api/v1/checkout
87
+ http_method: POST
88
+ good_event: # PT-BR: predicate booleano
89
+ result_success: true
90
+ duration_ms: { lt: 800 }
91
+ bad_event: # PT-BR: complemento
92
+ operator: not_good # qualquer evento que não é "good"
93
+
94
+ target: 0.999 # PT-BR: 99.9% — não 99.99%+ por design
95
+ window: 30d_sliding # PT-BR: nunca fixed/calendar
96
+
97
+ alerts: # PT-BR: ver skill burn-rate-alerting
98
+ - name: page_short_term
99
+ lookahead: 4h
100
+ baseline: 1h
101
+ severity: page
102
+ - name: ticket_long_term
103
+ lookahead: 3d
104
+ baseline: 18h
105
+ severity: ticket
106
+ ```
107
+
108
+ ### Pattern: SLI materialized view (Postgres)
109
+
110
+ ```sql
111
+ -- PT-BR: view materializa SLI events para queries baratas
112
+ -- Refresh agendado (pg_cron) ou em tempo real (trigger)
113
+ create materialized view obs.sli_checkout_success as
114
+ select
115
+ date_trunc('minute', timestamp) as bucket,
116
+ count(*) filter (where result_success = true and duration_ms < 800) as good,
117
+ count(*) filter (where not (result_success = true and duration_ms < 800)) as bad,
118
+ count(*) as total
119
+ from observability.events
120
+ where
121
+ service = 'orders-api'
122
+ and endpoint = '/api/v1/checkout'
123
+ and http_method = 'POST'
124
+ and timestamp > now() - interval '35 days' -- 30d + buffer
125
+ group by 1
126
+ with no data;
127
+
128
+ -- PT-BR: índice para queries de burn rate
129
+ create index on obs.sli_checkout_success (bucket);
130
+
131
+ -- PT-BR: refresh schedule via pg_cron — a cada 30s
132
+ select cron.schedule(
133
+ 'refresh_sli_checkout_success',
134
+ '*/30 * * * * *',
135
+ $$ refresh materialized view concurrently obs.sli_checkout_success $$
136
+ );
137
+ ```
138
+
139
+ ### Pattern: SLO compliance query (atual e histórico)
140
+
141
+ ```sql
142
+ -- PT-BR: compliance atual — % good no último 30d
143
+ select
144
+ sum(good)::float / nullif(sum(total), 0) as compliance_30d,
145
+ 0.999 as target,
146
+ case
147
+ when sum(good)::float / nullif(sum(total), 0) >= 0.999 then 'IN_BUDGET'
148
+ else 'OUT_OF_BUDGET'
149
+ end as status
150
+ from obs.sli_checkout_success
151
+ where bucket > now() - interval '30 days';
152
+
153
+ -- PT-BR: error budget remaining
154
+ -- Budget = (1 - target) × total_events
155
+ -- Remaining = budget - bad_events_so_far
156
+ select
157
+ (1 - 0.999) * sum(total) as budget,
158
+ sum(bad) as burned,
159
+ (1 - 0.999) * sum(total) - sum(bad) as remaining,
160
+ 100.0 * (1 - sum(bad) / nullif((1 - 0.999) * sum(total), 0)) as remaining_pct
161
+ from obs.sli_checkout_success
162
+ where bucket > now() - interval '30 days';
163
+ ```
164
+
165
+ ### Pattern: SLO replacing thresholds (case study Honeycomb)
166
+
167
+ ```text
168
+ ANTES (cap 12 do livro):
169
+ - Alert: CPU > 80% (false positive: garbage collector)
170
+ - Alert: memory > 90% (false positive: cache warming)
171
+ - Alert: 5xx > 1% in 5min (false negative: 0.5% por 1h burns 60% do budget)
172
+ - Alert: p99 latency > 500ms in 5min (false positive: 1 spike isolado)
173
+
174
+ DEPOIS:
175
+ - 1 SLO: checkout_success em 30d sliding
176
+ - 1 alert preditivo: burn rate sustained 4h+
177
+ - 1 alert ticket: burn rate sustained 3d+
178
+
179
+ RESULTADO: 60% menos paginations, 100% dos incidents reais detectados.
180
+ ```
181
+
182
+ ### Pattern: customer-facing SLI dimensions
183
+
184
+ | Dimensão | Valor | Por quê SLI deve incluir |
185
+ |---|---|---|
186
+ | `endpoint` | `/api/v1/checkout` | Granular — não SLO global |
187
+ | `customer.tier` | `'enterprise'` | Diferentes targets por tier (Pro = 99.95% vs Free = 99.5%) |
188
+ | `region` | `us-east-1` | Identificar problema regional vs global |
189
+ | `feature_flag.<name>` | `true`/`false` | SLO durante rollout incremental |
190
+ | `tenant_id` | `'acme'` | Big customers podem ter SLOs próprios |
191
+
192
+ ## Anti-patterns
193
+
194
+ ### ANTI: SLO 99.99% ou 99.999%
195
+
196
+ ```text
197
+ ANTI: target 99.99% em SLO de 30d sliding
198
+ - 30d × 24h × 60min × (1-0.9999) = 4.3 minutos de tolerância
199
+ - Sem tempo para reagir antes do budget esgotar
200
+ - Burn rate alerts disparam após o budget acabar (zero-level)
201
+
202
+ CERTO: target ≤ 99.95% para SLO real
203
+ Para 99.99%+, use métricas/dashboards informativos (não alerta)
204
+ ```
205
+
206
+ ### ANTI: SLO global "site up"
207
+
208
+ ```text
209
+ ANTI: 1 SLO "site availability" para tudo
210
+ - Falha em /api/v1/admin não conta para 99% dos clientes
211
+ - Falha em /api/v1/checkout = catastrófico
212
+ - Misturar = alarmes confusos, ações vagas
213
+
214
+ CERTO: 1 SLO por jornada crítica do user
215
+ - checkout_success: 99.9%
216
+ - login_success: 99.95%
217
+ - search_p95_latency: 99% < 200ms
218
+ - admin_panel: SEM SLO (uso baixo, latência aceitável)
219
+ ```
220
+
221
+ ### ANTI: SLO sem owner
222
+
223
+ ```text
224
+ ANTI: SLO definido em retrospectiva, sem dono nomeado
225
+ - Burn alert dispara → ninguém atende → escalation
226
+ - Sem follow-up no fim do mês
227
+
228
+ CERTO: SLO tem owner em arquivo (yaml ou tabela DB)
229
+ owner = team email ou pessoa específica
230
+ Burn alert roteia direto para owner antes de escalation
231
+ ```
232
+
233
+ ### ANTI: SLO == SLA externo
234
+
235
+ ```text
236
+ ANTI: usar SLA do contrato (99.9% uptime) como SLO interno
237
+
238
+ PROBLEMA: 0 margem de segurança. Atinge SLA mínimo no fio = 1 incident e quebra.
239
+
240
+ CERTO: SLO interno mais rígido que SLA externo
241
+ SLA externo: 99.9% (compromisso com cliente)
242
+ SLO interno: 99.95% (margem de 5× para reagir)
243
+ ```
244
+
245
+ ### ANTI: alterar SLI quando burn ocorre
246
+
247
+ ```text
248
+ ANTI: SLO está queimando → "vamos relaxar SLI para reduzir false positives"
249
+ (definir bad_event mais frouxo)
250
+
251
+ PROBLEMA: você está mascarando dor real. Próximo incident similar passa silencioso.
252
+
253
+ CERTO: SLI é compromisso com customer experience. Se está queimando, fixar
254
+ o problema (root cause via core-analysis-loop), não o SLI.
255
+ Se SLI sistematicamente errado (mede coisa errada): substituir, não relaxar.
256
+ ```
257
+
258
+ ### ANTI: fixed window (mensal/calendário)
259
+
260
+ ```text
261
+ ANTI: error budget reseta dia 1 do mês
262
+
263
+ PROBLEMA:
264
+ - "Tivemos outage dia 31, reseta amanhã" — cliente NÃO esquece
265
+ - Pressão para postergar fixes para "depois do reset"
266
+ - Behavioral hazard: deploy arriscado dia 30
267
+
268
+ CERTO: sliding window 30d
269
+ Outage dia 31 fica no budget até dia 30 do mês seguinte (sai gradualmente)
270
+ Sem incentivo perverso, comportamento humano realista
271
+ ```
272
+
273
+ ## Verificação
274
+
275
+ Antes de marcar SLO como produção-pronto:
276
+
277
+ 1. **Owner nomeado** — email/team em `slo.owner`
278
+ 2. **SLI event-based** — pred boolean, não time-bucket
279
+ 3. **Target ≤ 99.95%** — > 99.95% sinaliza informativo, não SLO
280
+ 4. **Window 30d sliding** — não fixed
281
+ 5. **Customer-facing journey** — SLI mede o que o cliente sente
282
+ 6. **Materialized view** existe e é refreshable (pg_cron)
283
+ 7. **Burn alerts** configurados (ver skill `burn-rate-alerting`)
284
+ 8. **Quero SLO ou metric?** — se a resposta é "informativo", crie metric, não SLO
285
+
286
+ ---
287
+
288
+ ## Ver também
289
+
290
+ - `kit/skills/_shared-observability/glossary.md` — termos canônicos SLI/SLO/error budget
291
+ - `kit/skills/structured-events/SKILL.md` — eventos canônicos para alimentar SLI
292
+ - `kit/skills/burn-rate-alerting/SKILL.md` — lookahead/baseline windows
293
+ - `kit/skills/core-analysis-loop/SKILL.md` — investigar quando SLO queima
294
+ - `kit/agents/slo-engineer.md` — gera SLO.md + SQL para materializar SLI
295
+
296
+ *Material-fonte: Observability Engineering (O'Reilly, 2022) — Cap 12: "Using Service-Level Objectives for Reliability".*