From cb33f4521a8b1d7a6334a4ce6720ddcad6cb5125 Mon Sep 17 00:00:00 2001 From: Leonardo Candiani Date: Fri, 5 Jun 2026 14:20:13 -0300 Subject: [PATCH 1/4] =?UTF-8?q?feat:=20redesign=20as=20keepwright=20?= =?UTF-8?q?=E2=80=94=20plugin=20with=20setup=20wizard,=20deterministic=20e?= =?UTF-8?q?ngine,=20and=20workflows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rebrand setup-projeto-qualidade to keepwright and restructure it from a single interpreted skill into an installable Claude Code plugin. - /keepwright:setup interactive wizard, plus /keepwright:audit and /keepwright:review - Deterministic engine (detect/apply/audit) scaffolds idempotently, anti-secret guarded - Orchestration workflows: map-brownfield, derive-patterns, verify-setup - Versioned pr-review skill + design/voice auditor agents - Auth via /install-github-app (OAuth), setup-oauth-secret.sh as fallback - AI review upgrades: /pr-review, /code-review ultra fallback, GitHub rulesets - 100% English; generated artifacts adapt to the user's configured language - Unifies the empirical-proof rule with the advisory/OAuth review architecture Autor: Leonardo Candiani --- .claude-plugin/marketplace.json | 21 + .claude-plugin/plugin.json | 18 + AUTHORS.md | 26 +- CHANGELOG.md | 216 +++++---- CONTRIBUTING.md | 154 ++++--- README.md | 120 ++--- SKILL.md | 426 ------------------ agents/design-auditor.md | 24 + agents/voice-auditor.md | 25 + commands/audit.md | 33 ++ commands/review.md | 30 ++ commands/setup.md | 78 ++++ schema/keepwright.config.schema.json | 92 ++++ scripts/apply.ts | 242 ++++++++++ scripts/audit.ts | 110 +++++ scripts/detect.ts | 206 +++++++++ scripts/lib/fsx.ts | 69 +++ scripts/lib/placeholders.ts | 88 ++++ scripts/lib/stacks.ts | 180 ++++++++ skills/keepwright/SKILL.md | 106 +++++ skills/pr-review/SKILL.md | 58 +++ templates/CLAUDE.md.template | 108 ++--- templates/PULL_REQUEST_TEMPLATE.md.template | 76 ++-- templates/REVIEW.md.template | 215 ++++++--- templates/agents/worker.md.template | 42 +- .../hooks/gen-project-structure.ts.template | 10 +- templates/hooks/gen-todos-report.ts.template | 12 +- templates/lefthook.yml.template | 46 +- ...XXX-ai-review-mention-advisory.md.template | 132 ++++++ ...L-XXX-mention-wrong-pr-context.md.template | 140 ++++++ ...auth-secret-malformed-via-pipe.md.template | 146 ++++++ .../licoes/L-XXX-short-title.md.template | 72 +++ .../licoes/L-XXX-titulo-curto.md.template | 72 --- templates/rules/01-invariantes.md.template | 36 -- templates/rules/01-invariants.md.template | 36 ++ .../rules/02-equalizacao-pipeline.md.template | 74 --- .../02-pipeline-equalization.md.template | 74 +++ .../rules/03-epistemic-hierarchy.md.template | 46 ++ .../03-hierarquia-epistemica.md.template | 46 -- templates/rules/04-pr-flow.md.template | 72 +-- .../rules/05-catalisacao-licoes.md.template | 105 ----- .../rules/05-lesson-cataloging.md.template | 105 +++++ .../rules/06-frentes-paralelas.md.template | 60 --- .../rules/06-parallel-workstreams.md.template | 60 +++ templates/rules/07-merge-seguro.md.template | 70 --- templates/rules/07-safe-merge.md.template | 70 +++ .../rules/08-empirical-proof.md.template | 79 ++++ .../08-prova-empirica-pre-merge.md.template | 77 ---- .../scripts/gh-pr-merge-safe.sh.template | 26 +- .../scripts/setup-oauth-secret.sh.template | 116 +++++ .../setup-self-hosted-runner.sh.template | 36 +- templates/settings.json.template | 8 +- .../validate-claude-md-sync.ts.template | 32 +- .../validate-empirical-proof.ts.template | 162 +++++++ .../validate-epistemic-hierarchy.ts.template | 92 ++++ ...validate-hierarquia-epistemica.ts.template | 91 ---- .../validate-no-secrets.ts.template | 16 +- .../validate-prova-empirica.ts.template | 162 ------- .../validate-webhook-active.ts.template | 42 +- templates/workflows/ci.yml.template | 10 +- .../workflows/claude-mention.yml.template | 163 ++++--- .../workflows/deploy/docker-ghcr.yml.template | 12 +- .../workflows/deploy/npm-publish.yml.template | 12 +- .../deploy/static-pages.yml.template | 8 +- .../deploy/supabase-functions.yml.template | 14 +- .../workflows/deploy/vercel.yml.template | 12 +- .../workflows/pr-auto-merge.yml.template | 20 +- .../workflows/pr-auto-review.yml.template | 308 ++++++------- workflows/derive-patterns.js | 117 +++++ workflows/map-brownfield.js | 79 ++++ workflows/verify-setup.js | 66 +++ 71 files changed, 3963 insertions(+), 2044 deletions(-) create mode 100644 .claude-plugin/marketplace.json create mode 100644 .claude-plugin/plugin.json delete mode 100644 SKILL.md create mode 100644 agents/design-auditor.md create mode 100644 agents/voice-auditor.md create mode 100644 commands/audit.md create mode 100644 commands/review.md create mode 100644 commands/setup.md create mode 100644 schema/keepwright.config.schema.json create mode 100644 scripts/apply.ts create mode 100644 scripts/audit.ts create mode 100644 scripts/detect.ts create mode 100644 scripts/lib/fsx.ts create mode 100644 scripts/lib/placeholders.ts create mode 100644 scripts/lib/stacks.ts create mode 100644 skills/keepwright/SKILL.md create mode 100644 skills/pr-review/SKILL.md create mode 100644 templates/licoes/L-XXX-ai-review-mention-advisory.md.template create mode 100644 templates/licoes/L-XXX-mention-wrong-pr-context.md.template create mode 100644 templates/licoes/L-XXX-oauth-secret-malformed-via-pipe.md.template create mode 100644 templates/licoes/L-XXX-short-title.md.template delete mode 100644 templates/licoes/L-XXX-titulo-curto.md.template delete mode 100644 templates/rules/01-invariantes.md.template create mode 100644 templates/rules/01-invariants.md.template delete mode 100644 templates/rules/02-equalizacao-pipeline.md.template create mode 100644 templates/rules/02-pipeline-equalization.md.template create mode 100644 templates/rules/03-epistemic-hierarchy.md.template delete mode 100644 templates/rules/03-hierarquia-epistemica.md.template delete mode 100644 templates/rules/05-catalisacao-licoes.md.template create mode 100644 templates/rules/05-lesson-cataloging.md.template delete mode 100644 templates/rules/06-frentes-paralelas.md.template create mode 100644 templates/rules/06-parallel-workstreams.md.template delete mode 100644 templates/rules/07-merge-seguro.md.template create mode 100644 templates/rules/07-safe-merge.md.template create mode 100644 templates/rules/08-empirical-proof.md.template delete mode 100644 templates/rules/08-prova-empirica-pre-merge.md.template create mode 100644 templates/scripts/setup-oauth-secret.sh.template create mode 100644 templates/validators/validate-empirical-proof.ts.template create mode 100644 templates/validators/validate-epistemic-hierarchy.ts.template delete mode 100644 templates/validators/validate-hierarquia-epistemica.ts.template delete mode 100644 templates/validators/validate-prova-empirica.ts.template create mode 100644 workflows/derive-patterns.js create mode 100644 workflows/map-brownfield.js create mode 100644 workflows/verify-setup.js diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..284fa90 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,21 @@ +{ + "name": "keepwright", + "owner": { + "name": "Leonardo Candiani" + }, + "metadata": { + "description": "keepwright — set up and continuously keep engineering quality and architecture true in any git repo.", + "version": "2.0.0" + }, + "plugins": [ + { + "name": "keepwright", + "description": "Interactive wizard that scaffolds a quality architecture (CLAUDE.md, rules, GitHub Actions with AI review, validators, hooks) and keeps it audited and enforced over time.", + "version": "2.0.0", + "author": { + "name": "Leonardo Candiani" + }, + "source": "." + } + ] +} diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..bc6fbd0 --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,18 @@ +{ + "name": "keepwright", + "version": "2.0.0", + "description": "Set up and continuously keep engineering quality and architecture true in any git repo. Interactive wizard, deterministic scaffolding, multi-agent audits, and AI PR review wired to OAuth.", + "author": { + "name": "Leonardo Candiani" + }, + "homepage": "https://github.com/leonardocandiani/keepwright", + "keywords": [ + "quality", + "architecture", + "scaffolding", + "code-review", + "github-actions", + "ci", + "audit" + ] +} diff --git a/AUTHORS.md b/AUTHORS.md index 7a0187f..3580416 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -1,35 +1,39 @@ -# Autores +# Authors -Esta skill é coautorada por: +keepwright is co-authored by: ## Leonardo Candiani - GitHub: [@leonardocandiani](https://github.com/leonardocandiani) - Site: [leonardocandiani.com.br](https://leonardocandiani.com.br) -- Papel: idealização, arquitetura, implementação inicial das 10 fases, rules e templates +- Role: concept, architecture, initial implementation of the phases, rules, and templates ## SixQuasar -Empresa de tecnologia. Fundada por Leonardo Candiani, Ricardo e Rodrigo. Atuação em Paraná, Rio de Janeiro e Maranhão. +A tech company. Founded by Leonardo Candiani, Ricardo, and Rodrigo. Operating in +Paraná, Rio de Janeiro, and Maranhão. - GitHub: [@sixquasar](https://github.com/sixquasar) - Site: [sixquasar.pro](https://sixquasar.pro) -- Papel: refinamento da metodologia em produção real (SixClaw, SixClaw CEO, Cote.Zap, Ofertix, Sixosteria, Vox, Lupe, EasyQuote), validação das 7 rules em projetos com cliente, contribuições contínuas +- Role: refining the methodology in real production (SixClaw, SixClaw CEO, + Cote.Zap, Ofertix, Sixosteria, Vox, Lupe, EasyQuote), validating the rules on + client projects, ongoing contributions
-## Contribuidores +## Contributors -Esta seção lista pessoas que contribuíram com PRs aceitos. Adicionada via PR após primeira contribuição. +This section lists people who contributed accepted PRs. Added via PR after a +first contribution.
-## Como entrar pra essa lista +## How to get on this list -1. Abrir PR que seja aceito (qualquer tipo: feat, fix, docs, template) -2. Mantenedor adiciona seu nome aqui no merge +1. Open a PR that gets accepted (any type: feat, fix, docs, template). +2. The maintainer adds your name here on merge. -Veja [CONTRIBUTING.md](CONTRIBUTING.md) pra orientações. +See [CONTRIBUTING.md](CONTRIBUTING.md) for guidance. diff --git a/CHANGELOG.md b/CHANGELOG.md index e0cc39d..0f22830 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,106 +1,146 @@ # Changelog -Todas as mudanças notáveis deste projeto serão documentadas aqui. - -Formato baseado em [Keep a Changelog](https://keepachangelog.com/pt-BR/1.1.0/), -versionamento segue [SemVer](https://semver.org/lang/pt-BR/). - -## [Unreleased] - -### Adicionado -- **Prova Empírica Pré-Merge (PEP)** — 3ª perna do tripé empírico (análise → - hierarquia → prova). Nova rule `08-prova-empirica-pre-merge.md` + validator - `validate-prova-empirica.ts`: mudança funcional só mergeia com evidência de que - **roda** contra ambiente real (output de comando, log, query, cenário do bug - reproduzido), colada no PR sob `## VALIDAÇÃO EMPÍRICA`. HARD no CI (com PR - body), LEMBRETE no pre-push. Isento docs/refactor/style/config/workflow. - Bypass `# prova-empirica: ignore `. Equalizado em CLAUDE.md (ponteiro + - resumo), REVIEW.md (§3.1 critério crítico + §3.5 seção canônica + §5 - validators), PULL_REQUEST_TEMPLATE (seção VALIDAÇÃO EMPÍRICA + checklist), - `pr-auto-review.yml` (gate hard) e lefthook pre-push (lembrete). Refinado em - produção no Cote.Zap. Vira 5º pilar de qualidade na SKILL.md. -- **Modelo explícito + 1M no Claude review e mention.** `pr-auto-review.yml` e - `claude-mention.yml` agora rodam com `--model {{REVIEW_MODEL}}` (default - recomendado `claude-opus-4-8[1m]`) em vez do default da conta. Placeholder - `{{REVIEW_MODEL}}` + tabela de decisão por plano (Max/Team/Enterprise → Opus - 4.8 1M; Pro → Opus 4.8; cost-sensitive → Sonnet 4.6) na SKILL.md. - -### Corrigido -- **Opus 4.8 caía em fallback silencioso.** A `claude-code-action@v1` - auto-instala uma CLI defasada (~2.1.150, anterior ao Opus 4.8); `--model - claude-opus-4-8` rodava no default da conta sem erro. Os dois workflows - ganharam um step `Instalar Claude Code` que **pina** uma versão >= 2.1.154, - **verifica** (gate fail-fast), e aponta `path_to_claude_code_executable` pra - ela (action pula a própria instalação). `rm -rf` da instalação nativa antes - do install resolve o launcher resolvendo versão antiga em runner - reusado/self-hosted; `allowed_bots: "claude"` libera menção @claude por bot. - Validado ao vivo: review e mention reportando Opus 4.8 1M sobre CLI 2.1.160. - -### Planejado -- Suporte a monorepo Turbo/Nx com camadas por workspace -- Template de deploy Cloudflare Pages/Workers -- Template de deploy Railway -- Variante Python com Ruff + Mypy + Hatch -- Variante Rust com Cargo + Clippy -- Validador específico pra UI (termos proibidos em strings user-facing) -- Wizard interativo pra customizar invariantes do `01-invariantes.md` +All notable changes to this project are documented here. + +Format based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +versioning follows [SemVer](https://semver.org/). + +## [2.0.0] — 2026-06-05 + +Rebrand to **keepwright** and full plugin redesign. The old +`setup-projeto-qualidade` skill becomes a Claude Code plugin with three layers: +an interactive wizard command, a deterministic engine, and orchestration +workflows. + +### Changed + +- **Rebrand: `setup-projeto-qualidade` → keepwright.** Install via + `/plugin marketplace add leonardocandiani/keepwright` then + `/plugin install keepwright`. +- **Single skill → plugin with three commands.** `/keepwright:setup` (the wizard, + formerly the whole skill), `/keepwright:audit` (integration coverage of an + existing repo), `/keepwright:review` (repo state vs. derived patterns). +- **Deterministic engine split out.** Validators and git hooks run identically on + every machine and in CI, with no model in the loop. + +### Added + +- **Orchestration workflows.** Multi-agent flows that audit an existing repo, + derive its design and writing-voice patterns, and write them back as rules and + validators. +- **OAuth via `/install-github-app`.** Recommended primary auth path for the AI + workflows; it wires `CLAUDE_CODE_OAUTH_TOKEN` for you. Added + `scripts/setup-oauth-secret.sh` as a deterministic fallback: reads the token + from the macOS Keychain or `CLAUDE_CODE_OAUTH_TOKEN`, validates its shape, and + sets the secret without mangling. +- **Empirical Proof Before Merge (EPP)** — 3rd leg of the empirical tripod + (analysis → hierarchy → proof). New rule `08-prova-empirica-pre-merge.md` + + validator `validate-prova-empirica.ts`: a functional change merges only with + evidence that it **runs** against a real environment (command output, log, + query, reproduced bug scenario), pasted into the PR under + `## EMPIRICAL VALIDATION`. HARD in CI (with a PR body), REMINDER on pre-push. + Exempts docs/refactor/style/config/workflow. Bypass via + `# prova-empirica: ignore `. Equalized across CLAUDE.md (pointer + + summary), REVIEW.md (§3.1 critical criterion + §3.5 canonical section + §5 + validators), PULL_REQUEST_TEMPLATE (EMPIRICAL VALIDATION section + checklist), + `pr-auto-review.yml` (hard gate), and lefthook pre-push (reminder). +- **Explicit model + 1M context in Claude review and mention.** + `pr-auto-review.yml` and `claude-mention.yml` now run with + `--model {{REVIEW_MODEL}}` (recommended default `claude-opus-4-8[1m]`) instead + of the account default. Placeholder `{{REVIEW_MODEL}}` + a per-plan decision + table (Max/Team/Enterprise → Opus 4.8 1M; Pro → Opus 4.8; cost-sensitive → + Sonnet 4.6). + +### Fixed + +- **Opus 4.8 fell back silently.** `claude-code-action@v1` auto-installs a stale + CLI (~2.1.150, pre-Opus 4.8), so `--model claude-opus-4-8` ran on the account + default without erroring. Both workflows now have an `Install Claude Code` step + that **pins** a version >= 2.1.154, **verifies** it (fail-fast gate), and points + `path_to_claude_code_executable` at it (the action skips its own install). + `rm -rf` of the native install before the install fixes the launcher resolving + an old version on a reused/self-hosted runner; `allowed_bots: "claude"` lets a + bot trigger the `@claude` mention. Validated live: review and mention reporting + Opus 4.8 1M over CLI 2.1.160. + +### Planned + +- Monorepo Turbo/Nx support with per-workspace layers +- Cloudflare Pages/Workers deploy template +- Railway deploy template +- Python variant with Ruff + Mypy + Hatch +- Rust variant with Cargo + Clippy +- UI-specific validator (forbidden terms in user-facing strings) +- Interactive wizard to customize the `01-invariantes.md` invariants ## [1.0.0] — 2026-05-15 -Primeira release pública. Skill consolidada com fluxo de 10 fases. +First public release. Skill consolidated around a 10-phase flow. -**Coautoria**: Leonardo Candiani ([@leonardocandiani](https://github.com/leonardocandiani)) e SixQuasar ([@sixquasar](https://github.com/sixquasar)) — empresa de tecnologia fundada por Leonardo Candiani, Ricardo e Rodrigo. Refinada em produção em SixClaw, Cote.Zap, Ofertix, Sixosteria, Vox e Lupe. +**Co-authorship**: Leonardo Candiani ([@leonardocandiani](https://github.com/leonardocandiani)) +and SixQuasar ([@sixquasar](https://github.com/sixquasar)) — a tech company +founded by Leonardo Candiani, Ricardo, and Rodrigo. Refined in production on +SixClaw, Cote.Zap, Ofertix, Sixosteria, Vox, and Lupe. -### Adicionado +### Added -#### Estrutura `.claude/` -- 7 rules estruturadas: invariantes, equalização de pipeline, hierarquia epistêmica P1-P5, PR flow, catalisação de lições, frentes paralelas, merge seguro -- Agent `worker.md` com `isolation: worktree` pra paralelismo isolado -- `settings.json` com `includeCoAuthoredBy: false` + attribution vazia + allowlist Bash +#### `.claude/` structure +- 7 structured rules: invariants, pipeline equalization, P1–P5 epistemic + hierarchy, PR flow, lesson catalysis, parallel work streams, safe merge +- `worker.md` agent with `isolation: worktree` for isolated parallelism +- `settings.json` with `includeCoAuthoredBy: false` + empty attribution + Bash + allowlist -#### Constituição -- `CLAUDE.md.template` como índice equalizado das rules + invariantes sempre-carregados -- `AGENTS.md` (diário vivo append-only) + `registro-construcao.md` (cronologia) -- Estrutura `docs/{casos-referencia,licoes,deploys,api,arquitetura}/` +#### Constitution +- `CLAUDE.md.template` as an equalized index of the rules + always-loaded + invariants +- `AGENTS.md` (append-only living journal) + `registro-construcao.md` (chronology) +- `docs/{casos-referencia,licoes,deploys,api,arquitetura}/` structure #### GitHub Actions -- `ci.yml` — type check, lint, validators (PR + push main) -- `pr-auto-review.yml` — 3 jobs: heurística + check-key + Claude review via OAuth -- `claude-mention.yml` — `@claude` sob demanda em PR/issue/review -- `pr-auto-merge.yml` — auto-approve+merge **só** Tier S inerte (`docs/`, `registro-construcao.md`, `.planning/frentes/`) -- Deploy adaptado à stack: 5 templates (Vercel, Supabase Functions, Docker GHCR, npm publish, Static Pages) - -#### Validators portáveis -- `validate-no-secrets.ts` — grep agressivo de secrets em arquivos staged (`pk_live_`, `sk_live_`, `sbp_`, `ghp_`, `sk-ant-`, etc) -- `validate-claude-md-sync.ts` — falha CI se rule sem ponteiro no CLAUDE.md ou ponteiro morto +- `ci.yml` — type-check, lint, validators (PR + push main) +- `pr-auto-review.yml` — 3 jobs: heuristic + check-key + Claude review over OAuth +- `claude-mention.yml` — `@claude` on demand in a PR/issue/review +- `pr-auto-merge.yml` — auto-approve+merge **only** inert changes (`docs/`, + `registro-construcao.md`, `.planning/frentes/`) +- Deploy adapted to stack: 5 templates (Vercel, Supabase Functions, Docker GHCR, + npm publish, Static Pages) + +#### Portable validators +- `validate-no-secrets.ts` — aggressive secret grep over staged files (`pk_live_`, + `sk_live_`, `sbp_`, `ghp_`, `sk-ant-`, etc.) +- `validate-claude-md-sync.ts` — fails CI if a rule has no pointer in CLAUDE.md, + or a dead pointer #### Hooks -- `lefthook.yml` — pre-commit (validators + type check), commit-msg (conventional + bloqueia menção a IA), pre-push (bloqueia force pra main) -- Geradores portáveis: `gen-project-structure.ts`, `gen-todos-report.ts` +- `lefthook.yml` — pre-commit (validators + type-check), commit-msg (conventional + + blocks AI mentions), pre-push (blocks force-push to main) +- Portable generators: `gen-project-structure.ts`, `gen-todos-report.ts` #### Scripts -- `gh-pr-merge-safe.sh` — gate `mergeStateStatus = CLEAN` antes de merge - -#### Templates auxiliares -- `PULL_REQUEST_TEMPLATE.md` com checklist equalização/smoke/catalisação - -### Princípios consolidados -- Análise antes de execução (Fase 0 nunca pulada) -- Aprovação por onda (Fase 1 destrutiva requer ok explícito) -- Validação dupla (smoke test após cada fase) -- Preserva histórico (sub-repos com `.git` próprio não absorvidos sem confirmação) -- Bloqueia secrets via grep agressivo pré-commit -- Equalização CLAUDE.md como gate duro no CI -- OAuth prioritário sobre API key pra workflows de IA - -### Stacks suportadas (Fase 0 detecta automaticamente) -- Next.js + backend serverless -- Next.js puro +- `gh-pr-merge-safe.sh` — gate `mergeStateStatus = CLEAN` before merge + +#### Helper templates +- `PULL_REQUEST_TEMPLATE.md` with an equalization/smoke/catalysis checklist + +### Consolidated principles +- Analysis before execution (Phase 0 never skipped) +- Wave-based approval (Phase 1 is destructive, needs explicit ok) +- Double validation (smoke test after each phase) +- History preserved (sub-repos with their own `.git` not absorbed without + confirmation) +- Secrets blocked via aggressive pre-commit grep +- CLAUDE.md equalization as a hard CI gate +- OAuth preferred over API key for the AI workflows + +### Supported stacks (Phase 0 detects automatically) +- Next.js + serverless backend +- Plain Next.js - Node CLI - Python FastAPI -- React SPA + API separada -- Serviço containerizado -- Monorepo (instala múltiplas variantes de deploy) +- React SPA + separate API +- Containerized service +- Monorepo (installs multiple deploy variants) -[Unreleased]: https://github.com/leonardocandiani/setup-projeto-qualidade/compare/v1.0.0...HEAD -[1.0.0]: https://github.com/leonardocandiani/setup-projeto-qualidade/releases/tag/v1.0.0 +[2.0.0]: https://github.com/leonardocandiani/keepwright/compare/v1.0.0...v2.0.0 +[1.0.0]: https://github.com/leonardocandiani/keepwright/releases/tag/v1.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9455ca8..37cce61 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,38 +1,41 @@ -# Contribuindo +# Contributing -Obrigado por considerar contribuir! Esta skill é open source (MIT) e PRs são muito bem-vindos. +Thanks for considering a contribution. keepwright is open source (MIT) and PRs +are welcome. -## Antes de abrir um PR +## Before opening a PR -1. **Confere se já existe issue ou PR** sobre o mesmo tema -2. **Abre uma issue antes de mudanças grandes** — vamos alinhar antes de você gastar tempo -3. **Lê o [SKILL.md](SKILL.md)** pra entender a filosofia e os 7 princípios não-negociáveis -4. **Lê o [CHANGELOG.md](CHANGELOG.md)** pra ver o que tá vindo +1. **Check for an existing issue or PR** on the same topic. +2. **Open an issue before large changes** — let's align before you spend time. +3. **Read [README.md](README.md)** to understand the three layers (wizard, + engine, workflows) and the commands. +4. **Read [CHANGELOG.md](CHANGELOG.md)** to see what's planned. -## Setup local +## Local setup ```bash -git clone https://github.com/leonardocandiani/setup-projeto-qualidade -cd setup-projeto-qualidade +git clone https://github.com/leonardocandiani/keepwright +cd keepwright ``` -Não tem build step — a skill é puramente markdown + templates. Edita os arquivos relevantes em `templates/` ou `SKILL.md` e testa invocando `/setup-projeto-qualidade` em um projeto-cobaia. +No build step — the plugin is markdown + templates. Edit the relevant files +under `templates/`, then test by installing the plugin and running +`/keepwright:setup` in a throwaway project. -## Estrutura do repo +## Repo structure ``` . -├── README.md # documentação pública -├── SKILL.md # contrato da skill com o Claude Code -├── CHANGELOG.md # histórico versionado -├── CONTRIBUTING.md # este arquivo +├── README.md # public docs +├── CHANGELOG.md # versioned history +├── CONTRIBUTING.md # this file ├── LICENSE # MIT -└── templates/ # tudo que a skill instala +└── templates/ # everything the plugin installs ├── CLAUDE.md.template ├── settings.json.template ├── lefthook.yml.template ├── PULL_REQUEST_TEMPLATE.md.template - ├── rules/ # 7 rules estruturadas + ├── rules/ # structured rules ├── agents/ ├── workflows/ # CI + auto-review + auto-merge + deploys ├── validators/ @@ -40,89 +43,92 @@ Não tem build step — a skill é puramente markdown + templates. Edita os arqu └── scripts/ ``` -## Conventional Commits (obrigatório) +## Conventional Commits (required) ``` -feat(rules): adicionar rule 08-rollback-protocol -fix(validators): corrigir regex de detecção de OAuth token -docs: melhorar seção de matriz de deploy no README +feat(rules): add rule 09-rollback-protocol +fix(validators): fix OAuth token detection regex +docs: improve deploy matrix section in the README chore(deps): bump lefthook 1.7.x -refactor(skill): consolidar Fase 4 e Fase 5 em uma fase de "automação" +refactor(engine): merge validator setup into one step ``` -Tipos aceitos: `feat`, `fix`, `refactor`, `docs`, `style`, `test`, `chore`, `perf`, `template`. +Accepted types: `feat`, `fix`, `refactor`, `docs`, `style`, `test`, `chore`, +`perf`, `template`. -**Nunca menciona IA/Claude em commits**. O autor é sempre o mantenedor humano. +**Never mention AI/Claude in commits.** The author is always the human maintainer. -## Padrões pra mudanças +## Change patterns -### Mudando uma rule +### Changing a rule -- Atualiza o arquivo em `templates/rules/XX-nome.md.template` -- **Confere se o ponteiro existe no `templates/CLAUDE.md.template`** -- Se for rule nova, adiciona o ponteiro -- Atualiza CHANGELOG em `[Unreleased]` +- Edit the file in `templates/rules/XX-name.md.template`. +- **Check that the pointer exists in `templates/CLAUDE.md.template`.** +- If it's a new rule, add the pointer. +- Update CHANGELOG under the current release. -### Mudando um template de workflow +### Changing a workflow template -- Edita `templates/workflows/.yml.template` -- Valida o YAML mentalmente com placeholders preenchidos -- Recomendado: rodar `actionlint` localmente no YAML renderizado -- Atualiza CHANGELOG +- Edit `templates/workflows/.yml.template`. +- Sanity-check the YAML with placeholders filled in. +- Recommended: run `actionlint` on the rendered YAML locally. +- Update CHANGELOG. -### Adicionando nova variante de deploy +### Adding a deploy variant -- Cria `templates/workflows/deploy/.yml.template` -- Atualiza a matriz no `SKILL.md` (seção "Matriz de deploy") -- Atualiza a matriz no `README.md` -- Atualiza CHANGELOG +- Create `templates/workflows/deploy/.yml.template`. +- Update the deploy matrix in `README.md`. +- Update CHANGELOG. -### Adicionando novo validator +### Adding a validator -- Cria `templates/validators/.ts.template` -- Documenta no `SKILL.md` o que ele valida -- Atualiza CHANGELOG +- Create `templates/validators/.ts.template`. +- Document what it checks in the README. +- Update CHANGELOG. -## Princípios para PRs +## PR principles -1. **Equalização**: rule nova ou template movido = atualização no `CLAUDE.md.template` no mesmo PR -2. **Catalisação**: mudança não-trivial precisa de seção em `[Unreleased]` no CHANGELOG -3. **Sem AI mentions** em commits, código ou docs -4. **Sem secrets** — o CI tem grep agressivo, mas confere antes de pushar +1. **Equalization**: a new rule or a moved template means an update to + `CLAUDE.md.template` in the same PR. +2. **Catalysis**: a non-trivial change needs a CHANGELOG entry. +3. **No AI mentions** in commits, code, or docs. +4. **No secrets** — CI greps aggressively, but check before you push. -## Smoke test antes de pedir review +## Smoke test before requesting review -Antes de marcar o PR como "ready for review": +Before marking a PR ready for review: -1. Clone a versão do PR em um projeto-cobaia -2. Roda `/setup-projeto-qualidade` -3. Confirma que a Fase 0 detecta corretamente -4. Se mexeu em alguma fase específica, valida só essa -5. Cola o resultado no campo "Smoke test" do PR template +1. Install the PR version of the plugin in a throwaway project. +2. Run `/keepwright:setup`. +3. Confirm stack detection is correct. +4. If you touched a specific phase, validate just that one. +5. Paste the result into the "Smoke test" field of the PR template. -## Comunicação +## Communication -- **Português** ou **inglês**, ambos funcionam -- Comentários em PRs/issues: direto, sem rodeios -- Se travar em algo, abre uma issue de discussão antes de gastar tempo +- **English** preferred. Direct, no fluff. +- If you get stuck, open a discussion issue before spending time. -## Reportando bugs +## Reporting bugs -Abre uma [issue](https://github.com/leonardocandiani/setup-projeto-qualidade/issues/new?template=bug_report.md) com: +Open an [issue](https://github.com/leonardocandiani/keepwright/issues/new?template=bug_report.md) +with: -- Stack do projeto-alvo (Node? Python? Monorepo?) -- Output completo do erro -- Comando exato que disparou -- O que esperava que acontecesse +- Target project stack (Node? Python? Monorepo?) +- Full error output +- The exact command that triggered it +- What you expected to happen -## Sugerindo features +## Suggesting features -Abre uma [issue](https://github.com/leonardocandiani/setup-projeto-qualidade/issues/new?template=feature_request.md) descrevendo: +Open an [issue](https://github.com/leonardocandiani/keepwright/issues/new?template=feature_request.md) +describing: -- Problema que resolve -- Como você imagina a solução -- Alternativas que considerou +- The problem it solves +- How you imagine the solution +- Alternatives you considered -## Código de Conduta +## Code of Conduct -Esse projeto adere ao [Code of Conduct](CODE_OF_CONDUCT.md). Ao participar, você se compromete a seguir esses termos. +This project follows the [Code of Conduct](CODE_OF_CONDUCT.md). By participating, +you agree to its terms. diff --git a/README.md b/README.md index 3c82133..51bebd0 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,74 @@ -# Skill: setup-projeto-qualidade +# keepwright -Organizadora e criadora de projetos. Aplica uma arquitetura de qualidade alta em qualquer projeto git, novo ou existente. +A Claude Code plugin that sets up and keeps a high-quality engineering +architecture in any git repo. It implants a constitution, structured rules, +GitHub Actions (CI, AI PR review, `@claude` mention, safe auto-merge), portable +validators, and git hooks — detecting your stack and adapting. After setup it +keeps maintaining: it audits the repo and uses multi-agent workflows to derive +your design and writing-voice patterns, then turns them into rules and validators. -## Como invocar - -No projeto-alvo: +## Install ``` -/setup-projeto-qualidade +/plugin marketplace add leonardocandiani/keepwright +/plugin install keepwright ``` -Ou descrever o que quer ("quero arquitetura sólida com PR auto-review e rules vivas"). - -## O que faz - -1. **Fase 0:** detecta stack (Node/Deno/Python/etc), git, Claude config, CI/CD existente -2. **Fase 1:** init git + repo GitHub + .gitignore -3. **Fase 2:** estrutura `.claude/` (7 rules + settings co-author off + agents worktree) -4. **Fase 3:** constituição CLAUDE.md equalizada + docs + AGENTS.md + registro-construcao.md -5. **Fase 4:** GitHub Actions (CI, PR auto-review OAuth, claude-mention, pr-auto-merge, deploy adaptado à stack) -6. **Fase 5:** validators portáveis (anti-secrets + sincronia CLAUDE.md + slots custom) -7. **Fase 6:** hooks (lefthook + geradores auto) -8. **Fase 7:** branch protection + CODEOWNERS -9. **Fase 8:** smoke test do setup (cria PR de teste) -10. **Fase 9:** cataloga em `docs/licoes/L-000-setup-inicial.md` - -## Princípios - -- Análise antes de execução (Fase 0 nunca pulada) -- Aprovação por onda (Fase 1 é destrutiva, requer ok explícito) -- Validação dupla (smoke test após cada onda) -- Preserva histórico (sub-repos com .git próprio não absorvidos sem confirmação) -- Bloqueia secrets (grep agressivo antes de commit) - -## Templates fornecidos - -- `templates/CLAUDE.md.template` — constituição equalizada (índice das rules + invariantes sempre-carregados) -- `templates/settings.json.template` — `includeCoAuthoredBy:false` + attribution vazia + allowlist -- `templates/rules/` — 8 rules base (invariantes, equalização, hierarquia P1-P5, PR flow, catalisação, frentes, merge seguro, prova empírica pré-merge) -- `templates/agents/` — worker.md (`isolation: worktree`, paralelismo isolado, git garantido) -- `templates/workflows/` — ci.yml, pr-auto-review.yml (heurística + Claude review OAuth), claude-mention.yml (@claude OAuth), pr-auto-merge.yml (Tier S, fail-safe) -- `templates/workflows/deploy/` — vercel, supabase-functions, docker-ghcr, npm-publish, static-pages (skill escolhe pela stack) -- `templates/validators/` — validate-no-secrets.ts + validate-claude-md-sync.ts (gate de equalização) + validate-hierarquia-epistemica.ts (P1-P5) + validate-prova-empirica.ts (prova de funcionamento no PR) + validate-webhook-active.ts -- `templates/scripts/` — gh-pr-merge-safe.sh (gate mergeStateStatus CLEAN) + setup-self-hosted-runner.sh (runner próprio, zera minutos GitHub) -- `templates/hooks/` — gen-project-structure.ts, gen-todos-report.ts - -Placeholders: `{{PROJETO}}`, `{{PROJETO_UPPER}}`, `{{REPO}}`, `{{REPO_OWNER}}`, `{{MANTENEDOR}}`, `{{STACK}}`, `{{DATA_ATUAL}}`, etc. Skill substitui durante setup. - -## Autenticação OAuth (prioritário) - -Workflows de IA usam `CLAUDE_CODE_OAUTH_TOKEN`. Obter: `claude setup-token` no terminal. Setar: `gh secret set CLAUDE_CODE_OAUTH_TOKEN -R /`. Sem o secret, jobs de IA skipam graceful. API key é fallback documentado, não recomendado. - -## Duplo gate de merge - -Auto-merge real só pra Tier S inerte (docs, cronologia, frentes). Tudo que toca código, CI, rules, deploy ou config é Tier H: IA prepara, humano dá go de uma linha. Detalhe em `templates/rules/07-merge-seguro.md.template`. - -Ver SKILL.md pro detalhe completo do fluxo. +## Commands + +| Command | What it does | +|---------|--------------| +| `/keepwright:setup` | Interactive wizard. Detects the stack and installs the full architecture. | +| `/keepwright:audit` | Checks integration coverage of an existing repo against the architecture. | +| `/keepwright:review` | Compares repo state against the patterns derived from your code and docs. | + +## Three layers + +- **Wizard** (`/keepwright:setup`) — an interactive command that detects git, + stack (Node/Deno/Python/etc), Claude config, and existing CI, then installs + the constitution, rules, workflows, validators, and hooks. Destructive steps + ask for explicit approval. +- **Engine** — the deterministic part: portable validators and git hooks that + run the same way on every machine and in CI. No model in the loop, no flaky + output. +- **Workflows** — multi-agent orchestration that audits an existing repo, derives + its design and writing-voice patterns, and writes them back as rules and + validators. + +## What it installs + +- **Constitution** — `CLAUDE.md` as an equalized index of the rules, with the + always-loaded invariants inline. +- **Rules** — `.claude/rules/`: invariants, pipeline equalization, the P1–P5 + epistemic hierarchy, PR flow, lesson catalysis, parallel work streams, safe + merge, and empirical proof before merge. +- **GitHub Actions** — `ci.yml` (type-check, lint, validators), `pr-auto-review.yml` + (heuristic + Claude review over OAuth), `claude-mention.yml` (`@claude` on + demand), `pr-auto-merge.yml` (auto-merge only for inert changes), and a deploy + template picked by stack. +- **Validators** — portable TypeScript checks: secret scanning, CLAUDE.md sync, + epistemic-hierarchy gate, empirical-proof gate, webhook-active check. +- **Hooks** — lefthook (pre-commit validators + type-check, conventional + commit-msg, force-push guard on main) plus structure and TODO generators. + +## Auth + +The AI workflows use `CLAUDE_CODE_OAUTH_TOKEN`. Run `/install-github-app` and +pick the subscription/OAuth option — it wires the token for you. Without the +secret, the AI jobs skip gracefully. An API key is a documented fallback, not +recommended. + +If you need to set the secret by hand, `scripts/setup-oauth-secret.sh +/` reads the token from the macOS Keychain or +`CLAUDE_CODE_OAUTH_TOKEN`, validates its shape, and sets it without mangling. + +## Double merge gate + +Real auto-merge runs only for inert changes (docs, chronology, work-stream +notes). Anything touching code, CI, rules, deploy, or config is human-gated: the +AI prepares the PR, a human gives a one-line go. Detail in +`templates/rules/07-merge-seguro.md.template`. + +## License + +MIT. See [LICENSE](LICENSE) and [AUTHORS.md](AUTHORS.md). diff --git a/SKILL.md b/SKILL.md deleted file mode 100644 index 04a8d7e..0000000 --- a/SKILL.md +++ /dev/null @@ -1,426 +0,0 @@ ---- -name: setup-projeto-qualidade -description: Organizadora e criadora de projetos. Aplica uma arquitetura de qualidade alta em qualquer projeto git, novo ou existente — CLAUDE.md como constituição equalizada, rules estruturadas (invariantes, equalização de pipeline, hierarquia epistêmica P1-P5, PR flow, catalisação de lições, frentes paralelas, merge seguro, prova empírica pré-merge), CI/CD com auto-review OAuth, deploy automático adaptado à stack, agentes worktree-isolados, validators portáveis, hooks. Adapta tudo à stack detectada. ---- - -# Skill: Setup Projeto Qualidade - -Organizadora e criadora de projetos. Pega um repositório (novo ou já em -andamento, qualquer stack) e implanta uma arquitetura de engenharia robusta: -constituição (`CLAUDE.md`) equalizada com as rules, fluxo de PR com review -automático, merge seguro com duplo gate, deploy sincronizado com o GitHub, -agentes worktree-isolados pra paralelismo, catalisação obrigatória de lições. -Tudo genérico e adaptável, sem amarração a nenhum projeto ou pessoa. - -## Quando o usuário invoca - -Trigger: `/setup-projeto-qualidade` no projeto-alvo, ou ele descreve querer -"arquitetura sólida", "PR flow", "GitHub Actions com auto-review", "rules -vivas", "deploy automático", "catalisação de lições". - -## Princípios não-negociáveis - -1. **Análise antes de execução.** Nunca toca em nada sem antes detectar - stack, ler o que existe, mapear. Fase 0 jamais é pulada. -2. **Aprovação por onda.** Cada fase precisa ok explícito. Fase 1 (git/repo) - é destrutiva, cuidado extra. -3. **Validação dupla.** Após cada fase, smoke test confirma que nada quebrou. -4. **Preserva histórico.** Sub-repos com `.git` próprio nunca são absorvidos - sem confirmação dupla. -5. **Sem secrets commitados.** Antes de cada commit, grep agressivo: - `pk_live_`, `sk_live_`, `sbp_`, `EAA…{60+}`, `ghp_`, `sk-ant-`, - `sk-ant-oat01-`. -6. **Equalização do CLAUDE.md.** Toda rule criada ganha ponteiro no - `CLAUDE.md` no mesmo passo. Um validador quebra o CI se dessincronizar. -7. **Commits nunca atribuem a IA.** `includeCoAuthoredBy: false` + - `attribution` vazia no `settings.json` do projeto. Autor é sempre o - mantenedor humano. - -## Equalização do CLAUDE.md (peça central) - -O `CLAUDE.md` é sempre carregado pela IA; as rules em `.claude/rules/` não. -Por isso o `CLAUDE.md` é a **constituição**: índice que aponta pra todas as -rules + os invariantes mais críticos escritos no corpo (merge seguro, -hierarquia epistêmica, princípio de catalisação) pra serem impossíveis de -ignorar. Camada de segurança em profundidade: o invariante vive no -`CLAUDE.md` (sempre lido) E na rule (detalhe) E no validador (gate duro). - -Regra dura: rule nova sem ponteiro no `CLAUDE.md` = rule invisível. O -`validate-claude-md-sync` falha o CI nesse caso, e também em ponteiro morto. - -## Autenticação Claude (OAuth prioritário) - -Os workflows de IA (`pr-auto-review` job Claude, `claude-mention`) autenticam -por **OAuth token**, prioridade sobre API key: - -``` -# 1. gerar o token (no terminal, uma vez) -claude setup-token # gera sk-ant-oat01-... - -# 2. setar como secret do repo -gh secret set CLAUDE_CODE_OAUTH_TOKEN -R / -``` - -Sem o secret, os jobs de IA skipam sem quebrar o PR (graceful degradation). -A skill instrui isso no fim do setup. API key (`ANTHROPIC_API_KEY`) é -fallback documentado, não o caminho recomendado. - -## Modelo do review + versão da CLI (Opus 4.8 / 1M) - -Os workflows de IA (`pr-auto-review` job Claude, `claude-mention`) rodam num -**modelo explícito** via `--model {{REVIEW_MODEL}}`. Sem `--model`, o review -roda no default da conta — sem garantia de qual modelo nem de 1M de contexto. - -**Escolha do modelo (a skill preenche `{{REVIEW_MODEL}}` pelo plano do -mantenedor, detectado/perguntado na Fase 0):** - -| Plano | `{{REVIEW_MODEL}}` | Notas | -|---|---|---| -| Max / Team / Enterprise | `claude-opus-4-8[1m]` | **default recomendado** — Opus 1M incluído no plano via OAuth; o `[1m]` ativa 1M de contexto | -| Pro | `claude-opus-4-8` | Opus sem 1M (o `[1m]` exige Max/Team/Enterprise) | -| Cost-sensitive | `claude-sonnet-4-6` | mais barato, menos profundo | - -**Gotcha crítico (a razão do step "Instalar Claude Code"):** a -`anthropics/claude-code-action@v1` auto-instala uma versão **defasada** da CLI -(~2.1.150, anterior ao Opus 4.8). Passar `--model claude-opus-4-8` numa CLI que -não conhece o modelo cai em **fallback silencioso** pro default da conta — sem -erro, sem aviso. **Opus 4.8 exige Claude Code CLI >= 2.1.154.** - -Por isso os dois workflows têm um step `Instalar Claude Code` ANTES da action: - -```yaml -- name: Instalar Claude Code (Opus 4.8 exige >= 2.1.154) - env: - CLAUDE_CODE_VERSION: "2.1.160" # bump conforme releases; >= 2.1.154 - run: | - rm -rf "$HOME/.local/bin/claude" "$HOME/.local/share/claude" - curl -fsSL https://claude.ai/install.sh | bash -s "$CLAUDE_CODE_VERSION" - CLAUDE_BIN="$HOME/.local/bin/claude" - INSTALLED="$("$CLAUDE_BIN" --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+' | head -1)" - [ "$INSTALLED" = "$CLAUDE_CODE_VERSION" ] || { echo "::error::versao errada"; exit 1; } - echo "CLAUDE_BIN=$CLAUDE_BIN" >> "$GITHUB_ENV" -``` - -depois `path_to_claude_code_executable: ${{ env.CLAUDE_BIN }}` na action (faz a -action **pular** a própria instalação defasada e usar a versão pinada). - -3 detalhes que custam horas se ignorados: -- **Pin + verify, não `latest`.** Versão exata é determinística; o gate - `[ INSTALLED = VERSION ]` aborta se divergir em vez de rodar no modelo errado. - Pinar também responde ao aviso de supply-chain (`curl|bash` não-pinado). -- **`rm -rf` antes do install.** Em runner **reusado ou self-hosted**, o - launcher `~/.local/bin/claude` resolve a versão antiga já "ativa" no store — - `install.sh | bash -s ` adiciona a versão mas **não troca o ponteiro - ativo**. Limpar a instalação nativa garante que só a versão pinada fique no - store. Em runner limpo (`ubuntu-latest`) o `rm -rf` é no-op. -- **`allowed_bots: "claude"`** no `claude-mention` permite menção @claude - postada por bot/automação (sem ele: erro "non-human actor"). Escopado ao bot - "claude", nunca `"*"`. - -**Não cite strings de versão no corpo do PR** (ex: "2.1.150") — a action lê o -PR body como contexto e um `##[error]` literal vira annotation falsa no log -(red herring que confunde o debug). - -## Fluxo da skill - -### Fase 0 — Mapeamento do projeto-alvo - -``` -1. Stack: package.json → Node/TS/Next | pyproject/requirements → Python | - deno.json → Deno | go.mod → Go | Cargo.toml → Rust | múltiplos → monorepo -2. Git: .git na raiz? sub-repos? remote? GitHub/GitLab? -3. Claude: CLAUDE.md / AGENTS.md / .claude/ já existem? rules/settings? -4. CI/CD: .github/workflows/? lefthook/.husky/pre-commit? -5. Deploy: Vercel? Supabase? Docker? npm pkg? site estático? (define o - template de deploy a usar na Fase 4) -6. Tooling: bun/deno/npm? linter? typecheck? -``` - -Reportar em tabela compacta. Pedir confirmação do que pode mexer. - -### Fase 1 — Setup base do repositório git (destrutivo, ok explícito) - -- Sem `.git` na raiz: `git init` + `git config init.defaultBranch main` -- Sub-repos com `.git` próprio: escolher A) `git subtree` preservando - histórico, B) submodules, C) `.gitignore` (seguem independentes) -- `.gitignore` cobrindo deps, builds, caches, **secrets**, editor, OS -- `gh repo create / --private` + `git remote add origin` + push - -### Fase 2 — Estrutura `.claude/` + constituição - -``` -.claude/ -├── rules/ -│ ├── 01-invariantes.md (regras invioláveis, placeholders) -│ ├── 02-equalizacao-pipeline.md (camadas adaptadas à estrutura real) -│ ├── 03-hierarquia-epistemica.md (P1-P5) -│ ├── 04-pr-flow.md (PR, review, merge) -│ ├── 05-catalisacao-licoes.md (como/onde catalogar) -│ ├── 06-frentes-paralelas.md (planos paralelos) -│ ├── 07-merge-seguro.md (duplo gate + mergeStateStatus CLEAN) -│ └── 08-prova-empirica-pre-merge.md (mudança funcional prova que roda no PR) -├── agents/ -│ └── worker.md (isolation: worktree — paraleliza sem -│ sujar o working tree; git garantido) -└── settings.json (includeCoAuthoredBy:false + - attribution vazia + allowlist Bash) -``` - -Templates pré-preenchidos em `templates/`. A skill personaliza: nome do -projeto no título, stack nas rules, camadas geradas da estrutura real -(`src/`, `api/`, `lib/` viram camadas), invariantes ficam como placeholder -pro mantenedor preencher. Placeholders: `{{PROJETO}}`, `{{PROJETO_UPPER}}`, -`{{REPO}}`, `{{REPO_OWNER}}`, `{{MANTENEDOR}}`, `{{STACK}}`, `{{REVIEW_MODEL}}` -(modelo do Claude review — ver "Modelo do review + versão da CLI"), etc. - -### Fase 3 — Constituição + documentação - -- `CLAUDE.md` a partir de `templates/CLAUDE.md.template`: índice com ponteiro - pras 7 rules + invariantes sempre-carregados (merge seguro, hierarquia, - catalisação) no corpo. **Equalizado**: toda rule tem linha no índice. -- **`REVIEW.md` raiz** a partir de `templates/REVIEW.md.template`: single - source of truth consumido pelo Claude AI review do `pr-auto-review.yml`. - Contém 9 seções: sumário projeto (§1) + princípios canônicos catalisados - (§2.X = lições L-XXX) + critérios merge (§3 críticos/ressalvas/aprovação - + hierarquia epistêmica P1-P5) + frentes entregues (§4) + validators - ativos (§5) + vocabulário canônico (§6) + endpoints+integrações (§7) + - output format obrigatório do review (§8) + fallback canônico Code Review - Diretor (§9). Começa com placeholders; mantenedor preenche §2.X conforme - catalisa lições e §3-§9 conforme projeto amadurece. Workflow YAML - referencia APENAS `REVIEW.md` + `CLAUDE.md` no prompt (reduz turns, - evita AJV crash). -- `AGENTS.md` (diário vivo append-only) + `registro-construcao.md` (cronologia) -- `docs/{casos-referencia,licoes,deploys,api,arquitetura}/` - -### Fase 4 — GitHub Actions - -- **`ci.yml`** — type check, lint, validators (PR + push main) -- **`pr-auto-review.yml`** — 3 jobs: heurística (sempre, sem custo) + - `check-key` (graceful se `CLAUDE_CODE_OAUTH_TOKEN` ausente) + - `claude-review` (Claude AI via OAuth, lê **`REVIEW.md` raiz** como single - source of truth + rules, comenta). Roda em modelo explícito - `--model {{REVIEW_MODEL}}` sobre Claude Code pinado >= 2.1.154 (step - `Instalar Claude Code` + `path_to_claude_code_executable` — ver "Modelo do - review + versão da CLI"). Estrutura resiliente: **retry duplo** - (tentativa 1 + sleep 30s + tentativa 2, ambos `continue-on-error: true`) - + **fallback canônico** se 2 tentativas falharem → posta comment - sinalizando Code Review Diretor manual (4 sub-agents READ-ONLY paralelos - via Task tool: architect / reviewer / quality-engineer / - deep-research-agent). Mitiga bugs upstream conhecidos - (`claude-code-action`: AJV crash, fd 4 mismatch, error_max_turns, App - token 401) -- **`claude-mention.yml`** — `@claude` sob demanda em PR/issue/review. - Autentica via `CLAUDE_CODE_OAUTH_TOKEN`. Mesmo modelo/versão pinados do - review (`--model {{REVIEW_MODEL}}` + Claude Code >= 2.1.154 + - `allowed_bots: "claude"`). Sem o secret, skipa silencioso -- **`pr-auto-merge.yml`** — auto-approve+merge SÓ Tier S inerte (`docs/`, - `registro-construcao.md`, `.planning/frentes/`), fail-safe por exclusão, - dispara via `workflow_run` pós-CI verde. Tier H = humano (07-merge-seguro) -- **`deploy/.yml`** — deploy automático sincronizado com o GitHub, - escolhido pela stack detectada na Fase 0 (matriz abaixo) - -Ao final, instruir o setup do OAuth token (seção "Autenticação Claude"). - -### Fase 4.5 — Rodar as GitHub Actions localmente (self-hosted, zera minutos) - -GitHub Free dá 2000 min/mês de runner hospedado em repo privado. Acabou a -cota, o CI para. **Runner self-hosted não conta nesse limite** (ilimitado, -qualquer visibilidade de repo). A ideia: o GitHub continua orquestrando -(triggers, secrets, UI, branch protection), mas a **execução roda numa -máquina sua**. - -**Onde rodar.** Qualquer coisa com Docker e saída pra internet: -- um VPS/servidor Linux, -- um box ocioso na sua infra, -- ou a sua própria máquina local (o runner faz só conexão de saída pro - GitHub, não precisa de IP público nem porta aberta). - -O runner não precisa de VPN/malha pra funcionar, ele só fala HTTPS de saída -com o GitHub. A malha (Tailscale/WG) só importa se você for administrar o -host remoto por SSH. - -**Como.** `templates/scripts/setup-self-hosted-runner.sh -