Steer focus: Refactor & Structural Improvement
Prioritize code quality, structure, and maintainability across this scenario’s implementation.
Do not change the intended behavior, regress tests, or weaken safety guarantees; all changes must maintain or improve completeness.
Focus on producing a cleaner, clearer, easier-to-extend codebase, guided by the following principles:
Required reading:
prompt-manager skills read knowledge-observatory-tools
**1. Preserve Behavior & Intent**
- Read the
problemsdoc for{{TARGET}}usingknowledge-observatory-toolsto understand existing tech debt.
- Treat existing passing tests, the PRD, and operational targets as the source of truth for behavior.
- Refactor in ways that preserve external behavior:
- same user-visible workflows and outcomes
- same API contracts, validation rules, and side effects
- Do not relax tests or assertions to “make refactors pass.” If you must adjust tests, ensure the new expectations are more accurate to the PRD, not looser.
**2. Improve Code Structure & Readability**
- Shorten or simplify overly long functions, components, or modules by extracting well-named helpers.
- Improve naming so that functions, variables, components, and files clearly express their purpose.
- Group related logic together and separate unrelated concerns:
- move cohesive logic into shared utilities where appropriate
- keep modules focused and well-scoped
- Prefer code that is self-explanatory over code that needs heavy comments to be understood.
**3. Reduce Duplication & Complexity**
- Identify duplicated logic and consolidate it into shared, reusable abstractions where it genuinely reduces complexity.
- Reduce unnecessary branching and deeply nested conditionals; favor early returns, clear guard clauses, and simple control flow.
- Eliminate dead code, unused props/parameters, unneeded indirection, and obsolete TODOs that are no longer relevant.
- Avoid over-engineering: do not introduce abstractions that aren’t clearly justified by current or near-term needs.
**4. Align with Existing Patterns & Architecture**
- Follow the established patterns, conventions, and architectural decisions already present in this scenario.
- Do not introduce new major frameworks, state management libraries, or architectural styles during this phase.
- Do not migrate technologies (e.g., switching UI frameworks, build tools, or data layers).
- When in doubt, extend and refine what exists rather than inventing an entirely new structure.
**5. Strengthen Tests & Safety (Without Gaming Metrics)**
- Where refactors touch important behavior, add or tighten tests to lock in the improved structure and prevent regressions.
- Prefer meaningful tests that cover realistic flows over trivial or redundant tests added solely to increase scores.
- Do not remove tests unless they are truly redundant or incorrect; when you remove or replace a test, ensure the behavior it covered is still validated.
**6. Scope & Change Size**
- Prefer small, coherent refactors that can be understood and reviewed as a single, logical improvement.
- Focus on high-leverage areas:
- core flows
- shared utilities
- heavily reused components or modules
- Avoid broad, cosmetic renames or mass edits that don't significantly improve clarity, structure, or safety.
**7. Memory Management with Tidiness Manager**
To ensure systematic coverage without repetition, use tidiness-manager to get intelligent refactor recommendations combining visited-tracker data with code quality metrics.
At the start of each iteration:
# Get 5 top-priority files (auto-scans if needed)
# Priority score combines: staleness + length + complexity + tech debt + missing tests
tidiness-manager recommend-refactors {{TARGET}} \
--limit 5 \
--sort-by priority \
--min-lines 50
# For scripting (returns just file paths, one per line):
tidiness-manager recommend-refactors {{TARGET}} \
--limit 5 \
--format paths
# Alternative sort options for specific improvement targets:
# --sort-by complexity # For reducing cyclomatic complexity
# --sort-by length # For breaking down long files
# --sort-by staleness # For unvisited/stale files (equivalent to visited-tracker)
# --sort-by duplication # For removing code duplication
Output formats:
--format detailed(default): Human-readable with all metrics--format paths: Just file paths, one per line (easy for shell loops)--format json: Raw JSON for programmatic processing
Output includes enriched data:
- File path, language, and line count
- Visit count and staleness score (from visited-tracker integration)
- Code quality metrics: TODO/FIXME/HACK counts, function counts, comment ratios
- Test file indicator (has_test_file: true if file has tests or is a test file)
- Optional: complexity and duplication metrics (when external analysis tools are available)
- Composite refactor priority score
After analyzing each file:
# Record your visit with specific notes about improvements and remaining work
tidiness-manager visit <file-path> \
--scenario {{TARGET}} \
--note "<summary of refactorings made and what remains>"
When a file is irrelevant to refactoring (config, build scripts, generated files, etc.):
# Mark it excluded so it doesn't resurface - this is NOT a refactor target
tidiness-manager exclude <file-path> \
--scenario {{TARGET}} \
--reason "Not a refactor target - config/generated/tooling/etc."
When a file is fully refactored:
# Mark it excluded so it doesn't resurface in future queries
tidiness-manager exclude <file-path> \
--scenario {{TARGET}} \
--reason "All refactoring complete - clean structure, clear naming, no duplication"
Before ending your session:
# Add campaign note for handoff context to the next iteration
tidiness-manager campaign-note \
--scenario {{TARGET}} \
--note "<overall progress summary, patterns observed, priority areas for next iteration>"
Interpreting the response:
- staleness_score scale: Unvisited files = 1000, visited files = 0-100 (higher = more stale)
- 1000: Never visited (highest priority for new files)
- 50-100: Stale visited files (neglected, need attention)
- 10-50: Moderately fresh (visited recently enough)
- 0-10: Recently visited (lowest staleness)
- Prioritize files with high refactor_priority - composite score combining staleness, length, complexity, tech debt
- Focus on low visit_count (0-2) - files not yet analyzed
- Review notes from previous visits - understand context and remaining work
Note format guidelines:
- File notes: Be specific about what you refactored and what still needs work
- ✅ Good: "Extracted 3 helpers, improved naming, removed duplication. Still need to simplify nested conditionals in handleSubmit."
- ❌ Bad: "Made some refactoring improvements"
- Campaign notes: Provide strategic context for the next agent
- ✅ Good: "Completed 14/38 files (37%). Focus areas: API layer has inconsistent error handling patterns, UI utils have significant duplication"
- ❌ Bad: "Made progress on refactoring"
**8. Output Expectations**
You may update:
- module boundaries and file organization
- function/component structure and naming
- shared utilities and helpers
- error handling and edge-case handling
- test organization and coverage (when supporting refactors)
You must:
- keep the scenario fully functional and aligned with its PRD
- avoid regressions and weakened safety
- leave the code simpler, clearer, and easier to change
- avoid gaming metrics or making superficial changes that don't materially improve structure
Focus this loop on delivering practical, targeted refactors that reduce complexity, remove duplication, and improve clarity, so future loops (and agents) can build on a stronger foundation.
**9. Documentation**
Use knowledge-observatory-tools to read the current problems doc for {{TARGET}}, then update the Tech Debt section with your findings (high-leverage refactoring targets, duplication patterns, refactors completed, remaining structural issues).