@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,212 @@
1
+ ---
2
+ name: caracterizar
3
+ description: Invoca legacy-characterizer — gera characterization tests (cap 13 Feathers) capturando comportamento atual como golden snapshots; cobre 5+ grupos de equivalência canônicos; valida cobertura via mutation testing.
4
+ argument-hint: "<target_file> [--symbol <name>] [--min-inputs N] [--gap-fill] [--fixtures-dir <path>] [--no-mutation]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Bash
10
+ - Grep
11
+ - Glob
12
+ - Task
13
+ ---
14
+
15
+ <objective>
16
+ Caracterizar arquivo de código legado (sem testes) gerando suite de characterization tests que congelam comportamento atual como oracle imutável durante refactor. Invoca o agente [`legacy-characterizer`](../agents/legacy-characterizer.md) que aplica a skill [`legacy-characterization-tests`](../skills/legacy-characterization-tests/SKILL.md) — 7 grupos canônicos de equivalência (empty/typical/boundary-low/boundary-up/recoverable-invalid/fatal-invalid/side-effect-heavy), golden snapshots com sanitização de PII, validação behavioral via mutation testing.
17
+
18
+ **Cria/Atualiza:**
19
+ - `tests/characterization/<file_stem>/` — suite de testes + snapshots + fakes auxiliares
20
+ - `tests/characterization/<file_stem>/README.md` — anotações de bugs preservados, fonte do oracle
21
+
22
+ **Após:** o user tem safety net que detecta regressão imediata em refactor. Gate `refactor-safety-auditor` muda de BLOCK → GO. Refactor pode prosseguir com `cover-and-modify` em vez de `edit-and-pray`.
23
+ </objective>
24
+
25
+ <context>
26
+ **Argumentos:**
27
+ - `<target_file>` — caminho do arquivo a caracterizar (relativo ao project root) — OBRIGATÓRIO
28
+ - `--symbol <name>` — caracterizar apenas símbolo específico (default: todos os exports)
29
+ - `--min-inputs N` — número mínimo de inputs (default: 8)
30
+ - `--gap-fill` — modo gap-fill: caracterizar APENAS o que falta para atingir 70% behavioral coverage (não recriar o que existe)
31
+ - `--fixtures-dir <path>` — diretório de payloads reais capturados (substitui inputs sintéticos por reais)
32
+ - `--no-mutation` — skip mutation testing após geração (default: roda se ferramenta detectada)
33
+ - `--output-dir <path>` — diretório base de output (default: `tests/characterization/<file_stem>/`)
34
+
35
+ **Exemplos:**
36
+ ```
37
+ /caracterizar src/orders/handler.ts # caracterização completa, defaults
38
+ /caracterizar src/orders/handler.ts --symbol processOrder # só um método
39
+ /caracterizar src/orders/handler.ts --gap-fill # só preenche lacunas (re-rodar pós-refactor)
40
+ /caracterizar supabase/functions/webhook/index.ts \
41
+ --fixtures-dir .planning/captured-payloads/webhook # usa payloads reais
42
+ ```
43
+
44
+ **Pré-requisitos:**
45
+ - Arquivo deve compilar/parsear no projeto atual
46
+ - Test framework instalado (Vitest, Jest, pytest, JUnit, go-test, etc.)
47
+ - (Recomendado) ferramenta de mutation testing instalada — Stryker (JS/TS), mutmut (Py), Pitest (Java)
48
+ - (Opcional) coverage tool com summary acessível (Istanbul/c8 para JS, coverage.py, JaCoCo)
49
+
50
+ **Quando este comando é o caminho certo:**
51
+ - Arquivo > 200 linhas com cobertura < 60% e mudança comportamental planejada
52
+ - Webhook/edge function/API pública sendo modificada
53
+ - Gate `refactor-safety-auditor` retornou BLOCK
54
+ - Refactor de monster method (cap 22) iniciando
55
+
56
+ **Quando NÃO é o caminho:**
57
+ - Arquivo trivial (< 50 linhas, sem branches significativas) — testes diretos sem ceremonial
58
+ - Mudança é apenas adicionar comportamento (sprout/wrap) — usar `/refactor-seguro --mode=sprout`
59
+ - Mudança é apenas mecânica (rename, extract-contiguous-block) — usar `/refactor-seguro --mode=safe-extract`
60
+ - Bug fix com TDD — TDD test do COMPORTAMENTO CORRETO é o caminho, não characterization
61
+ </context>
62
+
63
+ <process>
64
+
65
+ ## 1. Parsear argumentos
66
+
67
+ ```bash
68
+ # PT-BR: extrair primeiro positional como target_file
69
+ TARGET_FILE=$(echo "$ARGUMENTS" | awk '{print $1}')
70
+ SYMBOL=$(echo "$ARGUMENTS" | grep -oE -- '--symbol [^ ]+' | awk '{print $2}')
71
+ MIN_INPUTS=$(echo "$ARGUMENTS" | grep -oE -- '--min-inputs [0-9]+' | awk '{print $2}')
72
+ FIXTURES_DIR=$(echo "$ARGUMENTS" | grep -oE -- '--fixtures-dir [^ ]+' | awk '{print $2}')
73
+ OUTPUT_DIR=$(echo "$ARGUMENTS" | grep -oE -- '--output-dir [^ ]+' | awk '{print $2}')
74
+ GAP_FILL=false
75
+ NO_MUTATION=false
76
+
77
+ echo "$ARGUMENTS" | grep -qE -- '--gap-fill' && GAP_FILL=true
78
+ echo "$ARGUMENTS" | grep -qE -- '--no-mutation' && NO_MUTATION=true
79
+
80
+ [ -z "$MIN_INPUTS" ] && MIN_INPUTS=8
81
+
82
+ if [ -z "$TARGET_FILE" ]; then
83
+ echo "ERROR: target_file é obrigatório."
84
+ echo "Uso: /caracterizar <target_file> [opções]"
85
+ exit 1
86
+ fi
87
+
88
+ if [ ! -f "$TARGET_FILE" ]; then
89
+ echo "ERROR: arquivo não encontrado: $TARGET_FILE"
90
+ exit 1
91
+ fi
92
+ ```
93
+
94
+ ## 2. Validar pré-requisitos
95
+
96
+ ```bash
97
+ # PT-BR: detectar test framework + alertar se ausente
98
+ FRAMEWORK_OK=false
99
+ case "$TARGET_FILE" in
100
+ *.ts|*.tsx|*.js|*.jsx|*.mjs)
101
+ if [ -f "package.json" ]; then
102
+ jq -re '.devDependencies | (.vitest // .jest)' package.json >/dev/null 2>&1 && FRAMEWORK_OK=true
103
+ fi
104
+ ;;
105
+ *.py)
106
+ pip show pytest >/dev/null 2>&1 && FRAMEWORK_OK=true
107
+ ;;
108
+ *.java)
109
+ [ -f pom.xml ] || [ -f build.gradle ] && FRAMEWORK_OK=true
110
+ ;;
111
+ *.go)
112
+ [ -f go.mod ] && FRAMEWORK_OK=true
113
+ ;;
114
+ esac
115
+
116
+ if [ "$FRAMEWORK_OK" = false ]; then
117
+ echo "⚠ Test framework não detectado. Agent pode gerar testes mas execução exigirá setup."
118
+ fi
119
+
120
+ # PT-BR: avisar se gap-fill mas não há characterization existente
121
+ if [ "$GAP_FILL" = true ]; then
122
+ STEM=$(basename "$TARGET_FILE" | sed 's/\.[^.]*$//')
123
+ if ! find tests test __tests__ -path "*characterization*$STEM*" 2>/dev/null | head -1 | grep -q .; then
124
+ echo "⚠ --gap-fill solicitado mas nenhum characterization existente encontrado."
125
+ echo " Caindo em modo full-characterization."
126
+ GAP_FILL=false
127
+ fi
128
+ fi
129
+ ```
130
+
131
+ ## 3. Dispatch para `legacy-characterizer`
132
+
133
+ ```text
134
+ Task(
135
+ subagent_type="legacy-characterizer",
136
+ prompt="
137
+ target_file: ${TARGET_FILE}
138
+ ${SYMBOL:+target_symbol: ${SYMBOL}}
139
+ min_inputs: ${MIN_INPUTS}
140
+ ${FIXTURES_DIR:+payload_fixtures_dir: ${FIXTURES_DIR}}
141
+ ${OUTPUT_DIR:+output_dir: ${OUTPUT_DIR}}
142
+ mutation_check: $([ "$NO_MUTATION" = true ] && echo false || echo true)
143
+ mode: $([ "$GAP_FILL" = true ] && echo gap-fill || echo full)
144
+
145
+ Aplicar skill legacy-characterization-tests. Etapas canônicas:
146
+ 1. Análise estática: identificar exports, parâmetros, deps de I/O, side effects, branches
147
+ 2. Aplicar 7 grupos de equivalência canônicos (ou substituir por payloads reais se fixtures-dir fornecido)
148
+ 3. Construir fakes mínimos para deps de I/O (DB, HTTP, FS, clock, random, UUID)
149
+ 4. Executar código real com cada input + fakes; capturar return + sideEffects
150
+ 5. Sanitizar (PII, secrets, UUIDs voláteis) antes de salvar como snapshot
151
+ 6. Imprimir warning de revisão obrigatória dos snapshots
152
+ 7. Validar cobertura behavioral via mutation testing (Stryker/mutmut/Pitest)
153
+ 8. Output: tests/characterization/<file_stem>/ + README.md
154
+
155
+ Modo gap-fill (se aplicável): caracterizar APENAS branches/paths não cobertos pela suite existente; NÃO recriar tests existentes.
156
+ "
157
+ )
158
+ ```
159
+
160
+ ## 4. Pós-output: revisão obrigatória + integração com gate
161
+
162
+ Após o agent completar:
163
+
164
+ ```
165
+ ═══════════════════════════════════════════════════════════
166
+ framework ► CARACTERIZAR ▸ tests/characterization/<file_stem>/
167
+ ═══════════════════════════════════════════════════════════
168
+
169
+ [output do legacy-characterizer]
170
+
171
+ ## ⚠ REVISÃO MANUAL OBRIGATÓRIA dos snapshots
172
+
173
+ Localização: tests/characterization/<file_stem>/__snapshots__/
174
+
175
+ Steps antes de commit:
176
+ 1. Ler cada snapshot linha por linha
177
+ 2. Marcar bugs conhecidos como comments inline (// BUG #X: ...)
178
+ 3. Verificar redaction de PII/secrets adicional
179
+ 4. Confirmar zero secrets/UUIDs locais expostos
180
+
181
+ Não commitar como `chore: characterize <file>` sem revisão.
182
+
183
+ ## Próximos passos
184
+
185
+ 1. **Revisar snapshots** — manualmente, todos os arquivos em __snapshots__/
186
+ 2. **Rodar suite** — verificar todos verdes:
187
+ - JS/TS: `npm test -- tests/characterization/<file_stem>`
188
+ - Python: `pytest tests/characterization/<file_stem>`
189
+ - Java: `mvn test -Dtest='Characterization*'`
190
+ 3. **Commit** — `chore: characterize <file_stem>` (PR separado, NÃO misturar com refactor)
191
+ 4. **Re-auditar gate** — `/auditar-refactor <file>` deve agora retornar GO
192
+ 5. **Iniciar refactor** — `/refactor-seguro <file>` (ou diretamente PR de refactor)
193
+
194
+ ## Cross-suite
195
+
196
+ - Para sprout/wrap em vez de full characterization: `/refactor-seguro --mode=sprout <file>`
197
+ - Para safe-extract em vez de behavioral change: `/refactor-seguro --mode=safe-extract <file>`
198
+ - Para SLO protection durante refactor: `/instrumentar-fase` (v1.9 — captura behavioral diff)
199
+ ```
200
+
201
+ </process>
202
+
203
+ <success_criteria>
204
+ - [ ] $ARGUMENTS parseados (target_file obrigatório, 7 flags opcionais)
205
+ - [ ] Pré-requisitos validados (framework de teste detectado; warning se não)
206
+ - [ ] `legacy-characterizer` invocado via `Task(subagent_type=...)` com prompt completo (8 etapas)
207
+ - [ ] `tests/characterization/<file_stem>/` criado com tests + snapshots + fakes + README
208
+ - [ ] Output forwarded transparentemente do agent
209
+ - [ ] Warning de revisão manual emitido (snapshots NÃO são committed automaticamente)
210
+ - [ ] Próximos passos sugeridos: revisar, rodar, commitar, re-auditar gate, iniciar refactor
211
+ - [ ] Modo gap-fill respeitado se solicitado e characterization existente encontrada
212
+ </success_criteria>
@@ -205,4 +205,44 @@ Quando `workflow.complete_milestone_prr_gate = true` (default `false` — opt-in
205
205
  - "Gate ligado em projeto early stage" → bloco "Quando ligar gate" exige ≥ 2 sinais de production maturity
206
206
 
207
207
  **REQ:** INT-FW-V2-02.
208
- </sre_integration>
208
+ </sre_integration>
209
+
210
+ <sre_resilience_integration>
211
+ **Release pipeline policy gate (v1.11 — INT-FW-V3-01):**
212
+
213
+ Quando `workflow.complete_milestone_release_pipeline_gate = true` (default `false` — opt-in), o workflow inclui passo de validação de release pipeline **paralelo ao PRR gate**:
214
+
215
+ 1. Invocar `Task(subagent_type=release-pipeline-auditor, prompt="...")` para gerar `.planning/RELEASE-AUDIT.md` fresco
216
+ 2. Verificar score agregado:
217
+ - **ROBUST (≥ 25/30):** gate aprova — milestone arquivável
218
+ - **ADEQUATE (20-24):** warnings explícitos no archive; arquivável
219
+ - **FRAGILE (15-19):** BLOQUEIA — listar top 5 fixes; user resolve antes de re-tentar
220
+ - **BROKEN (< 15):** BLOQUEIA forte — escalation; pipeline não pode ser fonte de verdade
221
+ 3. Resultado salvo como anexo no `.planning/milestones/v<version>-MILESTONE.md` (audit trail)
222
+
223
+ **Quando ligar gate (paralelo ao PRR):**
224
+
225
+ - Projeto tem release frequency ≥ 1×/semana
226
+ - Projeto tem deploys que afetam usuários externos (não só dogfooding)
227
+ - Equipe quer disciplina release engineering (cap 8 livro Google SRE)
228
+ - Projeto já tem PRR gate ligado (sinal de production maturity)
229
+
230
+ **Quando manter desligado:**
231
+
232
+ - Projeto < 6 meses (pipeline ainda imatura)
233
+ - Solo dev sem CI/CD complexo
234
+ - Releases mensais ou raros (overhead > valor)
235
+
236
+ **Skills consultadas:** [hermetic-builds](../skills/hermetic-builds/SKILL.md), [release-engineering](../skills/release-engineering/SKILL.md) (cap 8 livro Google SRE).
237
+
238
+ **Gate executável:** `gates/release-pipeline-policy.md` (criado em Phase 47 — QA-SRE2-04). Workflow `.claude/framework/workflows/complete-milestone.md` consulta esse gate quando flag `true`.
239
+
240
+ **Anti-patterns prevenidos:**
241
+
242
+ - "Release pipeline frágil porque historicamente funcionou" → gate força quantificação objetiva
243
+ - "Build não-hermético com `npm install`" → gate Hermeticidade dimension catches
244
+ - "Branch protection desligada para velocidade" → gate Policy Enforcement dimension catches
245
+ - "Gate ligado em projeto early stage" → bloco "Quando ligar gate" exige sinais de maturity
246
+
247
+ **REQ:** INT-FW-V3-01.
248
+ </sre_resilience_integration>
@@ -0,0 +1,197 @@
1
+ ---
2
+ name: detectar-duplicacao
3
+ description: Invoca shotgun-surgery-detector — detecta duplicação sintática (jscpd/regex) + semântica (embeddings) cross-codebase, prioriza por size × frequency × extract feasibility. Modernização cap 21 Feathers.
4
+ argument-hint: "<root_dir> [--threshold 0.85] [--min-cluster-size 3] [--mode syntactic|semantic|both] [--provider openai|pgvector|auto]"
5
+ allowed-tools:
6
+ - Read
7
+ - Bash
8
+ - Grep
9
+ - Glob
10
+ - Task
11
+ - Write
12
+ - mcp__supabase__execute_sql
13
+ ---
14
+
15
+ <objective>
16
+ Detectar **shotgun surgery** (mesma mudança/lógica espalhada em N lugares) cross-codebase via:
17
+ 1. **Detecção sintática** — Feathers cap 21 original; jscpd/regex/AST
18
+ 2. **Detecção semântica** — modernização 2026; embeddings + cosine similarity
19
+
20
+ Invoca o agente [`shotgun-surgery-detector`](../agents/shotgun-surgery-detector.md) que aplica a skill [`legacy-shotgun-surgery`](../skills/legacy-shotgun-surgery/SKILL.md). Output: clusters priorizados por (size × frequency × extract feasibility).
21
+
22
+ **Cria/Atualiza:**
23
+ - `.planning/SHOTGUN-SURGERY.md` — clusters detectados, top 10 priorizados, sugestões extract
24
+
25
+ **Após:** o user tem lista acionável de candidates a extract method/class para reduzir change points. PR sequence canônica: extract first → modify second.
26
+ </objective>
27
+
28
+ <context>
29
+ **Argumentos:**
30
+ - `<root_dir>` — diretório raiz a analisar (default: `.`)
31
+ - `--threshold 0.85` — cosine similarity mínima para semantic cluster (default: 0.85)
32
+ - `--min-cluster-size 3` — Rule of 3 (default: 3)
33
+ - `--min-block-lines 10` — tamanho mínimo de bloco para análise (default: 10)
34
+ - `--mode syntactic|semantic|both` — modo (default: `both`)
35
+ - `--provider openai|pgvector|auto` — embedding provider (default: auto-detect)
36
+ - `--output PATH` — caminho do output (default: `.planning/SHOTGUN-SURGERY.md`)
37
+
38
+ **Exemplos:**
39
+ ```
40
+ /detectar-duplicacao src/ # both modes, defaults
41
+ /detectar-duplicacao . --mode=syntactic # só Feathers original (sem custo IA)
42
+ /detectar-duplicacao src/ --threshold 0.90 # mais conservador
43
+ /detectar-duplicacao src/ --min-cluster-size 5 # só clusters grandes
44
+ /detectar-duplicacao src/ --provider=pgvector # forçar self-hosted
45
+ ```
46
+
47
+ **Pré-requisitos:**
48
+ - jscpd disponível para sintática (`npm install -g jscpd` se não)
49
+ - OPENAI_API_KEY OR pgvector setup para semântica (auto-detect)
50
+ - Node.js 20+ no path para chamadas embeddings
51
+
52
+ **Quando este comando é o caminho:**
53
+ - Você sente "estou mudando isso em N lugares" — use detector pra confirmar/quantificar
54
+ - Refactor proposto inclui extract method/class — detector confirma 3+ ocorrências
55
+ - Code review onde reviewer suspeita de DRY violations
56
+ - Pré-requisito para `/legacy refactor` quando shotgun é a real causa raiz
57
+ </context>
58
+
59
+ <process>
60
+
61
+ ## 1. Parsear argumentos
62
+
63
+ ```bash
64
+ ROOT_DIR=$(echo "$ARGUMENTS" | awk '{print $1}')
65
+ THRESHOLD=$(echo "$ARGUMENTS" | grep -oE -- '--threshold [0-9.]+' | awk '{print $2}')
66
+ MIN_CLUSTER=$(echo "$ARGUMENTS" | grep -oE -- '--min-cluster-size [0-9]+' | awk '{print $2}')
67
+ MIN_BLOCK=$(echo "$ARGUMENTS" | grep -oE -- '--min-block-lines [0-9]+' | awk '{print $2}')
68
+ MODE=$(echo "$ARGUMENTS" | grep -oE -- '--mode[= ][^ ]+' | sed 's/--mode[= ]//')
69
+ PROVIDER=$(echo "$ARGUMENTS" | grep -oE -- '--provider[= ][^ ]+' | sed 's/--provider[= ]//')
70
+ OUTPUT_PATH=$(echo "$ARGUMENTS" | grep -oE -- '--output [^ ]+' | awk '{print $2}')
71
+
72
+ [ -z "$ROOT_DIR" ] && ROOT_DIR="."
73
+ [ -z "$THRESHOLD" ] && THRESHOLD="0.85"
74
+ [ -z "$MIN_CLUSTER" ] && MIN_CLUSTER=3
75
+ [ -z "$MIN_BLOCK" ] && MIN_BLOCK=10
76
+ [ -z "$MODE" ] && MODE="both"
77
+ [ -z "$PROVIDER" ] && PROVIDER="auto"
78
+ [ -z "$OUTPUT_PATH" ] && OUTPUT_PATH=".planning/SHOTGUN-SURGERY.md"
79
+
80
+ if [ ! -d "$ROOT_DIR" ]; then
81
+ echo "ERROR: root_dir não encontrado: $ROOT_DIR"
82
+ exit 1
83
+ fi
84
+
85
+ mkdir -p "$(dirname "$OUTPUT_PATH")"
86
+ ```
87
+
88
+ ## 2. Detectar capabilities
89
+
90
+ ```bash
91
+ HAS_JSCPD=false
92
+ command -v npx >/dev/null && npx jscpd --version >/dev/null 2>&1 && HAS_JSCPD=true
93
+
94
+ HAS_OPENAI=false
95
+ [ -n "$OPENAI_API_KEY" ] && HAS_OPENAI=true
96
+
97
+ HAS_PGVECTOR=false
98
+ if command -v psql >/dev/null && psql -tc "select 1 from pg_extension where extname='vector'" 2>/dev/null | grep -q 1; then
99
+ HAS_PGVECTOR=true
100
+ fi
101
+
102
+ # adjust mode if needed
103
+ if [ "$MODE" = "both" ] || [ "$MODE" = "semantic" ]; then
104
+ if [ "$HAS_OPENAI" = false ] && [ "$HAS_PGVECTOR" = false ]; then
105
+ echo "WARN: nenhum embedding provider disponível. Mode forçado para 'syntactic'."
106
+ MODE="syntactic"
107
+ fi
108
+ fi
109
+ ```
110
+
111
+ ## 3. Dispatch para `shotgun-surgery-detector`
112
+
113
+ ```text
114
+ Task(
115
+ subagent_type="shotgun-surgery-detector",
116
+ prompt="
117
+ root_dir: ${ROOT_DIR}
118
+ threshold: ${THRESHOLD}
119
+ min_cluster_size: ${MIN_CLUSTER}
120
+ min_block_lines: ${MIN_BLOCK}
121
+ mode: ${MODE}
122
+ embedding_provider: ${PROVIDER}
123
+ output_path: ${OUTPUT_PATH}
124
+
125
+ Aplicar skill legacy-shotgun-surgery. Etapas:
126
+ 1. Detecção sintática (sempre roda) — jscpd com min-lines + min-tokens
127
+ 2. Detecção semântica (se mode=semantic|both) — embeddings + cosine similarity
128
+ 3. Merge clusters (sintático + semântico); marker [SYNTACTIC] / [SEMANTIC] / [BOTH]
129
+ 4. Priorização canônica — score = (cluster_size × avg_block_lines × frequency_factor) / extract_feasibility
130
+ 5. Filter: cross-cutting noise (test files etc)
131
+ 6. Escrever .planning/SHOTGUN-SURGERY.md com:
132
+ - Resumo (X clusters totais)
133
+ - Top 10 priorizados com diff visual
134
+ - Sugestões de extract com nome canônico
135
+ - Esforço estimado por cluster
136
+ "
137
+ )
138
+ ```
139
+
140
+ ## 4. Pós-output
141
+
142
+ ```
143
+ ═══════════════════════════════════════════════════════════
144
+ framework ► DETECTAR-DUPLICACAO ▸ ${OUTPUT_PATH}
145
+ ═══════════════════════════════════════════════════════════
146
+
147
+ [output do shotgun-surgery-detector]
148
+
149
+ ## ⚠ Validação obrigatória
150
+
151
+ Cada cluster — especialmente semantic — precisa de **revisão humana**:
152
+ - Falsos positivos comuns: 2 funções com nomes/comments similares mas implementações diferentes
153
+ - Variations entre ocorrências podem ser INTENCIONAIS (rounding diferente, encoding diferente)
154
+ - Extract uniformiza → mudança comportamental possível
155
+
156
+ NÃO auto-extract. Cluster aprovado por humano vira PR.
157
+
158
+ ## Próximos passos por cluster aprovado
159
+
160
+ 1. **Caracterizar cada ocorrência** (capturar comportamento atual):
161
+ ```bash
162
+ /caracterizar <file-da-ocorrencia-1>
163
+ /caracterizar <file-da-ocorrencia-2>
164
+ ...
165
+ ```
166
+ 2. **Validar outputs idênticos** OU documentar diferenças intencionais
167
+ 3. **Escolher nome canônico** (resonates com TODAS as N localizações)
168
+ 4. **Extract para 1 lugar** (criar utility/módulo compartilhado)
169
+ 5. **Substituir cada ocorrência** (1 commit por substituição, revertível)
170
+ 6. **Re-rodar detector** após PRs para verificar redução de clusters
171
+
172
+ ## Custo (modo semantic)
173
+
174
+ - ~$<cost>/run com OpenAI text-embedding-3-small
175
+ - $0 com pgvector self-hosted
176
+ - 0 com mode=syntactic only
177
+
178
+ ## Cross-suite
179
+
180
+ - **/storytelling** (v1.12) — story dos módulos identifica clusters mais provável
181
+ - **/caracterizar** (v1.12) — characterize cada ocorrência ANTES de extract
182
+ - **/legacy refactor** (v1.12) — chain canônico para extract
183
+ - **/auditar-marco** — rerodar shotgun detector trimestral revela acumulação de débito
184
+ ```
185
+
186
+ </process>
187
+
188
+ <success_criteria>
189
+ - [ ] $ARGUMENTS parseados (root_dir opcional, defaults sensíveis)
190
+ - [ ] Capabilities detectadas (jscpd, OpenAI, pgvector)
191
+ - [ ] Mode degraded se provider de embedding indisponível
192
+ - [ ] `shotgun-surgery-detector` invocado via Task
193
+ - [ ] Output forwarded transparentemente
194
+ - [ ] Warning de validação manual obrigatória
195
+ - [ ] Próximos passos: characterize → validate → extract → substituir → re-detect
196
+ - [ ] Cross-references com /storytelling, /caracterizar, /legacy refactor
197
+ </success_criteria>
@@ -88,3 +88,44 @@ O `plan-checker` invocado pelo `/planejar-fase` (Phase 33 — INT-FW-02) lê est
88
88
 
89
89
  **REQ:** INT-FW-01.
90
90
  </observability_integration>
91
+
92
+ <legacy_refactor_integration>
93
+ **Integração com Suíte Legacy Code (Feathers):**
94
+
95
+ Quando o workflow detecta intent de **refactor** (palavras-chave em descrição da fase: "refator", "refactor", "extrair", "limpar", "reorganizar", "split", "quebrar classe/módulo"), inclui pergunta canônica:
96
+
97
+ > "Esta fase envolve refactor de arquivo existente? Se sim, qual é o arquivo alvo?"
98
+
99
+ Para cada arquivo identificado:
100
+ 1. Coleta line count + checa se path matches contrato externo (supabase/functions, src/api, webhooks, pages/api)
101
+ 2. Invoca [`refactor-safety-auditor`](../agents/refactor-safety-auditor.md) **em modo dry-run** para coletar evidências sem bloquear
102
+ 3. Resultado registrado em CONTEXT.md em seção `<refactor_safety>`:
103
+
104
+ ```markdown
105
+ <refactor_safety>
106
+ ## Arquivos alvo de refactor
107
+
108
+ | Arquivo | Linhas | Contrato externo | Cobertura | Char tests | Veredito do gate |
109
+ |---|---|---|---|---|---|
110
+ | src/orders/handler.ts | 724 | true | 12% | absent | BLOCK |
111
+ | src/orders/utils.ts | 89 | false | 78% | absent | GO |
112
+
113
+ ## Recomendação
114
+
115
+ Para `src/orders/handler.ts`:
116
+ - Caminho preferido: /caracterizar antes de refactor (custo: 8-16h)
117
+ - Alternativa: /refactor-seguro --mode=sprout (se mudança ADICIONA, não modifica)
118
+ - Para safe-extract: assinar checklist canônico de safe extraction
119
+ - Override possível com ticket + reason
120
+
121
+ Para `src/orders/utils.ts`:
122
+ - Refactor pode prosseguir; cobertura adequada existe.
123
+ </refactor_safety>
124
+ ```
125
+
126
+ `plan-checker` consume essa seção. Se gate retorna BLOCK e mode=blocking, plano não é aprovado até user escolher caminho explícito.
127
+
128
+ **Skill canônica:** [`pre-refactor-characterization`](../skills/pre-refactor-characterization/SKILL.md)
129
+
130
+ **Quando skip:** fase puramente de infraestrutura (markdown, config, tooling), fase greenfield (sem arquivos existentes a modificar), OR `workflow.legacy_refactor_questions=false` em config.
131
+ </legacy_refactor_integration>
@@ -0,0 +1,136 @@
1
+ ---
2
+ name: encontrar-seams
3
+ description: Invoca seam-finder — analisa código para identificar seams (object/link/preprocessing) e recomenda técnica do cap 25 Feathers para quebrar dependências bloqueantes. Pré-requisito quando deps externas impedem characterization.
4
+ argument-hint: "<target_file> [--symbol <name>] [--prefer object|link|preprocessing] [--output PATH]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Bash
9
+ - Grep
10
+ - Glob
11
+ - Task
12
+ ---
13
+
14
+ <objective>
15
+ Analisar código alvo para identificar **seams** (lugares onde se pode alterar comportamento sem editar lá) e recomendar **técnica do catálogo cap 25 Feathers** para quebrar dependências bloqueantes (DB real, HTTP, framework objects, singletons, clocks). Invoca o agente [`seam-finder`](../agents/seam-finder.md) que aplica a skill [`legacy-seams-and-test-harness`](../skills/legacy-seams-and-test-harness/SKILL.md) — decision tree por linguagem, prioridade pelo MENOR custo + MAIOR reversibilidade.
16
+
17
+ **Cria/Atualiza:**
18
+ - `.planning/SEAM-ANALYSIS.md` — relatório com deps bloqueantes, técnicas recomendadas, sequência canônica de commits
19
+
20
+ **Após:** o user tem plano mecânico para tornar código testável antes de invocar `/caracterizar`. Tipicamente 5-30 minutos por dep bloqueante; sequência de pequenos commits revertíveis.
21
+ </objective>
22
+
23
+ <context>
24
+ **Argumentos:**
25
+ - `<target_file>` — caminho do arquivo a analisar (relativo ao project root) — OBRIGATÓRIO
26
+ - `--symbol <name>` — analisar apenas símbolo específico (default: arquivo inteiro)
27
+ - `--prefer object|link|preprocessing` — preferência de tipo de seam (default: object)
28
+ - `--output PATH` — caminho do output (default: `.planning/SEAM-ANALYSIS.md`)
29
+
30
+ **Exemplos:**
31
+ ```
32
+ /encontrar-seams src/orders/OrderService.ts # análise completa
33
+ /encontrar-seams src/orders/OrderService.ts --symbol charge # método específico
34
+ /encontrar-seams src/legacy/Client.cpp --prefer link # forçar link seam (C++ legado)
35
+ ```
36
+
37
+ **Quando este comando é o caminho certo:**
38
+ - `/caracterizar` falhou porque deps externas impedem isolamento
39
+ - Construtor faz I/O direto (cria conexão DB no constructor)
40
+ - Usar singleton/global hardcoded no método a testar
41
+ - Framework type complexo (HttpServletRequest, Express.Request) bloqueando teste
42
+ - Código procedural (C, COBOL, Go) onde polimorfismo não está disponível
43
+
44
+ **Quando NÃO é o caminho:**
45
+ - Código já é testável (deps injetadas via DI) → usar `/caracterizar` direto
46
+ - Código é puro (sem I/O) → não precisa break-dep
47
+ - Mudança é safe-extraction (rename, IDE-extract) → usar `/refactor-seguro --mode=safe-extract`
48
+ </context>
49
+
50
+ <process>
51
+
52
+ ## 1. Parsear argumentos
53
+
54
+ ```bash
55
+ TARGET_FILE=$(echo "$ARGUMENTS" | awk '{print $1}')
56
+ SYMBOL=$(echo "$ARGUMENTS" | grep -oE -- '--symbol [^ ]+' | awk '{print $2}')
57
+ PREFER=$(echo "$ARGUMENTS" | grep -oE -- '--prefer [^ ]+' | awk '{print $2}')
58
+ OUTPUT_PATH=$(echo "$ARGUMENTS" | grep -oE -- '--output [^ ]+' | awk '{print $2}')
59
+
60
+ [ -z "$OUTPUT_PATH" ] && OUTPUT_PATH=".planning/SEAM-ANALYSIS.md"
61
+ [ -z "$PREFER" ] && PREFER="object"
62
+
63
+ if [ -z "$TARGET_FILE" ]; then
64
+ echo "ERROR: target_file é obrigatório."
65
+ echo "Uso: /encontrar-seams <target_file> [opções]"
66
+ exit 1
67
+ fi
68
+
69
+ if [ ! -f "$TARGET_FILE" ]; then
70
+ echo "ERROR: arquivo não encontrado: $TARGET_FILE"
71
+ exit 1
72
+ fi
73
+
74
+ mkdir -p "$(dirname "$OUTPUT_PATH")"
75
+ ```
76
+
77
+ ## 2. Dispatch para `seam-finder`
78
+
79
+ ```text
80
+ Task(
81
+ subagent_type="seam-finder",
82
+ prompt="
83
+ target_file: ${TARGET_FILE}
84
+ ${SYMBOL:+target_symbol: ${SYMBOL}}
85
+ output_path: ${OUTPUT_PATH}
86
+ prefer_technique: ${PREFER}
87
+
88
+ Aplicar skill legacy-seams-and-test-harness. Etapas:
89
+ 1. Detectar linguagem + paradigma (OO vs procedural)
90
+ 2. Mapear deps externas (network/DB/FS/clock/random/UUID/global/framework-type/construtor-caro)
91
+ 3. Identificar tipos de seam disponíveis (object/link/preprocessing)
92
+ 4. Aplicar decision tree do cap 25 escolhendo técnica de menor custo + maior reversibilidade
93
+ 5. Gerar SEAM-ANALYSIS.md com:
94
+ - tabela de deps bloqueantes
95
+ - técnica recomendada por dep com custo + reversibilidade
96
+ - exemplo ANTES/DEPOIS por técnica
97
+ - sequência canônica de commits (mais seguro → mais arriscado)
98
+ 6. Output curto para caller: lista de N deps + custo total estimado
99
+ "
100
+ )
101
+ ```
102
+
103
+ ## 3. Pós-output: integração com fluxo
104
+
105
+ ```
106
+ ═══════════════════════════════════════════════════════════
107
+ framework ► ENCONTRAR-SEAMS ▸ ${OUTPUT_PATH}
108
+ ═══════════════════════════════════════════════════════════
109
+
110
+ [output do seam-finder]
111
+
112
+ ## Próximos passos
113
+
114
+ 1. **Aplicar técnicas** — seguir sequência canônica em ${OUTPUT_PATH}
115
+ Cada commit é single-goal, mecânico, revertível
116
+ 2. **Rodar suite após cada commit** — compilação verde + tests verdes
117
+ 3. **/caracterizar <file>** — após break-deps complete, characterization fica viável
118
+ 4. **/auditar-refactor <file>** — gate deve retornar GO ou WARN agora (não mais BLOCK)
119
+
120
+ ## Cross-suite
121
+
122
+ - Em projetos Supabase com Edge Functions: `supabase-edge-fn-writer` (v1.8) já segue patterns testáveis
123
+ - Para skills de SOLID/DI: ver também `supabase-architect` (v1.8) — schema design considera testabilidade similarmente
124
+ - Para mudança em código que afeta SLOs: `/instrumentar-fase` (v1.9) durante refactor preserva visibility
125
+ ```
126
+
127
+ </process>
128
+
129
+ <success_criteria>
130
+ - [ ] $ARGUMENTS parseados (target_file obrigatório)
131
+ - [ ] `seam-finder` invocado via `Task(subagent_type=...)` com prompt completo (6 etapas)
132
+ - [ ] `.planning/SEAM-ANALYSIS.md` criado pelo agent com deps + técnicas + sequência de commits
133
+ - [ ] Output forwarded transparentemente do agent
134
+ - [ ] Próximos passos sugeridos: aplicar técnicas, rodar suite, /caracterizar, /auditar-refactor
135
+ - [ ] Cross-references com Suíte Supabase (v1.8) e Observabilidade (v1.9) onde aplicável
136
+ </success_criteria>