Required reading before starting
Before any judgment or action, first run the CodeStable preflight: read .codestable/attention.md; if missing, first cs-onboard; do not read an external AI entry point as a substitute (see .codestable/reference/execution-conventions.md)。
AI refactoring on its own has two stable failure modes: first, it does not know the module's real requirements and constraints, so what it changes is not functionally equivalent; second, the scope it swallows in one go exceeds what the context can carry, so by the time it gets to later changes it has forgotten the earlier constraints. This process inserts a scan checklist + method library between "wanting to optimize" and "starting to change code", so that AI only takes on work it can reliably do correctly.
scan(扫优化点清单)→ design(和用户定做哪几条 + 顺序)→ apply(逐条执行,每步人工放行)
Core discipline: behavior equivalence is the bottom line. Once external observable behavior would change → do not go through refactor; go through feature (requirement change) or issue (bug fix).
Architecture deepening mode: when the user says "architecture optimization / module too shallow / seam is wrong / poor testability / hard for AI to navigate", still go through this skill's three phases and do not generate HTML. For scan use codebase-design vocabulary to find deepening opportunities; this is an embedded vocabulary reference and does not switch to the standalone codebase-design skill. Write candidates into the standard {slug}-scan.md, and only after the user checks them do you proceed to design/checklist/apply.
Execution gate (worktree + commit)
Before entering apply, run the start gate, with{slug} being the refactor directory name:
python3 .codestable/tools/codestable-worktree-gate.py --root . --json start --unit .codestable/refactors/YYYY-MM-DD-{slug}
If the gate does not pass, do not start changing code; when overriding, first write in the unit directory worktree-override.md(reason / scope / approval). After apply is complete and before the final commit, run the commit gate (same command commit); if it does not pass, handle the findings first. For gate installation and the branch-guard hook, see .codestable/reference/branch-guard-hooks.md。
Fastforward mode (small refactoring)
Single function / single component / 1-3 optimization spots / can self-prove with tests / no visual inspection needed—going through the full three phases is too heavy. Trigger cs-refactor-ff: identify directly, align once, change in place, run tests to self-prove, and do not produce scan / design / checklist.
Trigger: "small refactoring", "quick refactoring", "just simply optimize function XX", "change it directly", "don't use so many steps".
Do not go ff: changes span > 1 file / estimated > 3 change points / visual verification needed / changing a public interface (requires Parallel Change) / no test coverage / cross-module. When encountered, persuade the user to go through the standard process. If after starting ff it turns out to be more complex, switch back to the full process and start from scan.
Where to put files
.codestable/refactors/{YYYY-MM-DD}-{slug}/
├── {slug}-scan.md ← 阶段 1 优化点清单
├── {slug}-refactor-design.md ← 阶段 2 执行方案
├── {slug}-checklist.yaml ← 阶段 2 生成,阶段 3 推进
└── {slug}-apply-notes.md ← 阶段 3 执行记录
Directory naming is the same as feature / issue. The slug should be short enough to see at a glance what is being changed (user-form-split、export-perf)。
Why open a separate directory instead of mixing into features: refactor artifacts are "a scan of the code's current state + execution record" and are highly time-sensitive; feature artifacts are "why it was designed this way" and are weakly time-sensitive. The archiving logic is different.
Three phases
| Phase | Output | Who leads |
|---|---|---|
| 1 scan | scan.md | AI scans + pre-checks, user checks off |
| 2 design | refactor-design.md + checklist.yaml | AI drafts, user reviews as a whole |
| 3 apply | Code changes + apply-notes.md | AI executes, manual approval at each step |
There are checkpoints between phases: if scan is not checked off, do not enter design; if design is not approved, do not touch code; in apply, if the HUMAN verification item is not approved, do not advance to the next step.
Phase 1: scan
Run the pre-checks first (7 items); if hit, stop
Run through them before starting to scan. If any one is hit → abort scan and give routing suggestions, don't force it. See the 7 checks and output format in reference/refusal-routing.md。
Zero valid outputs—if after scanning you really find nothing worth doing, just say so honestly; don't pad it.
Scan scope lock-in
Before entering scan, confirm:which files to scan this time. Default:
- User named specific files / components → scan just those
- "this page" → entry component + internal modules it directly imports; don't chase shared dependencies
- "this module" → files under the module directory; don't chase beyond the module boundary
- Scope > 15 files or > 3000 lines → trigger the check in item 6 and ask the user to narrow the scope first
The scope must include test files (used to judge the test coverage for the check in item 2).
What to look at while scanning
Use the method library's four layers as a template to find:
- L1 Behavior-equivalent migration: a function is called in many places but its interface/implementation needs to change → Parallel Change; a whole block of old logic is to be replaced by a new implementation → Strangler Fig
- L2 Code-level refactoring: overly long functions (> 50 lines / cyclomatic complexity > 10), duplicated conditional fragments, mysterious temporary variables, multi-level nested if-else
- L3 Structural splitting: component > 300 lines / file does multiple things / container and presentation mixed together / the same logic written separately in multiple components (frontend); Controller directly calls DB / Service missing / Repository bypassed (backend)
- L4 Performance: repeated computation (can be memoized) / N+1 queries / lists without virtualization or pagination / event listeners without cleanup / deeply reactive large objects (Vue)
- Architecture deepening: shallow module, pass-through wrapper, seam leakage, fake adapter, tests bypassing the interface, lack of locality. Write the candidate classification as "architecture", with fields per
reference/scan-checklist-format.mdarchitecture extension.
The complete method library is in reference/methods.md、reference/methods-l4.md and reference/methods-architecture.md; load it fully during scanning as the matching table.
Output format
{slug}-scan.md two parts:
- Top overview(one paragraph): scan scope / number of findings / distribution by category / distribution by risk / which items are recommended to do first / which items to be cautious about
- Checklist items(one block per item): field order and hard constraints are in
reference/scan-checklist-format.md
Hand the whole thing to the user;the user checks ✓ / ✗(write the reason for ✗) then proceed to stage 2.Don't check boxes on the user's behalf。
Stage 2: design
Input
- The user-checked
{slug}-scan.md - method library (each checked item must map to a method number M-Ln-NN, including architecture deepening methods)
What to do
- Order them—checked items with dependencies go first (L1's Parallel Change usually runs first; L2's extraction follows after). For independent ones, prioritize "low risk + AI can self-verify"; put HUMAN verification items later and handle them in batches
- Add execution details to each item: method number / steps / preconditions / exit signal / verification owner (AI / HUMAN) / rollback strategy
- Identify prerequisite dependencies—items with insufficient test coverage are preceded by "add characterization tests"; changes to public interfaces are preceded by "search for callers"
- Overall review: submit the full draft to the user; after approval,
status: approved - extract checklist: steps correspond to execution order; checks correspond to each step's exit signal
design file structure
---
doc_type: refactor-design
refactor: {YYYY-MM-DD}-{slug}
status: draft | approved
scope: {扫描范围一句话}
summary: {本次要做的几条是什么,一句话}
---
# {slug} refactor design
## 1. 本次范围
- 从 scan 勾选了哪几条(编号)
- 明确不做的(被 ✗ 的)和理由
- 预估总工作量 / 总风险档位
## 2. 前置依赖
- 测试覆盖补齐(如需)
- 调用方搜索(如需)
- 其他一次性准备
## 3. 执行顺序
按步骤列,每步一块:
- 步骤 N:{一句话动作}
- 引用方法:M-Ln-NN {方法名}
- 具体操作:{照方法库步骤落到本项目具体文件 / 函数}
- 退出信号:{AI 跑什么测试 / HUMAN 看什么页面}
- 验证责任:AI 自证 | HUMAN
- 回滚:{出问题怎么还原,通常 git revert 某步}
## 4. 风险与看点
- 高风险步骤汇总
- 容易出错的点(跨步骤数据流变化等)
Phase 3: apply
Guiding rules
- One step at a time, no batching——strictly follow the checklist order; do not start the next step until the current step is complete
- Verify after each step:
- AI self-verification: run the specified tests / type checks / lint / grep for no leftover old references. If it passes, record apply-notes and continue
- HUMAN verification:Stopreport "Step N is complete, please visually confirm on {specific page / action}; I'll continue after you confirm." Do not proceed unless the user explicitly says "continue"
- Record deviations on the spot——when something the plan didn't account for is discovered during execution (e.g., there's a caller inside a dynamic import),stop and report, don't improvise. After aligning with the user, append to apply-notes; if necessary, go back to Phase 2 and revise the design
- Behavior-equivalence self-check——at the end of each step, additionally ask "could this step have changed externally observable behavior?" If in doubt, roll back that step
apply-notes format
---
doc_type: refactor-apply-notes
refactor: {YYYY-MM-DD}-{slug}
---
# {slug} apply notes
## 步骤 1: {动作}
- 完成时间: {date}
- 改动文件: {file list}
- 验证结果: {测试输出 / HUMAN 确认语录}
- 偏离: {无 / 具体描述}
## 步骤 2: ...
After everything is complete
- After completion, first enter
cs-code-reviewfor an independent diff review; do not proceed to commit until Critical/Important are zeroed out; the authority to initiate scoped-commit belongs tocs-code-review - Run the full test suite + type checks + lint
- For the last time, ask the user for an overall visual confirmation (frontend: open the main pages and click around)
- After confirmation passes, wrap up with a commit, and reference the refactor directory in the message
Exit conditions
- The scan pre-check has been run, hits have been routed, and only non-hits proceed to scan
-
{slug}-scan.mdThe user has checked (✓/✗) - Every checked item in the design maps to a method number
- The design has passed the user's overall review
status: approved - checklist.yaml has been generated and passed
validate-yaml.py - Every apply step has a verification record (AI self-verification with logs attached, HUMAN with the user's confirmation quote attached)
- Full tests / type checks / lint pass
- The user's final visual confirmation passes
Common pitfalls
- AI forcing a checklist——when the pre-check clearly hits but it finds excuses to bypass it, and scans out a bunch of "the code could be more elegant" items with no quantified problems
- Smuggling in behavior changes——"incidentally fixed a bug / improved the copy" in the middle of refactoring——split it into a separate issue or feature
- Merging actions across steps——doing 2-3 steps in one commit, losing the ability to "roll back a single step"
- Listing taste items in the checklist——naming preferences / quotes / arrow functions vs function——put them in decisions
- Scanning a large module and getting straight to work——entering scan with > 15 files / > 3000 lines without splitting, producing a long checklist that can't be decided on
- Skipping HUMAN verification items yourself——the AI can't see frontend effects, so "type checks passed" cannot replace manual visual inspection
- Pushing ahead with insufficient coverage——directly modifying modules without tests; "behavior equivalence" is just a verbal promise
Boundaries with adjacent workflows
- feature: adding new capabilities / changing requirements. If "incidentally implement X" comes up during refactor, stop and split it out
- issue: fixing bugs / behavior is wrong. Bugs found during refactor are recorded as new issues, not fixed secretly
- decisions: Whole-project long-term constraints ("use composable from now on", "disable mixin"). A refactor may reference existing decisions but does not produce decisions
- architecture: Re-drawing cross-module boundaries / layering adjustments. A single refactor does not cross modules; crossing modules must be split into "update architecture + record decision + N module-level refactors"
- tricks / learning: Techniques discovered during the refactor → tricks; pitfalls encountered → learning
Related documents
cs-refactor-ff/SKILL.md— Ultra-lightweight channel for small refactorsreference/scan-checklist-format.md— scan checklist item fields / order / hard constraintsreference/refusal-routing.md— 7 pre-scan checks + routing tablereference/methods.md— Method library (L1-L3)reference/methods-l4.md— Method library (L4 performance and async)reference/methods-architecture.md— Method library (architecture deepening).codestable/reference/shared-conventions.md— Shared conventions across workflows