Refactor
Overview
Optional quality step on completed features. Not a status-gate — features are DONE after /game-verify. This skill improves code structure, naming, and patterns on already-finished features.
Batch-first architecture: analyzes ALL features in parallel via Explore agents, triages clean vs dirty, generates GDScript-aware refactor patterns via Context7, creates one combined plan with one approval, and applies changes with per-feature rollback.
Trigger: /game-refactor or /game-refactor {feature-name}
Copied & pre-adapted for game-ship. When run by game-ship PHASE 4 (AGENT 3), this tree executes
as a non-interactive subagent under references/non-interactive-contract.md — that adapter
blanket-overrides the machinery below: no TaskCreate/TaskUpdate, no EnterPlanMode, no
AskUserQuestion (the PHASE 3 plan is auto-approved with scope "Apply everything"), headless GUT
test-guard (revert-on-red), single-feature scope, pre-merge in the feature worktree — never
merge. Do not
blind-sync.
Scope Rule: Feature Files Only
This skill ONLY refactors files that belong to the feature.
- Extract all code file paths from
feature.json → files[] — these are the pipeline files
- ONLY these files may be analyzed, planned, and modified
- NEVER touch, scan, plan, or modify files outside this list
- Valid path patterns:
scripts/, scenes/, resources/, tests/
- Exception: New utility/helper scripts may be created if they exclusively extract code from pipeline files (e.g., extracting shared logic into a new
utils/ script). Existing external files may NEVER be modified.
- If a pattern scan or research finding points to an external file — skip it, do not include in plan
- If a DRY violation spans a pipeline file and an external file — only refactor the pipeline file side
This rule exists because refactoring external files risks breaking other features and creates unpredictable side effects.
When to Use
- After
/game-verify completes (features in DONE status)
- When
.project/features/{name}/feature.json exists with tests section
- NOT for: fixing bugs (/game-verify), adding features (/game-define), planning (/project-plan)
Input
Reads .project/features/{feature-name}/feature.json: requirements, files, build, tests sections.
Output Structure
.project/features/{feature-name}/
└── feature.json # Enriched with refactor section (status, improvements, decisions)
Two Research Layers
.claude/research/
├── architecture-baseline.md ← EXISTING: Godot patterns, scene architecture, conventions
│ Read in PHASE 2 for research decision
│
└── refactor-patterns.md ← NEW: GDScript-specific code smells & anti-patterns
Generated via Context7 on first refactor
Reused on subsequent refactors
architecture-baseline.md = "how to use Godot/GDScript correctly" (conventions)
refactor-patterns.md = "what mistakes to look for in GDScript code" (anti-patterns)
Workflow
Phase tracking — first action of the skill: call TaskCreate with these 6 items (status pending), then use TaskUpdate to set each phase in_progress at start and completed at end. During context compaction the task list remains visible — no risk of forgotten phases.
- PHASE 0: Batch Context Loading + Refactor Patterns
- PHASE 1: Parallel Batch Analysis + Triage
- PHASE 2: Aggregated Research Decision
- PHASE 3: Combined Plan + Single Approval
- PHASE 4: Apply + Test Per Feature
- PHASE 5: Batch Completion (feature.json writes → learnings (patterns + pitfalls) → sync → commit → archive)
PHASE 0: Batch Context Loading + Refactor Patterns
Todo: call ToolSearch query="select:TaskCreate,TaskUpdate" first — both tools are deferred and unusable without their schemas. Then call TaskCreate with the 6 phase items (see above). Mark PHASE 0 → in_progress via TaskUpdate. If the tools didn't resolve, skip seeding and continue.
Read backlog for pipeline status:
Backlog load: node ~/.claude/scripts/backlog-load.js "$REPO" game-queue DONE refactoring → { backlogPresent, items } (see shared/GAME-BACKLOG-LOAD.md). Auto-select first entry with transition === "refactoring" — pre-select. Fallback: re-run with no transition arg (game-queue DONE) to list all DONE features.
- For each DONE feature, check
.project/features/{name}/feature.json for existing refactor section
- Categorize:
unrefactored (no refactor section) vs refactored (has refactor section)
Determine feature queue:
Todo: Read .claude/skills/game-ship/references/game-refactor/references/queue-selection.md for scope selection logic (a/b/c paths + codebase mode).
Team-mode batch guard — after the queue is built, before step 3:
If TEAM_MODE == "team" AND (feature_queue.length > 1 OR codebase-mode) → follow shared/PROJECT-MODE.md § Team-mode batch guard.
Worktree switch (single-mode only):
If feature_queue.length == 1 and not in codebase-mode: execute the procedure in shared/WORKTREE.md with the feature-name. Automatically switches to worktree-{feature-name} if it exists. On FAIL: stop with the message from WORKTREE.md.
Todo: follow shared/WORKTREE.md → Symlink Integrity Gate (post-switch auto-repair).
Load feature.json for every feature in queue:
For each feature: node ~/.claude/scripts/context-load.js "$REPO" game-feature-verify "{feature-name}" (see shared/GAME-FEATURE-LOAD.md). Extracts: requirements[] (with tuningLevers), files[], checklist[], design, build. Use requirements[] for architecture analysis, files[] for file list, checklist[] to check verification coverage. Full architecture is available from the game-build profile (step 6).
present: false → remove from queue and warn.
Build pipeline files list per feature:
For each feature, extract all code file paths from feature.json → files[]:
- Primary: parse
files[].path from feature.json
- Fallback: grep for file paths matching
scripts/, scenes/, resources/, tests/
- Store as
pipeline_files[feature_name]
Load project conventions + learnings (for Explore agent context):
Project context load: node ~/.claude/scripts/context-load.js "$REPO" game-build (see shared/GAME-CONTEXT-LOAD.md) — use the projectContext half of the output only. Extracts: structure, patterns (max 15), full architecture. Store patterns as PROJECT_CONVENTIONS and architecture as scene-graph context for injection into Explore agent prompts (PHASE 1).
Conventions status check (see shared/CONVENTIONS.md): head -1 .project/conventions.md → set → store conventions_set = true for the PHASE 1 agent prompt (agents read the file themselves). none or absent → skip silently — no elicitation here (that lives in core-setup + dev-ship's refactor phase).
Learnings load via shared/LEARNINGS-LOAD.md:
scopes: [component]
pitfall-prefix: true
current-feature: <feature-name if feature-mode, otherwise "none">
Store as KNOWN_PITFALLS for injection into Explore agent prompts (PHASE 1) — prevents reintroduction of known Godot/GDScript bugs and helps agents distinguish between "intentional project pattern" and "code smell".
Load or generate refactor-patterns.md:
IF .claude/research/refactor-patterns.md exists:
→ Load cached patterns, skip Context7
→ Log: "Refactor patterns loaded (cached)"
IF NOT exists:
→ Context7 resolve-library-id for Godot/GDScript
→ Context7 query-docs:
"Common code smells, anti-patterns, and refactoring opportunities
in GDScript/Godot 4 projects. Focus on: performance pitfalls,
signal misuse, scene tree anti-patterns, memory leaks, and
code organization issues."
→ Compile results into .claude/research/refactor-patterns.md
→ Log: "Refactor patterns generated via Context7 (Godot/GDScript)"
Format for refactor-patterns.md:
# Refactor Patterns
<!-- Generated via Context7 for: Godot 4.x / GDScript -->
<!-- Regenerate: delete this file and run /game-refactor -->
## Performance Anti-patterns
- {pattern}: {description} — {what to look for in code}
## Signal Anti-patterns
- {pattern}: {description} — {what to look for in code}
## Scene Tree Anti-patterns
- {pattern}: {description} — {what to look for in code}
## Memory Management Anti-patterns
- {pattern}: {description} — {what to look for in code}
## Code Organization Anti-patterns
- {pattern}: {description} — {what to look for in code}
Output:
BATCH CONTEXT LOADED
| Metric | Value |
|--------|-------|
| Features in queue | {N} |
| Total pipeline files | {sum across all features} |
| Refactor patterns | {cached / generated via Context7} |
Features:
{for each feature:}
- {name}: {M} pipeline files
→ Starting parallel analysis...
Capture git baseline (for scoped commit at end of skill):
mkdir -p .project/session
git status --porcelain | sort > .project/session/pre-skill-status.txt
echo '{"skill":"refactor"}' | node ~/.claude/scripts/ship-checkpoint.js signal {feature-name}
PHASE 1: Parallel Batch Analysis + Triage
Todo: mark PHASE 0 → completed, PHASE 1 → in_progress.
Goal: Analyze ALL features in parallel, then triage into CLEAN vs HAS_FINDINGS.
Todo: Read .claude/skills/game-ship/references/game-refactor/references/analysis-prompt.md for the full Godot scan template, agent prompt, parsing instructions, triage logic, and output format.
Enter Plan Mode (conditional, after triage) — only when ≥1 feature is HAS_FINDINGS: follow shared/PLAN-MODE.md Entry protocol now. PHASE 2 + PHASE 3 run in plan mode because the fix plan is a reviewable artefact whose rejection changes what happens next — a genuine approval gate, not a model-routing device. All-CLEAN runs never enter plan mode — proceed to PHASE 5 directly, zero approval friction. Skip the call if plan mode is already active (see PLAN-MODE.md skip-check). All file writes (refactor-patterns.md appends, source changes, .project/ mutations) wait until after ExitPlanMode at the end of PHASE 3.
PHASE 2: Aggregated Research Decision
Todo: mark PHASE 1 → completed, PHASE 2 → in_progress.
Goal: One research decision for all affected features combined (not per-feature).
Steps:
Aggregate architecture info from all HAS_FINDINGS features:
- Collect all Godot systems mentioned in ARCHITECTURE sections
- Collect patterns and scene structures
- Identify areas not covered by architecture-baseline.md or refactor-patterns.md
Read architecture baseline:
- Read
.claude/research/architecture-baseline.md (if exists)
- Note which Godot patterns/systems are already documented
Decide: is Context7 research needed?
| Signal |
Research needed? |
| Architecture baseline + refactor-patterns cover all systems |
NO |
| Findings are concrete, directly actionable |
NO |
| Complex Godot system usage not in baseline (shaders, networking, etc.) |
YES — research those systems |
| Advanced signal/scene patterns |
YES — research Godot patterns |
| No architecture baseline exists at all |
YES — research core Godot patterns |
If research NOT needed — proceed directly to PHASE 3.
If research needed — spawn one Explore agent (subagent_type: Explore, model: "sonnet", thoroughness: "very thorough") to research Godot patterns in an isolated context. This keeps Context7 results out of the main session.
Determine which research domains to include based on findings:
| Domain |
Include when |
| Godot patterns |
Complex scene architecture, signal design, state machines |
| Performance |
_process bottlenecks, physics optimization, draw calls |
| Resource management |
Memory management, resource loading strategies |
Agent prompt — include only domains identified as needed:
Research Godot 4.x best practices for a refactoring task.
Architecture baseline: {from architecture-baseline.md, or "none"}
Aggregated analysis:
{ANALYSIS_START..ANALYSIS_END blocks from all HAS_FINDINGS features}
{If godot patterns domain needed:}
GODOT PATTERNS:
- resolve-library-id for Godot → query-docs
- Focus: scene composition, signal patterns (signals up, methods down), state machines, component pattern, typed GDScript
{If performance domain needed:}
PERFORMANCE:
- Focus: _process vs _physics_process optimization, draw call reduction, physics layer usage, object pooling
{If resource management domain needed:}
RESOURCE MANAGEMENT:
- Focus: ResourceLoader, preload vs load, custom Resources, memory management, scene instancing
Also read: .claude/skills/game-ship/references/game-build/techniques/architecture-decisions.md for decision tree context.
RETURN FORMAT:
RESEARCH_START
Godot patterns: {3-5 bullet points: scene architecture, signals, state machines}
Performance: {3-5 bullet points: optimization patterns, bottleneck fixes}
Resource management: {3-5 bullet points: loading strategies, memory patterns}
RESEARCH_END
Only include sections for domains you were asked to research.
If uncovered patterns found — also gather material for refactor-patterns.md:
- Context7 query for each uncovered Godot system
- Collect the new sections in memory as
pendingPatternAppends — plan mode blocks the refactor-patterns.md write; PHASE 5 appends them during completion (see references/completion-batch.md)
Output:
Parse the agent's RESEARCH_START...END block. Display:
RESEARCH DECISION
| Source | Coverage |
|--------|----------|
| architecture-baseline.md | {list of documented patterns} |
| refactor-patterns.md | {list of covered anti-patterns} |
| Uncovered | {list or "none"} |
{if no research:}
Research: Skipped (existing knowledge sufficient)
{if research:}
Research: Explore agent ({domains researched})
Refactor patterns queued for PHASE 5 update: {yes/no}
→ Ready for combined plan.
PHASE 3: Combined Plan + Single Approval
Todo: mark PHASE 2 → completed, PHASE 3 → in_progress.
Goal: One plan combining ALL findings from ALL affected features, one user approval.
Steps:
Create ranked improvements list:
Combine all findings from all HAS_FINDINGS features:
- Cross-feature deduplication: same pattern in multiple files — 1 plan item with multiple locations
- Each improvement gets impact level: HIGH / MED / LOW
- Sort: HIGH first (security, memory leaks), then MED (performance, DRY, signals), then LOW (clarity, typing)
- Only pipeline files may be included
- Group by feature for clarity
Write the plan to the plan file (path from the plan-mode system-reminder received at the PHASE 1 conditional entry). In chat show only a short progress marker (e.g. Plan written: {M} improvements across {N} features. Plan file updated.) — no chat dump. Plan-file format:
REFACTOR PLAN ({N} features, {M} improvements)
HIGH: [X] improvements (security, memory leaks)
MED: [Y] improvements (performance, DRY, signals, scene tree)
LOW: [Z] improvements (clarity, typing, code quality)
-- {feature-1} --
1. HIGH {file}:{line} — {issue} → {fix}
Before: {code snippet}
After: {proposed change}
2. MED {file}:{line} — {issue} → {fix}
Before: {code snippet}
After: {proposed change}
-- {feature-2} --
3. MED {file}:{line} — {issue} → {fix}
...
──────────────────
Files to be modified: [count]
- {file1} ([N] changes) — {feature}
- {file2} ([M] changes) — {feature}
Per-feature rollback: YES (feature A succeeds, B fails → only B rolled back)
Ask for scope (1 AskUserQuestion for all features):
Use AskUserQuestion tool:
- header: "Scope"
- question: "Which improvements do you want to apply? ({M} total across {N} features)"
- options:
- label: "Apply everything (Recommended)", description: "All {M} improvements in {N} features"
- label: "HIGH + MED only", description: "{X+Y} improvements, skip LOW"
- label: "HIGH only", description: "{X} improvements, security/memory only"
- label: "Choose per feature", description: "Select which improvements to apply per feature"
- multiSelect: false
If "Choose per feature" — show per-feature AskUserQuestion with multiSelect:
- header: "Features"
- question: "Which features do you want to refactor?"
- options: one per feature with finding count
- multiSelect: true
Only approved features proceed to PHASE 4. Non-selected features get CLEAN status.
The user can also type "Cancel" via the built-in "Other" option — EXIT with "Refactor cancelled by user"
Exit plan mode: record the chosen scope in the plan file (one line under the plan, e.g. Scope chosen: HIGH + MED ({X+Y} improvements)), then follow shared/PLAN-MODE.md Exit protocol — ExitPlanMode presents the plan for approval. After approval the skill continues with PHASE 4. Rejected plan → re-ask scope (back to step 3) or exit with "Refactor cancelled by user".
PHASE 4: Apply + Test Per Feature
Todo: mark PHASE 3 → completed, PHASE 4 → in_progress. Read .claude/skills/game-ship/references/game-refactor/references/apply-rollback.md for priority order, per-feature apply + GUT test + rollback steps.
PHASE 5: Batch Completion
Todo: mark PHASE 4 → completed, PHASE 5 → in_progress. Read .claude/skills/game-ship/references/game-refactor/references/completion-batch.md for full batch completion steps.
Todo: mark PHASE 5 → completed.
Error Handling
Todo: Read .claude/skills/game-ship/references/game-refactor/references/error-handling.md for all error scenarios and recovery steps.
Restrictions
This skill must NEVER:
- Read pipeline source files directly in the main conversation (always use Explore agent)
- Pass full file contents to research agents (pass structured analysis from Explore agent)
- Analyze, plan, or modify files outside pipeline_files (extracted from feature.json files[])
- Include external file findings in any plan
- Proceed without existing feature.json with tests section
- Make breaking changes (signal signatures, exported variables, public methods)
- Over-simplify code by removing helpful abstractions or combining too many concerns
- Prioritize fewer lines over readability (explicit > compact)
- Create "clever" solutions that are hard to understand or debug
- Skip user approval at PHASE 3 (unless 0 findings across all features)
- Skip GUT test verification in PHASE 4
- Proceed if tests fail without analyzing failure type first (stale test vs regression)
- Apply improvements without user scope selection
- Run Explore agents sequentially when multiple features are in the queue (use parallel)
- Create disproportionate documentation for clean features
This skill must ALWAYS:
- Enforce the pipeline_files scope boundary at every phase
- Launch Explore agents in parallel for batch analysis (
model: "sonnet" each, max 10 concurrent)
- Triage features into CLEAN vs HAS_FINDINGS after analysis
- Early-exit CLEAN features (skip PHASE 2-4)
- Use refactor-patterns.md for GDScript-aware analysis (generate on first run, cache thereafter)
- Aggregate research decisions across all features (1 decision, not N)
- Present ONE combined plan with ONE user approval for all features
- Deduplicate cross-feature findings (same pattern — 1 plan item)
- Apply per-feature rollback (feature A succeeds, feature B fails — only B rolled back)
- Write proportional documentation (compact for CLEAN, full for REFACTORED)
- Make a single commit for all features
- Re-read each file immediately before editing (prevents "File has not been read yet" errors)
- Group edits by file: read file — apply ALL edits for that file — next file
- Run full GUT test suite after applying changes per feature
- Analyze test failures before rollback (distinguish stale tests from regressions)
- Apply balance filter: skip findings where the "fix" reduces readability
- Check CLAUDE.md,
.project/project.json, and .project/project-context.json for project-specific conventions during analysis
1---2name: game-refactor3description: Batch refactor Godot code quality after testing. Use with /game-refactor.4---56# Refactor78## Overview910Optional quality step on completed features. Not a status-gate — features are DONE after `/game-verify`. This skill improves code structure, naming, and patterns on already-finished features.1112Batch-first architecture: analyzes ALL features in parallel via Explore agents, triages clean vs dirty, generates GDScript-aware refactor patterns via Context7, creates one combined plan with one approval, and applies changes with per-feature rollback.1314**Trigger**: `/game-refactor` or `/game-refactor {feature-name}`1516> **Copied & pre-adapted for game-ship.** When run by game-ship PHASE 4 (AGENT 3), this tree executes17> as a **non-interactive subagent** under `references/non-interactive-contract.md` — that adapter18> **blanket-overrides** the machinery below: no `TaskCreate`/`TaskUpdate`, no `EnterPlanMode`, no19> `AskUserQuestion` (the PHASE 3 plan is auto-approved with scope "Apply everything"), headless GUT20> test-guard (revert-on-red), single-feature scope, pre-merge in the feature worktree — **never21> merge**. Do not22> blind-sync.2324## Scope Rule: Feature Files Only2526**This skill ONLY refactors files that belong to the feature.**2728- Extract all code file paths from `feature.json` → `files[]` — these are the **pipeline files**29- ONLY these files may be analyzed, planned, and modified30- **NEVER** touch, scan, plan, or modify files outside this list31- Valid path patterns: `scripts/`, `scenes/`, `resources/`, `tests/`32- **Exception:** New utility/helper scripts may be **created** if they exclusively extract code from pipeline files (e.g., extracting shared logic into a new `utils/` script). Existing external files may NEVER be modified.33- If a pattern scan or research finding points to an external file — skip it, do not include in plan34- If a DRY violation spans a pipeline file and an external file — only refactor the pipeline file side3536This rule exists because refactoring external files risks breaking other features and creates unpredictable side effects.3738## When to Use3940- After `/game-verify` completes (features in DONE status)41- When `.project/features/{name}/feature.json` exists with `tests` section42- NOT for: fixing bugs (/game-verify), adding features (/game-define), planning (/project-plan)4344## Input4546Reads `.project/features/{feature-name}/feature.json`: requirements, files, build, tests sections.4748## Output Structure4950```51.project/features/{feature-name}/52└── feature.json # Enriched with refactor section (status, improvements, decisions)53```5455## Two Research Layers5657```58.claude/research/59├── architecture-baseline.md ← EXISTING: Godot patterns, scene architecture, conventions60│ Read in PHASE 2 for research decision61│62└── refactor-patterns.md ← NEW: GDScript-specific code smells & anti-patterns63 Generated via Context7 on first refactor64 Reused on subsequent refactors65```6667**architecture-baseline.md** = "how to use Godot/GDScript correctly" (conventions)68**refactor-patterns.md** = "what mistakes to look for in GDScript code" (anti-patterns)6970## Workflow7172**Phase tracking** — first action of the skill: call `TaskCreate` with these 6 items (status `pending`), then use `TaskUpdate` to set each phase `in_progress` at start and `completed` at end. During context compaction the task list remains visible — no risk of forgotten phases.73741. PHASE 0: Batch Context Loading + Refactor Patterns752. PHASE 1: Parallel Batch Analysis + Triage763. PHASE 2: Aggregated Research Decision774. PHASE 3: Combined Plan + Single Approval785. PHASE 4: Apply + Test Per Feature796. PHASE 5: Batch Completion (feature.json writes → learnings (patterns + pitfalls) → sync → commit → archive)8081### PHASE 0: Batch Context Loading + Refactor Patterns8283> **Todo**: call `ToolSearch query="select:TaskCreate,TaskUpdate"` first — both tools are deferred and unusable without their schemas. Then call `TaskCreate` with the 6 phase items (see above). Mark PHASE 0 → `in_progress` via `TaskUpdate`. If the tools didn't resolve, skip seeding and continue.84851. **Read backlog for pipeline status:**8687 Backlog load: `node ~/.claude/scripts/backlog-load.js "$REPO" game-queue DONE refactoring` → `{ backlogPresent, items }` (see [shared/GAME-BACKLOG-LOAD.md](../shared/GAME-BACKLOG-LOAD.md)). Auto-select first entry with `transition === "refactoring"` — pre-select. Fallback: re-run with no transition arg (`game-queue DONE`) to list all DONE features.88 - For each DONE feature, check `.project/features/{name}/feature.json` for existing `refactor` section89 - Categorize: `unrefactored` (no refactor section) vs `refactored` (has refactor section)90912. **Determine feature queue:**9293 > **Todo**: Read `.claude/skills/game-ship/references/game-refactor/references/queue-selection.md` for scope selection logic (a/b/c paths + codebase mode).9495 **Team-mode batch guard** — after the queue is built, before step 3:96 If `TEAM_MODE == "team"` AND (`feature_queue.length > 1` OR codebase-mode) → follow `shared/PROJECT-MODE.md § Team-mode batch guard`.97983. **Worktree switch** (single-mode only):99100 If `feature_queue.length == 1` and not in codebase-mode: execute the procedure in `shared/WORKTREE.md` with the feature-name. Automatically switches to `worktree-{feature-name}` if it exists. On FAIL: stop with the message from WORKTREE.md.101102 > **Todo**: follow `shared/WORKTREE.md → Symlink Integrity Gate (post-switch auto-repair)`.1031044. **Load feature.json for every feature in queue:**105106 For each feature: `node ~/.claude/scripts/context-load.js "$REPO" game-feature-verify "{feature-name}"` (see [shared/GAME-FEATURE-LOAD.md](../shared/GAME-FEATURE-LOAD.md)). Extracts: `requirements[]` (with tuningLevers), `files[]`, `checklist[]`, `design`, `build`. Use `requirements[]` for architecture analysis, `files[]` for file list, `checklist[]` to check verification coverage. Full `architecture` is available from the `game-build` profile (step 6).107108 `present: false` → remove from queue and warn.1091105. **Build pipeline files list per feature:**111112 For each feature, extract all code file paths from `feature.json` → `files[]`:113 - Primary: parse `files[].path` from feature.json114 - Fallback: grep for file paths matching `scripts/`, `scenes/`, `resources/`, `tests/`115 - Store as `pipeline_files[feature_name]`1161176. **Load project conventions + learnings** (for Explore agent context):118119 Project context load: `node ~/.claude/scripts/context-load.js "$REPO" game-build` (see [shared/GAME-CONTEXT-LOAD.md](../shared/GAME-CONTEXT-LOAD.md)) — use the `projectContext` half of the output only. Extracts: `structure`, `patterns` (max 15), full `architecture`. Store `patterns` as `PROJECT_CONVENTIONS` and `architecture` as scene-graph context for injection into Explore agent prompts (PHASE 1).120121 **Conventions status check** (see [shared/CONVENTIONS.md](../shared/CONVENTIONS.md)): `head -1 .project/conventions.md` → `set` → store `conventions_set = true` for the PHASE 1 agent prompt (agents read the file themselves). `none` or absent → skip silently — **no elicitation here** (that lives in core-setup + dev-ship's refactor phase).122123 **Learnings load** via [shared/LEARNINGS-LOAD.md](../shared/LEARNINGS-LOAD.md):124125 ```126 scopes: [component]127 pitfall-prefix: true128 current-feature: <feature-name if feature-mode, otherwise "none">129 ```130131 Store as `KNOWN_PITFALLS` for injection into Explore agent prompts (PHASE 1) — prevents reintroduction of known Godot/GDScript bugs and helps agents distinguish between "intentional project pattern" and "code smell".1321337. **Load or generate refactor-patterns.md:**134135 ```136 IF .claude/research/refactor-patterns.md exists:137 → Load cached patterns, skip Context7138 → Log: "Refactor patterns loaded (cached)"139140 IF NOT exists:141 → Context7 resolve-library-id for Godot/GDScript142 → Context7 query-docs:143 "Common code smells, anti-patterns, and refactoring opportunities144 in GDScript/Godot 4 projects. Focus on: performance pitfalls,145 signal misuse, scene tree anti-patterns, memory leaks, and146 code organization issues."147 → Compile results into .claude/research/refactor-patterns.md148 → Log: "Refactor patterns generated via Context7 (Godot/GDScript)"149 ```150151 **Format for refactor-patterns.md:**152153 ```markdown154 # Refactor Patterns155156 <!-- Generated via Context7 for: Godot 4.x / GDScript -->157 <!-- Regenerate: delete this file and run /game-refactor -->158159 ## Performance Anti-patterns160161 - {pattern}: {description} — {what to look for in code}162163 ## Signal Anti-patterns164165 - {pattern}: {description} — {what to look for in code}166167 ## Scene Tree Anti-patterns168169 - {pattern}: {description} — {what to look for in code}170171 ## Memory Management Anti-patterns172173 - {pattern}: {description} — {what to look for in code}174175 ## Code Organization Anti-patterns176177 - {pattern}: {description} — {what to look for in code}178 ```179180**Output:**181182```183BATCH CONTEXT LOADED184185| Metric | Value |186|--------|-------|187| Features in queue | {N} |188| Total pipeline files | {sum across all features} |189| Refactor patterns | {cached / generated via Context7} |190191Features:192{for each feature:}193- {name}: {M} pipeline files194195→ Starting parallel analysis...196```197198---199200**Capture git baseline** (for scoped commit at end of skill):201202```bash203mkdir -p .project/session204git status --porcelain | sort > .project/session/pre-skill-status.txt205echo '{"skill":"refactor"}' | node ~/.claude/scripts/ship-checkpoint.js signal {feature-name}206```207208### PHASE 1: Parallel Batch Analysis + Triage209210> **Todo**: mark PHASE 0 → `completed`, PHASE 1 → `in_progress`.211212**Goal:** Analyze ALL features in parallel, then triage into CLEAN vs HAS_FINDINGS.213214> **Todo**: Read `.claude/skills/game-ship/references/game-refactor/references/analysis-prompt.md` for the full Godot scan template, agent prompt, parsing instructions, triage logic, and output format.215216**Enter Plan Mode (conditional, after triage)** — only when ≥1 feature is HAS_FINDINGS: follow [shared/PLAN-MODE.md](../shared/PLAN-MODE.md) Entry protocol now. PHASE 2 + PHASE 3 run in plan mode because the fix plan is a reviewable artefact whose rejection changes what happens next — a genuine approval gate, not a model-routing device. All-CLEAN runs never enter plan mode — proceed to PHASE 5 directly, zero approval friction. Skip the call if plan mode is already active (see PLAN-MODE.md skip-check). All file writes (refactor-patterns.md appends, source changes, `.project/` mutations) wait until after `ExitPlanMode` at the end of PHASE 3.217218---219220### PHASE 2: Aggregated Research Decision221222> **Todo**: mark PHASE 1 → `completed`, PHASE 2 → `in_progress`.223224**Goal:** One research decision for all affected features combined (not per-feature).225226**Steps:**2272281. **Aggregate architecture info from all HAS_FINDINGS features:**229 - Collect all Godot systems mentioned in ARCHITECTURE sections230 - Collect patterns and scene structures231 - Identify areas not covered by architecture-baseline.md or refactor-patterns.md2322332. **Read architecture baseline:**234 - Read `.claude/research/architecture-baseline.md` (if exists)235 - Note which Godot patterns/systems are already documented2362373. **Decide: is Context7 research needed?**238239 | Signal | Research needed? |240 | ---------------------------------------------------------------------- | ---------------------------------- |241 | Architecture baseline + refactor-patterns cover all systems | NO |242 | Findings are concrete, directly actionable | NO |243 | Complex Godot system usage not in baseline (shaders, networking, etc.) | YES — research those systems |244 | Advanced signal/scene patterns | YES — research Godot patterns |245 | No architecture baseline exists at all | YES — research core Godot patterns |246247 **If research NOT needed** — proceed directly to PHASE 3.248249 **If research needed** — spawn one Explore agent (`subagent_type: Explore`, `model: "sonnet"`, thoroughness: "very thorough") to research Godot patterns in an isolated context. This keeps Context7 results out of the main session.250251 Determine which research domains to include based on findings:252253 | Domain | Include when |254 | ------------------- | --------------------------------------------------------- |255 | Godot patterns | Complex scene architecture, signal design, state machines |256 | Performance | \_process bottlenecks, physics optimization, draw calls |257 | Resource management | Memory management, resource loading strategies |258259 Agent prompt — include only domains identified as needed:260261 ```262 Research Godot 4.x best practices for a refactoring task.263264 Architecture baseline: {from architecture-baseline.md, or "none"}265266 Aggregated analysis:267 {ANALYSIS_START..ANALYSIS_END blocks from all HAS_FINDINGS features}268269 {If godot patterns domain needed:}270 GODOT PATTERNS:271 - resolve-library-id for Godot → query-docs272 - Focus: scene composition, signal patterns (signals up, methods down), state machines, component pattern, typed GDScript273274 {If performance domain needed:}275 PERFORMANCE:276 - Focus: _process vs _physics_process optimization, draw call reduction, physics layer usage, object pooling277278 {If resource management domain needed:}279 RESOURCE MANAGEMENT:280 - Focus: ResourceLoader, preload vs load, custom Resources, memory management, scene instancing281282 Also read: .claude/skills/game-ship/references/game-build/techniques/architecture-decisions.md for decision tree context.283284 RETURN FORMAT:285 RESEARCH_START286 Godot patterns: {3-5 bullet points: scene architecture, signals, state machines}287 Performance: {3-5 bullet points: optimization patterns, bottleneck fixes}288 Resource management: {3-5 bullet points: loading strategies, memory patterns}289 RESEARCH_END290291 Only include sections for domains you were asked to research.292 ```293294 **If uncovered patterns found** — also gather material for refactor-patterns.md:295 - Context7 query for each uncovered Godot system296 - Collect the new sections in memory as `pendingPatternAppends` — plan mode blocks the refactor-patterns.md write; PHASE 5 appends them during completion (see `references/completion-batch.md`)297298**Output:**299300Parse the agent's `RESEARCH_START...END` block. Display:301302```303RESEARCH DECISION304305| Source | Coverage |306|--------|----------|307| architecture-baseline.md | {list of documented patterns} |308| refactor-patterns.md | {list of covered anti-patterns} |309| Uncovered | {list or "none"} |310311{if no research:}312Research: Skipped (existing knowledge sufficient)313314{if research:}315Research: Explore agent ({domains researched})316Refactor patterns queued for PHASE 5 update: {yes/no}317318→ Ready for combined plan.319```320321---322323### PHASE 3: Combined Plan + Single Approval324325> **Todo**: mark PHASE 2 → `completed`, PHASE 3 → `in_progress`.326327**Goal:** One plan combining ALL findings from ALL affected features, one user approval.328329**Steps:**3303311. **Create ranked improvements list:**332333 Combine all findings from all HAS_FINDINGS features:334 - **Cross-feature deduplication**: same pattern in multiple files — 1 plan item with multiple locations335 - Each improvement gets impact level: HIGH / MED / LOW336 - Sort: HIGH first (security, memory leaks), then MED (performance, DRY, signals), then LOW (clarity, typing)337 - **Only pipeline files** may be included338 - Group by feature for clarity3393402. **Write the plan to the plan file** (path from the plan-mode system-reminder received at the PHASE 1 conditional entry). In chat show only a short progress marker (e.g. `Plan written: {M} improvements across {N} features. Plan file updated.`) — no chat dump. Plan-file format:341342 ```343 REFACTOR PLAN ({N} features, {M} improvements)344345 HIGH: [X] improvements (security, memory leaks)346 MED: [Y] improvements (performance, DRY, signals, scene tree)347 LOW: [Z] improvements (clarity, typing, code quality)348349 -- {feature-1} --350351 1. HIGH {file}:{line} — {issue} → {fix}352 Before: {code snippet}353 After: {proposed change}354355 2. MED {file}:{line} — {issue} → {fix}356 Before: {code snippet}357 After: {proposed change}358359 -- {feature-2} --360361 3. MED {file}:{line} — {issue} → {fix}362 ...363364 ──────────────────365366 Files to be modified: [count]367 - {file1} ([N] changes) — {feature}368 - {file2} ([M] changes) — {feature}369370 Per-feature rollback: YES (feature A succeeds, B fails → only B rolled back)371 ```3723733. **Ask for scope (1 AskUserQuestion for all features):**374375 Use **AskUserQuestion** tool:376 - header: "Scope"377 - question: "Which improvements do you want to apply? ({M} total across {N} features)"378 - options:379 - label: "Apply everything (Recommended)", description: "All {M} improvements in {N} features"380 - label: "HIGH + MED only", description: "{X+Y} improvements, skip LOW"381 - label: "HIGH only", description: "{X} improvements, security/memory only"382 - label: "Choose per feature", description: "Select which improvements to apply per feature"383 - multiSelect: false384385 **If "Choose per feature"** — show per-feature AskUserQuestion with multiSelect:386 - header: "Features"387 - question: "Which features do you want to refactor?"388 - options: one per feature with finding count389 - multiSelect: true390391 Only approved features proceed to PHASE 4. Non-selected features get CLEAN status.392393 The user can also type "Cancel" via the built-in "Other" option — EXIT with "Refactor cancelled by user"3943954. **Exit plan mode:** record the chosen scope in the plan file (one line under the plan, e.g. `Scope chosen: HIGH + MED ({X+Y} improvements)`), then follow [shared/PLAN-MODE.md](../shared/PLAN-MODE.md) Exit protocol — `ExitPlanMode` presents the plan for approval. After approval the skill continues with PHASE 4. Rejected plan → re-ask scope (back to step 3) or exit with "Refactor cancelled by user".396397---398399### PHASE 4: Apply + Test Per Feature400401> **Todo**: mark PHASE 3 → `completed`, PHASE 4 → `in_progress`. Read `.claude/skills/game-ship/references/game-refactor/references/apply-rollback.md` for priority order, per-feature apply + GUT test + rollback steps.402403---404405### PHASE 5: Batch Completion406407> **Todo**: mark PHASE 4 → `completed`, PHASE 5 → `in_progress`. Read `.claude/skills/game-ship/references/game-refactor/references/completion-batch.md` for full batch completion steps.408409> **Todo**: mark PHASE 5 → `completed`.410411---412413## Error Handling414415> **Todo**: Read `.claude/skills/game-ship/references/game-refactor/references/error-handling.md` for all error scenarios and recovery steps.416417## Restrictions418419This skill must NEVER:420421- Read pipeline source files directly in the main conversation (always use Explore agent)422- Pass full file contents to research agents (pass structured analysis from Explore agent)423- Analyze, plan, or modify files outside pipeline_files (extracted from feature.json files[])424- Include external file findings in any plan425- Proceed without existing feature.json with tests section426- Make breaking changes (signal signatures, exported variables, public methods)427- Over-simplify code by removing helpful abstractions or combining too many concerns428- Prioritize fewer lines over readability (explicit > compact)429- Create "clever" solutions that are hard to understand or debug430- Skip user approval at PHASE 3 (unless 0 findings across all features)431- Skip GUT test verification in PHASE 4432- Proceed if tests fail without analyzing failure type first (stale test vs regression)433- Apply improvements without user scope selection434- Run Explore agents sequentially when multiple features are in the queue (use parallel)435- Create disproportionate documentation for clean features436437This skill must ALWAYS:438439- Enforce the pipeline_files scope boundary at every phase440- Launch Explore agents in parallel for batch analysis (`model: "sonnet"` each, max 10 concurrent)441- Triage features into CLEAN vs HAS_FINDINGS after analysis442- Early-exit CLEAN features (skip PHASE 2-4)443- Use refactor-patterns.md for GDScript-aware analysis (generate on first run, cache thereafter)444- Aggregate research decisions across all features (1 decision, not N)445- Present ONE combined plan with ONE user approval for all features446- Deduplicate cross-feature findings (same pattern — 1 plan item)447- Apply per-feature rollback (feature A succeeds, feature B fails — only B rolled back)448- Write proportional documentation (compact for CLEAN, full for REFACTORED)449- Make a single commit for all features450- Re-read each file immediately before editing (prevents "File has not been read yet" errors)451- Group edits by file: read file — apply ALL edits for that file — next file452- Run full GUT test suite after applying changes per feature453- Analyze test failures before rollback (distinguish stale tests from regressions)454- Apply balance filter: skip findings where the "fix" reduces readability455- Check CLAUDE.md, `.project/project.json`, and `.project/project-context.json` for project-specific conventions during analysis