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/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 7505e04..43e1e33 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -1,45 +1,45 @@ --- name: Bug report -about: Reportar um comportamento incorreto da skill +about: Report incorrect behavior in keepwright title: "[bug] " labels: bug assignees: leonardocandiani --- -## Descrição +## Description - + -## Como reproduzir +## How to reproduce -1. Stack do projeto-alvo (Node/Python/etc): -2. Estado inicial (git, CLAUDE.md, .claude/ existiam?): -3. Comando exato disparado: +1. Target project stack (Node/Python/etc): +2. Initial state (did git, CLAUDE.md, .claude/ already exist?): +3. Exact command run: ``` - /setup-projeto-qualidade + /keepwright:setup ``` -4. Fase em que falhou: -5. Output do erro: +4. Step where it failed: +5. Error output: ``` - + ``` -## Comportamento esperado +## Expected behavior - + -## Comportamento observado +## Observed behavior - + -## Ambiente +## Environment -- Versão da skill: +- keepwright version: - Claude Code: - OS: - Shell: - gh CLI: -## Contexto adicional +## Additional context - + diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 7febb60..7469073 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,8 +1,8 @@ blank_issues_enabled: false contact_links: - - name: Discussão geral - url: https://github.com/leonardocandiani/setup-projeto-qualidade/discussions - about: Para dúvidas, ideias ou conversa aberta sobre a skill - - name: Site do autor + - name: General discussion + url: https://github.com/leonardocandiani/keepwright/discussions + about: For questions, ideas, or open conversation about keepwright + - name: Author's site url: https://leonardocandiani.com.br - about: Contato direto e outros projetos + about: Direct contact and other projects diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 3038086..64abe17 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -1,40 +1,40 @@ --- name: Feature request -about: Sugerir uma nova capacidade ou melhoria +about: Suggest a new capability or improvement title: "[feat] " labels: enhancement assignees: leonardocandiani --- -## Problema que resolve +## Problem it solves - + -## Solução proposta +## Proposed solution - + -## Alternativas consideradas +## Alternatives considered - + -## Categoria +## Category -- [ ] Nova rule em `templates/rules/` -- [ ] Nova variante de deploy em `templates/workflows/deploy/` -- [ ] Novo validator em `templates/validators/` -- [ ] Novo workflow em `templates/workflows/` -- [ ] Mudança no fluxo das fases (SKILL.md) -- [ ] Suporte a nova stack/runtime -- [ ] Documentação -- [ ] Outro: +- [ ] New rule in `templates/rules/` +- [ ] New deploy variant in `templates/workflows/deploy/` +- [ ] New validator in `templates/validators/` +- [ ] New workflow in `templates/workflows/` +- [ ] Change to the setup wizard flow (`commands/`) +- [ ] Support for a new stack/runtime +- [ ] Documentation +- [ ] Other: -## Stack/contexto relacionado +## Related stack/context - + -## Disposição pra contribuir +## Willingness to contribute -- [ ] Posso abrir o PR -- [ ] Posso ajudar a testar -- [ ] Só sugerindo, sem disponibilidade pra implementar +- [ ] I can open the PR +- [ ] I can help test +- [ ] Just suggesting, no availability to implement diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e12432e..d1376b9 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,44 +1,44 @@ -## O que muda +## What changes - + - - -## Por que +## Why - + -## Tipo +## Type -- [ ] feat — nova funcionalidade -- [ ] fix — correção de bug -- [ ] refactor — refatoração sem mudança de comportamento -- [ ] docs — apenas documentação -- [ ] chore — manutenção, configs, deps -- [ ] template — mudança em algum `templates/*` +- [ ] feat — new capability +- [ ] fix — bug fix +- [ ] refactor — behavior-preserving change +- [ ] docs — documentation only +- [ ] chore — maintenance, config, deps +- [ ] template — change under `templates/*` ## Checklist -- [ ] Mudança em rule? Atualizei o ponteiro no CLAUDE.md.template -- [ ] Mudança em template? Renderei mentalmente com placeholders preenchidos e confere -- [ ] Mudança em workflow? Testei o YAML com `actionlint` (ou `gh workflow view`) -- [ ] Sem secrets no diff -- [ ] CHANGELOG.md atualizado em `[Unreleased]` -- [ ] Commit segue conventional commits e não menciona IA +- [ ] Changed a rule? Updated its pointer in `templates/CLAUDE.md.template` +- [ ] Changed a template? Rendered it mentally with placeholders filled and it holds +- [ ] Changed a workflow? Checked the YAML with `actionlint` (or `gh workflow view`) +- [ ] No secrets in the diff +- [ ] CHANGELOG.md updated under `[Unreleased]` +- [ ] Commit follows Conventional Commits and does not mention AI ## Smoke test - + ```bash -# exemplo: -cd projeto-teste/ +# example: +cd test-project/ claude -> /setup-projeto-qualidade -# esperar: ... +> /keepwright:setup +# expect: ... ``` -## Observações +## Notes - + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd716f7..5528ceb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -12,17 +12,36 @@ permissions: jobs: validate: - name: Validate skill structure + name: Validate plugin structure runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - name: Check SKILL.md exists with frontmatter + - name: Check plugin manifest run: | - test -f SKILL.md || { echo "SKILL.md missing"; exit 1; } - head -1 SKILL.md | grep -q "^---$" || { echo "SKILL.md missing frontmatter"; exit 1; } - grep -q "^name: setup-projeto-qualidade$" SKILL.md || { echo "SKILL.md frontmatter name missing"; exit 1; } - grep -q "^description:" SKILL.md || { echo "SKILL.md frontmatter description missing"; exit 1; } + test -f .claude-plugin/plugin.json || { echo ".claude-plugin/plugin.json missing"; exit 1; } + test -f .claude-plugin/marketplace.json || { echo ".claude-plugin/marketplace.json missing"; exit 1; } + node -e "const p=JSON.parse(require('fs').readFileSync('.claude-plugin/plugin.json','utf8')); if(p.name!=='keepwright'){console.error('plugin.json name is not keepwright');process.exit(1)}" + node -e "JSON.parse(require('fs').readFileSync('.claude-plugin/marketplace.json','utf8'))" || { echo "marketplace.json is not valid JSON"; exit 1; } + + - name: Check commands exist + run: | + for c in setup audit review; do + test -f "commands/$c.md" || { echo "commands/$c.md missing"; exit 1; } + done + + - name: Check skill exists with frontmatter + run: | + test -f skills/keepwright/SKILL.md || { echo "skills/keepwright/SKILL.md missing"; exit 1; } + head -1 skills/keepwright/SKILL.md | grep -q "^---$" || { echo "SKILL.md missing frontmatter"; exit 1; } + grep -q "^name: keepwright$" skills/keepwright/SKILL.md || { echo "SKILL.md frontmatter name missing"; exit 1; } + grep -q "^description:" skills/keepwright/SKILL.md || { echo "SKILL.md frontmatter description missing"; exit 1; } + + - name: Check orchestration workflows exist + run: | + for w in map-brownfield derive-patterns verify-setup; do + test -f "workflows/$w.js" || { echo "workflows/$w.js missing"; exit 1; } + done - name: Check README.md exists run: test -f README.md @@ -40,14 +59,15 @@ jobs: "templates/settings.json.template" "templates/lefthook.yml.template" "templates/PULL_REQUEST_TEMPLATE.md.template" - "templates/rules/01-invariantes.md.template" - "templates/rules/02-equalizacao-pipeline.md.template" - "templates/rules/03-hierarquia-epistemica.md.template" + "templates/REVIEW.md.template" + "templates/rules/01-invariants.md.template" + "templates/rules/02-pipeline-equalization.md.template" + "templates/rules/03-epistemic-hierarchy.md.template" "templates/rules/04-pr-flow.md.template" - "templates/rules/05-catalisacao-licoes.md.template" - "templates/rules/06-frentes-paralelas.md.template" - "templates/rules/07-merge-seguro.md.template" - "templates/rules/08-prova-empirica-pre-merge.md.template" + "templates/rules/05-lesson-cataloging.md.template" + "templates/rules/06-parallel-workstreams.md.template" + "templates/rules/07-safe-merge.md.template" + "templates/rules/08-empirical-proof.md.template" "templates/agents/worker.md.template" "templates/workflows/ci.yml.template" "templates/workflows/pr-auto-review.yml.template" @@ -60,9 +80,14 @@ jobs: "templates/workflows/deploy/static-pages.yml.template" "templates/validators/validate-no-secrets.ts.template" "templates/validators/validate-claude-md-sync.ts.template" + "templates/validators/validate-epistemic-hierarchy.ts.template" + "templates/validators/validate-empirical-proof.ts.template" + "templates/validators/validate-webhook-active.ts.template" "templates/hooks/gen-project-structure.ts.template" "templates/hooks/gen-todos-report.ts.template" "templates/scripts/gh-pr-merge-safe.sh.template" + "templates/scripts/setup-oauth-secret.sh.template" + "templates/scripts/setup-self-hosted-runner.sh.template" ) MISSING=0 for f in "${REQUIRED[@]}"; do 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..b507a13 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-empirical-proof.md` + + validator `validate-empirical-proof.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 + `# empirical-proof: 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-invariants.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) + `build-log.md` (chronology) +- `docs/{reference-cases,lessons,deploys,api,architecture}/` 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/`, + `build-log.md`, `.planning/workstreams/`) +- 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/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index fca56e9..2fffba4 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,41 +1,83 @@ -# Código de Conduta +# Contributor Covenant Code of Conduct -## Nossa promessa +## Our Pledge -Como contribuidores e mantenedores, nos comprometemos a fazer da participação neste projeto uma experiência sem assédio para todos, independente de idade, tamanho corporal, deficiência, etnia, identidade e expressão de gênero, nível de experiência, nacionalidade, aparência pessoal, raça, religião ou identidade e orientação sexual. +We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. -## Nossos padrões +We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. -Exemplos de comportamento que contribuem pra um ambiente positivo: +## Our Standards -- Linguagem acolhedora e inclusiva -- Respeito a pontos de vista e experiências diferentes -- Aceitar feedback construtivo de boa fé -- Focar no que é melhor pro projeto e pra comunidade -- Demonstrar empatia com outros membros +Examples of behavior that contributes to a positive environment for our community include: -Exemplos de comportamento inaceitável: +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience +* Focusing on what is best not just for us as individuals, but for the overall community -- Linguagem ou imagens sexualizadas + atenção sexual indesejada -- Trolling, insultos, comentários depreciativos, ataques pessoais ou políticos -- Assédio público ou privado -- Publicar informação privada de terceiros sem permissão -- Outra conduta razoavelmente considerada inadequada em contexto profissional +Examples of unacceptable behavior include: -## Responsabilidades dos mantenedores +* The use of sexualized language or imagery, and sexual attention or advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a professional setting -Mantenedores são responsáveis por clarificar os padrões de comportamento aceitável e devem tomar ação corretiva apropriada e justa em resposta a comportamentos inaceitáveis. +## Enforcement Responsibilities -Mantenedores têm o direito e a responsabilidade de remover, editar ou rejeitar comentários, commits, código, edições de wiki, issues e outras contribuições que não estejam alinhadas com esse Código de Conduta, e bania temporariamente ou permanentemente qualquer contribuidor por comportamentos considerados inadequados, ameaçadores, ofensivos ou prejudiciais. +Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. -## Escopo +Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. -Esse Código de Conduta aplica-se em todos os espaços do projeto, e também em espaços públicos quando um indivíduo representa o projeto ou a comunidade. Exemplos de representação: usar endereço de e-mail oficial do projeto, postar via conta oficial em redes sociais, atuar como representante designado em eventos online ou offline. +## Scope -## Aplicação +This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. -Instâncias de comportamento abusivo, assediador ou inaceitável podem ser reportadas para [contato@leonardocandiani.com.br](mailto:contato@leonardocandiani.com.br). Todas as reclamações serão revisadas e investigadas, resultando em resposta considerada necessária e apropriada às circunstâncias. O time de mantenedores é obrigado a manter confidencialidade sobre quem reportou um incidente. +## Enforcement -## Atribuição +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at contato@leonardocandiani.com.br. All complaints will be reviewed and investigated promptly and fairly. -Esse Código de Conduta é adaptado do [Contributor Covenant](https://www.contributor-covenant.org), versão 1.4, disponível em https://www.contributor-covenant.org/version/1/4/code-of-conduct.html. +All community leaders are obligated to respect the privacy and security of the reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of actions. + +**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations 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..0f4e1cb 100644 --- a/README.md +++ b/README.md @@ -1,58 +1,81 @@ -# Skill: setup-projeto-qualidade +
-Organizadora e criadora de projetos. Aplica uma arquitetura de qualidade alta em qualquer projeto git, novo ou existente. +keepwright -## Como invocar +# keepwright -No projeto-alvo: +**Set up and keep a high-quality engineering architecture in any git repo.** -``` -/setup-projeto-qualidade -``` - -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 +A Claude Code plugin that 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. -- `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 +## Install -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`. +``` +/plugin marketplace add leonardocandiani/keepwright +/plugin install keepwright +``` -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-safe-merge.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 -