O que o Prompt 04 Entrega
Rotação de personas + geração do relatório estruturado
O Prompt 04 transforma o runner genérico em três runners especializados — um por persona — e adiciona o código que consolida os findings em .claudex/reviews/PR-NNN.md.
scripts/generate-report.sh que consolida findings em PR-NNN.mdO Prompt 04 Completo
Cole este texto no Claude Code com o SPEC.md em contexto
Prompt 04 — Cole no Claude Code
Read SPEC.md — personas section is your reference.
You are building Prompt 04: add persona system prompts to the runner
generator and create the report consolidation script.
**Part A — Persona system prompts in write_runner:**
Update the write_runner helper in hooks/stop-hook.sh to inject a
persona-specific system prompt based on the current round:
Round 1 — Author persona:
"You are reviewing this PR as the AUTHOR of the code. Your job is to
verify that the implementation matches the stated intent in the PR
description. Look for: missing edge cases the description implies,
incomplete implementations, code that doesn't match the PR title.
Output ONLY a YAML list of findings."
Round 2 — Reviewer persona:
"You are a senior engineer reviewing this PR for correctness and
maintainability. Look for: logic errors, off-by-one errors, null
pointer risks, resource leaks, API misuse, missing error handling,
performance issues. Output ONLY a YAML list of findings."
Round 3 — Security persona:
"You are a security engineer reviewing this PR for vulnerabilities.
Look for: injection risks (SQL, command, path traversal), authentication
bypass, authorization gaps, sensitive data in logs, insecure defaults,
hardcoded secrets, SSRF vectors. Output ONLY a YAML list of findings."
**Part B — Structured findings schema:**
Each runner must instruct Claude to output findings as YAML only:
findings:
- file: "relative/path/to/file.go"
line: 42
severity: HIGH # CRITICAL|HIGH|MEDIUM|LOW
persona: "Reviewer"
description: "One sentence describing the issue"
suggestion: "One sentence fix suggestion"
**Part C — generate-report.sh:**
Create `scripts/generate-report.sh <pr_number>`:
1. Read all findings from state/review.yaml
2. Group findings by file
3. Sort by severity (CRITICAL first)
4. Generate .claudex/reviews/PR-$pr_number.md with:
- Header: # PR Review #NNN — [date]
- Executive summary: N findings (X CRITICAL, Y HIGH, Z MEDIUM, W LOW)
- Severity badges in header
- Per-file sections with findings
- Footer: "Generated by pr-reviewer plugin"
5. Create .claudex/reviews/ dir if not exists
**Call generate-report.sh from the SUMMARIZING phase in stop-hook.sh**
before transitioning to DONE.
**Constraints:**
- Personas must be injected in single-quoted heredocs (no interpolation)
- generate-report.sh must work even if findings list is empty
(output "No findings" section in that case)
- Severity sort order: CRITICAL > HIGH > MEDIUM > LOW
**Verification:**
- Run the full loop on a test PR (use `--print` mock if needed)
- Check that .claudex/reviews/PR-NNN.md exists after SUMMARIZING
- Verify severity grouping is correct in the report
- Report: "X findings found, report saved to .claudex/reviews/PR-NNN.md"
As 3 Personas
Author, Reviewer e Security — perspectivas complementares
Cada persona ativa um conjunto diferente de heurísticas no modelo. O Author nunca procura SQL injection. O Security nunca avalia se a implementação atende ao requisito. A cobertura surge da composição.
Author — Round 1
Pergunta: "A implementação faz o que o PR diz que faz?"
Encontra: edge cases que o PR description implica mas o código ignora, implementações parciais, discrepâncias entre título e código.
Reviewer — Round 2
Pergunta: "Este código vai funcionar em produção?"
Encontra: erros de lógica, off-by-one, null pointer, resource leak, API misuse, missing error handling, problemas de performance.
Security — Round 3
Pergunta: "Este código pode ser explorado?"
Encontra: injection (SQL, command, path traversal), auth bypass, dados sensíveis em logs, secrets hardcoded, SSRF, configurações inseguras.
O Formato do Relatório
Severidade, agrupamento por arquivo, métricas — output acionável
Um relatório útil não é um dump de texto. É um documento estruturado que permite ao time priorizar e agir imediatamente.
Estrutura do PR-NNN.md
# PR Review #123 — 2026-04-29 14:32 UTC
## Executive Summary
**3 findings** — 🔴 1 CRITICAL · 🟠 1 HIGH · 🟡 1 MEDIUM · ⚪ 0 LOW
---
## Findings by File
### `auth/token_handler.go`
#### 🔴 CRITICAL — Line 47
**Persona:** Security
**Issue:** Token transmitted without TLS enforcement check. If
`REQUIRE_HTTPS` is not set, tokens can be sent over plain HTTP.
**Suggestion:** Add `if !config.RequireHTTPS { return ErrInsecureConfig }`.
---
### `api/users.go`
#### 🟠 HIGH — Line 128
**Persona:** Reviewer
**Issue:** `db.Query()` result not checked for error before iterating.
**Suggestion:** `rows, err := db.Query(...); if err != nil { return err }`.
---
## Metrics
- Rounds completed: 3 (Author, Reviewer, Security)
- Files reviewed: 8
- Lines changed: 247
- Review duration: ~4m
---
*Generated by pr-reviewer plugin · Claude Code*
Salvando o Relatório como Artefato
.claudex/reviews/PR-NNN.md — histórico persistente
O relatório é gerado na fase SUMMARIZING e salvo em .claudex/reviews/PR-123-20260429.md. O timestamp no nome permite múltiplas revisões do mesmo PR ao longo do tempo.
Versionamento
Adicionar .claudex/ ao .gitignore para não versionar relatórios automaticamente. Ou incluir no git para histórico de revisões — depende da política do time.
Múltiplas Revisões
Nome com timestamp: PR-123-20260429-1432.md. O Prompt 05 adiciona `gh pr comment` que posta o relatório mais recente.
Verificação: Revisar um PR Real de Teste
Conferir as 3 personas e o relatório gerado
Use um PR de teste com bugs conhecidos intencionais — isso permite verificar se o revisor encontra o que você plantou.
Criar PR com bugs plantados
1 bug de lógica (off-by-one), 1 SQL sem parameterização, 1 inconsistência entre PR description e código. Três bugs conhecidos, um por persona.
Verificar cobertura por persona
O bug de Author deve aparecer com persona=Author. O SQL injection com persona=Security. Erros de cobertura indicam problema no system prompt da persona.
Conferir formato do relatório
Abrir .claudex/reviews/PR-NNN.md. Verificar: sumário executivo com contagem, findings agrupados por arquivo, severidades corretas, sugestões de fix.
Verificar artefato salvo
O arquivo deve existir após o ciclo completo. Se não existe, o generate-report.sh não foi chamado na fase SUMMARIZING — verificar o hook.
✅ Resumo do Módulo 4.5
Próximo Módulo:
4.6 — Prompt 05: Safety Pass e Produção — auditoria das 6 primitivas e integração GitHub