repo-native-refactor Skill
审查 diff 或 PR 但不修改,或在不改变行为的前提下整理变更集。适用于“帮我审查改动”“检查这个 diff 是否破坏了契约”“开 PR 前清理一下”“这样安全吗”“合并重复项”。
安装方式:把技能目录放入 ~/.claude/skills/(Claude Code)或在 claude.ai 设置中启用;也可复制右侧安装命令一键添加。
技能指令原文(SKILL.md)
Repo-native refactor
Produce the smallest coherent change that belongs naturally in the target repository.
Prioritize in order:
- Correctness and security: prevent regressions, avoid new security vulnerabilities, handle boundary conditions.
- Semantic integrity: preserve existing invariants, state transitions, validation, and error boundaries.
- Contracts stay as declared: the rule lives in
references/shared-contracts.md§1. Preserve the authorized target contract; otherwise keep exact declared types. Internal helpers are fine when exposed contracts stay exact. - Repository conformity: match surrounding naming, domain conventions, and architectural precedents.
- Economy and simplicity: minimal intervention. Delete dead weight, avoid premature abstractions.
This is a post-implementation audit and small cleanup skill. It is not permission to redesign the repository. Establish a concrete consequence such as inconsistent behavior, duplicated policy that must change together, unclear ownership, avoidable resource cost, or a demonstrated maintenance obstacle. Leave healthy code unchanged when the benefit is speculative.
Minimal intervention and evidence gate
- Evidence-based intervention: refactor only with concrete evidence of divergence, defect, or operational risk. If greenfield code or an additive diff is already minimal, idiomatic, and passing, leave it. A pattern you recognize is a candidate finding, not a reason to change anything.
- Semantic DRY (Cost-benefit consolidation): merge duplicated logic only when the copies share an owner, an invariant, and a reason to change, and only if merging saves more than it costs. Leave similar-looking checks in separate domains alone, and keep small local duplication when merging would obscure ownership.
- Contract boundary protection: preserve public interfaces, parameter names, and return types, except where the task clearly authorizes the change. During cleanup, keep the authorized target contract; don't revert to the old one.
Operating modes
- Review vs. Refactor Authority: first establish the outcome: findings, edits, or both. Review-only means inspection and verification, no source edits. Authorized cleanup allows bounded corrections; don't ask approval again for routine choices.
- Change-set cleanup: for a working tree, branch, commit range, feature, or bounded checkpoint. Work diff-first; read surrounding code only to understand ownership, contracts, and precedent.
- Repository rehabilitation: only when explicitly requested across multiple domains. Read repository rehabilitation, build a short profile, and work in batches you can verify independently.
Evidence hierarchy
Use the evidence hierarchy to guide investigation, not to resolve material contradictions automatically. Reconcile conflicting requirements, documentation, callers, and tests before changing the affected contract. When repository patterns conflict, resolve in order:
- User requirements and explicitly authorized scope.
- Documented architecture and repository guidelines.
- Observable public contracts and persisted schemas.
- Healthy sibling code within the same domain and runtime boundary.
- Relevant tests, schemas, callers, and dependencies.
- Dominant local conventions.
- Language and runtime idioms.
- Conservative, idiomatic defaults.
Never treat a temporary workaround, buggy sibling, or accidental pattern as precedent.
Workflow
1. Establish scope and baseline
Before mutating code, identify:
- Comparison base and working-tree state.
- In-scope files vs. untouched user modifications.
- Existing verification commands and their current pass/fail status.
Differentiate pre-existing failures from regressions introduced by this pass. Never claim a check ran when it did not.
2. Establish intent, ownership, and preservation
Refactoring is behavior-preserving by default. Protect:
- Public APIs, serializations, and database schemas.
- Concurrency guarantees, idempotency, timeouts, and retries.
- Resource lifecycles (file handles, sockets, database transactions).
If a bug requires an observable change, classify and report it as an intentional behavioral correction rather than routine cleanup.
3. Inventory findings before rewriting
Inspect the authorized scope for:
- Validation or control flow whose structure obscures an invariant, creates inconsistent behavior, or duplicates the same owned policy.
- Misplaced domain ownership or leaky abstractions.
- Leaked unmanaged resources or missing atomic flush/sync calls.
- Unnecessary boilerplate, dead code, or commentary narrating syntax.
Read finding taxonomy for complex cases. Establish the smallest adequate correction before editing.
4. Classify risk and refactor
Risk bands:
- R0 - Mechanical: Established formatter or locally provable cleanup.
- R1 - Low Structural: Local residue with straightforward test verification.
- R2 - Contextual Structural: Renames, control-flow changes, extraction of shared predicates.
- R3 - Semantic: Errors, fallbacks, retries, serialization, transactions, async, or lifecycles.
- R4 - Critical Boundary: Auth, permissions, crypto, data migrations, persistence durability.
Read semantic risk for R2+ changes. Never mass-rewrite R3 or R4 behavior without explicit instructions and verified tests.
5. Audit code prose
- When prose is in scope, treat comments, docstrings, CLI output, and error messages as distinct surfaces. Read repository prose for that work.
- Delete comments that merely narrate obvious syntax or execution order.
- Preserve and tighten comments that explain non-obvious invariants, protocol quirks, rounding, or hardware workarounds.
- Never invent fictitious tickets, PR references, or production incident IDs.
6. Verify and review
- Run the smallest repository-native checks that meaningfully exercise the change. For R3/R4 changes or weak test suites, read error and reliability boundaries and testing integrity.
- Prioritize diff reviewability and coherence over raw line minimization; do not compress code into unreadable one-liners.
- Distinguish intentional behavioral corrections from mechanical cleanup.
- Review the final diff like a skeptical maintainer. Every line needs a reason. No contract changed without permission, no test got weaker, no dependency moved for nothing.
Reference routing
Read supporting references only when the corresponding trigger occurs:
- references/shared-contracts.md: Canonical contract + evidence hierarchy. Read when touching any public interface or reconciling conflicts.
- references/refactor-examples.md: R0–R4 good/bad diffs. Read before rewriting a candidate finding.
- references/finding-taxonomy.md: Read for complex multi-smell diffs to name owner + consequence.
- references/semantic-risk.md: Read for R2+ changes, justification gate, and stop conditions.
- references/repository-prose.md: Read when editing comments, docstrings, CLI output, or error messages.
- references/error-reliability.md + references/testing-integrity.md: Read for R3/R4 or weak test suites.
- references/deterministic-tooling.md: Read before introducing new scanners or bulk-codemod tools.
- references/repository-rehabilitation.md: Read only for explicitly requested multi-domain rehabilitation, in verifiable batches.
Hard stops
Do not force a refactor where intent, ownership, public-contract consequences, migration semantics, or concurrency behavior cannot be established. Do not guess between conflicting architectural patterns without evidence.
Completion Report
Scale the completion report to the change. Omit empty sections. Format completion concisely:
Result
Use one: Verified, Verified with caveats, Needs review, or Failed verification.
For review-only requests, an empty findings list is a complete result, not an
embarrassing one. Never manufacture findings to fill a report: each reported
finding needs a producer, a consumer, and an observed consequence, or it is
not reported.
Changed
Summarize material corrections by file and function.
Preserved intentionally
Note specific patterns or contracts deliberately retained to avoid breaking downstream consumers.
Verification
List exact verification commands executed and their outcomes.
Residual uncertainty
Document unresolved limitations or high-risk boundaries intentionally deferred.
When NOT to Use
- Clean greenfield code: Do not refactor newly written code that is already minimal, idiomatic, and passing all tests.
- Speculative cleanup: If you cannot state the domain owner and the concrete maintenance consequence in a single sentence, leave the code unmodified.
- Risk classification: When uncertain between risk bands (such as R2 structural vs. R3 semantic), default conservatively to the higher risk band and require explicit justification.