@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,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).*
@@ -0,0 +1,358 @@
1
+ ---
2
+ name: legacy-api-only-applications
3
+ description: Use ao escrever ou refatorar código que é maioritariamente wrapper de API externa (cap 15 Feathers + Supabase Edge Functions). Adapter / anti-corruption layer canônico — interface mínima testável + adapter para API real.
4
+ ---
5
+
6
+ # Legacy — API-Only Applications
7
+
8
+ ## Quando usar
9
+
10
+ LLM carrega esta skill quando user trabalha em código que é primariamente wrapper de API externa. Trigger phrases:
11
+
12
+ - "essa edge function só chama Stripe/OpenAI/Twilio"
13
+ - "como testar integração com [vendor]?"
14
+ - "anti-corruption layer", "adapter pattern"
15
+ - "API-only application", "cap 15 Feathers"
16
+ - "wrapper de API"
17
+ - arquivo em `supabase/functions/<name>/index.ts` com 60%+ de chamadas a SDKs/APIs externos
18
+
19
+ ## Regras absolutas
20
+
21
+ - **Adapter pattern é a resposta canônica.** Code de produção depende de **interface mínima**, não da API completa do vendor. Adapter concreto envolve a API real.
22
+ - **Interface mínima = só o que VOCÊ usa.** SDKs do Stripe/OpenAI/etc têm 100+ métodos; você usa 5. Sua interface tem 5.
23
+ - **Anti-corruption layer (DDD) = adapter + tradução de tipos.** Tipos do vendor (e.g., `Stripe.Charge`, `OpenAI.ChatCompletion`) NÃO atravessam camadas internas. Adapter traduz vendor type → domain type.
24
+ - **Modernização Supabase Edge Functions:** Edge Function que wrappar Stripe/OpenAI é o caso paradigmático moderno do cap 15. Pattern canônico: handler depende de interface, adapter implementa, adapter testado isolado, fake adapter em testes.
25
+ - **Modernização LLM providers:** OpenAI/Anthropic clients são API externa. Aplicar exatamente o mesmo pattern — `LLMProvider` interface + `OpenAIAdapter` + `AnthropicAdapter` + `FakeLLMProvider`. Nunca acoplar handler ao SDK específico.
26
+ - **Versionar a interface, não a API do vendor.** Quando vendor muda assinatura, adapter absorve a mudança; consumidor (handler interno) não vê.
27
+ - **Idempotência via adapter.** Adapter pode adicionar idempotency key, retry com jitter, deadline propagation, sem que handler precise saber.
28
+
29
+ ## Patterns canônicos
30
+
31
+ ### Pattern 1: Adapter para vendor API (Stripe canônico)
32
+
33
+ ```ts
34
+ // ANTES — handler acoplado ao SDK Stripe (intestável sem mock global)
35
+ import Stripe from 'stripe'
36
+
37
+ const stripe = new Stripe(Deno.env.get('STRIPE_KEY')!)
38
+
39
+ Deno.serve(async (req) => {
40
+ const order = await req.json()
41
+ const charge = await stripe.charges.create({ // ← acoplamento direto
42
+ amount: order.totalCents,
43
+ currency: order.currency,
44
+ source: order.cardToken,
45
+ })
46
+ return new Response(JSON.stringify({ id: charge.id, status: charge.status }))
47
+ })
48
+
49
+ // DEPOIS — handler depende de interface mínima
50
+ interface PaymentGateway {
51
+ charge(input: ChargeInput): Promise<ChargeResult>
52
+ }
53
+ type ChargeInput = { amountCents: number; currency: string; cardToken: string }
54
+ type ChargeResult = { id: string; status: 'succeeded' | 'failed' | 'pending' }
55
+
56
+ class StripeAdapter implements PaymentGateway {
57
+ constructor(private stripe: Stripe) {}
58
+ async charge(input: ChargeInput): Promise<ChargeResult> {
59
+ const c = await this.stripe.charges.create({
60
+ amount: input.amountCents,
61
+ currency: input.currency,
62
+ source: input.cardToken,
63
+ })
64
+ // anti-corruption: traduz Stripe.Charge.status para nosso domain enum
65
+ const status = this.translateStatus(c.status)
66
+ return { id: c.id, status }
67
+ }
68
+ private translateStatus(s: Stripe.Charge.Status): ChargeResult['status'] {
69
+ if (s === 'succeeded') return 'succeeded'
70
+ if (s === 'failed' || s === 'canceled') return 'failed'
71
+ return 'pending'
72
+ }
73
+ }
74
+
75
+ // Em produção
76
+ const gateway: PaymentGateway = new StripeAdapter(new Stripe(Deno.env.get('STRIPE_KEY')!))
77
+
78
+ // Handler — agora testável
79
+ async function handleCharge(req: Request, gateway: PaymentGateway) {
80
+ const order = await req.json()
81
+ const result = await gateway.charge({
82
+ amountCents: order.totalCents,
83
+ currency: order.currency,
84
+ cardToken: order.cardToken,
85
+ })
86
+ return new Response(JSON.stringify(result))
87
+ }
88
+
89
+ Deno.serve(req => handleCharge(req, gateway))
90
+
91
+ // Em teste
92
+ class FakePaymentGateway implements PaymentGateway {
93
+ charged: ChargeInput[] = []
94
+ result: ChargeResult = { id: 'ch_fake', status: 'succeeded' }
95
+ async charge(input: ChargeInput): Promise<ChargeResult> {
96
+ this.charged.push(input)
97
+ return this.result
98
+ }
99
+ }
100
+
101
+ test('handleCharge — typical input', async () => {
102
+ const gw = new FakePaymentGateway()
103
+ const req = new Request('http://x', {
104
+ method: 'POST',
105
+ body: JSON.stringify({ totalCents: 5000, currency: 'BRL', cardToken: 'tok_x' }),
106
+ })
107
+ await handleCharge(req, gw)
108
+ expect(gw.charged).toHaveLength(1)
109
+ expect(gw.charged[0].amountCents).toBe(5000)
110
+ })
111
+ ```
112
+
113
+ ### Pattern 2: Adapter para LLM provider (modernização total — sem precedente em 2004)
114
+
115
+ ```ts
116
+ // LLM provider como dependência testável (canônico em 2026)
117
+ interface LLMProvider {
118
+ generate(input: GenerateInput): Promise<GenerateResult>
119
+ }
120
+ type GenerateInput = {
121
+ prompt: string
122
+ maxTokens: number
123
+ temperature?: number
124
+ seed?: number // determinismo em testes
125
+ }
126
+ type GenerateResult = {
127
+ text: string
128
+ finishReason: 'stop' | 'length' | 'content_filter'
129
+ inputTokens: number
130
+ outputTokens: number
131
+ }
132
+
133
+ class OpenAIAdapter implements LLMProvider {
134
+ constructor(private client: OpenAI) {}
135
+ async generate(input: GenerateInput): Promise<GenerateResult> {
136
+ const r = await this.client.chat.completions.create({
137
+ model: 'gpt-4',
138
+ messages: [{ role: 'user', content: input.prompt }],
139
+ max_tokens: input.maxTokens,
140
+ temperature: input.temperature ?? 0,
141
+ seed: input.seed,
142
+ })
143
+ return {
144
+ text: r.choices[0].message.content ?? '',
145
+ finishReason: this.translateFinish(r.choices[0].finish_reason),
146
+ inputTokens: r.usage?.prompt_tokens ?? 0,
147
+ outputTokens: r.usage?.completion_tokens ?? 0,
148
+ }
149
+ }
150
+ private translateFinish(f: string): GenerateResult['finishReason'] {
151
+ if (f === 'stop') return 'stop'
152
+ if (f === 'length') return 'length'
153
+ return 'content_filter'
154
+ }
155
+ }
156
+
157
+ class AnthropicAdapter implements LLMProvider {
158
+ constructor(private client: Anthropic) {}
159
+ async generate(input: GenerateInput): Promise<GenerateResult> {
160
+ const r = await this.client.messages.create({
161
+ model: 'claude-opus-4-7',
162
+ messages: [{ role: 'user', content: input.prompt }],
163
+ max_tokens: input.maxTokens,
164
+ temperature: input.temperature ?? 0,
165
+ })
166
+ return {
167
+ text: r.content[0].type === 'text' ? r.content[0].text : '',
168
+ finishReason: this.translateStop(r.stop_reason),
169
+ inputTokens: r.usage.input_tokens,
170
+ outputTokens: r.usage.output_tokens,
171
+ }
172
+ }
173
+ private translateStop(s: string | null): GenerateResult['finishReason'] {
174
+ if (s === 'end_turn') return 'stop'
175
+ if (s === 'max_tokens') return 'length'
176
+ return 'content_filter'
177
+ }
178
+ }
179
+
180
+ class FakeLLMProvider implements LLMProvider {
181
+ responses: GenerateResult[] = []
182
+ callIndex = 0
183
+ async generate(_: GenerateInput): Promise<GenerateResult> {
184
+ if (this.callIndex < this.responses.length) return this.responses[this.callIndex++]
185
+ return { text: 'fake response', finishReason: 'stop', inputTokens: 10, outputTokens: 5 }
186
+ }
187
+ }
188
+ ```
189
+
190
+ **Insight:** sem essa abstração, edge function fica acoplada a 1 vendor. Trocar OpenAI → Anthropic = rewrite. Com adapter = trocar 1 linha (`new AnthropicAdapter(...)` em vez de `new OpenAIAdapter(...)`).
191
+
192
+ ### Pattern 3: Anti-corruption layer (DDD)
193
+
194
+ ```ts
195
+ // VENDOR types — bagunça típica (Stripe, OpenAI, Twilio têm shapes próprios)
196
+ type StripeChargeRaw = {
197
+ id: string
198
+ amount: number // cents
199
+ currency: string // lowercase ISO
200
+ status: 'succeeded' | 'pending' | 'failed' | 'canceled'
201
+ receipt_url?: string // snake_case do vendor
202
+ metadata?: Record<string, string>
203
+ }
204
+
205
+ // DOMAIN types — sua linguagem
206
+ type Charge = {
207
+ chargeId: string
208
+ amountCents: number
209
+ currencyIso4217: string // uppercase
210
+ status: ChargeStatus // domain enum, NÃO o do vendor
211
+ receiptUrl?: string
212
+ }
213
+ type ChargeStatus = 'succeeded' | 'failed' | 'pending' // simplificou; canceled vira failed
214
+
215
+ // Adapter ABSORVE diferenças — domain interno NÃO vê StripeChargeRaw
216
+ class StripeAdapter implements PaymentGateway {
217
+ async charge(input: ChargeInput): Promise<ChargeResult> {
218
+ const raw = await this.stripe.charges.create(...)
219
+ return this.toDomain(raw)
220
+ }
221
+ private toDomain(raw: StripeChargeRaw): Charge {
222
+ return {
223
+ chargeId: raw.id,
224
+ amountCents: raw.amount,
225
+ currencyIso4217: raw.currency.toUpperCase(),
226
+ status: raw.status === 'canceled' || raw.status === 'failed' ? 'failed' : raw.status,
227
+ receiptUrl: raw.receipt_url,
228
+ }
229
+ }
230
+ }
231
+ ```
232
+
233
+ ### Pattern 4: Adapter aplicando cross-cutting concerns
234
+
235
+ Adapter é lugar canônico para retry, timeout, idempotency, instrumentation:
236
+
237
+ ```ts
238
+ class StripeAdapterResilient implements PaymentGateway {
239
+ constructor(private stripe: Stripe, private logger: Logger) {}
240
+
241
+ async charge(input: ChargeInput): Promise<ChargeResult> {
242
+ const idempotencyKey = await crypto.randomUUID()
243
+ const startMs = performance.now()
244
+
245
+ try {
246
+ const c = await retryWithJitter(
247
+ () => this.stripe.charges.create(
248
+ { amount: input.amountCents, currency: input.currency, source: input.cardToken },
249
+ { idempotencyKey, timeout: 5000 }
250
+ ),
251
+ { maxRetries: 3, baseMs: 250 }
252
+ )
253
+
254
+ const latency = performance.now() - startMs
255
+ this.logger.info('stripe.charge', { latency_ms: latency, status: c.status })
256
+ return this.toDomain(c)
257
+ } catch (e) {
258
+ this.logger.warn('stripe.charge.failed', { error: e.message })
259
+ throw e
260
+ }
261
+ }
262
+ }
263
+ ```
264
+
265
+ **Cross-suite:**
266
+ - Retry pattern de v1.11 (`retry-strategies`) aplicável aqui
267
+ - Logging segue v1.9 (`structured-events`)
268
+ - Latency histogram segue v1.10 (`four-golden-signals`)
269
+ - Adapter é exatamente onde "instrumentation shift-left" (v1.9 ODD) faz mais sentido
270
+
271
+ ### Pattern 5: Quando NÃO criar adapter
272
+
273
+ ```text
274
+ - Vendor SDK já tem interface mínima e estável (raríssimo)
275
+ - Edge function é one-shot script (não tem testes nem manutenção continuada)
276
+ - Spike/POC para validar viabilidade (descartável após decisão)
277
+ - Adapter custaria > 4h e prazo é < 1 dia (faça inline com warning de débito)
278
+ ```
279
+
280
+ ## Anti-patterns
281
+
282
+ ### ANTI: handler depende direto do SDK do vendor
283
+
284
+ ```text
285
+ ANTI: handler.ts: import Stripe from 'stripe'; ... stripe.charges.create(...)
286
+
287
+ PROBLEMA: handler intestável sem mocking SDK inteiro. Trocar vendor
288
+ = rewrite. Vendor SDK breaking change = bugs em handler.
289
+
290
+ CERTO: handler depende de interface mínima `PaymentGateway`. Adapter
291
+ absorve SDK. Testes do handler usam fake. Trocar vendor =
292
+ trocar 1 linha (constructor injection).
293
+ ```
294
+
295
+ ### ANTI: adapter expondo tipos do vendor
296
+
297
+ ```text
298
+ ANTI: interface PaymentGateway { charge(input): Promise<Stripe.Charge> }
299
+
300
+ PROBLEMA: Stripe.Charge atravessa camadas internas. Quando Stripe
301
+ renomeia field, refactor cascateia. Sem anti-corruption.
302
+
303
+ CERTO: interface tem TIPO próprio (ChargeResult). Adapter traduz.
304
+ Stripe.Charge fica encapsulado dentro do adapter.
305
+ ```
306
+
307
+ ### ANTI: 1 adapter por método do vendor
308
+
309
+ ```text
310
+ ANTI: StripeChargeAdapter, StripeRefundAdapter, StripePayoutAdapter,
311
+ StripeCustomerAdapter — 1 classe por endpoint.
312
+
313
+ PROBLEMA: explosão. 30 adapters para 1 vendor. Cross-cutting (retry,
314
+ logging) duplicado em cada um.
315
+
316
+ CERTO: 1 adapter por VENDOR + capability cluster. StripePaymentAdapter
317
+ (charge + refund), StripeCustomerAdapter (create + update).
318
+ Cross-cutting concerns aplicados consistente.
319
+ ```
320
+
321
+ ### ANTI: fake adapter testando o vendor real
322
+
323
+ ```text
324
+ ANTI: FakeStripeAdapter faz HTTP real para Stripe sandbox em testes.
325
+
326
+ PROBLEMA: testes lentos, flaky, dependentes de rede, custam $.
327
+ Sandbox vendor pode ter rate limits.
328
+
329
+ CERTO: FakeStripeAdapter implementa interface NÃO depende de Stripe.
330
+ Coleta inputs em array; retorna outputs canned. Test puramente
331
+ local. Fast, deterministic, free.
332
+ ```
333
+
334
+ ## Verificação
335
+
336
+ 1. Handler depende de interface, não de SDK do vendor diretamente
337
+ 2. Adapter implementa interface, encapsula SDK do vendor
338
+ 3. Tipos do vendor não atravessam adapter (anti-corruption)
339
+ 4. Fake adapter existe; tests do handler usam fake
340
+ 5. Adapter centraliza retry/timeout/idempotency/logging (cross-cutting)
341
+ 6. Tipos de DOMAIN são uppercase ISO/etc (não passam por convenção do vendor)
342
+ 7. Trocar vendor = trocar 1 linha (constructor)
343
+
344
+ ---
345
+
346
+ ## Ver também
347
+
348
+ - [`_shared-legacy/glossary.md`](../_shared-legacy/glossary.md) — vocabulário (adapter, anti-corruption layer)
349
+ - [`legacy-seams-and-test-harness`](../legacy-seams-and-test-harness/SKILL.md) — extract-interface é técnica do cap 25 que produz adapter
350
+ - [`legacy-characterization-tests`](../legacy-characterization-tests/SKILL.md) — characterize handler usando fake adapter (sem rede)
351
+ - [`supabase-edge-functions`](../supabase-edge-functions/SKILL.md) (v1.8) — Edge Functions são API-only paradigmáticas; adapter pattern aplicável
352
+ - [`supabase-edge-fn-writer`](../../agents/supabase-edge-fn-writer.md) (v1.8) — patch v1.12: adapter pattern como template default
353
+ - [`four-golden-signals`](../four-golden-signals/SKILL.md) (v1.10) — adapter é lugar canônico de instrumentation
354
+ - [`retry-strategies`](../retry-strategies/SKILL.md) (v1.11 — quando entregar) — retry pattern aplicado dentro do adapter
355
+ - [`llm-as-dependency`](../llm-as-dependency/SKILL.md) — caso especial de API-only para LLM providers
356
+
357
+ *Material-fonte: Working Effectively with Legacy Code — Feathers, 2004 — Cap 15: "My Application Is All API Calls".*
358
+ *Modernização (2026):* Supabase Edge Functions + LLM providers (OpenAI/Anthropic) como aplicação canônica do pattern.