AgentSkillsCN

refactoring

当您重构代码、重新组织模块、重命名类型、删除旧路径,或进行架构迁移时使用此技能。在进行任何结构性代码变更前,务必仔细阅读相关说明。这有助于防止因重构不彻底而悄然破坏下游消费者。

SKILL.md
--- frontmatter
name: refactoring
description: Use when refactoring code, reorganizing modules, renaming types, deleting old paths, or migrating architecture. MUST read before any structural code change. Prevents incomplete refactoring that silently breaks downstream consumers.
allowed-tools: [Read, Glob, Grep, Edit, Write, Bash, Task]

Refactoring

Prove the new path inherits every contract from the old path before deleting it. If you cannot prove it, do not delete.

Past Incidents

DateWhat happenedWhyImpact
2/14externalState handler became a throw stubNew path was not implemented when old path was deletedcompletionType functionality lost
2/14Deno cache served stale version--reload not run, so fixed code was not picked upFix existed but bug reproduced
2/13V1 handler exports removedAdapter not created, old interface compatibility lostimport errors
1/18Legacy completionType aliases removedOld agent.json configs broken with no migration grace periodConfig file incompatibility
1/9Dead code left behind (cli.ts, runner/cli.ts)Old entry points not cleaned up after migrationMultiple paths caused confusion

Failure Patterns

PatternWhy it breaksPrevention
Old path deleted + new path incompleteContract breaks in the intermediate stateList all contracts in Before/After table before deleting
Parameter gate declaration missingFilter blocks undeclared arguments silentlyVerify declarations at every gate from entry to consumer
Build cache inconsistencyCache serves old module instead of updated oneRun --reload or clear cache after every change
Dead code left behindProduces false positives in grep/search, causes confusionDelete superseded code in the same PR
Documentation not updatedUsers cannot discover preconditionsGrep docs for changed names and update all references

Phase 1: Inventory

Map everything being removed or changed before writing any code.

1. Removal Inventory — List what is being removed, who consumes it, and what parameters it receives.

markdown
| Item                    | File          | Consumers             | Parameters            |
| ----------------------- | ------------- | --------------------- | --------------------- |
| createCompletionHandler | factory.ts:42 | builder.ts, runner.ts | args.issue, args.repo |

2. Gateway Audit — Trace every value from entry point to consumer, identifying filters and gates in between. Confirm the new path passes every parameter the old path consumed.

code
Entry (CLI) → Filter (run-agent.ts:196) → Runner → Factory → Handler
                 ↑ blocked if not declared in definition.parameters

3. Consumer Audit — Grep imports and call sites to identify every consumer. Determine the migration target for each. If any consumer has no migration target, deletion is not allowed.

Phase 2: Contract & Verification Design

Define what contracts to preserve and how to prove preservation before writing any code.

4. Before/After Table — List each old-path behavior as a row and describe how the new path achieves it. Any row with an empty "After" column means the refactoring is not ready.

markdown
| Behavior                   | Before                                 | After                                        | Verified |
| -------------------------- | -------------------------------------- | -------------------------------------------- | -------- |
| args.issue reaches handler | Direct path in createCompletionHandler | Registry + definition.parameters declaration | [ ]      |

5. Verification Design — For each row in the Before/After table, decide what to verify, why, and how.

What (what to protect): The input/output and error contracts that callers depend on. Boundary behavior, not implementation details.

Why (why verify there): Past failures show that breakage occurs at boundaries, not at the point of change.

Fragile boundaryWhy it breaksExample
Parameter reachabilityIntermediate filter blocks undeclared args--issue lost because definition.parameters lacked declaration
Interface compatibilityOld and new API method signatures differV2 refreshState/check vs V1 isComplete
Export continuityRemoving re-exports breaks downstream importsV1 exports bulk deletion
Module resolutionCache serves old version of the moduleDENO_DIR split across two directories

How (how to choose the proof method): Match proof method to path complexity. Tests are a means of proof, not a goal.

Path characteristicProof method
Straight line, 1-2 hopsCode review is sufficient
Contains branches, filters, or asyncAutomated test on boundary input/output pairs
Depends on external state (cache, API)E2E execution through the real environment

Phase 3: Execute

6. 1 commit = 1 concern. Separate into: add new path → migrate consumers → delete old path → update docs.

7. Every commit must pass deno task ci. If the intermediate state breaks, the commit granularity is too coarse.

8. Delete dead code in the same PR. "Cleanup later" never comes.

Phase 4: Verify

9. Cache clear — On macOS, DENO_DIR can split across ~/.cache/deno and ~/Library/Caches/deno. Clear both.

bash
deno cache --reload <entry-point>

10. E2E parameter trace — Confirm changed parameters reach the endpoint by running the actual command.

11. Consumer grep — Ensure zero remaining references. grep -r "OldName" --include='*.ts' | grep -v test must return empty.

12. Docs grep — Ensure zero stale references in docs. grep -r "OldName" --include='*.md' must return empty. See docs-consistency skill for full procedure.


Anti-Patterns

BadGood
Delete old path, implement new path laterMake new path work first, then delete old
Assume "nobody uses this" without grepShow evidence via consumer audit
Combine refactor and feature in one PRSeparate for bisectability
Fix the throw siteTrace where the parameter was lost
Skip cache clear after refactorAlways --reload after changes

Related Skills

SkillWhen to use together
fix-checklistRoot cause analysis before deciding what to refactor
functional-testingAutomated test design in Phase 2
docs-consistencyDocumentation updates in Phase 4
workflowTeam delegation for large-scale refactors