@luanpdd/kit-mcp 1.9.0 → 1.11.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 (84) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +58 -0
  3. package/gates/ai-prompt-stability.md +120 -0
  4. package/gates/golden-signals-coverage.md +133 -0
  5. package/gates/legacy-refactor-safety.md +178 -0
  6. package/gates/observability-coverage.md +151 -0
  7. package/gates/postmortem-template-required.md +127 -0
  8. package/gates/prr-checklist-coverage.md +128 -0
  9. package/gates/release-pipeline-policy.md +132 -0
  10. package/kit/COMANDOS.md +15 -0
  11. package/kit/agents/ai-mutation-tester.md +298 -0
  12. package/kit/agents/cascading-failures-auditor.md +306 -0
  13. package/kit/agents/executor.md +13 -0
  14. package/kit/agents/golden-signals-instrumenter.md +241 -0
  15. package/kit/agents/legacy-characterizer.md +378 -0
  16. package/kit/agents/load-shedding-instrumenter.md +297 -0
  17. package/kit/agents/observability-coverage-auditor.md +325 -0
  18. package/kit/agents/omm-auditor.md +99 -0
  19. package/kit/agents/payload-capture-instrumenter.md +283 -0
  20. package/kit/agents/planner.md +29 -0
  21. package/kit/agents/postmortem-writer.md +282 -0
  22. package/kit/agents/prr-conductor.md +296 -0
  23. package/kit/agents/refactor-safety-auditor.md +414 -0
  24. package/kit/agents/release-pipeline-auditor.md +360 -0
  25. package/kit/agents/seam-finder.md +367 -0
  26. package/kit/agents/shotgun-surgery-detector.md +359 -0
  27. package/kit/agents/storytelling-analyst.md +309 -0
  28. package/kit/agents/supabase-architect.md +49 -0
  29. package/kit/agents/supabase-edge-fn-writer.md +114 -0
  30. package/kit/agents/supabase-migration-writer.md +80 -0
  31. package/kit/agents/supabase-storage-implementer.md +156 -0
  32. package/kit/agents/toil-auditor.md +277 -0
  33. package/kit/agents/verifier.md +30 -0
  34. package/kit/commands/auditar-cascading.md +111 -0
  35. package/kit/commands/auditar-marco.md +124 -1
  36. package/kit/commands/auditar-observabilidade-cobertura.md +183 -0
  37. package/kit/commands/auditar-refactor.md +219 -0
  38. package/kit/commands/auditar-release.md +109 -0
  39. package/kit/commands/auditar-toil.md +129 -0
  40. package/kit/commands/capturar-payloads.md +193 -0
  41. package/kit/commands/caracterizar-prompt.md +195 -0
  42. package/kit/commands/caracterizar.md +212 -0
  43. package/kit/commands/concluir-marco.md +95 -1
  44. package/kit/commands/detectar-duplicacao.md +197 -0
  45. package/kit/commands/discutir-fase.md +41 -0
  46. package/kit/commands/encontrar-seams.md +136 -0
  47. package/kit/commands/forense.md +103 -1
  48. package/kit/commands/golden-signals.md +142 -0
  49. package/kit/commands/legacy.md +263 -0
  50. package/kit/commands/load-shedding.md +117 -0
  51. package/kit/commands/observabilidade.md +2 -0
  52. package/kit/commands/postmortem.md +179 -0
  53. package/kit/commands/prr.md +205 -0
  54. package/kit/commands/refactor-seguro.md +321 -0
  55. package/kit/commands/risk-budget.md +220 -0
  56. package/kit/commands/sre.md +230 -0
  57. package/kit/commands/storytelling.md +179 -0
  58. package/kit/skills/_shared-legacy/glossary.md +389 -0
  59. package/kit/skills/_shared-sre/glossary.md +712 -0
  60. package/kit/skills/ai-prompt-characterization/SKILL.md +335 -0
  61. package/kit/skills/blameless-postmortems/SKILL.md +340 -0
  62. package/kit/skills/cascading-failures/SKILL.md +307 -0
  63. package/kit/skills/eliminating-toil/SKILL.md +243 -0
  64. package/kit/skills/event-based-slos/SKILL.md +22 -0
  65. package/kit/skills/four-golden-signals/SKILL.md +314 -0
  66. package/kit/skills/hermetic-builds/SKILL.md +323 -0
  67. package/kit/skills/legacy-api-only-applications/SKILL.md +358 -0
  68. package/kit/skills/legacy-characterization-tests/SKILL.md +330 -0
  69. package/kit/skills/legacy-effect-analysis/SKILL.md +331 -0
  70. package/kit/skills/legacy-extract-class/SKILL.md +203 -0
  71. package/kit/skills/legacy-monster-methods/SKILL.md +444 -0
  72. package/kit/skills/legacy-programming-by-difference/SKILL.md +252 -0
  73. package/kit/skills/legacy-seams-and-test-harness/SKILL.md +460 -0
  74. package/kit/skills/legacy-shotgun-surgery/SKILL.md +286 -0
  75. package/kit/skills/legacy-sprout-wrap-techniques/SKILL.md +434 -0
  76. package/kit/skills/legacy-storytelling-naked-crc/SKILL.md +270 -0
  77. package/kit/skills/llm-as-dependency/SKILL.md +436 -0
  78. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -0
  79. package/kit/skills/pre-refactor-characterization/SKILL.md +421 -0
  80. package/kit/skills/production-readiness-review/SKILL.md +305 -0
  81. package/kit/skills/release-engineering/SKILL.md +367 -0
  82. package/kit/skills/retry-strategies/SKILL.md +372 -0
  83. package/kit/skills/sre-risk-management/SKILL.md +221 -0
  84. package/package.json +2 -2
@@ -0,0 +1,314 @@
1
+ ---
2
+ name: four-golden-signals
3
+ description: Use ao instrumentar serviço user-facing — Latency + Traffic + Errors + Saturation, percentis (não mean), histogram exponencial, latência success vs error separadas.
4
+ ---
5
+
6
+ # SRE — Four Golden Signals
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao instrumentar Edge Function/serviço/microservice user-facing. Trigger phrases:
11
+
12
+ - "golden signals", "4 sinais dourados"
13
+ - "latency, traffic, errors, saturation"
14
+ - "instrumentar serviço", "métricas mínimas"
15
+ - "p99 latency", "percentis vs mean"
16
+ - "black-box vs white-box monitoring"
17
+ - "Google SRE cap 6"
18
+ - "Latency success vs error"
19
+
20
+ ## Regras absolutas
21
+
22
+ - **4 sinais são universais para serviço user-facing** — Latency + Traffic + Errors + Saturation. Se mede esses 4, captura ~95% da saúde operacional. Outros sinais (CPU, memória, disco I/O) são **causas potenciais**, não sintomas — vão em white-box monitoring secundário.
23
+ - **Latency success vs error sempre separadas** — falhas rápidas (HTTP 500 em 5ms) mascaram latência ruim de successes se misturadas. Sempre `histogram(duration_ms, {result: 'success'})` e `histogram(duration_ms, {result: 'error'})` em séries distintas.
24
+ - **NUNCA mean para latency** — long tail invisível: mean=50ms mas p99=5000ms é UX ruim para 1% dos usuários (tipicamente os mais valiosos: enterprise tier). SEMPRE histogram com percentis.
25
+ - **Histogram com bucketing exponencial** — buckets `[1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000]` ms ou base 1.5/2. Captura long tail sem cardinality explosion.
26
+ - **Errors counter por error.type (não message)** — `error.type` enumerado (5-15 valores: `timeout`, `validation`, `auth`, `rate_limit`, `db`, `provider_down`, ...). `error.message` é alta cardinalidade — não usar como dimension.
27
+ - **Saturation é resource-specific** — não existe métrica genérica de saturação. Para HTTP service: connection pool used %. Para DB: tablespace used %. Para queue: queue depth. Para CPU-bound: load average. Identificar O recurso mais escasso ANTES de instrumentar.
28
+ - **Black-box monitora UX, white-box monitora internals** — black-box (synthetic prober HTTP) detecta "site offline" mesmo se métricas internas estão verdes (corner case clássico). White-box (golden signals) explica "porquê" quando black-box dispara.
29
+ - **Reportar p50, p95, p99, p99.9 — não só p99** — p50 (mediana) é UX típica; p95 é primeiro deslize; p99 é cauda; p99.9 é seu 1 em 1000 que é seu cliente enterprise. Cada percentil conta uma história diferente.
30
+
31
+ ## Patterns canônicos
32
+
33
+ ### Pattern: definição canônica dos 4 signals (tabela)
34
+
35
+ | Signal | Definição | Tipo de instrument | Granularity recomendada |
36
+ |---|---|---|---|
37
+ | **Latency** | Tempo de request bem-sucedido vs falho — SEPARADO | Histogram (ms) com bucketing exponencial | Por endpoint × `result` (success/error) |
38
+ | **Traffic** | Volume de demanda — requests/s, msgs/s, bytes/s | Counter | Por endpoint × method |
39
+ | **Errors** | Taxa de requests que falharam (explícitas: 5xx; implícitas: 200 com payload errado; políticas: > SLO target) | Counter | Por endpoint × `error.type` |
40
+ | **Saturation** | "Quão cheio" o serviço está — % do recurso mais escasso | ObservableGauge (%) | Por resource (connection pool, queue, CPU) |
41
+
42
+ ### Pattern: instrumentação canônica em OTel SDK (TypeScript/Deno)
43
+
44
+ ```ts
45
+ // PT-BR: 4 golden signals em Edge Function — copiar este shape
46
+ import { trace, metrics } from '@opentelemetry/api'
47
+
48
+ const tracer = trace.getTracer('orders-service')
49
+ const meter = metrics.getMeter('orders-service')
50
+
51
+ // PT-BR: 1. LATENCY — histogram bucketed exponencial
52
+ const latencyHistogram = meter.createHistogram('http_request_duration_ms', {
53
+ description: 'Request latency in ms — split by result',
54
+ unit: 'ms',
55
+ advice: { explicitBucketBoundaries: [1, 2, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000] }
56
+ })
57
+
58
+ // PT-BR: 2. TRAFFIC — counter de requests recebidos
59
+ const trafficCounter = meter.createCounter('http_requests_total', {
60
+ description: 'Total HTTP requests received'
61
+ })
62
+
63
+ // PT-BR: 3. ERRORS — counter por error.type (categoria, não message)
64
+ const errorsCounter = meter.createCounter('http_errors_total', {
65
+ description: 'Total HTTP errors by error.type'
66
+ })
67
+
68
+ // PT-BR: 4. SATURATION — gauge do recurso mais escasso
69
+ const saturationGauge = meter.createObservableGauge('db_connection_pool_used_pct', {
70
+ description: 'DB connection pool utilization %',
71
+ unit: '%'
72
+ })
73
+ saturationGauge.addCallback((result) => {
74
+ // PT-BR: callback executado em scrape — lê estado atual do pool
75
+ result.observe(getConnectionPoolUsedPct(), { resource: 'db_pool', service: 'orders' })
76
+ })
77
+
78
+ export async function placeOrder(req: Request) {
79
+ const startMs = performance.now()
80
+ const dims = { endpoint: '/api/v1/orders', method: 'POST' }
81
+
82
+ // PT-BR: 2. Traffic — incrementar antes de processar
83
+ trafficCounter.add(1, dims)
84
+
85
+ return tracer.startActiveSpan('place_order', async (span) => {
86
+ try {
87
+ const order = await db.insertOrder(req.body)
88
+ // PT-BR: 1. Latency success — só após success confirmar
89
+ const durationMs = performance.now() - startMs
90
+ latencyHistogram.record(durationMs, { ...dims, result: 'success' })
91
+ return order
92
+ } catch (e) {
93
+ // PT-BR: 1. Latency error — separada da success
94
+ const durationMs = performance.now() - startMs
95
+ latencyHistogram.record(durationMs, { ...dims, result: 'error' })
96
+ // PT-BR: 3. Errors — counter por error.type (enum baixa cardinalidade)
97
+ errorsCounter.add(1, { ...dims, error_type: classify(e) })
98
+ throw e
99
+ } finally {
100
+ span.end()
101
+ }
102
+ })
103
+ }
104
+
105
+ // PT-BR: classifier — enum estável de 5-15 valores
106
+ function classify(e: unknown): string {
107
+ if (e instanceof TimeoutError) return 'timeout'
108
+ if (e instanceof ValidationError) return 'validation'
109
+ if (e instanceof AuthError) return 'auth'
110
+ if (e instanceof RateLimitError) return 'rate_limit'
111
+ if (e instanceof DbError) return 'db'
112
+ return 'unknown'
113
+ }
114
+ ```
115
+
116
+ ### Pattern: queries SQL para 4 signals em 1 dashboard
117
+
118
+ ```sql
119
+ -- PT-BR: dashboard único — 4 golden signals últimos 60 minutos, por minuto
120
+ select
121
+ date_trunc('minute', timestamp) as minute,
122
+ -- Traffic
123
+ count(*) as traffic_rpm,
124
+ -- Errors (por error.type)
125
+ count(*) filter (where result_success = false) as errors_total,
126
+ count(*) filter (where error_type = 'timeout') as errors_timeout,
127
+ count(*) filter (where error_type = 'rate_limit') as errors_rate_limit,
128
+ count(*) filter (where error_type = 'db') as errors_db,
129
+ -- Latency p50/p95/p99 — APENAS success
130
+ percentile_cont(0.50) within group (order by duration_ms)
131
+ filter (where result_success = true) as latency_p50_success,
132
+ percentile_cont(0.95) within group (order by duration_ms)
133
+ filter (where result_success = true) as latency_p95_success,
134
+ percentile_cont(0.99) within group (order by duration_ms)
135
+ filter (where result_success = true) as latency_p99_success,
136
+ -- Latency p99 — APENAS error (visibilidade de error path lentidão)
137
+ percentile_cont(0.99) within group (order by duration_ms)
138
+ filter (where result_success = false) as latency_p99_error,
139
+ -- Saturation (gauge max no minuto)
140
+ max(connection_pool_used_pct) as saturation_pool_max
141
+ from observability.events
142
+ where service = 'orders-api' and timestamp > now() - interval '60 minutes'
143
+ group by minute
144
+ order by minute desc;
145
+ ```
146
+
147
+ ### Pattern: black-box probe complementar (synthetic check)
148
+
149
+ ```ts
150
+ // PT-BR: black-box monitoring — chamar serviço como cliente externo
151
+ // Roda em CI ou serviço external (uptimerobot, datadog synthetics)
152
+ async function blackBoxProbe(): Promise<{ ok: boolean; durationMs: number }> {
153
+ const startMs = Date.now()
154
+ const r = await fetch('https://api.example.com/api/v1/orders/probe', {
155
+ method: 'POST',
156
+ body: JSON.stringify({ probe: true, sku: 'TEST-001' }),
157
+ headers: { 'X-Probe': 'true' }
158
+ })
159
+ const durationMs = Date.now() - startMs
160
+ // PT-BR: validar resposta — não basta status 200
161
+ const body = await r.json()
162
+ const ok = r.status === 200 && body.order_id != null && durationMs < 1000
163
+ return { ok, durationMs }
164
+ }
165
+
166
+ // PT-BR: rodar a cada 30s; alerta se 3 consecutivos falham (debounce contra flake)
167
+ ```
168
+
169
+ ### Pattern: saturation por tipo de serviço
170
+
171
+ | Tipo de serviço | Recurso mais escasso | Métrica de saturation |
172
+ |---|---|---|
173
+ | HTTP API stateless | Connection pool DB | `db_connection_pool_used_pct` |
174
+ | API com cache | Memory do cache | `cache_memory_used_pct` |
175
+ | Worker async | Queue depth | `queue_depth_messages` |
176
+ | Edge Function | Concurrency limit Deno | `concurrent_executions_pct` |
177
+ | DB | Tablespace ou WAL | `disk_used_pct`, `wal_lag_bytes` |
178
+ | CPU-bound (encoder, ML) | Load average | `cpu_load_avg_5min` |
179
+ | Network egress | Bandwidth | `egress_bytes_per_sec_pct` |
180
+
181
+ ## Anti-patterns
182
+
183
+ ### ANTI: mean latency
184
+
185
+ ```text
186
+ ANTI: alerta/dashboard com avg(duration_ms) — long tail invisível.
187
+
188
+ PROBLEMA: mean=50ms mas p99=5000ms = UX ruim invisível; cliente enterprise
189
+ (no p99) sofre sem nunca disparar alerta. Mean é puxado para baixo
190
+ por mass de requests rápidos; sinaliza "tudo ok" enquanto 1% dos
191
+ users espera 5s.
192
+
193
+ CERTO: histogram com percentile_cont(0.99); alertar em p99 > target.
194
+ Reportar p50/p95/p99/p99.9 para ver formato da distribuição.
195
+ ```
196
+
197
+ ### ANTI: latência success+error misturadas
198
+
199
+ ```text
200
+ ANTI: histogram(duration_ms) sem dimension result.
201
+
202
+ PROBLEMA: falhas rápidas (HTTP 500 em 5ms quando timeout dispara cedo)
203
+ puxam mean/percentis para baixo; mascaram lentidão real de
204
+ requests bem-sucedidos. Dashboard mostra "p99=80ms" mas
205
+ successes reais são 800ms.
206
+
207
+ CERTO: dimension {result: 'success'} vs {result: 'error'} SEMPRE separadas
208
+ em séries distintas. SLI/SLO computado APENAS sobre success path.
209
+ ```
210
+
211
+ ### ANTI: Errors com error.message como dimension
212
+
213
+ ```text
214
+ ANTI: errorsCounter.add(1, { error_message: e.message })
215
+
216
+ PROBLEMA: cada mensagem única é uma série temporal; cardinality explosion
217
+ (1M+ séries em horas se message contém timestamps/IDs/random);
218
+ time-series DB OOMs ou throttles; queries lentas/impossíveis;
219
+ custo de armazenamento explode.
220
+
221
+ CERTO: enum error.type com 5-15 valores fixos (timeout, validation, auth,
222
+ rate_limit, db, provider_down, unknown); error.message em
223
+ log/span attribute (não métrica) para debug pontual.
224
+ ```
225
+
226
+ ### ANTI: monitoring causes não symptoms
227
+
228
+ ```text
229
+ ANTI: alertar em "CPU > 80% / memory < 10% / threads > N"
230
+
231
+ PROBLEMA: mistura "what" (sintoma user-facing) com "why" (causa interna);
232
+ falsos positivos (cron job legítimo dispara CPU);
233
+ falsos negativos (sistema lento sem CPU alta — saturação em
234
+ connection pool ou rede); on-call paginado por nada e
235
+ incidents reais passam silenciosos.
236
+
237
+ CERTO: alertar em SLO burn rate sobre os 4 signals (event-based,
238
+ customer-impacting); usar CPU/memory como debug context em
239
+ white-box monitoring, não como alert source.
240
+ ```
241
+
242
+ ### ANTI: saturation genérica
243
+
244
+ ```text
245
+ ANTI: copiar pattern de saturation de outro serviço sem identificar o
246
+ gargalo real.
247
+
248
+ PROBLEMA: mede CPU em serviço onde gargalo é connection pool; mede memory
249
+ em serviço CPU-bound; saturation alerta nunca dispara antes do
250
+ incident; quando incident acontece, dashboard mostra "saturação
251
+ OK" e ninguém sabe explicar por quê.
252
+
253
+ CERTO: identificar EXPLICITAMENTE o recurso mais escasso (DB pool? queue
254
+ depth? Deno concurrency? tablespace?) ANTES de instrumentar (ver
255
+ Pattern: saturation por tipo de serviço). Cada serviço tem 1 ou 2
256
+ gargalos reais — instrumentar esses, não copiar template.
257
+ ```
258
+
259
+ ### ANTI: black-box only (sem white-box)
260
+
261
+ ```text
262
+ ANTI: só prober externo (synthetic check), sem instrumentação interna.
263
+
264
+ PROBLEMA: sabe que "site offline" mas não sabe porquê; debug requer SSH
265
+ em prod / log dive sem instrumentation; MTTR cresce horas;
266
+ incidents repetem porque root cause nunca foi capturada.
267
+
268
+ CERTO: black-box detecta UX impact (cliente real não consegue) + white-box
269
+ (4 signals) explica root cause. Os dois juntos: black-box dispara,
270
+ white-box mostra qual signal degradou (latency? errors? saturation?)
271
+ e em qual endpoint.
272
+ ```
273
+
274
+ ## Verificação
275
+
276
+ Antes de marcar instrumentação como production-ready, validar:
277
+
278
+ 1. **Os 4 signals presentes** — Latency (histogram), Traffic (counter), Errors (counter por error.type), Saturation (gauge resource-specific)
279
+ 2. **Latency separada** — `result: 'success'` e `result: 'error'` em séries distintas
280
+ 3. **Histogram com bucketing exponencial** — não fixed buckets lineares
281
+ 4. **error.type é enum (5-15 valores)** — não `error.message` como dimension
282
+ 5. **Saturation tem o recurso certo identificado** — connection pool? queue depth? concurrency? CPU load?
283
+ 6. **Black-box probe complementar** — synthetic check do happy path principal a cada 30s
284
+ 7. **Dashboard de 4 signals** existe e é o **primeiro** lugar de debug em incident
285
+
286
+ ## Saturation as cascading failure trigger (v1.11)
287
+
288
+ **Saturation > threshold é early warning de cascading failure** (cap 22). Quando ainda há tempo para load shedding manter SLO; quando hit 100%, já está em cascade. Threshold tuning canônico:
289
+
290
+ | Recurso | Warning | Critical | Ação automática |
291
+ |---|---|---|---|
292
+ | **CPU load** | > 70% | > 90% | Load shed; scale up |
293
+ | **Memory used** | > 80% | > 95% | Load shed; OOM protection |
294
+ | **Queue depth (pgmq)** | > 70% capacity | > 90% capacity | Drop oldest; scale consumers |
295
+ | **Connection pool (DB)** | > 70% used | > 90% used | Throttle slow queries; scale pool |
296
+ | **Concurrency limit** | > 80% inflight | > 95% inflight | Reject new (503 + Retry-After) |
297
+ | **File descriptors** | > 70% ulimit | > 90% ulimit | Close idle conns; scale up |
298
+
299
+ **Resposta canônica:** quando saturation > Critical, server-side ativa load shedding (skill `load-shedding-graceful-degradation` v1.11) — retorna 503 + Retry-After ANTES de aceitar request que vai falhar. Coopera com caller-side defesas (skill `retry-strategies` v1.11 — full jitter respeita Retry-After).
300
+
301
+ Cross-ref: `cascading-failures` (v1.11) detalha 5 triggers; `cascading-failures-auditor` (v1.11) detecta gaps em código.
302
+
303
+ ## Ver também
304
+
305
+ - [`_shared-sre/glossary.md`](../_shared-sre/glossary.md) — termos canônicos golden signals, black-box, white-box, percentile
306
+ - [`opentelemetry-standard`](../opentelemetry-standard/SKILL.md) (v1.9) — OTel SDK base, exporter, OTLP
307
+ - [`structured-events`](../structured-events/SKILL.md) (v1.9) — wide events que alimentam SLI de Errors
308
+ - [`event-based-slos`](../event-based-slos/SKILL.md) (v1.9) — SLO sobre Errors+Latency forma SLI canônico
309
+ - [`burn-rate-alerting`](../burn-rate-alerting/SKILL.md) (v1.9) — alertar em SLO burn-rate, não em CPU
310
+ - [`production-readiness-review`](../production-readiness-review/SKILL.md) — PRR axis "Instrumentation" exige 4 signals
311
+
312
+ ---
313
+
314
+ *Material-fonte: Site Reliability Engineering — Beyer, Jones, Petoff, Murphy (Google/O'Reilly, 2016) — Cap 6: "Monitoring Distributed Systems" (Four Golden Signals).*
@@ -0,0 +1,323 @@
1
+ ---
2
+ name: hermetic-builds
3
+ description: Use ao desenhar/auditar pipeline de build — reproducibility + isolation + provenance + lockfiles + frozen-install + SLSA framework. Cap 8 livro Google SRE.
4
+ ---
5
+
6
+ # SRE — Hermetic Builds
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao desenhar/auditar CI/CD ou ao investigar discrepância "no meu ambiente roda". Trigger phrases:
11
+
12
+ - "hermetic build", "reproducible build"
13
+ - "build cache", "lockfile"
14
+ - "frozen-lockfile", "npm ci", "pnpm install --frozen-lockfile"
15
+ - "build provenance", "SLSA"
16
+ - "config drift entre environments"
17
+ - "cap 8 Google SRE"
18
+
19
+ ## Regras absolutas
20
+
21
+ - **Hermetic = mesmo input → mesmo output, qualquer máquina, qualquer momento.** Sem essa propriedade, build não é determinístico → forensics impossível.
22
+ - **Lockfile commitado SEMPRE.** `package-lock.json`, `pnpm-lock.yaml`, `deno.lock`, `Cargo.lock`, `go.sum`, `Pipfile.lock`. Sem lockfile = não-reproducible.
23
+ - **CI usa `frozen-lockfile` mode.** `npm ci` (não `npm install`), `pnpm install --frozen-lockfile`, `cargo install --locked`, `pip install --require-hashes`. Modo CI FALHA se lockfile não-sincronizado.
24
+ - **Sem network durante build (após install step).** Build hermético: depois de baixar deps, build OFFLINE. Network durante build = não-reprodutível.
25
+ - **Sem timestamps em output.** `--no-timestamps` em compilers; SOURCE_DATE_EPOCH em outros. Output bit-idêntico entre runs.
26
+ - **Build provenance gerada (SLSA framework).** Metadata: commit SHA + builder ID + deps versions + signatures. Cada artefato tem proveniência.
27
+ - **Build cache require hermeticidade.** Cache hit baseado em hash de input; só funciona se output é determinístico.
28
+
29
+ ## Patterns canônicos
30
+
31
+ ### Pattern 1: Lockfile workflow canônico (JS/TS)
32
+
33
+ ```bash
34
+ # DEV — adicionando dep
35
+ pnpm add zod # atualiza package.json + lockfile
36
+ git add package.json pnpm-lock.yaml
37
+ git commit -m "deps: add zod"
38
+
39
+ # CI — install
40
+ pnpm install --frozen-lockfile # falha se lockfile dessincronizado
41
+ # (= alguém esqueceu de commitar lockfile)
42
+
43
+ # OUTROS LOCKS canônicos:
44
+ # Node/npm: npm ci (npm 7+, requer package-lock.json)
45
+ # Node/yarn: yarn install --immutable (yarn 2+)
46
+ # Node/pnpm: pnpm install --frozen-lockfile
47
+ # Deno: deno install --frozen
48
+ # Python/pip: pip install --require-hashes -r requirements.txt
49
+ # Python/poetry: poetry install --no-interaction
50
+ # Rust: cargo install --locked (locked == respect Cargo.lock)
51
+ # Go: go mod download (go.sum acts como lockfile)
52
+ # Ruby: bundle install --frozen
53
+ ```
54
+
55
+ ### Pattern 2: GitHub Actions hermetic recipe
56
+
57
+ ```yaml
58
+ # .github/workflows/build.yml — hermetic build
59
+ name: Build & Test
60
+ on: [push, pull_request]
61
+
62
+ jobs:
63
+ build:
64
+ runs-on: ubuntu-latest
65
+ steps:
66
+ - uses: actions/checkout@v6
67
+ with:
68
+ # PT-BR: full clone para git provenance
69
+ fetch-depth: 0
70
+
71
+ - uses: actions/setup-node@v6
72
+ with:
73
+ node-version: '24' # ← VERSÃO PINADA
74
+ cache: 'pnpm'
75
+
76
+ # PT-BR: pnpm cache sincronizado com lockfile hash
77
+ - uses: pnpm/action-setup@v4
78
+ with:
79
+ version: 9.15.0 # ← VERSÃO PINADA
80
+
81
+ # PT-BR: install com frozen-lockfile (falha se desync)
82
+ - run: pnpm install --frozen-lockfile
83
+
84
+ # PT-BR: build OFFLINE — sem rede após install
85
+ - run: pnpm build
86
+ env:
87
+ # disable any network call
88
+ NODE_OPTIONS: '--no-network-family-autoselection'
89
+
90
+ # PT-BR: tests
91
+ - run: pnpm test
92
+
93
+ # PT-BR: provenance attestation (SLSA Level 3)
94
+ - uses: actions/attest-build-provenance@v3
95
+ if: github.event_name == 'push'
96
+ with:
97
+ subject-path: 'dist/**/*'
98
+ ```
99
+
100
+ ### Pattern 3: Dockerfile hermetic
101
+
102
+ ```dockerfile
103
+ # PT-BR: Dockerfile reprodutível
104
+ # Versão de base PINADA por hash, não por tag mutável
105
+ FROM node:24-alpine@sha256:abc123def456...
106
+
107
+ WORKDIR /app
108
+
109
+ # PT-BR: lockfile copiado primeiro para cache hit
110
+ COPY package.json pnpm-lock.yaml ./
111
+
112
+ # PT-BR: install determinístico
113
+ RUN corepack enable && \
114
+ pnpm install --frozen-lockfile --prod
115
+
116
+ # PT-BR: copiar source DEPOIS para cache de install
117
+ COPY . .
118
+
119
+ # PT-BR: build sem timestamps
120
+ ENV SOURCE_DATE_EPOCH=0
121
+ RUN pnpm build
122
+
123
+ # Runtime stage
124
+ FROM node:24-alpine@sha256:abc123def456...
125
+ COPY --from=0 /app/dist /app/dist
126
+ COPY --from=0 /app/node_modules /app/node_modules
127
+ COPY --from=0 /app/package.json /app/
128
+
129
+ CMD ["node", "/app/dist/index.js"]
130
+ ```
131
+
132
+ **Key:** image base PINADA por SHA, não tag. Tag `node:24-alpine` muta; SHA é imutável.
133
+
134
+ ### Pattern 4: Build provenance via SLSA
135
+
136
+ SLSA (Supply chain Levels for Software Artifacts) tem 4 níveis:
137
+
138
+ ```text
139
+ SLSA Level 1 — basic
140
+ - source/build documentado
141
+ - provenance gerada (algum metadata)
142
+
143
+ SLSA Level 2 — hosted build
144
+ - build em CI hosted (não local)
145
+ - provenance assinada por builder
146
+ - source version controlled
147
+
148
+ SLSA Level 3 — non-falsifiable provenance
149
+ - builder isolado, não controlável por dev
150
+ - provenance includes: source SHA, build env, deps
151
+ - cryptographically signed
152
+
153
+ SLSA Level 4 — hermetic + 2-party review
154
+ - hermetic build (esta skill)
155
+ - 2 reviewers required
156
+ - reproducible: 2 builders independentes produzem hash igual
157
+ ```
158
+
159
+ GitHub Actions tem `actions/attest-build-provenance` para SLSA Level 3.
160
+
161
+ ### Pattern 5: Detectando builds não-hermético
162
+
163
+ Heurísticas para detectar:
164
+
165
+ ```bash
166
+ # 1. Build referencia variáveis de tempo
167
+ grep -rE "Date\.now|new Date|time\.Now|datetime\.now" Dockerfile build.sh
168
+ # OK em runtime; problema se em build step (timestamp em output)
169
+
170
+ # 2. Build faz network calls após install
171
+ strace -f -e trace=network make build 2>&1 | grep -E "connect|sendto"
172
+ # Esperado: zero output após "install" step
173
+
174
+ # 3. Build depende de env var não-pinada
175
+ env | grep -E "BUILD_|RELEASE_" | grep -v -E "VERSION=|HASH="
176
+ # Vars dinâmicas = build difere entre runs
177
+
178
+ # 4. Lockfile dessincronizado
179
+ pnpm install --frozen-lockfile --offline
180
+ # Falha se lockfile desync; sucesso = OK
181
+
182
+ # 5. 2 builds consecutivos produzem mesmo hash?
183
+ hash1=$(make build && sha256sum dist/main.js)
184
+ make clean && hash2=$(make build && sha256sum dist/main.js)
185
+ [ "$hash1" = "$hash2" ] && echo "hermetic" || echo "non-hermetic"
186
+ ```
187
+
188
+ ### Pattern 6: Common pitfalls
189
+
190
+ ```text
191
+ PITFALL 1: Floating tags em base images
192
+ FROM node:latest ← muta toda hora
193
+ FROM node:24 ← muta minor versions
194
+ FROM node:24-alpine ← muta patch versions
195
+ FROM node:24-alpine@sha256:abc... ← imutável (DESEJADO)
196
+
197
+ PITFALL 2: env vars dinâmicas em build
198
+ RUN echo "BUILD_TIME=$(date)" > /app/build-info ← timestamp variável
199
+ RUN echo "BUILD_TIME=$BUILD_TIME" > /app/build-info ← OK se passa em arg pinado
200
+
201
+ PITFALL 3: random ports/UUIDs em build
202
+ RUN node -e "fs.writeFileSync('id.txt', crypto.randomUUID())"
203
+ ← cada build = id diferente. Anti-hermético.
204
+
205
+ PITFALL 4: dependências baixadas em build, não install
206
+ RUN apk add curl && curl https://example.com/script.sh | sh
207
+ ← não-deterministic. Vendor pode mudar script.
208
+
209
+ PITFALL 5: __pycache__ / .DS_Store em image
210
+ ← pode invalidar cache; varia entre OS de dev
211
+ ```
212
+
213
+ ### Pattern 7: Build cache (hermetic permits caching)
214
+
215
+ ```text
216
+ Build cache só funciona com hermeticidade:
217
+
218
+ cache_key = hash(source_files + deps_lockfile + build_config)
219
+
220
+ Se hermético:
221
+ same input → same output
222
+ cache_key colide → reuse output (10-100× faster)
223
+
224
+ Se não-hermético:
225
+ same input → different output
226
+ cache cant be trusted; always rebuild
227
+
228
+ GitHub Actions cache action exemplo:
229
+ - uses: actions/cache@v4
230
+ with:
231
+ path: |
232
+ ~/.pnpm-store
233
+ node_modules
234
+ key: ${{ runner.os }}-pnpm-${{ hashFiles('pnpm-lock.yaml') }}
235
+ restore-keys: |
236
+ ${{ runner.os }}-pnpm-
237
+ ```
238
+
239
+ ## Anti-patterns
240
+
241
+ ### ANTI: lockfile não commitado
242
+
243
+ ```text
244
+ ANTI: pnpm-lock.yaml em .gitignore. "Cada dev resolve sozinho".
245
+
246
+ PROBLEMA: builds não-reprodutíveis. Bugs irrelacionáveis ao código.
247
+ "No meu ambiente funciona" eternal.
248
+
249
+ CERTO: lockfile SEMPRE commitado. Single source of truth de dep
250
+ versions. CI valida sincronia via --frozen-lockfile.
251
+ ```
252
+
253
+ ### ANTI: `npm install` em CI
254
+
255
+ ```text
256
+ ANTI: CI roda `npm install` (não `npm ci`).
257
+
258
+ PROBLEMA: install pode resolver versions diferentemente entre CI runs.
259
+ Bug que aparece "às vezes".
260
+
261
+ CERTO: `npm ci` (CI mode) — falha se lockfile desync; install
262
+ puramente determinístico.
263
+ ```
264
+
265
+ ### ANTI: image base por tag mutável
266
+
267
+ ```text
268
+ ANTI: FROM node:24-alpine
269
+
270
+ PROBLEMA: cada rebuild puxa versão diferente quando Alpine atualiza.
271
+ Build de hoje !== build de amanhã.
272
+
273
+ CERTO: FROM node:24-alpine@sha256:abc...
274
+ Imutável. Update explicitamente trocando SHA.
275
+ ```
276
+
277
+ ### ANTI: build sem provenance
278
+
279
+ ```text
280
+ ANTI: artefato em prod sem metadata sobre origem.
281
+
282
+ PROBLEMA: incident — qual commit? que deps? quem buildou? Sem provenance,
283
+ forensics chaves manuais.
284
+
285
+ CERTO: attest-build-provenance ativa SLSA. Cada artefato tem JSON
286
+ attestado: source SHA, build env, deps, signatures.
287
+ ```
288
+
289
+ ### ANTI: build cache em ambiente não-hermético
290
+
291
+ ```text
292
+ ANTI: cache hit em build não-deterministic. Output cacheado pode estar
293
+ bugged.
294
+
295
+ PROBLEMA: bug "cacheado", aparece intermitente.
296
+
297
+ CERTO: hermeticidade primeiro, cache depois. Se 2 builds não produzem
298
+ mesmo hash, cache é inválido.
299
+ ```
300
+
301
+ ## Verificação
302
+
303
+ 1. Lockfile commitado para cada package manager usado
304
+ 2. CI usa frozen-lockfile mode (`npm ci`, `--frozen-lockfile`, `--locked`, `--require-hashes`)
305
+ 3. Image base pinada por SHA (não tag mutável)
306
+ 4. Sem network calls após install step
307
+ 5. Sem timestamps/UUIDs/random gerados em build
308
+ 6. SOURCE_DATE_EPOCH=0 ou similar em compilers
309
+ 7. Build provenance gerada (SLSA Level 3 mínimo)
310
+ 8. 2 builds consecutivos produzem hash igual
311
+
312
+ ---
313
+
314
+ ## Ver também
315
+
316
+ - [`_shared-sre/glossary.md`](../_shared-sre/glossary.md) — vocabulário (hermetic, lockfile, SLSA, etc.)
317
+ - [`release-engineering`](../release-engineering/SKILL.md) (v1.11) — pipeline orchestration; hermetic é fundação
318
+ - [`production-readiness-review`](../production-readiness-review/SKILL.md) (v1.10) — PRR Axe 5 verifica hermeticidade
319
+ - [`prr-conductor`](../../agents/prr-conductor.md) (v1.10 + patch v1.11) — Axe 5 ganha checks de hermeticidade
320
+ - [`release-pipeline-auditor`](../../agents/release-pipeline-auditor.md) (v1.11) — agent que audita
321
+ - [`/auditar-release`](../../commands/auditar-release.md) (v1.11) — comando
322
+
323
+ *Material-fonte: Site Reliability Engineering — Beyer/Jones/Petoff/Murphy (Google/O'Reilly, 2016) — Cap 8 (subsection sobre hermetic builds, build orchestration). Plus SLSA framework (slsa.dev).*