@luanpdd/kit-mcp 1.10.0 → 1.12.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 (63) hide show
  1. package/gates/ai-prompt-stability.md +120 -0
  2. package/gates/legacy-refactor-safety.md +178 -0
  3. package/gates/observability-coverage.md +151 -0
  4. package/gates/release-pipeline-policy.md +132 -0
  5. package/kit/COMANDOS.md +15 -0
  6. package/kit/agents/ai-mutation-tester.md +298 -0
  7. package/kit/agents/cascading-failures-auditor.md +306 -0
  8. package/kit/agents/executor.md +13 -0
  9. package/kit/agents/legacy-characterizer.md +378 -0
  10. package/kit/agents/load-shedding-instrumenter.md +297 -0
  11. package/kit/agents/observability-coverage-auditor.md +325 -0
  12. package/kit/agents/omm-auditor.md +47 -0
  13. package/kit/agents/payload-capture-instrumenter.md +283 -0
  14. package/kit/agents/planner.md +29 -0
  15. package/kit/agents/prr-conductor.md +8 -0
  16. package/kit/agents/refactor-safety-auditor.md +414 -0
  17. package/kit/agents/release-pipeline-auditor.md +360 -0
  18. package/kit/agents/seam-finder.md +367 -0
  19. package/kit/agents/shotgun-surgery-detector.md +359 -0
  20. package/kit/agents/storytelling-analyst.md +309 -0
  21. package/kit/agents/supabase-edge-fn-writer.md +12 -0
  22. package/kit/agents/verifier.md +30 -0
  23. package/kit/commands/auditar-cascading.md +111 -0
  24. package/kit/commands/auditar-marco.md +44 -1
  25. package/kit/commands/auditar-observabilidade-cobertura.md +183 -0
  26. package/kit/commands/auditar-refactor.md +219 -0
  27. package/kit/commands/auditar-release.md +109 -0
  28. package/kit/commands/capturar-payloads.md +193 -0
  29. package/kit/commands/caracterizar-prompt.md +195 -0
  30. package/kit/commands/caracterizar.md +212 -0
  31. package/kit/commands/concluir-marco.md +41 -1
  32. package/kit/commands/detectar-duplicacao.md +197 -0
  33. package/kit/commands/discutir-fase.md +41 -0
  34. package/kit/commands/encontrar-seams.md +136 -0
  35. package/kit/commands/forense.md +40 -1
  36. package/kit/commands/legacy.md +263 -0
  37. package/kit/commands/load-shedding.md +117 -0
  38. package/kit/commands/observabilidade.md +2 -0
  39. package/kit/commands/refactor-seguro.md +321 -0
  40. package/kit/commands/sre.md +3 -0
  41. package/kit/commands/storytelling.md +179 -0
  42. package/kit/skills/_shared-legacy/glossary.md +389 -0
  43. package/kit/skills/_shared-sre/glossary.md +139 -0
  44. package/kit/skills/ai-prompt-characterization/SKILL.md +335 -0
  45. package/kit/skills/cascading-failures/SKILL.md +307 -0
  46. package/kit/skills/four-golden-signals/SKILL.md +17 -0
  47. package/kit/skills/hermetic-builds/SKILL.md +323 -0
  48. package/kit/skills/legacy-api-only-applications/SKILL.md +358 -0
  49. package/kit/skills/legacy-characterization-tests/SKILL.md +330 -0
  50. package/kit/skills/legacy-effect-analysis/SKILL.md +331 -0
  51. package/kit/skills/legacy-extract-class/SKILL.md +203 -0
  52. package/kit/skills/legacy-monster-methods/SKILL.md +444 -0
  53. package/kit/skills/legacy-programming-by-difference/SKILL.md +252 -0
  54. package/kit/skills/legacy-seams-and-test-harness/SKILL.md +460 -0
  55. package/kit/skills/legacy-shotgun-surgery/SKILL.md +286 -0
  56. package/kit/skills/legacy-sprout-wrap-techniques/SKILL.md +434 -0
  57. package/kit/skills/legacy-storytelling-naked-crc/SKILL.md +270 -0
  58. package/kit/skills/llm-as-dependency/SKILL.md +436 -0
  59. package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -0
  60. package/kit/skills/pre-refactor-characterization/SKILL.md +421 -0
  61. package/kit/skills/release-engineering/SKILL.md +367 -0
  62. package/kit/skills/retry-strategies/SKILL.md +372 -0
  63. package/package.json +2 -2
@@ -0,0 +1,372 @@
1
+ ---
2
+ name: retry-strategies
3
+ description: Use ao implementar retry — full/equal/decorrelated jitter, exponential backoff cap, retry budget, idempotency keys, when NOT to retry. Cap 22 livro Google SRE.
4
+ ---
5
+
6
+ # SRE — Retry Strategies
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill ao escrever código que chama dep externa e precisa lidar com failure transient. Trigger phrases:
11
+
12
+ - "retry", "exponential backoff"
13
+ - "jitter", "thundering herd"
14
+ - "retry budget"
15
+ - "idempotency key", "safe to retry?"
16
+ - "quando NÃO retentar?"
17
+ - "retry storm"
18
+
19
+ ## Regras absolutas
20
+
21
+ - **Retry SEM jitter = retry storm garantido.** Sempre adicione jitter (full por default).
22
+ - **Retry SEM deadline = work zumbi.** Cada retry respeita deadline propagation; após deadline aborta.
23
+ - **Retry SOMENTE em erros retentáveis.** 5xx, timeout, connection reset = retry. 4xx (validation, auth, not_found) = NÃO retry.
24
+ - **Idempotency key OBRIGATÓRIA em retry de write operation.** Sem idempotency, retry pode duplicar (charge double, send email twice, etc.).
25
+ - **Retry budget global limita amplificação.** Sem budget, retry total = N clients × M retries × cascading.
26
+ - **Max retries ≤ 3-5.** Mais que isso = bug não-transient mascarado.
27
+ - **Backoff cap obrigatório.** Sem cap, último retry pode ser horas. `min(base × 2^attempt, cap)`.
28
+ - **Não retry em rate limit a menos que respeite Retry-After.** 429 sem header → wait default; com header → respeita.
29
+
30
+ ## Patterns canônicos
31
+
32
+ ### Pattern 1: Tipos de jitter (cap 22)
33
+
34
+ ```ts
35
+ // Full jitter — DEFAULT canônico (Google SRE recomenda)
36
+ function fullJitter(baseMs: number, attempt: number, capMs = 30000): number {
37
+ const expBase = Math.min(baseMs * Math.pow(2, attempt), capMs)
38
+ return Math.random() * expBase // [0, expBase)
39
+ }
40
+
41
+ // Equal jitter — variação; metade fixa, metade jitter
42
+ function equalJitter(baseMs: number, attempt: number, capMs = 30000): number {
43
+ const expBase = Math.min(baseMs * Math.pow(2, attempt), capMs)
44
+ return expBase / 2 + Math.random() * (expBase / 2)
45
+ }
46
+
47
+ // Decorrelated jitter — para bursty load (AWS recomenda)
48
+ function decorrelatedJitter(baseMs: number, lastDelayMs: number, capMs = 30000): number {
49
+ return Math.min(capMs, Math.random() * (lastDelayMs * 3 - baseMs) + baseMs)
50
+ }
51
+
52
+ // Comparação:
53
+ // FULL JITTER: spread máximo, simples, default canônico
54
+ // EQUAL JITTER: spread parcial, predictable mínimo
55
+ // DECORRELATED: spread depende do último; melhor pra long outages
56
+ ```
57
+
58
+ ### Pattern 2: Retry com deadline propagation
59
+
60
+ ```ts
61
+ async function callWithRetry<T>(
62
+ call: () => Promise<T>,
63
+ opts: {
64
+ maxRetries: number
65
+ baseMs: number
66
+ capMs?: number
67
+ deadlineMs: number // unix ms; retry só se ainda há tempo
68
+ isRetryable?: (e: Error) => boolean
69
+ retryBudget?: RetryBudget
70
+ }
71
+ ): Promise<T> {
72
+ const startMs = performance.now()
73
+ let lastError: Error | undefined
74
+
75
+ for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
76
+ // Check deadline antes de cada attempt
77
+ if (Date.now() > opts.deadlineMs) {
78
+ throw new DeadlineExceededError(lastError)
79
+ }
80
+
81
+ try {
82
+ return await call()
83
+ } catch (e) {
84
+ lastError = e as Error
85
+
86
+ // Não-retentável → throw imediato
87
+ if (opts.isRetryable && !opts.isRetryable(lastError)) throw lastError
88
+
89
+ // Retry budget global
90
+ if (opts.retryBudget && !opts.retryBudget.tryAcquire()) {
91
+ throw new RetryBudgetExhaustedError(lastError)
92
+ }
93
+
94
+ // Last attempt — não delay
95
+ if (attempt >= opts.maxRetries) throw lastError
96
+
97
+ // Calcula delay com full jitter
98
+ const delayMs = fullJitter(opts.baseMs, attempt, opts.capMs)
99
+
100
+ // Não exceder deadline
101
+ const remainingMs = opts.deadlineMs - Date.now()
102
+ if (delayMs >= remainingMs) {
103
+ throw new DeadlineExceededError(lastError)
104
+ }
105
+
106
+ await sleep(delayMs)
107
+ }
108
+ }
109
+ throw lastError!
110
+ }
111
+ ```
112
+
113
+ ### Pattern 3: When NOT to retry — decision tree
114
+
115
+ ```text
116
+ Erro recebido. Retry?
117
+
118
+ 1. HTTP status 4xx (excluding 408, 429)?
119
+ → NÃO retry. Validation/auth/not_found.
120
+ 400, 401, 403, 404, 422 → throw imediato.
121
+
122
+ 2. HTTP status 408 (Request Timeout)?
123
+ → SIM retry. Servidor pediu (request expirou no servidor).
124
+
125
+ 3. HTTP status 429 (Too Many Requests)?
126
+ → SIM retry, COM Retry-After header se presente.
127
+ Sem Retry-After → backoff default + retry budget.
128
+
129
+ 4. HTTP status 5xx?
130
+ → SIM retry. Server error transient.
131
+
132
+ 5. Network error (connection reset, DNS failure)?
133
+ → SIM retry. Network transient.
134
+
135
+ 6. Timeout local (AbortSignal.timeout estourou)?
136
+ → SIM retry, mas check deadline global.
137
+
138
+ 7. Custom error (validation interna, business rule)?
139
+ → NÃO retry. Bug; retry não resolve.
140
+
141
+ 8. OperationCancelled (deadline upstream)?
142
+ → NÃO retry. Caller já desistiu.
143
+ ```
144
+
145
+ ```ts
146
+ function isRetryable(e: any): boolean {
147
+ // 4xx geralmente não retry
148
+ if (e.statusCode >= 400 && e.statusCode < 500) {
149
+ if (e.statusCode === 408) return true
150
+ if (e.statusCode === 429) return true
151
+ return false
152
+ }
153
+
154
+ // 5xx retry
155
+ if (e.statusCode >= 500 && e.statusCode < 600) return true
156
+
157
+ // Network errors
158
+ if (e.code === 'ECONNRESET' || e.code === 'ETIMEDOUT' || e.code === 'EAI_AGAIN') return true
159
+
160
+ // Aborts não retry (caller desistiu)
161
+ if (e.name === 'AbortError' || e instanceof DeadlineExceededError) return false
162
+
163
+ // Default: não retry
164
+ return false
165
+ }
166
+ ```
167
+
168
+ ### Pattern 4: Idempotency key em writes
169
+
170
+ ```ts
171
+ // PT-BR: idempotency key permite retry seguro de writes
172
+ import { randomUUID } from 'crypto'
173
+
174
+ interface CreateOrderInput {
175
+ customerId: string
176
+ items: OrderItem[]
177
+ idempotencyKey?: string // gerado se não fornecido
178
+ }
179
+
180
+ async function createOrderSafe(client: PaymentClient, input: CreateOrderInput): Promise<Order> {
181
+ const key = input.idempotencyKey ?? randomUUID()
182
+
183
+ return callWithRetry(
184
+ () => client.createOrder({ ...input, idempotencyKey: key }), // ← SAME KEY em retry
185
+ {
186
+ maxRetries: 3,
187
+ baseMs: 500,
188
+ capMs: 30000,
189
+ deadlineMs: Date.now() + 30000,
190
+ isRetryable,
191
+ }
192
+ )
193
+ }
194
+
195
+ // Server-side
196
+ async function createOrderHandler(input: CreateOrderInput): Promise<Order> {
197
+ // Check se já processamos esta key
198
+ const existing = await db.findByIdempotencyKey(input.idempotencyKey)
199
+ if (existing) return existing // retorna mesmo result; safe to retry
200
+
201
+ // Process; record com idempotency_key (UNIQUE constraint)
202
+ return await db.transaction(async (tx) => {
203
+ const order = await tx.orders.insert({
204
+ ...input,
205
+ idempotency_key: input.idempotencyKey, // UNIQUE constraint catches duplicate
206
+ created_at: new Date(),
207
+ })
208
+ return order
209
+ })
210
+ }
211
+ ```
212
+
213
+ **Anti-corruption:** idempotency keys SEMPRE em writes. Stripe, AWS S3, todos suportam. Se sua API não suporta, adicione (1 column UNIQUE).
214
+
215
+ ### Pattern 5: Retry budget (cap 22)
216
+
217
+ ```ts
218
+ // PT-BR: retry budget global limita amplificação
219
+ class RetryBudget {
220
+ private tokens: number
221
+ private readonly maxTokens: number
222
+ private readonly refillRate: number // tokens per second
223
+ private lastRefillMs: number
224
+
225
+ constructor(opts: { maxTokens: number; refillPerSec: number }) {
226
+ this.tokens = opts.maxTokens
227
+ this.maxTokens = opts.maxTokens
228
+ this.refillRate = opts.refillPerSec
229
+ this.lastRefillMs = Date.now()
230
+ }
231
+
232
+ tryAcquire(): boolean {
233
+ this.refill()
234
+ if (this.tokens < 1) return false
235
+ this.tokens--
236
+ return true
237
+ }
238
+
239
+ private refill(): void {
240
+ const now = Date.now()
241
+ const elapsed = (now - this.lastRefillMs) / 1000
242
+ const refill = elapsed * this.refillRate
243
+ this.tokens = Math.min(this.maxTokens, this.tokens + refill)
244
+ this.lastRefillMs = now
245
+ }
246
+ }
247
+
248
+ // Configuração canônica:
249
+ // - maxTokens = 10% da capacidade normal de calls/sec
250
+ // - refillPerSec = mesmo
251
+ // Se sua dep aguenta 1000 RPS, retry budget = 100 RPS de retries.
252
+ // Excede = circuit breaker abre OR caller falha rápido.
253
+
254
+ const retryBudget = new RetryBudget({ maxTokens: 100, refillPerSec: 100 })
255
+ ```
256
+
257
+ ### Pattern 6: Configuração canônica por tipo de call
258
+
259
+ | Tipo de call | Max retries | Base | Cap | Jitter |
260
+ |---|---|---|---|---|
261
+ | **Read DB query** | 3 | 50ms | 1000ms | full |
262
+ | **Write DB transaction** | 3 (com idempotency key) | 100ms | 5000ms | full |
263
+ | **HTTP API third-party** | 3 | 500ms | 30000ms | full |
264
+ | **Webhook delivery** | 5 | 1000ms | 60000ms | decorrelated |
265
+ | **Background job** | 5+ | 5000ms | 600000ms (10min) | decorrelated |
266
+ | **Real-time message** | 0-1 | — | — | — (deadline tight) |
267
+
268
+ ### Pattern 7: Observability de retry
269
+
270
+ Métricas a instrumentar:
271
+
272
+ ```ts
273
+ // Counter de retries por (dep, attempt)
274
+ metrics.counter('retries_total', { dep: 'stripe', attempt: '1' }) // attempt 1, 2, 3
275
+
276
+ // Counter de outcomes finais
277
+ metrics.counter('retry_outcomes_total', { dep: 'stripe', outcome: 'success_after_retry' })
278
+ metrics.counter('retry_outcomes_total', { dep: 'stripe', outcome: 'exhausted_max' })
279
+ metrics.counter('retry_outcomes_total', { dep: 'stripe', outcome: 'budget_exhausted' })
280
+ metrics.counter('retry_outcomes_total', { dep: 'stripe', outcome: 'deadline_exceeded' })
281
+
282
+ // Histogram de delay total adicionado por retry
283
+ metrics.histogram('retry_delay_added_ms', delayMs, { dep: 'stripe' })
284
+ ```
285
+
286
+ Alertas:
287
+ - `rate(retries_total) > 10% × rate(requests_total)` → dep degradada; investigate
288
+ - `retry_outcomes{outcome="budget_exhausted"} > 0` → sistema sob storm; load shedding pode ajudar
289
+ - `histogram retry_delay_added_ms > p99 baseline × 5` → delays inflados; deps lentas
290
+
291
+ ## Anti-patterns
292
+
293
+ ### ANTI: retry sem jitter
294
+
295
+ ```text
296
+ ANTI: setTimeout(call, 1000 * 2^attempt) — fixed exponential.
297
+
298
+ PROBLEMA: 1000 clients sincroniza retries. Storm na recovery.
299
+
300
+ CERTO: Math.random() * 1000 * 2^attempt — full jitter.
301
+ ```
302
+
303
+ ### ANTI: retry em 4xx
304
+
305
+ ```text
306
+ ANTI: catch (e) { return retry(call) } sem checar status.
307
+
308
+ PROBLEMA: 400/422/404 retentado infinitamente. Bug não corrige sozinho.
309
+
310
+ CERTO: isRetryable(e) check antes de retry. 4xx (excluding 408, 429)
311
+ throw imediato.
312
+ ```
313
+
314
+ ### ANTI: retry sem deadline
315
+
316
+ ```text
317
+ ANTI: retry com max=5, base=1s. Worst case: 1+2+4+8+16=31s de delays.
318
+ Plus call time. Cliente já desistiu.
319
+
320
+ PROBLEMA: work zumbi. Recursos consumidos sem benefit.
321
+
322
+ CERTO: deadline propagation. Cada attempt checa Date.now() vs deadline.
323
+ Aborta cedo.
324
+ ```
325
+
326
+ ### ANTI: idempotency key per-attempt
327
+
328
+ ```text
329
+ ANTI: retry gera NEW idempotency key cada attempt.
330
+
331
+ PROBLEMA: cada attempt vira write distinta. Charge double, email
332
+ duplicado.
333
+
334
+ CERTO: idempotency key gerada UMA vez por call lógica. Mesma key
335
+ em todos os attempts.
336
+ ```
337
+
338
+ ### ANTI: max retries muito alto
339
+
340
+ ```text
341
+ ANTI: maxRetries = 20.
342
+
343
+ PROBLEMA: bug não-transient mascarado. Erro real demora pra aparecer.
344
+ Logs de retry inundam observability.
345
+
346
+ CERTO: max 3-5. Mais que isso = error real, não transient. Falha
347
+ rápido + alert > retry esperançoso.
348
+ ```
349
+
350
+ ## Verificação
351
+
352
+ 1. Toda retry tem jitter (full por default)
353
+ 2. Toda retry respeita deadline propagation
354
+ 3. isRetryable() check em cada attempt
355
+ 4. Idempotency key em writes
356
+ 5. Retry budget global ativo
357
+ 6. Max retries ≤ 5
358
+ 7. Backoff cap ≤ 60s para user-facing
359
+ 8. Métricas instrumentadas (counter retries, outcome, histogram delay)
360
+
361
+ ---
362
+
363
+ ## Ver também
364
+
365
+ - [`_shared-sre/glossary.md`](../_shared-sre/glossary.md) — vocabulário (jitter types, retry storm, etc.)
366
+ - [`cascading-failures`](../cascading-failures/SKILL.md) (v1.11) — retry sem jitter é trigger principal de cascade
367
+ - [`load-shedding-graceful-degradation`](../load-shedding-graceful-degradation/SKILL.md) (v1.11) — server-side coopera (503 + Retry-After)
368
+ - [`four-golden-signals`](../four-golden-signals/SKILL.md) (v1.10) — métricas de retry instrumentadas seguindo padrão
369
+ - [`supabase-edge-fn-writer`](../../agents/supabase-edge-fn-writer.md) (v1.8 + patch v1.11) — Edge Functions ganham retry-with-jitter built-in
370
+ - [`cascading-failures-auditor`](../../agents/cascading-failures-auditor.md) (v1.11) — agent detecta retry sem jitter
371
+
372
+ *Material-fonte: Site Reliability Engineering — Beyer/Jones/Petoff/Murphy (Google/O'Reilly, 2016) — Cap 22 (subsections sobre retry, jitter, deadline propagation).*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luanpdd/kit-mcp",
3
- "version": "1.10.0",
3
+ "version": "1.12.0",
4
4
  "description": "Generic infrastructure to ship YOUR personal kit of agents/commands/skills as an MCP server, with cross-IDE sync (Claude Code, Cursor, Codex, Gemini, Windsurf, Antigravity, Copilot, Trae).",
5
5
  "type": "module",
6
6
  "bin": {
@@ -51,7 +51,7 @@
51
51
  "@inquirer/prompts": "^8.4.2",
52
52
  "@modelcontextprotocol/sdk": "^1.0.0",
53
53
  "chokidar": "^5.0.0",
54
- "commander": "^12.1.0",
54
+ "commander": "^14.0.3",
55
55
  "open": "^11.0.0",
56
56
  "picocolors": "^1.1.1"
57
57
  }