@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.
- package/CHANGELOG.md +86 -0
- package/README.md +58 -0
- package/gates/ai-prompt-stability.md +120 -0
- package/gates/golden-signals-coverage.md +133 -0
- package/gates/legacy-refactor-safety.md +178 -0
- package/gates/observability-coverage.md +151 -0
- package/gates/postmortem-template-required.md +127 -0
- package/gates/prr-checklist-coverage.md +128 -0
- package/gates/release-pipeline-policy.md +132 -0
- package/kit/COMANDOS.md +15 -0
- package/kit/agents/ai-mutation-tester.md +298 -0
- package/kit/agents/cascading-failures-auditor.md +306 -0
- package/kit/agents/executor.md +13 -0
- package/kit/agents/golden-signals-instrumenter.md +241 -0
- package/kit/agents/legacy-characterizer.md +378 -0
- package/kit/agents/load-shedding-instrumenter.md +297 -0
- package/kit/agents/observability-coverage-auditor.md +325 -0
- package/kit/agents/omm-auditor.md +99 -0
- package/kit/agents/payload-capture-instrumenter.md +283 -0
- package/kit/agents/planner.md +29 -0
- package/kit/agents/postmortem-writer.md +282 -0
- package/kit/agents/prr-conductor.md +296 -0
- package/kit/agents/refactor-safety-auditor.md +414 -0
- package/kit/agents/release-pipeline-auditor.md +360 -0
- package/kit/agents/seam-finder.md +367 -0
- package/kit/agents/shotgun-surgery-detector.md +359 -0
- package/kit/agents/storytelling-analyst.md +309 -0
- package/kit/agents/supabase-architect.md +49 -0
- package/kit/agents/supabase-edge-fn-writer.md +114 -0
- package/kit/agents/supabase-migration-writer.md +80 -0
- package/kit/agents/supabase-storage-implementer.md +156 -0
- package/kit/agents/toil-auditor.md +277 -0
- package/kit/agents/verifier.md +30 -0
- package/kit/commands/auditar-cascading.md +111 -0
- package/kit/commands/auditar-marco.md +124 -1
- package/kit/commands/auditar-observabilidade-cobertura.md +183 -0
- package/kit/commands/auditar-refactor.md +219 -0
- package/kit/commands/auditar-release.md +109 -0
- package/kit/commands/auditar-toil.md +129 -0
- package/kit/commands/capturar-payloads.md +193 -0
- package/kit/commands/caracterizar-prompt.md +195 -0
- package/kit/commands/caracterizar.md +212 -0
- package/kit/commands/concluir-marco.md +95 -1
- package/kit/commands/detectar-duplicacao.md +197 -0
- package/kit/commands/discutir-fase.md +41 -0
- package/kit/commands/encontrar-seams.md +136 -0
- package/kit/commands/forense.md +103 -1
- package/kit/commands/golden-signals.md +142 -0
- package/kit/commands/legacy.md +263 -0
- package/kit/commands/load-shedding.md +117 -0
- package/kit/commands/observabilidade.md +2 -0
- package/kit/commands/postmortem.md +179 -0
- package/kit/commands/prr.md +205 -0
- package/kit/commands/refactor-seguro.md +321 -0
- package/kit/commands/risk-budget.md +220 -0
- package/kit/commands/sre.md +230 -0
- package/kit/commands/storytelling.md +179 -0
- package/kit/skills/_shared-legacy/glossary.md +389 -0
- package/kit/skills/_shared-sre/glossary.md +712 -0
- package/kit/skills/ai-prompt-characterization/SKILL.md +335 -0
- package/kit/skills/blameless-postmortems/SKILL.md +340 -0
- package/kit/skills/cascading-failures/SKILL.md +307 -0
- package/kit/skills/eliminating-toil/SKILL.md +243 -0
- package/kit/skills/event-based-slos/SKILL.md +22 -0
- package/kit/skills/four-golden-signals/SKILL.md +314 -0
- package/kit/skills/hermetic-builds/SKILL.md +323 -0
- package/kit/skills/legacy-api-only-applications/SKILL.md +358 -0
- package/kit/skills/legacy-characterization-tests/SKILL.md +330 -0
- package/kit/skills/legacy-effect-analysis/SKILL.md +331 -0
- package/kit/skills/legacy-extract-class/SKILL.md +203 -0
- package/kit/skills/legacy-monster-methods/SKILL.md +444 -0
- package/kit/skills/legacy-programming-by-difference/SKILL.md +252 -0
- package/kit/skills/legacy-seams-and-test-harness/SKILL.md +460 -0
- package/kit/skills/legacy-shotgun-surgery/SKILL.md +286 -0
- package/kit/skills/legacy-sprout-wrap-techniques/SKILL.md +434 -0
- package/kit/skills/legacy-storytelling-naked-crc/SKILL.md +270 -0
- package/kit/skills/llm-as-dependency/SKILL.md +436 -0
- package/kit/skills/load-shedding-graceful-degradation/SKILL.md +396 -0
- package/kit/skills/pre-refactor-characterization/SKILL.md +421 -0
- package/kit/skills/production-readiness-review/SKILL.md +305 -0
- package/kit/skills/release-engineering/SKILL.md +367 -0
- package/kit/skills/retry-strategies/SKILL.md +372 -0
- package/kit/skills/sre-risk-management/SKILL.md +221 -0
- package/package.json +2 -2
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: legacy-effect-analysis
|
|
3
|
+
description: Use ao decidir quais testes escrever em código sem testes — effect sketch (cap 11-12 Feathers) rastreia propagação de efeitos do change point para inflection/pinch points onde 1 teste cobre N caminhos.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Legacy — Effect Analysis
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill quando user precisa decidir QUAIS testes escrever em código legado. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "que tests preciso escrever para essa mudança?"
|
|
13
|
+
- "como sei que cobri tudo?"
|
|
14
|
+
- "effect sketch", "rastrear efeitos"
|
|
15
|
+
- "cap 11 Feathers", "cap 12 Feathers"
|
|
16
|
+
- "inflection point", "pinch point", "ponto de interceptação"
|
|
17
|
+
- "muitas mudanças na mesma área"
|
|
18
|
+
- "efeito propaga", "ripple effect"
|
|
19
|
+
|
|
20
|
+
Carrega entre `legacy-seams-and-test-harness` (já tenho seam) e `legacy-characterization-tests` (vou escrever quais testes?). Resposta: testes nos pinch points.
|
|
21
|
+
|
|
22
|
+
## Regras absolutas
|
|
23
|
+
|
|
24
|
+
- **Effect = qualquer mudança observável após chamar o código.** 4 vetores: return value, parâmetros mutados, globals/state estático, side effects via colaborador (DB, HTTP, FS, log, queue).
|
|
25
|
+
- **Effect sketch SEMPRE em papel/whiteboard primeiro.** Diagramar à mão, não em ferramenta. Velocidade > formato. Goal é entender, não documentar.
|
|
26
|
+
- **Inflection point = funil estreito.** Lugar onde N caminhos convergem antes de divergir. 1 teste lá cobre N branches a montante. Foque tempo de teste aqui.
|
|
27
|
+
- **Pinch point é definido pelo problema, não pela arquitetura.** "É onde os efeitos da minha mudança convergem", pode ou não coincidir com camadas/módulos.
|
|
28
|
+
- **Effect-narrowing precede characterization.** Se sketch tem 30 efeitos, primeiro reduza superfície (encapsular variáveis, eliminar globals). Depois characterize a fronteira reduzida.
|
|
29
|
+
- **Shotgun surgery = mesmo change espalhado em N lugares.** Effect sketch detecta. Resposta canônica: extrair para 1 lugar antes de mudar (cap 21 — Single Responsibility Principle aplicado retroativamente).
|
|
30
|
+
- **Não confunda effect com call graph.** Call graph mostra QUEM chama QUEM. Effect sketch mostra O QUE MUDA. Função pode ser chamada 100 vezes e mudar nada (pure); função chamada 1 vez pode mudar 50 coisas.
|
|
31
|
+
|
|
32
|
+
## Patterns canônicos
|
|
33
|
+
|
|
34
|
+
### Pattern 1: 4 vetores de propagação de efeito
|
|
35
|
+
|
|
36
|
+
```text
|
|
37
|
+
1. RETURN VALUE
|
|
38
|
+
foo() retorna X → callers usam X em decisões/cálculos
|
|
39
|
+
Trace: grep callers de foo() + grep usos do resultado
|
|
40
|
+
|
|
41
|
+
2. MUTATED PARAMETERS (output params)
|
|
42
|
+
foo(list) faz list.push(x) → caller continua a usar list mutada
|
|
43
|
+
Trace: parâmetros não-primitivos (objetos, arrays, ponteiros)
|
|
44
|
+
|
|
45
|
+
3. GLOBAL / STATIC STATE
|
|
46
|
+
foo() faz globalCounter++ ou Foo.lastResult = X
|
|
47
|
+
Trace: writes em variáveis fora do escopo da função
|
|
48
|
+
|
|
49
|
+
4. SIDE EFFECTS VIA COLLABORATOR
|
|
50
|
+
foo() chama db.save(), http.post(), log.warn(), fs.writeFile()
|
|
51
|
+
Trace: identificar colaboradores injetados/globais e verificar writes
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**Heurística:** se um vetor é vazio, ótimo (efeito mais contido). Se múltiplos, sketch é necessário antes de qualquer change.
|
|
55
|
+
|
|
56
|
+
### Pattern 2: Workflow de effect sketch (cap 11)
|
|
57
|
+
|
|
58
|
+
```text
|
|
59
|
+
1. DESENHAR change point
|
|
60
|
+
Caixa central com nome do método/variável que vai mudar.
|
|
61
|
+
|
|
62
|
+
2. ENUMERAR EFEITOS DIRETOS (1 nível)
|
|
63
|
+
Setas saindo da caixa central para tudo que MUDA quando aquele
|
|
64
|
+
change point muda:
|
|
65
|
+
- retorno (caixa "return")
|
|
66
|
+
- cada parâmetro mutado
|
|
67
|
+
- cada global escrito
|
|
68
|
+
- cada side effect
|
|
69
|
+
|
|
70
|
+
3. ENUMERAR EFEITOS DERIVADOS (2 níveis)
|
|
71
|
+
Para cada efeito direto, perguntar: "quem usa isso?"
|
|
72
|
+
- return é consumido por callers — desenhe callers
|
|
73
|
+
- parâmetros mutados — quem inspeciona estado?
|
|
74
|
+
- globals — todos os leitores
|
|
75
|
+
- side effects — todos os observadores (queue consumers, DB readers)
|
|
76
|
+
|
|
77
|
+
4. CONTINUE até bordas naturais
|
|
78
|
+
- Outro processo/serviço (effect cruza process boundary)
|
|
79
|
+
- Caller que não inspeciona resultado
|
|
80
|
+
- Side effect terminal (log persistido, sem ler de volta)
|
|
81
|
+
|
|
82
|
+
5. IDENTIFICAR INFLECTION POINTS
|
|
83
|
+
Pontos onde múltiplas setas convergem ou divergem.
|
|
84
|
+
Inflection point é "o gargalo" — testar ali cobre subgrafos inteiros.
|
|
85
|
+
|
|
86
|
+
6. PRIORIZAR TESTES
|
|
87
|
+
Test escrito num inflection point cobre N efeitos a montante.
|
|
88
|
+
1 teste em pinch point > 10 testes em folhas.
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Pattern 3: Exemplo concreto — sketch de OrderProcessor.processOrder()
|
|
92
|
+
|
|
93
|
+
```text
|
|
94
|
+
┌──────────────────┐
|
|
95
|
+
│ Order.discount │ ← change point (mudando lógica)
|
|
96
|
+
└────────┬─────────┘
|
|
97
|
+
│
|
|
98
|
+
┌────────────────────────┼─────────────────────────┐
|
|
99
|
+
▼ ▼ ▼
|
|
100
|
+
Order.totalCents OrderEvent.payload AuditLog.entry
|
|
101
|
+
│ │ │
|
|
102
|
+
▼ ▼ ▼
|
|
103
|
+
PaymentRequest.amount EventBus.publish AuditDB.write
|
|
104
|
+
│ │ │
|
|
105
|
+
▼ ▼ ▼
|
|
106
|
+
Stripe.charge QueueConsumers (3 svcs) ComplianceReader
|
|
107
|
+
│
|
|
108
|
+
▼
|
|
109
|
+
bank ledger
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
**Inflection point óbvio:** `Order.totalCents` — TODOS os efeitos no payment side passam por essa propriedade.
|
|
113
|
+
|
|
114
|
+
**Estratégia de testes:**
|
|
115
|
+
- 1 test que asserta `Order.totalCents` para 5+ inputs (boundary, typical, etc.) → cobre subárvore Stripe inteira sem precisar mockar Stripe
|
|
116
|
+
- 1 test que asserta `OrderEvent.payload` shape → cobre EventBus side
|
|
117
|
+
- 1 test que asserta `AuditLog.entry` shape → cobre Audit side
|
|
118
|
+
|
|
119
|
+
3 testes de 5 minutos cada cobrem 15+ pontos de propagação. Sem sketch, escreveria 15 testes em 5 lugares diferentes.
|
|
120
|
+
|
|
121
|
+
### Pattern 4: Heurísticas para encontrar inflection points
|
|
122
|
+
|
|
123
|
+
| Sintoma no sketch | Provável inflection |
|
|
124
|
+
|---|---|
|
|
125
|
+
| Várias setas convergem em 1 nó antes de irradiar | Esse nó (estado intermediário) |
|
|
126
|
+
| Bordas de processo (call externo) | Antes da borda (assertar mensagem enviada) |
|
|
127
|
+
| Pontos de serialização/desserialização | Bem ali — congele forma serializada |
|
|
128
|
+
| Persistência (DB write) | Snapshot do row escrito |
|
|
129
|
+
| Eventos publicados em queue/bus | Snapshot do event payload |
|
|
130
|
+
| Function purity (sem side effect) | Return value direto |
|
|
131
|
+
|
|
132
|
+
### Pattern 5: Effect-narrowing (cap 12)
|
|
133
|
+
|
|
134
|
+
Quando sketch tem 20+ efeitos, primeiro REDUZA antes de testar. Técnicas:
|
|
135
|
+
|
|
136
|
+
| Técnica | Reduz | Trade-off |
|
|
137
|
+
|---|---|---|
|
|
138
|
+
| **Encapsular variável global** | Globals viram fields → menos vetor 3 (state) | Caller pode precisar passar instância |
|
|
139
|
+
| **Imutabilidade no parâmetro** | Mutated params viram return values → menos vetor 2 | Allocation a cada call |
|
|
140
|
+
| **Extract method para state mutation** | Side effect concentrado em 1 método (pinch criado) | + 1 método na classe |
|
|
141
|
+
| **Replace temp with query** | Variável local → método; reduz dispersão | Computação repetida |
|
|
142
|
+
| **Move method (fora de classe X para Y)** | Effect sai do escopo de X → menos efeito a rastrear em X | Pode quebrar outros sketches |
|
|
143
|
+
|
|
144
|
+
**Princípio:** narrowing é PRECEDENTE a refactor. Faça-o com características de "pure mechanical" — pequena, reversível, comportamento idêntico.
|
|
145
|
+
|
|
146
|
+
### Pattern 6: 4 perguntas canônicas antes de change
|
|
147
|
+
|
|
148
|
+
```text
|
|
149
|
+
1. "Que efeitos esse change tem?"
|
|
150
|
+
→ desenhe sketch (vetores 1-4)
|
|
151
|
+
|
|
152
|
+
2. "Onde converge antes de divergir?"
|
|
153
|
+
→ inflection point(s)
|
|
154
|
+
|
|
155
|
+
3. "O que preciso testar para SENSE essas convergências?"
|
|
156
|
+
→ 1 test por inflection (input variado), assertando estado intermediário
|
|
157
|
+
|
|
158
|
+
4. "Quais são as bordas naturais?"
|
|
159
|
+
→ onde termina o sketch; depois disso é território de outras teams/serviços
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
### Pattern 7: Detect shotgun surgery via sketch
|
|
163
|
+
|
|
164
|
+
Se ao desenhar sketch para mudança X, você encontra que X aparece em N lugares idênticos espalhados:
|
|
165
|
+
|
|
166
|
+
```text
|
|
167
|
+
(mudança X)
|
|
168
|
+
│
|
|
169
|
+
┌───────┬────────┬───┴───┬────────┬───────┐
|
|
170
|
+
▼ ▼ ▼ ▼ ▼ ▼
|
|
171
|
+
FileA FileB FileC FileD FileE FileF
|
|
172
|
+
linha linha linha linha linha linha
|
|
173
|
+
42 189 67 23 104 56
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
**Sintoma:** mesma lógica copiada em N pontos.
|
|
177
|
+
**Resposta:** ANTES de mudar, extrair para função/classe única (cap 21). Depois, mudança vira UM ponto. Effect sketch original com 6 setas vira 1 seta para 1 ponto.
|
|
178
|
+
|
|
179
|
+
### Pattern 8: Effect sketch tooling
|
|
180
|
+
|
|
181
|
+
Não precisa de ferramenta sofisticada. Em ordem de preferência:
|
|
182
|
+
|
|
183
|
+
1. **Papel + caneta** (sempre primeiro — velocidade)
|
|
184
|
+
2. **Whiteboard físico** (se mais que 1 pessoa)
|
|
185
|
+
3. **Whiteboard digital** (Excalidraw, Miro) — quando precisa salvar/compartilhar
|
|
186
|
+
4. **Texto ASCII em PR description** (quando vira artefato persistente)
|
|
187
|
+
5. **Mermaid graph** (last resort — overhead de syntax > benefit visual)
|
|
188
|
+
|
|
189
|
+
**Anti-tooling:** UML "official", Visio, ferramentas que exigem layout perfeito. Sketch é descartável e iterativo.
|
|
190
|
+
|
|
191
|
+
### Pattern 9: Heurística de cobertura via inflection
|
|
192
|
+
|
|
193
|
+
Para mudança em legacy code, cobertura mínima = 1 test por inflection point.
|
|
194
|
+
|
|
195
|
+
```text
|
|
196
|
+
N inflection points identificados via sketch
|
|
197
|
+
× 5+ inputs cobrindo grupos de equivalência (ver legacy-characterization-tests Pattern 2)
|
|
198
|
+
= N × 5 testes mínimos para refactor
|
|
199
|
+
|
|
200
|
+
Se muito alto (50+), considere effect-narrowing primeiro.
|
|
201
|
+
Se muito baixo (1 inflection × 5 inputs = 5), provavelmente sketch
|
|
202
|
+
incompleto — verifique se cobriu todos os 4 vetores.
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
## Anti-patterns
|
|
206
|
+
|
|
207
|
+
### ANTI: pular sketch "porque é óbvio"
|
|
208
|
+
|
|
209
|
+
```text
|
|
210
|
+
ANTI: "esse método tem 50 linhas, eu vejo o que ele faz, vou testar
|
|
211
|
+
direto".
|
|
212
|
+
|
|
213
|
+
PROBLEMA: efeitos não-óbvios são exatamente os que escapam:
|
|
214
|
+
- mutação de parâmetro objeto que caller depende
|
|
215
|
+
- side effect via dependency injetada (parece pure mas não é)
|
|
216
|
+
- global lido condicionalmente em caminho raro
|
|
217
|
+
Bug em prod 3 semanas depois pelos efeitos não-vistos.
|
|
218
|
+
|
|
219
|
+
CERTO: SEMPRE 5 minutos de sketch. Mesmo método "óbvio" → desenhe,
|
|
220
|
+
confirme, então teste. 5 min poupam horas.
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
### ANTI: testar todas as folhas do sketch
|
|
224
|
+
|
|
225
|
+
```text
|
|
226
|
+
ANTI: 30 setas no sketch → 30 testes (1 por folha).
|
|
227
|
+
|
|
228
|
+
PROBLEMA: massive test suite, slow CI, alto custo de manutenção,
|
|
229
|
+
tests redundantes (várias folhas testam mesma branch a
|
|
230
|
+
montante). Sinal de "test theatre" — looks safe but isn't.
|
|
231
|
+
|
|
232
|
+
CERTO: 1 teste por inflection point. Se inflection cobre 10 folhas,
|
|
233
|
+
teste lá. Folhas só ganham teste próprio se há comportamento
|
|
234
|
+
distinto (folha = inflection menor naquele contexto).
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### ANTI: testar APENAS na superfície (1 nível de sketch)
|
|
238
|
+
|
|
239
|
+
```text
|
|
240
|
+
ANTI: testar só `processOrder` retorno, sem verificar side effects.
|
|
241
|
+
|
|
242
|
+
PROBLEMA: side effects são tipicamente onde regressão escapa.
|
|
243
|
+
processOrder pode retornar valor correto MAS escrever no
|
|
244
|
+
DB errado, publicar event errado, logar PII. Test verde
|
|
245
|
+
mascara breakage.
|
|
246
|
+
|
|
247
|
+
CERTO: percorrer sketch completo. Side effect significativo
|
|
248
|
+
(DB write, event publish, log) recebe assertion no test
|
|
249
|
+
relevante. Use fakes que coletam side effects, asserte sobre
|
|
250
|
+
state final do fake.
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
### ANTI: confundir call graph com effect sketch
|
|
254
|
+
|
|
255
|
+
```text
|
|
256
|
+
ANTI: "fiz um call graph IDE-generated, isso é meu effect sketch".
|
|
257
|
+
|
|
258
|
+
PROBLEMA: call graph mostra "fooCallsBar". Não mostra que `bar`
|
|
259
|
+
modifica global lido por `baz` que retorna decisão para
|
|
260
|
+
`qux`. Effect path passa por chamadas + state, não só
|
|
261
|
+
chamadas.
|
|
262
|
+
|
|
263
|
+
CERTO: sketch tem que ser feito por pessoa, lendo código, perguntando
|
|
264
|
+
"o que muda?". Call graph é input ao sketch, não substituto.
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### ANTI: change com sketch não-validado
|
|
268
|
+
|
|
269
|
+
```text
|
|
270
|
+
ANTI: desenhei sketch, achei 3 inflection points, escrevi tests,
|
|
271
|
+
mudei código. Sketch não foi validado contra o código real
|
|
272
|
+
por outra pessoa.
|
|
273
|
+
|
|
274
|
+
PROBLEMA: effect omitido (vetor 4 — side effect via colaborador raro)
|
|
275
|
+
significa teste ausente significa regressão escapa.
|
|
276
|
+
|
|
277
|
+
CERTO: sketch validado por 2ª pessoa OU validado contra mutation
|
|
278
|
+
testing. Mutants survived = pontos não-cobertos = potencial
|
|
279
|
+
gap no sketch original.
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### ANTI: shotgun surgery sem extract first
|
|
283
|
+
|
|
284
|
+
```text
|
|
285
|
+
ANTI: "mesma lógica em 6 lugares, vou alterar todos os 6".
|
|
286
|
+
|
|
287
|
+
PROBLEMA: 6 chances de errar. PR de 600 linhas. Test exigiria 6×
|
|
288
|
+
characterization. Próxima mudança = mesma cirurgia.
|
|
289
|
+
|
|
290
|
+
CERTO: extract first (cap 21). PR1 — extrair para função única,
|
|
291
|
+
cada chamada vira call para a função. PR2 — alterar a função.
|
|
292
|
+
Sketch original encolhe de 6 setas → 1 seta. Tests também.
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
## Verificação
|
|
296
|
+
|
|
297
|
+
Antes de declarar effect analysis completa:
|
|
298
|
+
|
|
299
|
+
1. **Sketch desenhado** — papel/whiteboard com change point central + 4 vetores explorados
|
|
300
|
+
2. **Todos os 4 vetores considerados** — return, mutated params, globals, side effects via collaborator
|
|
301
|
+
3. **Pelo menos 1 inflection point identificado** — se não, sketch incompleto OU change é trivial demais
|
|
302
|
+
4. **Effect-narrowing aplicado** se sketch tem > 15 efeitos
|
|
303
|
+
5. **Plano de testes derivado do sketch** — N testes em inflection points, NÃO em folhas
|
|
304
|
+
6. **Sketch validado** — 2ª pessoa OR mutation testing pós-implementação
|
|
305
|
+
7. **Bordas naturais identificadas** — onde para de rastrear (process boundary, terminal side effect)
|
|
306
|
+
|
|
307
|
+
## Limiar de "pronto para testar/refatorar"
|
|
308
|
+
|
|
309
|
+
```text
|
|
310
|
+
Sketch desenhado: sim
|
|
311
|
+
Vetores 1-4 enumerados: todos cobertos
|
|
312
|
+
Inflection points identificados: ≥ 1 (1-3 típico)
|
|
313
|
+
Plano de testes mapeado para sketch: sim (1 teste por inflection)
|
|
314
|
+
Cobertura esperada com tests planejados: ≥ 70% behavioral
|
|
315
|
+
Effect-narrowing aplicado: se necessário
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
Se algum item incompleto → não inicie testes/refactor. Volte ao sketch.
|
|
319
|
+
|
|
320
|
+
---
|
|
321
|
+
|
|
322
|
+
## Ver também
|
|
323
|
+
|
|
324
|
+
- [`_shared-legacy/glossary.md`](../_shared-legacy/glossary.md) — vocabulário (effect sketch, inflection point, pinch point, shotgun surgery)
|
|
325
|
+
- [`legacy-characterization-tests`](../legacy-characterization-tests/SKILL.md) — characterization rodada NOS inflection points achados aqui
|
|
326
|
+
- [`legacy-seams-and-test-harness`](../legacy-seams-and-test-harness/SKILL.md) — break-deps em inflection points = test harness mínimo
|
|
327
|
+
- [`legacy-monster-methods`](../legacy-monster-methods/SKILL.md) — monster method tem sketch interno (em uma única função)
|
|
328
|
+
- [`legacy-sprout-wrap-techniques`](../legacy-sprout-wrap-techniques/SKILL.md) — sprout point ideal = inflection point pré-existente
|
|
329
|
+
- [`pre-refactor-characterization`](../pre-refactor-characterization/SKILL.md) — gate exige effect sketch para refactor de arquivos grandes/críticos
|
|
330
|
+
|
|
331
|
+
*Material-fonte: Working Effectively with Legacy Code — Feathers, 2004 — Cap 11: "I Need to Make a Change. What Methods Should I Test?" + Cap 12: "I Need to Make Many Changes in One Area" + Cap 16: "I Don't Understand the Code Well Enough to Change It".*
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: legacy-extract-class
|
|
3
|
+
description: Use ao identificar classes "muito grandes" (cap 20 Feathers) com responsibility hot spots — extract class para separar responsabilidades. Aplicado a domain classes Supabase (OrderService → OrderValidator + Repository + Notifier).
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Legacy — Extract Class
|
|
7
|
+
|
|
8
|
+
## Quando usar
|
|
9
|
+
|
|
10
|
+
LLM carrega esta skill quando uma classe ultrapassa thresholds de tamanho/complexidade ou tem múltiplas responsabilidades distintas. Trigger phrases:
|
|
11
|
+
|
|
12
|
+
- "essa classe é grande demais", "this class is too big"
|
|
13
|
+
- "extract class", "extrair classe", "split class"
|
|
14
|
+
- "responsibility hot spot", "single responsibility"
|
|
15
|
+
- "cap 20 Feathers"
|
|
16
|
+
- "OrderService faz validação, persistência E notificação"
|
|
17
|
+
- arquivo de classe > 300 linhas com múltiplos métodos públicos não-relacionados
|
|
18
|
+
|
|
19
|
+
## Regras absolutas
|
|
20
|
+
|
|
21
|
+
- **Heurísticas de "classe muito grande":** > 300 linhas; > 10 fields; > 12 métodos públicos; > 3 responsabilidades distintas (hot spots). Pelo menos 2 dos 4 = candidato.
|
|
22
|
+
- **Extract class != extract method.** Extract method move bloco contíguo dentro da mesma classe; extract class move responsabilidade INTEIRA para classe nova com state próprio.
|
|
23
|
+
- **Identifique o "hot spot" primeiro.** Cluster de fields + métodos que se referenciam mais entre si do que com o resto da classe = unidade extraível.
|
|
24
|
+
- **Compilação verde a cada commit.** Pequenos passos: (1) criar classe nova vazia; (2) mover 1 field; (3) ajustar callers; (4) repetir.
|
|
25
|
+
- **Não introduza herança especulativa.** Extract class produz composição (classe original tem field do tipo extraído); herança só se faz parte do design intencional.
|
|
26
|
+
- **Aplicação canônica em Supabase domain classes:** `OrderService` que faz validação + persistência + notificação + audit → extract para `OrderValidator`, `OrderRepository`, `OrderNotifier`, `OrderAuditor` (modernização: SRP em layer de domínio).
|
|
27
|
+
|
|
28
|
+
## Patterns canônicos
|
|
29
|
+
|
|
30
|
+
### Pattern 1: Detecção de hot spots
|
|
31
|
+
|
|
32
|
+
```text
|
|
33
|
+
Para cada field e método da classe alvo:
|
|
34
|
+
Crie matriz de coupling — quem usa quem.
|
|
35
|
+
Cluster fields/métodos que SE REFERENCIAM mais.
|
|
36
|
+
Cluster com 2+ fields E 3+ métodos = hot spot extraível.
|
|
37
|
+
|
|
38
|
+
Exemplo — OrderService 450 linhas:
|
|
39
|
+
Cluster A (validação):
|
|
40
|
+
fields: validators[], strictMode
|
|
41
|
+
methods: validate, validateField, addCustomValidator
|
|
42
|
+
Cluster B (persistência):
|
|
43
|
+
fields: db, cache
|
|
44
|
+
methods: save, findById, findRecent
|
|
45
|
+
Cluster C (notificação):
|
|
46
|
+
fields: notifier, templateEngine
|
|
47
|
+
methods: notifyCustomer, formatNotification
|
|
48
|
+
|
|
49
|
+
→ 3 hot spots → 3 extract class candidatos.
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
### Pattern 2: Workflow de extract class
|
|
53
|
+
|
|
54
|
+
```text
|
|
55
|
+
1. Criar classe nova vazia com nome descritivo
|
|
56
|
+
class OrderValidator {}
|
|
57
|
+
|
|
58
|
+
2. Mover 1 field (e seus referentes diretos)
|
|
59
|
+
- Mover field
|
|
60
|
+
- Adicionar field correspondente na classe original APONTANDO para nova
|
|
61
|
+
- Ajustar todos os usos (this.X → this.validator.X)
|
|
62
|
+
- Compilar verde
|
|
63
|
+
|
|
64
|
+
3. Mover 1 método relacionado
|
|
65
|
+
- Mover método (com edits triviais para acessar fields da classe nova)
|
|
66
|
+
- Atualizar callers
|
|
67
|
+
- Compilar verde
|
|
68
|
+
|
|
69
|
+
4. Repetir para cada field/método do hot spot
|
|
70
|
+
5. Adicionar test harness para classe nova (agora menor → fácil testar)
|
|
71
|
+
6. (Opcional) extract interface se existem múltiplas implementações
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Pattern 3: Aplicação canônica Supabase
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
// ANTES — OrderService 450 linhas, 4 responsabilidades
|
|
78
|
+
class OrderService {
|
|
79
|
+
constructor(private db: SupabaseClient, private notifier: SmtpClient) {}
|
|
80
|
+
|
|
81
|
+
// validation
|
|
82
|
+
validate(order: Order): ValidationResult { /* 80 linhas */ }
|
|
83
|
+
validateField(field: string, value: any) { /* ... */ }
|
|
84
|
+
|
|
85
|
+
// persistence
|
|
86
|
+
async save(order: Order) { await this.db.from('orders').insert(...) }
|
|
87
|
+
async findById(id: string) { return this.db.from('orders').select().eq('id', id) }
|
|
88
|
+
|
|
89
|
+
// notification
|
|
90
|
+
async notifyCustomer(order: Order) { /* template + smtp send */ }
|
|
91
|
+
|
|
92
|
+
// audit
|
|
93
|
+
async logAudit(action: string, order: Order) { /* db audit_log insert */ }
|
|
94
|
+
|
|
95
|
+
// orchestration (entrypoint)
|
|
96
|
+
async place(order: Order): Promise<Result> {
|
|
97
|
+
const v = this.validate(order)
|
|
98
|
+
if (!v.ok) return { error: v.errors }
|
|
99
|
+
await this.save(order)
|
|
100
|
+
await this.notifyCustomer(order)
|
|
101
|
+
await this.logAudit('placed', order)
|
|
102
|
+
return { ok: true }
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// DEPOIS — 4 classes coesas + orquestrador enxuto
|
|
107
|
+
class OrderValidator { validate(order: Order): ValidationResult { /* 60 linhas */ } }
|
|
108
|
+
|
|
109
|
+
class OrderRepository {
|
|
110
|
+
constructor(private db: SupabaseClient) {}
|
|
111
|
+
async save(order: Order) { /* ... */ }
|
|
112
|
+
async findById(id: string) { /* ... */ }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
class OrderNotifier {
|
|
116
|
+
constructor(private smtp: SmtpClient) {}
|
|
117
|
+
async notifyCustomer(order: Order) { /* ... */ }
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
class OrderAuditor {
|
|
121
|
+
constructor(private db: SupabaseClient) {}
|
|
122
|
+
async log(action: string, order: Order) { /* ... */ }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
class OrderService {
|
|
126
|
+
constructor(
|
|
127
|
+
private validator = new OrderValidator(),
|
|
128
|
+
private repo: OrderRepository,
|
|
129
|
+
private notifier: OrderNotifier,
|
|
130
|
+
private auditor: OrderAuditor,
|
|
131
|
+
) {}
|
|
132
|
+
|
|
133
|
+
async place(order: Order): Promise<Result> {
|
|
134
|
+
const v = this.validator.validate(order)
|
|
135
|
+
if (!v.ok) return { error: v.errors }
|
|
136
|
+
await this.repo.save(order)
|
|
137
|
+
await this.notifier.notifyCustomer(order)
|
|
138
|
+
await this.auditor.log('placed', order)
|
|
139
|
+
return { ok: true }
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
// OrderService final: ~25 linhas. Cada classe extraída testável isolada.
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### Pattern 4: Effort budget
|
|
146
|
+
|
|
147
|
+
| Tamanho classe | Hot spots típicos | Esforço extract class | Output |
|
|
148
|
+
|---|---|---|---|
|
|
149
|
+
| 300-500 linhas | 2-3 | 1-2 dias | classe principal + 2-3 extracted classes |
|
|
150
|
+
| 500-1000 linhas | 3-5 | 3-7 dias | classe principal + 3-5 extracted; tests acumulados |
|
|
151
|
+
| > 1000 linhas | 5+ | 1-3 semanas (pode requerer scratch refactoring antes) | considere extract interface se múltiplas implementações |
|
|
152
|
+
|
|
153
|
+
## Anti-patterns
|
|
154
|
+
|
|
155
|
+
### ANTI: extract class antes de characterization
|
|
156
|
+
|
|
157
|
+
```text
|
|
158
|
+
ANTI: identificou hot spots e move tudo de uma vez.
|
|
159
|
+
|
|
160
|
+
PROBLEMA: extract class MOVE state e métodos. Sem characterization,
|
|
161
|
+
regressão silenciosa em ordem de chamadas, side effects,
|
|
162
|
+
state compartilhado.
|
|
163
|
+
|
|
164
|
+
CERTO: characterize primeiro (cap 13). Snapshots da classe ANTES.
|
|
165
|
+
Extract incremental. Snapshots devem continuar verdes a cada
|
|
166
|
+
commit (comportamento idêntico).
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### ANTI: extract class sem hot spot real
|
|
170
|
+
|
|
171
|
+
```text
|
|
172
|
+
ANTI: "vou extrair Helper class só pra reduzir linhas".
|
|
173
|
+
|
|
174
|
+
PROBLEMA: classe nova sem coesão. Helper recebe métodos
|
|
175
|
+
arbitrários. Reviewer não consegue justificar a divisão.
|
|
176
|
+
Resultado: god class virou god class + helper class.
|
|
177
|
+
|
|
178
|
+
CERTO: hot spot REAL = cluster de fields + métodos com forte coupling
|
|
179
|
+
interno. Sem cluster, não extract — refactor outro
|
|
180
|
+
(extract method, eliminar dead code).
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
## Verificação
|
|
184
|
+
|
|
185
|
+
1. Hot spots identificados via matriz de coupling
|
|
186
|
+
2. Compilação verde a cada commit
|
|
187
|
+
3. Extracted classes têm coesão alta (fields + métodos relacionam-se)
|
|
188
|
+
4. Classe original encolheu significativamente (≥ 30%)
|
|
189
|
+
5. Tests acumulados nas classes extraídas (≥ 60% coverage)
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## Ver também
|
|
194
|
+
|
|
195
|
+
- [`_shared-legacy/glossary.md`](../_shared-legacy/glossary.md) — vocabulário canônico
|
|
196
|
+
- [`legacy-characterization-tests`](../legacy-characterization-tests/SKILL.md) — characterize ANTES de extract class
|
|
197
|
+
- [`legacy-monster-methods`](../legacy-monster-methods/SKILL.md) — extract method é precursor; extract class lida com classe inteira
|
|
198
|
+
- [`legacy-effect-analysis`](../legacy-effect-analysis/SKILL.md) — sketch identifica hot spots antes do extract
|
|
199
|
+
- [`legacy-shotgun-surgery`](../legacy-shotgun-surgery/SKILL.md) — duplicação cross-class detecta candidatos a extract class
|
|
200
|
+
- [`supabase-architect`](../../agents/supabase-architect.md) (v1.8) — referencia extract class quando design domain inicial cresce além do esperado
|
|
201
|
+
|
|
202
|
+
*Material-fonte: Working Effectively with Legacy Code — Feathers, 2004 — Cap 20: "This Class Is Too Big and I Don't Want It to Get Any Bigger".*
|
|
203
|
+
*Modernização (2026):* Aplicação canônica em domain classes Supabase com SRP retroativo.
|