From 47c41c8578ef5bc3afe3866d9a4ef492bb8d502b Mon Sep 17 00:00:00 2001 From: Cleber Rangel Date: Wed, 12 Aug 2026 11:59:24 -0300 Subject: [PATCH 1/3] docs: complementaridade com OCR e disciplina de cobertura no protocolo. Documenta OCR como vizinho opcional (sem vendoring), e absorve preview nomeado, coverage mandate e residual risks da disciplina de review. --- CHANGELOG.md | 23 ++ LICENSE | 7 + README.en.md | 64 ++- README.md | 60 ++- SKILL.md | 71 +++- agents/cleanup-phase-1.md | 13 +- docs/open-code-review-comparison-research.md | 386 +++++++++++++++++++ references/audit.md | 31 ++ references/complementarity-opencodereview.md | 56 +++ references/duplication.md | 26 ++ references/final-report.md | 25 ++ 11 files changed, 739 insertions(+), 23 deletions(-) create mode 100644 docs/open-code-review-comparison-research.md create mode 100644 references/complementarity-opencodereview.md diff --git a/CHANGELOG.md b/CHANGELOG.md index b99cd50..c1a799a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,29 @@ do manifesto é a chave de cache que decide se uma instalação enxerga atualização, e esquecer o bump falha em silêncio dos dois lados — ninguém recebe erro, a correção só nunca chega. +## [Unreleased] + +### Adicionado + +- Pesquisa de comparação com OpenCodeReview: + `docs/open-code-review-comparison-research.md` (vizinhos vs substitutos, + o que a skill absorveu como disciplina de processo e o que permanece + ferramenta externa). +- Documentação de complementaridade com OpenCodeReview (CLI opcional Apache-2.0, + sem vendoring): `references/complementarity-opencodereview.md`, receita + `ocr review` / `ocr delegate` na branch `cleanup/`, e menção no relatório + final. +- **Coverage mandate** nas varreduras 1.4 e 1.5: checklist + `reviewed|skipped+reason` e `coverage_rate` em `CLEANUP_PROGRESS.md`. +- **Preview** nomeado antes da primeira mutação da fase 1.3 (lista no log, + commit próprio; GREEN segue autónomo). +- Seção **Residual risks** com severidade no relatório final. + +### Alterado + +- `LICENSE`: notice de que o OCR é ferramenta externa opcional; o código deste + repositório permanece MIT. + ## [0.9.0] — 2026-08-11 Quatro decisões de texto normativo tomadas com medição, e um terceiro mecanismo do mesmo defeito diff --git a/LICENSE b/LICENSE index 71cb38b..a2e0550 100644 --- a/LICENSE +++ b/LICENSE @@ -26,3 +26,10 @@ Third-party notice: portions of references/audit.md are derived from tech-debt-audit by ksimback (https://github.com/ksimback/tech-debt-skill), licensed under the MIT License — Copyright (c) ksimback. The permission notice above applies to those portions as well. + +Optional external tool (not incorporated): documentation in this repository +may describe using the OpenCodeReview CLI +(https://github.com/alibaba/open-code-review), licensed under the Apache +License 2.0, as an optional post-cleanup review step. That CLI is not +vendored, bundled, or required to run this skill; this project's own source +and documentation remain under the MIT License above. diff --git a/README.en.md b/README.en.md index e85dbdc..52b28e9 100644 --- a/README.en.md +++ b/README.en.md @@ -136,12 +136,14 @@ codebase-cleanup/ │ └── cleanup-phase-4-impl.md applies tier A and the approved tier B ├── docs/ │ ├── plugin-spec-research.md host limits, official advice and mere habit -│ └── attribution-frontier.md what the skill buys and what the model already brings +│ ├── attribution-frontier.md what the skill buys and what the model already brings +│ └── open-code-review-comparison-research.md complementarity with OpenCodeReview ├── hooks/ │ └── hooks.json registers the guard on the PreToolUse event ├── references/ │ ├── gate.md the gate contract: exit codes, watchdog, scripts │ ├── audit.md phase 1.4 audit protocol +│ ├── complementarity-opencodereview.md optional OCR on the cleanup/ branch │ ├── final-report.md the report template and how to fill it │ ├── knip-config.md knip configuration without pitfalls │ ├── duplication.md duplicate functions and the churn rule @@ -393,25 +395,44 @@ With the level announced, it creates the cleanup branch and proceeds: - **Phase 1 — dead code.** Configures knip until the hints reach zero, runs in production mode and deletes in atomic commits, one per category: unused - deps, orphan files, dead exports. Each step stages only pathspecs of that - step's artifacts (`git add -- …`, never `git add -A`), and only lands with a - green gate. At the end, it produces an audit of what is left. + deps, orphan files, dead exports. Before the first deletion, it writes an + explicit **Preview (phase 1.3)** into `CLEANUP_PROGRESS.md` — the concrete + deps, files and exports the report would remove — and commits that log + update alone (`chore: preview phase 1 deletions`). On GREEN it proceeds + without asking after that record exists; on YELLOW the preview simply omits + what the level will not touch. Each delete step stages only pathspecs of + that step's artifacts (`git add -- …`, never `git add -A`), and only lands + with a green gate. At the end, phase **1.4** produces a full audit; every + unit in the sweep ends `reviewed` or `skipped` with a reason, and the + counts plus `coverage_rate` land under `## Coverage` in the progress log — + a rate below 100% without a recorded Decisions gap leaves the step + incomplete. - **Phase 1.5 — duplicate functions** (closes phase 1). Sweeps for functions with different names doing the same thing (similarity-ts or fallow on JS/TS, jscpd on other stacks) and applies the churn rule: a pair that changes together in git is real duplication and becomes a phase 2 candidate; a pair that evolves independently is structural coincidence and - is left alone. Report only — nothing is deleted here. + is left alone. The same **coverage mandate** applies: every detector pair + is `reviewed` or `skipped` with a reason and a `coverage_rate` before the + survey commit. Report only — nothing is deleted here. - **Phase 2 — consolidation.** Surfaces up to 5 shallow module candidates (starting from the phase 1.5 pairs), recommends one and asks a single question. Answer "go" and it implements. - **Phase 3 — structure.** Diagnosis of the folder tree, plan, and moves with `git mv`, one folder per commit. +The final report (template in `references/final-report.md`) includes open +findings from the 1.4 audit as **Residual risks**, each with the audit's own +severity (`Critical` / `High` / `Medium` / `Low`) — unfinished business from +the cleanup, not a second audit. When the run left a `cleanup/` branch, the +summary may point to an optional OCR review under **Optional next step** +(see [Complementarity with OpenCodeReview](#complementarity-with-opencodereview)); +never as a required protocol stage. + Between phases the skill asks for `/clear` — context accumulated from one phase degrades the judgment of the next. Progress lives in -`CLEANUP_PROGRESS.md` at the repo root, so the next session resumes where it -stopped without you re-explaining anything. In environments with subagents, +`CLEANUP_PROGRESS.md` at the repo root (including Preview and Coverage), so +the next session resumes where it stopped without you re-explaining anything. In environments with subagents, the skill runs as an orchestrator and dispatches each phase to a disposable context. Installed as a plugin, those subagents come declared in `agents/`: `cleanup-phase-1` (phases 1 and 1.5), plus a survey and an implementation @@ -420,6 +441,22 @@ how the checkpoint stops depending on good intentions: the question reaches you before anything changed, and the implementation only starts after your answer. The protocol is in Step 0.2 of SKILL.md. +### Complementarity with OpenCodeReview + +This skill and [Alibaba OpenCodeReview](https://github.com/alibaba/open-code-review) +(OCR) solve different jobs. Cleanup mutates the tree behind a gate — dead +code, shallow modules, folders, local reshaping. OCR reviews a diff or PR +and leaves line-level comments; auto-fix without a human is out of its +roadmap. They are neighbours, not substitutes: OCR's "dead code" heuristics +on a diff are not a replacement for knip or vulture. + +The skill does **not** install, vendor, or call the OCR Go binary. OCR stays +an optional CLI you install yourself when you want review QA after a cleanup. +The recipe — `ocr review` / `ocr delegate` against `cleanup/YYYYMMDD` — lives +in `references/complementarity-opencodereview.md`. When a run produced that +branch, the final summary may mention it as an optional next step; it is +never required. + ### How to revert Each category lives in its own commit. If something breaks later: @@ -546,12 +583,23 @@ Skills and materials used in building this one: - [Signs of AI writing](https://en.wikipedia.org/wiki/Wikipedia:Signs_of_AI_writing), from Wikipedia's WikiProject AI Cleanup — the basis of the local adaptation `humanizer-pt-br`, used to write this README. +- [OpenCodeReview](https://github.com/alibaba/open-code-review), by Alibaba + (Apache-2.0) — not embedded here; its review discipline (preview before + spend, coverage checklists, severity on findings) informed the named + preview, coverage mandate and residual-risks sections of this protocol. + Optional post-cleanup QA recipe: + `references/complementarity-opencodereview.md`. None of them is a runtime dependency: they were sources and development tools — nothing beyond this folder needs to be installed to use -codebase-cleanup. +codebase-cleanup. OCR remains optional and external if you choose to run it. ## License MIT — use, copy, modify and redistribute freely. Full text in [LICENSE](LICENSE). + +The optional OpenCodeReview CLI is licensed under Apache-2.0 and is **not** +vendored, bundled, or required by this skill. Describing how to use it does +not relicense this repository; this project's own source and documentation +stay MIT. diff --git a/README.md b/README.md index db69e7e..15b83ed 100644 --- a/README.md +++ b/README.md @@ -133,12 +133,14 @@ codebase-cleanup/ │ └── cleanup-phase-4-impl.md aplica tier A e o tier B aprovado ├── docs/ │ ├── plugin-spec-research.md o que é limite do host, conselho e hábito -│ └── attribution-frontier.md o que a skill compra e o que o modelo já traz +│ ├── attribution-frontier.md o que a skill compra e o que o modelo já traz +│ └── open-code-review-comparison-research.md complementaridade com OpenCodeReview ├── hooks/ │ └── hooks.json registra o guarda no evento PreToolUse ├── references/ │ ├── gate.md o contrato do gate: exit codes, watchdog, scripts │ ├── audit.md protocolo de auditoria da fase 1.4 +│ ├── complementarity-opencodereview.md OCR opcional na branch cleanup/ │ ├── final-report.md o modelo do relatório e como preenchê-lo │ ├── knip-config.md configuração do knip sem armadilhas │ ├── duplication.md funções duplicadas e a regra do churn @@ -270,6 +272,23 @@ o vocabulário de consolidação da fase 2 em créditos não muda o comportamento em runtime; elas são fonte, não dependência. +### Vizinho opcional: OpenCodeReview + +Esta skill e o [OpenCodeReview](https://github.com/alibaba/open-code-review) +(OCR) da Alibaba resolvem trabalhos diferentes — são **vizinhos**, não +substitutos. A cleanup mexe na árvore (código morto, módulos rasos, pastas, +remodelagem local) atrás de gate e branch `cleanup/`. O OCR comenta risco e +defeito em diff/PR, linha a linha; não é o caminho para apagar o que o knip +ou o vulture marcam como inalcançável. + +A skill **não** instala, chama nem embute o binário Go do OCR, nem copia +prompts ou regras dele. Quem quiser review de QA depois da faxina instala o +CLI por conta (Apache-2.0; requisitos como Git ≥ 2.41 e endpoint de LLM são +do OCR). A receita opcional — `ocr review` / `ocr delegate` contra a branch +`cleanup/` — está em `references/complementarity-opencodereview.md`. O +relatório final pode citar esse passo sob "Optional next step"; nunca como +obrigação do protocolo. + ### O que o `SKILL.md` carrega, e o que ele adia Todo byte do `SKILL.md` é pago em **toda** invocação: ele entra inteiro no @@ -390,23 +409,40 @@ Com o nível anunciado, ela cria a branch de limpeza e segue: - **Fase 1 — código morto.** Configura o knip até os hints zerarem, roda em modo produção e deleta em commits atômicos, um por categoria: deps não - usadas, arquivos órfãos, exports mortos. Cada passo faz stage só com - pathspecs dos artefatos daquele passo (`git add -- …`, nunca `git add -A`), - e só entra com gate verde. No fim, produz uma auditoria do que sobrou. + usadas, arquivos órfãos, exports mortos. Antes da primeira mutação da + fase 1.3, grava um **preview** em `CLEANUP_PROGRESS.md` (lista concreta + por categoria, commit próprio `chore: preview phase 1 deletions`) — no + GREEN segue sozinha depois desse registro; no YELLOW o preview só omite o + que o nível já proíbe. Cada passo faz stage só com pathspecs dos + artefatos daquele passo (`git add -- …`, nunca `git add -A`), e só entra + com gate verde. No fim, produz uma auditoria do que sobrou (fase 1.4), + com **coverage mandate**: cada unidade da varredura fecha como + `reviewed` ou `skipped` com motivo, e o `coverage_rate` vai no log — + taxa abaixo de 100% sem gap registrado em Decisions deixa o passo + incompleto. - **Fase 1.5 — funções duplicadas** (fecha a fase 1). Varre funções com nomes diferentes fazendo a mesma coisa (similarity-ts ou fallow em JS/TS, jscpd nos demais stacks) e aplica a regra do churn: par que muda junto no git é duplicação real e vira candidato da fase 2; par que evolui separado é - coincidência estrutural e fica em paz. Só relatório — nada é deletado aqui. + coincidência estrutural e fica em paz. O mesmo mandate de cobertura vale + para cada par que o detector emitiu. Só relatório — nada é deletado aqui. - **Fase 2 — consolidação.** Levanta até 5 candidatos de módulos rasos (começando pelos pares da fase 1.5), recomenda um e faz uma única pergunta. Respondeu "vai", ela implementa. - **Fase 3 — estrutura.** Diagnóstico da árvore de pastas, plano, e movimentos com `git mv`, uma pasta por commit. +O relatório final traz **Residual risks**: achados abertos da auditoria 1.4 +que a limpeza não fechou, cada um com a severidade do audit (`Critical` / +`High` / `Medium` / `Low`) — não é uma segunda auditoria, é o que ficou +pendente. Quando a run deixou branch `cleanup/`, o sumário pode apontar um +passo opcional de review com OCR (seção [Vizinho opcional](#vizinho-opcional-opencodereview)); +nunca como etapa obrigatória. + Entre as fases a skill pede `/clear` — contexto acumulado de uma fase piora o julgamento da seguinte. O progresso fica em `CLEANUP_PROGRESS.md` na raiz do -repo, então a sessão seguinte retoma de onde parou sem você reexplicar nada. +repo (incluindo Preview e Coverage), então a sessão seguinte retoma de onde +parou sem você reexplicar nada. Em ambientes com subagentes, a skill roda como orquestrador e despacha cada fase para um contexto descartável. Instalada como plugin, esses subagentes vêm declarados em `agents/`: `cleanup-phase-1` (fases 1 e 1.5), e mais um par @@ -540,6 +576,13 @@ Skills e materiais usados na construção desta: do WikiProject AI Cleanup da Wikipedia — base da adaptação local `humanizer-pt-br`, usada na escrita deste README. +Ferramenta complementar (opcional, sem vendoring): + +- [OpenCodeReview](https://github.com/alibaba/open-code-review) (Alibaba, + Apache-2.0) — CLI de review de diff/PR que a documentação desta skill + pode citar como passo opcional depois da branch `cleanup/`. Não entra no + runtime; a receita está em `references/complementarity-opencodereview.md`. + Nenhuma delas é dependência de runtime: são fontes e ferramentas de desenvolvimento — nada além desta pasta precisa estar instalado para usar a codebase-cleanup. @@ -548,3 +591,8 @@ codebase-cleanup. MIT — use, copie, modifique e redistribua à vontade. Texto completo em [LICENSE](LICENSE). + +O CLI OpenCodeReview, quando você o instala à parte, é Apache-2.0 e +permanece ferramenta externa: este repositório não o vende, não o embute e +não o exige. Usá-lo não relicencia o código desta skill; o notice correspondente +está no final do [LICENSE](LICENSE). diff --git a/SKILL.md b/SKILL.md index ed811f0..58a881f 100644 --- a/SKILL.md +++ b/SKILL.md @@ -275,6 +275,22 @@ Branch: cleanup/20260808 · Level: GREEN · Started: 2026-08-08 - [x] Phase 1.2 — deps removed (7) · commit a3f9c21 - [ ] Phase 1.3 — orphan files ... +## Preview (phase 1.3) +- unused deps: lodash.merge, left-pad (2) +- orphan files: src/legacy/unused.ts (1) +- dead exports: formatPercent @ src/utils.ts (1) # GREEN only; omit on YELLOW +Recorded before the first category mutates. GREEN proceeds without asking; +YELLOW/cap already gates what may run. +## Coverage +### 1.4 audit +- reviewed: 18 · skipped: 2 · coverage_rate: 100% (20/20 units) +- skipped: src/vendor/big.ts — generated, out of scope +### 1.5 duplication +- reviewed: 12 · skipped: 1 · coverage_rate: 100% (13/13 pairs) +- skipped: src/generated/a.ts ↔ src/generated/b.ts — generated sources +Every unit from the scan ends `reviewed` or `skipped` with a reason. A rate +below 100% means the sweep is unfinished — finish or record the gap under +Decisions before closing the step. ## Decisions - `lodash.merge` kept: used by a build script outside the graph ## Pending for the human @@ -401,6 +417,19 @@ Never exclude tests with `ignore` to get the same effect. ## 1.3 Delete in atomic commits, one per category +**Preview before the first mutation.** After the 1.2 report is trustworthy and +**before** any delete, install, or pathspec stage, write a `## Preview +(phase 1.3)` section into `CLEANUP_PROGRESS.md`: one bullet per category that +this level allows, listing the concrete deps / files / exports that the +current report would remove (counts plus names; truncate long lists with +`… and N more` after ~20 items). Commit that log update alone +(`chore: preview phase 1 deletions`) — still no source change. On GREEN, +proceed autonomously after the preview is recorded; do not ask for +confirmation of the list. On YELLOW (or any stack cap that already forbids a +category), the preview simply omits what the level will not touch — the cap +is the confirmation. A run that mutates without a preview in the log skipped +a named step; do not skip it to "save a commit". + **Default scope.** Run all three without asking (GREEN level) or the first two (YELLOW). Each one is: delete → (deps only: install / re-resolve) → stage pathspecs → gate → commit → log-only `CLEANUP_PROGRESS.md` → regenerate the @@ -547,8 +576,9 @@ with no surprises. With the garbage gone, the graph is clean and the audit becomes precise. Follow the protocol in `references/audit.md` — nine dimensions with -`file:line` citations, severity and effort per finding, and the deliverable -template for `TECH_DEBT_AUDIT.md`. The protocol is distilled from ksimback's +`file:line` citations, severity and effort per finding, the coverage +mandate for large sweeps, and the deliverable template for +`TECH_DEBT_AUDIT.md`. The protocol is distilled from ksimback's tech-debt-audit (MIT; credited in the README), so no other skill needs to be installed for this step. @@ -556,6 +586,15 @@ Always include a **"looks bad but is fine"** section — the calls you considere making and decided not to make, with the reason. If that section comes out empty, the audit did not look deep enough and you must go back. +**Coverage mandate.** Before closing 1.4, every unit the sweep took in hand +(module, top hot file, or dimension×scope slice — see `references/audit.md`) +ends as `reviewed` or `skipped` with a one-line reason. Write the counts and +`coverage_rate` under `## Coverage` → `### 1.4 audit` in +`CLEANUP_PROGRESS.md`. A rate below 100% means the step is unfinished: finish +the checklist or record the gap under `## Decisions` before committing the +audit. Cutting a large repo short without that record is the failure mode +this mandate exists to catch. + Commit the report (GREEN/YELLOW; at RED nothing is committed — it goes into the final report instead). Update `CLEANUP_PROGRESS.md`. @@ -571,8 +610,8 @@ analysis surfaces alone. For JS/TS the ladder is: `similarity-ts` (AST comparison per function) if it is on PATH, else `npx fallow@3.14.0 dupes` (pin verified 2026-08-09; never bare `npx fallow`); other stacks fall back to `npx jscpd@5.0.14`. Tools, -flags, thresholds and the report format are in `references/duplication.md` — -read it before running anything. +flags, thresholds, the coverage mandate and the report format are in +`references/duplication.md` — read it before running anything. **The churn rule.** High similarity is not a verdict. Check whether the pair changes together in git history: pairs that co-change are real duplication @@ -581,6 +620,14 @@ coincidence — two domains that will diverge, where abstracting early costs more than duplicating. Record those as "left alone on purpose" with the churn evidence. +**Coverage mandate.** Every candidate pair the detector emitted ends as +`reviewed` (verdict filled: phase 2 candidate / left alone / no signal) or +`skipped` with a reason (generated code, minified vendor, binary, tool noise). +Write the counts and `coverage_rate` under `## Coverage` → +`### 1.5 duplication` in `CLEANUP_PROGRESS.md` before the survey commit. A +thin sample that ignores most of the detector output without skipped reasons +is an incomplete sweep — same rule as 1.4. + Nothing is merged or deleted in this step — which of two duplicate functions survives is a naming-and-intent decision, and that belongs to the phase 2 checkpoint. Commit the report (`chore: duplication survey`) on GREEN/YELLOW; @@ -593,7 +640,9 @@ the N files that survived phase 1" is what this step found, and the next session reads it to know the question was asked and answered rather than skipped. Do not treat an empty pair table as "not applicable" and move on: the commit is the only durable mark that phase 1 reached its end, and a judgement that lives in the chat -is gone with the session. +is gone with the session. Record coverage as `reviewed: 0 · skipped: 0 · +coverage_rate: 100% (0/0 pairs)` so the mandate is visibly satisfied, not +omitted. --- @@ -807,8 +856,16 @@ the level and the commit count; one row per phase with what that phase actually removed; the quality delta against the Step 0 baseline, measured by running `"${CLAUDE_PLUGIN_ROOT:-.}/scripts/metrics.sh"` again and diffing it; how to revert (`git revert ` — commits are atomic per category); what failed or -was left undone, and why; and what is pending the user's decision. The template -and the rules for filling each part are in `references/final-report.md`. +was left undone, and why; residual risks from the 1.4 audit still open, each +with a severity (`Critical` / `High` / `Medium` / `Low`); and what is pending +the user's decision. The template and the rules for filling each part are in +`references/final-report.md`. + +When the run produced a `cleanup/` branch, add one short **Optional next +step** line pointing at `references/complementarity-opencodereview.md` — OCR +review/delegate on that branch is optional QA for logical regressions the +gate may miss. Never install OCR, never treat it as required, never vendor +its code or prompts. If the level was RED, the report is diagnosis only: list what you would do and what needs to exist or be fixed (tests, typecheck, a baseline that passes) to diff --git a/agents/cleanup-phase-1.md b/agents/cleanup-phase-1.md index 3874860..b7ff91f 100644 --- a/agents/cleanup-phase-1.md +++ b/agents/cleanup-phase-1.md @@ -31,9 +31,12 @@ answer — anything the level or a stack cap sends to a checkpoint — is not yours to decide. Record it in `CLEANUP_PROGRESS.md` under what is pending and leave it undone. -Every rule of the protocol applies to you as written, and four of them are +Every rule of the protocol applies to you as written, and five of them are the ones that get lost in delegation: +- **preview before the first 1.3 mutation** — write `## Preview (phase 1.3)` + into the log and commit it alone before any delete/install/stage; GREEN + proceeds without asking after that record exists; - one commit per category, staged by pathspec, never a whole-tree add; - the progress log is never in a category commit — update it in a commit of its own after the category lands; @@ -42,6 +45,12 @@ the ones that get lost in delegation: - if a security hook blocks a command, follow the hook rule at the top of SKILL.md — the rollback being blocked aborts the pipeline. +**Coverage mandate (1.4 and 1.5).** Every audit unit and every detector pair +ends `reviewed` or `skipped` with a reason; write `coverage_rate` under +`## Coverage` in `CLEANUP_PROGRESS.md` before closing those steps. A rate +below 100% without a Decision explaining the gap means the step is not done. + Update `CLEANUP_PROGRESS.md` in a log-only commit after each category — it is the canonical state, not your reply — and return a short summary: what each -category removed, what failed and why, and what is waiting on a human. +category removed, what failed and why, coverage rates for 1.4/1.5, and what +is waiting on a human. diff --git a/docs/open-code-review-comparison-research.md b/docs/open-code-review-comparison-research.md new file mode 100644 index 0000000..18d704f --- /dev/null +++ b/docs/open-code-review-comparison-research.md @@ -0,0 +1,386 @@ +# Research: Alibaba OpenCodeReview × codebase-cleanup + +Pesquisa consolidada para responder: **o que o projeto local pode aproveitar do [alibaba/open-code-review](https://github.com/alibaba/open-code-review)?** + +As fontes foram consultadas em **2026-08-12**. Afirmações factuais sobre o OCR vêm do repositório GitHub (README, docs em `pages/src/content/docs/en/`, skills, `action.yml`, `ROADMAP.md`, `LICENSE`) e da API do GitHub (`gh repo view` / `gh api`). Afirmações sobre o projeto local vêm dos arquivos deste repositório (`README.md`, `SKILL.md`, `.claude-plugin/plugin.json`, `docs/`). Onde a fonte não diz, está escrito que não diz. + +Nada aqui recomenda commit ou merge automático de código Apache-2.0 neste repositório MIT — ver seção de licença. + +--- + +## 1. Veredito em uma frase + +São produtos **complementares**, não substitutos: o **codebase-cleanup** é uma skill Claude Code de faxina estrutural (código morto → consolidação → pastas → remodelagem local) com gate e commits atômicos; o **OpenCodeReview (OCR)** é um CLI Go de *code review* por diff, com pipeline determinístico + agente LLM, regras multi-linguagem e integrações CI/IDE. O que vale aproveitar são **padrões de engenharia e disciplina de cobertura**, não embutir o OCR como dependência de runtime da skill de limpeza. + +--- + +## 2. Projeto local — codebase-cleanup + +### Propósito + +Skill (e plugin) de limpeza de codebase para Claude Code. Quatro fases, nessa ordem: (1) código morto, (1.5) funções duplicadas, (2) consolidação de módulos rasos, (3) reorganização de pastas, (4) remodelagem local do que sobrou. Ordem fixa porque organizar antes de apagar morto é “arrumar lixo em gaveta bonita”. + +Fonte: [`README.md`](../README.md) (consultado 2026-08-12). + +### Escopo e não-escopo + +| Faz | Não faz (explícito na `description` do `SKILL.md`) | +| --- | --- | +| Remover deps/arquivos/exports mortos | Formatação / lint | +| Detectar duplicação com regra de churn | Atualização de deps vulneráveis | +| Consolidar módulos rasos | Otimização de bundle size | +| Reorganizar pastas com `git mv` | Limpeza de banco | +| Remodelar funções (tier A/B) | Reescrita de histórico git | +| Gate multi-stack + rollback | Code review de PR / comentários line-level | + +Fonte: frontmatter de [`SKILL.md`](../SKILL.md). + +### Stack e forma de distribuição + +- Artefato: Markdown de skill + agents + `references/` + scripts bash (`gate.sh`, `guard.sh`, testes). +- Host: Claude Code (plugin marketplace / cópia em `~/.claude/skills/`). +- Versão do plugin: `0.9.0` ([`.claude-plugin/plugin.json`](../.claude-plugin/plugin.json)). +- Licença: **MIT** ([`LICENSE`](../LICENSE), README). +- Ferramentas externas por stack: knip (JS/TS pinado), vulture/deadcode, cargo-udeps, jscpd/similarity-ts, etc. — a skill aponta o que falta; não instala toolchain à força. +- Autonomia calibrada: níveis GREEN / YELLOW / RED via `scripts/gate.sh`. +- Guardas PreToolUse: nunca `git add -A`; também bloqueiam `git reset --hard`, `git clean`, `git push` e commit na `main`. + +### Arquitetura operacional + +``` +Step 0 (calibração) → branch cleanup/YYYYMMDD + → Fase 1 (+1.5) → /clear → Fase 2 (checkpoint) → /clear + → Fase 3 (checkpoint) → /clear → Fase 4 (tier B conditional) + → relatório final + CLEANUP_PROGRESS.md +``` + +Subagentes em `agents/` (survey read-only vs impl) para não burlar checkpoints. Progresso durável em `CLEANUP_PROGRESS.md`. + +### Maturidade (local) + +Repositório próprio com CI multi-plataforma (ubuntu + macOS), suítes de contrato (`gate_test`, `guard_test`, `rollback_test`, `metrics_test`, `coherence_test`, `mutation_test`) e evals de modelo (`eval.sh`). Foco em **protocolo seguro de mutação do repo**, não em achar bugs de lógica em diffs de PR. + +--- + +## 3. Alibaba OpenCodeReview — fatos da fonte primária + +### Identidade e maturidade + +| Campo | Valor (2026-08-12) | Fonte | +| --- | --- | --- | +| Repo | `alibaba/open-code-review` | GitHub | +| Site | https://open-codereview.ai | README | +| Descrição | Hybrid architecture code review: deterministic pipelines + LLM Agent; line-level comments; multi-language ruleset | `gh repo view` description | +| Criado | 2026-05-18 | API | +| Stars / forks | ~20 240 / ~1 420 | API | +| Issues abertas | ~112 | API | +| Release | **v1.9.2** (2026-08-12) | `gh release list` | +| Linguagem principal | Go (~2.1 MB de código Go; também TS/JS na extensão VS Code e pages) | API languages | +| Pacote npm | `@alibaba-group/open-code-review` (wrapper que baixa binário) | `package.json` | +| Licença | **Apache-2.0** | `LICENSE`, badge README | +| OpenSSF | Badge Gold (README) | README | +| Origem | Assistente interno da Alibaba Group; “tens of thousands of developers”, “millions of code defects” (claim do README — não auditado aqui) | README | + +### Propósito + +CLI `ocr` que lê diffs Git, envia arquivos alterados a um LLM com tool-use, e gera comentários estruturados com precisão de linha. Também `ocr scan` para auditar arquivos inteiros sem diff significativo. + +Citação (README): + +> “It reads Git diffs, sends changed files to a configurable LLM via an agent with tool-use capabilities, and generates structured review comments with line-level precision.” + +### Problema que o OCR diz resolver (vs agents genéricos) + +O README lista falhas de skills de review puramente em linguagem natural: + +1. Cobertura incompleta em changesets grandes (“cut corners”). +2. Drift de posição (linha/arquivo errados). +3. Qualidade instável com pequenas variações de prompt. + +Causa declarada: falta de **hard constraints** no processo. + +### Arquitetura (docs oficiais no repo) + +Pipeline documentado em `pages/src/content/docs/en/architecture.md`: + +1. **Bootstrap** — resolve endpoint LLM, carrega template, tools, system rules. +2. **Diff provider** — modos Workspace / Commit / Range (`merge-base(a,b)..b`). +3. **Filter & rules** — filtro de 5 gates; regra por arquivo. +4. **Subtask dispatch** — um sub-agente por arquivo (concorrência default 8); plan opcional se >50 linhas alteradas; main loop com tools. +5. **Comment processing** — resolução de linha, re-location opcional, review-filter LLM, render text/JSON. +6. **Persistência** — sessões JSONL em `~/.opencodereview/sessions/…`; `ocr viewer`. + +Filosofia: **engenharia determinística × agente híbrido**. + +| Determinístico | Agente | +| --- | --- | +| Seleção precisa de arquivos | Prompts sintonizados para review | +| Bundling de arquivos relacionados | Toolset destilado de traços de produção | +| Matching de regras por path (template engine) | Decisões dinâmicas e busca de contexto | +| Módulos externos de posicionamento e “reflection” | Comentários via `code_comment` | + +### Regras + +Cadeia de 4 camadas (`pages/.../review-rules.md`): + +1. `--rule` (CLI) +2. `/.opencodereview/rule.json` +3. `~/.opencodereview/rule.json` +4. `system_rules.json` embutido (sempre presente) + +Regras built-in por extensão/caminho: Java, Go, TS/JS, Python, Rust, Kotlin, C/C++, PHP, Terraform, Prisma, GraphQL, workflows GitHub, `package.json`, MyBatis mappers, etc. Exemplo TS inclui dead code local, XSS, hooks React, `==` vs `===` — **review heurístico**, não deleção via grafo (diferente do knip). + +### Integração + +| Canal | O que oferece | Fonte | +| --- | --- | --- | +| CLI | `ocr review`, `scan`, `delegate`, `config`, `session`, `viewer`, `rules check` | README | +| Claude Code plugin | `/plugin marketplace add alibaba/open-code-review` → slash commands | `plugins/.../README.md` | +| Codex / Cursor plugins | Skills portáteis | mesmo | +| Delegation mode | OCR só filtra arquivos + resolve regras; host agent faz o review com a LLM da assinatura | `integrations/delegate.md` | +| GitHub Action | `action.yml` — comentários inline, sticky summary, incremental | `action.yml`, `examples/github_actions/` | +| Outros CI | GitLab, Gerrit, Bitbucket, GitFlic, Codeup (examples/) | tree do repo | +| VS Code extension | `extensions/vscode/` | tree | +| MCP | Documentado no README / ROADMAP | README | +| Telemetry | OpenTelemetry | README / architecture | + +### O que o OCR declara fora de escopo + +`ROADMAP.md` (“Not Planned”): + +- Automated code fixing **without human review** +- General-purpose AI coding assistant (geração, **refactoring**, chat coding) +- Self-hosted LLM bundling + +Isso reforça a complementaridade: refactoring/cleanup estrutural **não é roadmap do OCR**. + +### Benchmark (claim do README) + +Benchmark próprio: 50 repos, 200 PRs, 10 linguagens, 1 505 issues anotadas por 80+ engenheiros. Vs Claude Code genérico: maior Precision/F1, ~1/9 dos tokens, Recall menor (trade-off deliberado). **Não reproduzido nesta pesquisa** — tratado como claim do projeto. + +--- + +## 4. Comparação lado a lado + +| Dimensão | codebase-cleanup | OpenCodeReview | +| --- | --- | --- | +| **Job-to-be-done** | Reduzir dívida estrutural no repo (morto, raso, pastas, forma local) | Encontrar defeitos/riscos em mudanças (diff/PR) com comentários | +| **Unidade de trabalho** | Categorias e fases sobre a árvore inteira | Arquivo/diff no changeset | +| **Mutação do código** | Sim — deleções, moves, refactors com gate | Primário: só reporta; fix é opcional e o ROADMAP rejeita auto-fix sem humano | +| **Rede de segurança** | Gate typecheck+test; branch dedicada; commits atômicos; guardas PreToolUse | Filtro de arquivos, review-filter LLM, posicionamento de linha; CI posta comentários | +| **Host** | Claude Code skill/plugin | CLI + plugins multi-host + Action + VS Code | +| **Stack de implementação** | Markdown + bash | Go (binário) + npm installer + TS (extensão) | +| **LLM** | Usa o modelo do Claude Code (host) | Endpoint configurável **ou** delegation ao host | +| **Regras de domínio** | Protocolo de limpeza + catalogs em `references/` | `rule.json` + system rules por linguagem | +| **Cobertura de changeset** | N/A (não é review de PR) | Hard constraint: seleção determinística + checklist de coverage no delegate | +| **CI do produto** | Testa a skill (contratos) | Também oferece Action para review de PRs de terceiros | +| **Licença** | MIT | Apache-2.0 | +| **Sobreposição funcional** | Baixa | Baixa | + +### Fluxo de “code review” + +- **Local:** não há fluxo de code review. Há *revisão humana* só nos checkpoints de fronteira de módulo / plano de pastas / tier B, e caps de diff reviewável na fase 4 (“Cap per session: 5 tier A…”) — isso é orçamento de remodelagem, não review de defeitos. +- **OCR:** preview → (plan) → main loop com tools → code_comment → resolve linhas → filter → saída agent/human/CI. + +### Extensibilidade + +| | Local | OCR | +| --- | --- | --- | +| Adiar contexto | `references/*.md` lidos sob demanda | Prompts em `internal/config/template/prompts/` (rebuild) | +| Customizar política | Editar SKILL/agents; caps em `other-stacks.md` | `.opencodereview/rule.json`, `--rule`, tools JSON | +| Outros hosts | Claude Code (primário) | Claude, Codex, Cursor, OpenCode, QCA, MCP | + +--- + +## 5. O que o local já cobre vs o que o OCR oferece de diferente + +### Já coberto (não precisa do OCR) + +- Deleção segura de código morto com grafo (knip etc.) e níveis GREEN/YELLOW/RED. +- Duplicação com churn git (fase 1.5). +- Consolidação e estrutura de pastas. +- Remodelagem local limitada e reviewável. +- Rollback e proibição de push/commit na main. +- Relatório final de limpeza (`references/final-report.md`). +- Distribuição como plugin Claude Code com hooks. + +### OCR oferece e o local não tem (e em geral não deveria absorver como core) + +- Review line-level de PR/diff com precisão de âncora. +- Ruleset multi-linguagem de defeitos (NPE, XSS, SQL injection, thread-safety…). +- GitHub Action / GitLab / Gerrit posting. +- Session viewer, SARIF, telemetry OTel. +- Benchmark de qualidade de review (Precision/Recall). +- Extensão VS Code. +- Bundling concorrente de arquivos relacionados para review estável em PRs enormes. +- Delegation mode: scaffolding determinístico + LLM do host. + +### Zona cinzenta (parecem vizinhos, mas não são a mesma coisa) + +| Aparência | Realidade | +| --- | --- | +| Regra TS do OCR menciona “Dead Code” | É heurística de review no diff; cleanup usa knip/vulture e **deleta** com gate | +| Ambos falam em “cobertura” | OCR: todo arquivo do changeset revisado; cleanup: categorias do knip + gate verde | +| Ambos têm plugin Claude Code | OCR invoca `ocr` CLI; cleanup *é* o protocolo | +| Ambos usam agents | OCR: sub-agentes por arquivo de review; cleanup: survey/impl por fase | + +--- + +## 6. O que pode ser aproveitado + +Ordenado do mais útil ao mais cosmético. “Aproveitar” aqui significa **padrão, receita ou uso complementar** — não fork do binário Go. + +### Ideias e padrões (alto valor) + +1. **Híbrido determinístico × agente** + Hard constraints no que não pode errar (seleção, filtro, ordem, checklist de coverage); LLM só onde há julgamento. O cleanup já faz isso no gate/guardas; o OCR reforça o mesmo princípio no domínio review — útil para endurecer fases grandes (1 e 1.5) contra “cortar caminho” do modelo. + +2. **`ocr review --preview` / `ocr delegate preview`** + Dry-run que lista o que seria tocado **antes** de gastar tokens. Análogo desejável: preview da fase 1 (lista de deletes) já existe em espírito via knip report; formalizar “preview sem mutação” como passo nomeado ajuda UX. + +3. **Mandato de coverage no delegate** + Skill `open-code-review-delegate`: todo arquivo previewed deve terminar `reviewed` ou `skipped` com razão + métricas `coverage_rate`. Padrão importável para varreduras da fase 1.5 / auditoria 1.4 quando o changeset/repo é grande. + +4. **Camadas de regra por path (`.opencodereview/rule.json`)** + Não copiar o formato para “ser OCR”, mas o *modelo mental*: política de projeto versionada, override global, override CLI. Útil se no futuro a cleanup quiser checklists de domínio na fase 4 (ex.: “nunca fundir X com Y”) sem inflar o `SKILL.md`. + +5. **Classificação severidade × categoria no relatório** + OCR usa `critical|high|medium|low` e categorias (`bug`, `security`, …). O relatório final de cleanup poderia adotar severidade para *riscos residuais* da auditoria 1.4 (já tem dimensões) — melhora priorização humana pós-faxina. + +6. **Concorrência com isolamento de contexto** + Subtask por arquivo, concurrency=N, falha isolada. Para cleanup, o paralelo já existe via subagentes de fase; o insight é **não compartilhar contexto poluído entre unidades** (OCR: um arquivo; cleanup: já pede `/clear` entre fases). + +7. **Uso complementar do produto** + Em times que já usam Claude Code: **OCR (delegate ou managed) no PR** + **cleanup na dívida estrutural**. ROADMAP do OCR exclui refactoring — encaixa com o produto local. + +8. **Empacotamento multi-host** + OCR publica Claude + Cursor + Codex a partir do mesmo repo. Se o cleanup quiser Cursor no futuro, o layout `plugins/…` + skills portáteis é referência de packaging (não de domínio). + +### Módulos / prompts / regras (aproveitamento seletivo) + +| Artefato OCR | Aproveitar? | Como | +| --- | --- | --- | +| `rule_docs/*.md` (ex. dead code em TS) | Parcial | Como *checklist de auditoria humana*, não como motor de deleção | +| `main_task_system.md` (foco no diff novo, ignorar achados fora do arquivo) | Ideia | Analogia: fase N não “conserta” o que a fase N+1 vai mexer | +| `REVIEW_FILTER_TASK` (segunda passagem que remove falso positivo) | Ideia | Pós-processar candidatos knip/duplicação antes de deletar/consolidar | +| `RE_LOCATION_TASK` / line resolution | Não | Cleanup não ancora comentários em PR | +| Action.yml / CI examples | Não no core | Outro produto; usuário pode adotar no *seu* app, não neste repo de skill | +| Binário Go / agent loop | Não | Stack e job diferentes; viraria dependência pesada | + +### Integrações + +- **Recomendação de documentação:** “Para review de PR, use OCR; para faxina, use esta skill.” +- **Receita opcional (não runtime):** após merge da branch `cleanup/`, rodar `ocr review --from main --to cleanup/…` (ou delegate) como QA da própria limpeza — detecta regressões lógicas que o gate de testes não pegou. +- **Delegation mode:** se o usuário já está no Claude Code, `ocr delegate` evita segunda API key — alinhado ao modelo econômico do cleanup (usa o host). + +--- + +## 7. O que NÃO faz sentido copiar + +1. **Embutir `@alibaba-group/open-code-review` como dependência obrigatória da skill** + Viola o desenho “nenhuma outra skill/ferramenta de review é obrigatória”; o cleanup já é autossuficiente com knip/gate. OCR exige Git ≥ 2.41 e (no modo managed) LLM endpoint. + +2. **Trocar knip/vulture por regras de “Dead Code” do OCR** + São problemas diferentes: grafo de alcance vs impressão do modelo no diff. False positives de review ≠ candidatos seguros a `rm`. + +3. **Virar produto de code review** + Escopo do cleanup é faxina; o OCR já ocupa review com escala e CI. Duplicar fragmentaria o produto local. + +4. **Auto-fix agressivo pós-review** + O próprio OCR coloca “automated fixing without human review” como Not Planned. O cleanup já tem política estrita de mutação; misturar “review and fix” diluiria os guardrails. + +5. **Copiar prompts/código Go em volume para este repo MIT** + Licença Apache-2.0 exige preservação de notices/ATTRIBUTION ao redistribuir código coberto; ideias e APIs públicas são outra história. Preferir citar e linkar. + +6. **System rules de segurança (XSS, SQLi) como fase da cleanup** + Fora do job-to-be-done; melhor apontar SAST/OCR. + +7. **Session JSONL viewer / OTel / SARIF** + Infra de produto SaaS/CLI maduro; custo alto, benefício baixo para uma skill de protocolo. + +8. **Benchmark de 200 PRs** + Bom *inspiração metodológica* para evals; o cleanup já tem `eval.sh` + mutation — não precisa importar o harness do OCR. + +--- + +## 8. Oportunidades concretas de adaptação + +Prioridade = impacto para o usuário do cleanup × esforço de implementação **neste** repositório. + +| # | Oportunidade | Impacto | Esforço | Notas | +| --- | --- | --- | --- | --- | +| **A** | Doc “complementaridade”: quando usar cleanup vs OCR; receita pós-cleanup `ocr review` / `ocr delegate` na branch | Alto | Baixo | Só documentação + talvez seção no README; zero runtime | +| **B** | Formalizar **coverage mandate** nas varreduras grandes (fase 1.5 / audit): checklist de arquivos/pares, `reviewed|skipped+reason`, taxa de cobertura no `CLEANUP_PROGRESS` | Alto | Médio | Padrão da skill delegate; não precisa do binário OCR | +| **C** | Passo nomeado **Preview** antes de mutação na fase 1 (lista knip → confirmação só se YELLOW/cap já exige; em GREEN manter autonomia mas gravar preview no progress) | Médio | Baixo–médio | Espelha `ocr review --preview` | +| **D** | Segunda passagem tipo **review-filter** nos candidatos de deleção/duplicação (“provably incorrect → drop”) antes do commit | Médio | Médio | Prompt curto + invariante; cuidado para não virar review de bug | +| **E** | Severidade no relatório final / auditoria 1.4 para resíduos | Médio | Baixo | Cosmético mas útil na decisão humana | +| **F** | Regras de domínio versionadas (arquivo de projeto) para restrições da fase 2/4 (“não consolidar billing×auth”) | Médio | Médio | Inspirado em `rule.json`; formato próprio MIT | +| **G** | Packaging Cursor (espelhar layout OCR) | Baixo–médio | Médio | Só se houver demanda de host; domínio continua cleanup | +| **H** | Integrar CLI `ocr` no pipeline da skill | Baixo (produto) / Alto (risco) | Alto | **Não recomendado** como default; conflita autossuficiência e licença/ops | +| **I** | Adotar Action do OCR no CI **deste** repo de skill | Baixo | Baixo | CI da skill valida contratos bash, não PRs de app; pouco valor | + +### Top 3 recomendadas + +1. **A — Documentar complementaridade + receita opcional OCR na branch de cleanup** (alto/baixo). +2. **B — Coverage mandate nas varreduras** (alto/médio) — ataca a mesma falha que o OCR aponta em agents genéricos. +3. **C ou E — Preview explícito e/ou severidade no relatório** (médio/baixo) — ganho de previsibilidade sem mudar o core. + +--- + +## 9. Licença e outros bloqueios + +### Licença + +| | cleanup | OCR | +| --- | --- | --- | +| SPDX | MIT | Apache-2.0 | + +- **Usar o CLI/npm como ferramenta externa** (usuário instala `ocr` na máquina): geralmente ok; Apache-2.0 permite uso. +- **Copiar código/prompts substanciais para dentro deste repo MIT:** exige cumprimento Apache-2.0 (notices, NOTICE se aplicável, estado de mudanças). Risco de incompatibilidade de *relicensing* se o projeto quiser permanecer MIT puro sem dual-license. +- **Recomendação desta research:** aproveitar **ideias e APIs CLI** por referência; não vendorar `internal/` do OCR. + +### Outros bloqueios / ressalvas + +- Site `open-codereview.ai/docs` retornou 404 neste ambiente em 2026-08-12; a doc canônica usada foi a árvore `pages/src/content/docs/en/` no GitHub (mesma fonte do site). +- Claims de escala interna Alibaba e números do benchmark **não foram reproduzidos**. +- OCR default de idioma de comentário: docs da skill mencionam default Chinese na config — relevante se integrar em time PT-BR (configurável). +- Delegation e managed mode mudam o custo (assinatura host vs API key); qualquer receita deve deixar isso explícito. +- Git ≥ 2.41 no OCR pode ser mais novo que o Git de alguns ambientes; cleanup hoje é mais permissivo no Git. + +### Lacunas de doc + +- Não foi auditado o código Go linha a linha (só docs + samples de rules/prompts). +- Não foi medido token/latência do OCR vs skill cleanup (jobs diferentes — comparação numérica seria enganosa). + +--- + +## 10. Fontes consultadas (2026-08-12) + +### OpenCodeReview + +- https://github.com/alibaba/open-code-review (README, LICENSE, ROADMAP, AGENTS.md, action.yml, package.json, go.mod) +- `pages/src/content/docs/en/architecture.md` +- `pages/src/content/docs/en/review-rules.md` +- `pages/src/content/docs/en/integrations/delegate.md` +- `skills/open-code-review/SKILL.md` +- `skills/open-code-review-delegate/SKILL.md` +- `plugins/open-code-review/README.md` +- `plugins/open-code-review/claude-code/commands/review.md` +- `internal/config/rules/rule_docs/default.md`, `ts_js_tsx_jsx.md` +- `internal/config/template/prompts/main_task_system.md` +- `examples/github_actions/ocr-review.yml` +- `gh repo view` / `gh api` / `gh release list` — metadados e tree + +### codebase-cleanup + +- [`README.md`](../README.md) +- [`SKILL.md`](../SKILL.md) +- [`.claude-plugin/plugin.json`](../.claude-plugin/plugin.json) +- [`docs/plugin-spec-research.md`](plugin-spec-research.md) (convenção de research no repo) +- [`references/final-report.md`](../references/final-report.md) + +--- + +## 11. Conclusão operacional + +Trate o OCR como **vizinho de ecossistema**, não como biblioteca a embutir. O maior retorno para este repositório é importar a **disciplina** (preview, coverage, filtro de falso positivo, regras de projeto em camadas) e, opcionalmente, **apontar** o OCR para review de PR / QA da branch `cleanup/`. O menor retorno — e o maior risco — é fundir os dois produtos ou vendorar o CLI Go sob a skill MIT de faxina. diff --git a/references/audit.md b/references/audit.md index a941b7e..920b4d9 100644 --- a/references/audit.md +++ b/references/audit.md @@ -131,3 +131,34 @@ written into the repo — the same content goes into the final report instead. Whoever runs this step (the orchestrator, or the phase 1 subagent when phase 1 is itself delegated) merges, dedupes and ranks down to the 30–80 target. + +## Coverage mandate + +Large sweeps cut corners unless every unit is accounted for. Before the audit +commit (or before folding the same content into the final report at RED): + +1. Build the **unit list** up front. On a normal repo the units are the + intersection of the 20 largest and 20 hottest files, plus each top-level + module that falls outside that intersection. On a large repo the units are + the modules dispatched to subagents (one unit per module). Dimension 9 and + the README contradiction check are units too when they apply. +2. Close every unit as **`reviewed`** (findings written, or an explicit + "Nothing material" for that slice) or **`skipped`** with a one-line reason + (generated tree, vendored minified blob, binary, path the user scoped out). +3. Write the tally into `CLEANUP_PROGRESS.md` under `## Coverage` → + `### 1.4 audit`: + + ```markdown + ### 1.4 audit + - reviewed: N · skipped: M · coverage_rate: R% (N+M / N+M units) + - skipped: path — reason + ``` + + `coverage_rate` is `(reviewed + skipped) / units_planned × 100`. Planned + units that are neither reviewed nor skipped are unfinished work — the rate + is then below 100% and the step is not closed. Skipping with a reason + counts toward coverage; silently omitting a unit does not. + +4. Carry Critical/High open findings forward: they feed the final report's + **Residual risks** table (`references/final-report.md`). Severity in that + table is this audit's severity — do not invent a second scale. diff --git a/references/complementarity-opencodereview.md b/references/complementarity-opencodereview.md new file mode 100644 index 0000000..b514e4e --- /dev/null +++ b/references/complementarity-opencodereview.md @@ -0,0 +1,56 @@ +# Complementary tools — OpenCodeReview (optional) + +This skill and [Alibaba OpenCodeReview](https://github.com/alibaba/open-code-review) +(OCR) solve different jobs. They are **neighbours**, not substitutes. + +| | codebase-cleanup | OpenCodeReview | +|---|---|---| +| Job | Structural debt: dead code, shallow modules, folders, local reshaping | Defect/risk review on a diff or PR, with line-level comments | +| Mutates the tree? | Yes — deletions, moves, limited refactors behind a gate | Primary output is comments; auto-fix without a human is out of OCR's roadmap | +| Safety net | Gate (typecheck + tests), `cleanup/` branch, atomic commits, PreToolUse guards | File filters, review-filter, line relocation; CI can post comments | +| License | MIT (this repository) | Apache-2.0 | + +**Use this skill** for a faxina on the tree. **Use OCR** for PR/diff review +and for defect heuristics the cleanup gate does not catch. Do not treat OCR's +"dead code" rules as a replacement for knip/vulture — those are review +heuristics on a diff; this skill deletes from a reachability graph. + +## What this skill does **not** do + +- Install, vendor, or call the OCR Go binary at runtime. +- Copy OCR prompts, rules, or source into this repository. +- Depend on `@alibaba-group/open-code-review` as a required toolchain. + +OCR remains an **optional CLI the user installs** when they want review QA. +This project's own code stays MIT. Using the OCR CLI under Apache-2.0 does +not relicense this skill; no OCR code is embedded here. + +## Optional recipe — review the `cleanup/` branch + +After phases finish (or after you merge `cleanup/YYYYMMDD`), you may run OCR +against the cleanup branch to catch logical regressions the gate's tests +missed. Install and configure OCR yourself +([upstream README](https://github.com/alibaba/open-code-review)); requirements +such as Git ≥ 2.41 and an LLM endpoint (or delegation mode) are OCR's, not +this skill's. + +Substitute the real branch name and base (`main` / `master`): + +```bash +# Managed mode — OCR drives the LLM endpoint you configured +ocr review --from main --to cleanup/YYYYMMDD + +# Preview first (lists what would be reviewed; no review spend yet) +ocr review --preview --from main --to cleanup/YYYYMMDD + +# Delegation — OCR filters files + resolves rules; the host agent reviews +# with the model already attached to the session (no second API key) +ocr delegate --from main --to cleanup/YYYYMMDD +``` + +`ocr delegate` fits Claude Code sessions that already pay for a host model. +Comment language and other OCR defaults are configured on the OCR side. + +Mention this recipe in the final cleanup summary under a short "Optional +next step" line when the run produced a `cleanup/` branch — never as a +required step, and never by installing OCR for the user. diff --git a/references/duplication.md b/references/duplication.md index 4a6e22f..01ae48d 100644 --- a/references/duplication.md +++ b/references/duplication.md @@ -176,3 +176,29 @@ The "phase 2 candidate" rows feed the survey in analysis alone. Nothing gets merged or deleted in this phase — which of two duplicate functions survives is a naming-and-intent decision, and that is exactly what the phase 2 checkpoint exists for. + +## Coverage mandate + +Detectors over-produce; agents under-read. Before committing the survey +(GREEN/YELLOW) or folding the table into the final report (RED): + +1. The **unit list** is every pair (or clone-family member pairing) the chosen + ladder rung emitted after the threshold / min-tokens filters — not a + hand-picked sample. +2. Close every unit as **`reviewed`** (verdict column filled) or **`skipped`** + with a reason (generated sources, vendored/minified, path outside the + user's scope, tool noise the rung cannot score). "Left alone on purpose" + after the churn rule is **reviewed**, not skipped — a verdict was reached. +3. Write the tally into `CLEANUP_PROGRESS.md` under `## Coverage` → + `### 1.5 duplication`: + + ```markdown + ### 1.5 duplication + - reviewed: N · skipped: M · coverage_rate: R% (N+M / N+M pairs) + - skipped: pathA ↔ pathB — reason + ``` + + Same arithmetic as the audit: `(reviewed + skipped) / units_planned × 100`. + An empty detector result is `0/0` at 100% — the question was asked. A + non-empty list with rows missing from both the table and the skipped + bullets is an incomplete sweep; do not close the step. diff --git a/references/final-report.md b/references/final-report.md index d77316b..002b7db 100644 --- a/references/final-report.md +++ b/references/final-report.md @@ -40,8 +40,25 @@ to be a comparison. - dead exports: typecheck broke in `src/api/routes.ts` (dynamic import) - orphan files: out of scope — user asked deps only +### Residual risks (from 1.4) +Rank open findings the cleanup did not fix. Severity is the audit's +`Critical` / `High` / `Medium` / `Low` — copy it, do not invent a parallel +scale. Cap at ~10; if the audit had a Top 5, those lead. No open findings +means the line `(none)` — do not omit the section. + +| ID | Severity | Summary | +|---|---|---| +| TD-12 | High | auth boundary accepts untyped payloads (`src/api/auth.ts:88`) | +| TD-03 | Medium | god file still >500 LOC after dead-code pass (`src/legacy/ops.ts`) | + ### Pending your decision - (nothing) + +### Optional next step +OCR (Apache-2.0 CLI, not bundled here) can review the cleanup branch for +logical regressions the gate missed — recipe in +`references/complementarity-opencodereview.md`. Skip this line when no +`cleanup/` branch exists or the user already declined. ``` The phase 1 line counts what each category actually removed, tallied per commit @@ -65,3 +82,11 @@ own sake. Report the lines that moved and say which phase moved them; a line that did not move is not worth a row. No baseline — the run started before it was taken, or the file is gone — means no delta section at all. An unanchored "after" is a number pretending to be a comparison. + +Residual risks are the audit's unfinished business, not a second audit. Pull +IDs and severities from `TECH_DEBT_AUDIT.md` (or from the RED diagnosis when +nothing was committed). Do not re-score findings to make the summary look +calmer. Coverage rates from `CLEANUP_PROGRESS.md` belong in the phase rows or +under Failed / not done when a sweep closed below 100% without a Decision +recording why — they are not optional footnotes. + From 6237c0ed94d386e0b20e4737dfb3288971e02926 Mon Sep 17 00:00:00 2001 From: Cleber Rangel Date: Wed, 12 Aug 2026 12:02:41 -0300 Subject: [PATCH 2/3] fix(docs): alinha residual risks, unidades de coverage e preview com escopo. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove contradições entre audit/SKILL/exemplo do log que o review marcou como bloqueantes. --- SKILL.md | 27 +++++++++++++++++---------- references/audit.md | 8 +++++--- 2 files changed, 22 insertions(+), 13 deletions(-) diff --git a/SKILL.md b/SKILL.md index 58a881f..8cdd200 100644 --- a/SKILL.md +++ b/SKILL.md @@ -272,15 +272,17 @@ anything. Branch: cleanup/20260808 · Level: GREEN · Started: 2026-08-08 - [x] Phase 1.1 — knip hints down to zero (3 rounds) -- [x] Phase 1.2 — deps removed (7) · commit a3f9c21 +- [x] Phase 1.2 — production report ready +- [ ] Phase 1.3 — unused deps - [ ] Phase 1.3 — orphan files +- [ ] Phase 1.3 — dead exports ... ## Preview (phase 1.3) - unused deps: lodash.merge, left-pad (2) - orphan files: src/legacy/unused.ts (1) - dead exports: formatPercent @ src/utils.ts (1) # GREEN only; omit on YELLOW -Recorded before the first category mutates. GREEN proceeds without asking; -YELLOW/cap already gates what may run. +Recorded after 1.2 and before the first 1.3 category mutates. GREEN proceeds +without asking; YELLOW/cap and user scope already gate what may run. ## Coverage ### 1.4 audit - reviewed: 18 · skipped: 2 · coverage_rate: 100% (20/20 units) @@ -420,9 +422,11 @@ Never exclude tests with `ignore` to get the same effect. **Preview before the first mutation.** After the 1.2 report is trustworthy and **before** any delete, install, or pathspec stage, write a `## Preview (phase 1.3)` section into `CLEANUP_PROGRESS.md`: one bullet per category that -this level allows, listing the concrete deps / files / exports that the -current report would remove (counts plus names; truncate long lists with -`… and N more` after ~20 items). Commit that log update alone +this run will actually touch — categories the level forbids **and** categories +the user scoped out (see Partial run below) are omitted here; the scoped-out +ones still get a `## Decisions` line. List the concrete deps / files / exports +that the current report would remove (counts plus names; truncate long lists +with `… and N more` after ~20 items). Commit that log update alone (`chore: preview phase 1 deletions`) — still no source change. On GREEN, proceed autonomously after the preview is recorded; do not ask for confirmation of the list. On YELLOW (or any stack cap that already forbids a @@ -586,10 +590,13 @@ Always include a **"looks bad but is fine"** section — the calls you considere making and decided not to make, with the reason. If that section comes out empty, the audit did not look deep enough and you must go back. -**Coverage mandate.** Before closing 1.4, every unit the sweep took in hand -(module, top hot file, or dimension×scope slice — see `references/audit.md`) -ends as `reviewed` or `skipped` with a one-line reason. Write the counts and -`coverage_rate` under `## Coverage` → `### 1.4 audit` in +**Coverage mandate.** Before closing 1.4, every unit from the upfront list in +`references/audit.md` ends as `reviewed` or `skipped` with a one-line reason. +On a normal repo that list is the intersection of the 20 largest and 20 +hottest files, plus each top-level module outside that intersection; on a +large repo it is one unit per module dispatched to a subagent. Dimension 9 +and the README contradiction check are units too when they apply. Write the +counts and `coverage_rate` under `## Coverage` → `### 1.4 audit` in `CLEANUP_PROGRESS.md`. A rate below 100% means the step is unfinished: finish the checklist or record the gap under `## Decisions` before committing the audit. Cutting a large repo short without that record is the failure mode diff --git a/references/audit.md b/references/audit.md index 920b4d9..7fa16db 100644 --- a/references/audit.md +++ b/references/audit.md @@ -159,6 +159,8 @@ commit (or before folding the same content into the final report at RED): is then below 100% and the step is not closed. Skipping with a reason counts toward coverage; silently omitting a unit does not. -4. Carry Critical/High open findings forward: they feed the final report's - **Residual risks** table (`references/final-report.md`). Severity in that - table is this audit's severity — do not invent a second scale. +4. Carry **open findings of any severity** (`Critical` / `High` / `Medium` / + `Low`) forward: they feed the final report's **Residual risks** table + (`references/final-report.md`). Cap and ranking live in that template; the + severity column is this audit's severity — do not invent a second scale or + drop Medium/Low to make the table look calmer. From 0513a48e6af8a6dfa7f3120ef6bcb627ee304118 Mon Sep 17 00:00:00 2001 From: Cleber Rangel Date: Wed, 12 Aug 2026 12:02:46 -0300 Subject: [PATCH 3/3] =?UTF-8?q?fix(agents):=20preview=20da=201.3=20tamb?= =?UTF-8?q?=C3=A9m=20omite=20categorias=20fora=20do=20escopo=20do=20usu?= =?UTF-8?q?=C3=A1rio.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Alinha o agente da fase 1 com a regra de preview já corrigida no SKILL. --- agents/cleanup-phase-1.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/agents/cleanup-phase-1.md b/agents/cleanup-phase-1.md index b7ff91f..9a2676c 100644 --- a/agents/cleanup-phase-1.md +++ b/agents/cleanup-phase-1.md @@ -35,8 +35,9 @@ Every rule of the protocol applies to you as written, and five of them are the ones that get lost in delegation: - **preview before the first 1.3 mutation** — write `## Preview (phase 1.3)` - into the log and commit it alone before any delete/install/stage; GREEN - proceeds without asking after that record exists; + into the log and commit it alone before any delete/install/stage; omit + categories the level forbids or the user scoped out; GREEN proceeds without + asking after that record exists; - one commit per category, staged by pathspec, never a whole-tree add; - the progress log is never in a category commit — update it in a commit of its own after the category lands;