pre-refactor-test-harness
Before modularizing or refactoring a package, analyze the code for extraction points, write characterization tests for current behavior, then modularize under test protection. Use when a package has monolithic files that need to be broken into testable modules.
Best use case
pre-refactor-test-harness is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Before modularizing or refactoring a package, analyze the code for extraction points, write characterization tests for current behavior, then modularize under test protection. Use when a package has monolithic files that need to be broken into testable modules.
Teams using pre-refactor-test-harness should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/pre-refactor-test-harness/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How pre-refactor-test-harness Compares
| Feature / Agent | pre-refactor-test-harness | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Before modularizing or refactoring a package, analyze the code for extraction points, write characterization tests for current behavior, then modularize under test protection. Use when a package has monolithic files that need to be broken into testable modules.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
# Pre-Refactor Test Harness
## Rule Anchor
- `AGENTS.md` > "Test-Driven Development"
- `AGENTS.md` > "Build Requirements"
- `AGENTS.md` > "No Fallback Policy"
## Use This Skill When
- A package has monolithic files (>300 lines) with mixed responsibilities.
- User requests modularization, refactoring, or "clean up" of a package.
- About to restructure code that lacks adequate test coverage.
- **Trigger phrase patterns**: "modularize", "break up", "split into modules", "refactor [package]", "clean up [file]", "too much in one file".
## Core Principle
**Never refactor without tests. Never modularize without first proving the current behavior is captured.**
The sequence is always: **Analyze → Test → Extract → Verify**.
## Execution Steps
### Phase 1: Analysis (no code changes)
1. **Read the target files** and catalog each responsibility block:
- Pure logic (no I/O, no framework deps) → immediately extractable
- I/O operations (fs, network, process) → extract behind interface
- Framework-coupled (React hooks, state) → extract logic, leave glue
- UI rendering → test only if behavior-critical
2. **Classify each block** into a table:
| Block | Lines | Dependencies | Extractable | Test Priority |
|-------|-------|-------------|-------------|---------------|
| (name) | ~N | pure/IO/React | yes/partial/no | P1/P2/P3 |
3. **Identify extraction targets** — functions or logic that can become:
- A pure function in a new module (highest value)
- A class/module behind an interface
- A custom hook with testable logic separated
4. **Present the analysis to the user** with a proposed module structure and ask for approval before proceeding.
### Phase 2: Characterization Tests (before any refactoring)
5. **Write tests for current behavior** of each P1 extraction target:
- Test the function/logic as-is, even if inline
- If inline and untestable, write the test for the extracted signature first (RED)
- Focus on: input → output contracts, edge cases, error paths
6. **Run tests** — all must pass (or fail predictably for RED tests):
```bash
pnpm --filter @robota-sdk/<pkg> test
```
7. **Commit tests separately** before any extraction:
- Commit message: `test(<pkg>): add characterization tests for <target> before refactor`
- This preserves a rollback point
### Phase 3: Extract (one module at a time)
8. **Extract one module** — move the logic to its new file:
- Pure function extraction: move function, update imports
- Interface extraction: define interface, implement, inject
- Keep the original call site as a thin wrapper initially
9. **Run tests after each extraction**:
```bash
pnpm --filter @robota-sdk/<pkg> test
pnpm --filter @robota-sdk/<pkg> build
```
10. **Commit each extraction individually**:
- Commit message: `refactor(<pkg>): extract <module> from <source>`
11. **Repeat steps 8-10** for each extraction target.
### Phase 4: Verify
12. **Run full verification**:
```bash
pnpm build
pnpm test
pnpm typecheck
```
13. **Update SPEC.md** — add new files to File Structure, update module descriptions.
14. **Summarize** what was extracted, what tests were added, and what remains.
## Stop Conditions
- Do NOT extract code without existing or new tests covering it.
- Do NOT extract multiple modules in one commit.
- Do NOT change behavior during extraction — pure move only.
- Do NOT skip the analysis phase — present the plan first.
- Do NOT proceed without user approval of the extraction plan.
## Extraction Priority Rules
| Priority | Criteria | Example |
|----------|----------|---------|
| **P1** | Pure function, no deps, high reuse | `extractToolCalls()`, `formatTokenCount()` |
| **P2** | I/O behind interface, moderate complexity | `SettingsIO.read()`, `PrintTerminal` |
| **P3** | Framework-coupled, needs hook/state refactor | `usePermissionQueue`, `useSessionRunner` |
- Always extract P1 first — highest test value, lowest risk.
- P2 requires interface definition before extraction.
- P3 may require architectural decisions — discuss with user.
## Anti-Patterns
- **Big bang refactor**: extracting everything at once without incremental tests.
- **Test-after-extract**: moving code first, writing tests second (breaks rollback safety).
- **Behavior change during extraction**: "while I'm here, let me also fix..."
- **Skipping analysis**: jumping to extraction without understanding dependencies.
- **Over-extraction**: creating a module for 5 lines of code that's used once.
## Checklist
- [ ] Target file(s) read and responsibilities cataloged
- [ ] Extraction targets classified with priority (P1/P2/P3)
- [ ] Analysis presented to user and approved
- [ ] Characterization tests written for P1 targets
- [ ] Tests committed before any extraction
- [ ] Each extraction is one commit with passing tests
- [ ] SPEC.md updated with new file structure
- [ ] Full build + test + typecheck passes
## Related Skills
- `tdd-red-green-refactor` — TDD cycle for new behavior after extraction
- `repo-change-loop` — build/test/verify workflow
- `spec-code-conformance` — SPEC update after structural changes
- `vitest-testing-strategy` — testing patterns and conventionsRelated Skills
vitest-testing-strategy
Defines a practical testing strategy for TypeScript and JavaScript using Vitest across unit, integration, and type-level tests. Use when adding features, refactoring, or preventing regressions with fast feedback loops.
tdd-red-green-refactor
Kent Beck's TDD workflow. Use when writing new code or modifying existing behavior. Enforces the Red-Green-Refactor cycle with small, verifiable steps.
scenario-verification-harness
Applies the Robota scenario verification loop by checking scope, preserving canonical ownership, re-recording only when necessary, and stopping on strict-policy failures. Use when scenario files, example flows, or execution-path behavior changes.
harness-governance
Governs the Robota harness by checking rule-skill-owner consistency, finding undefined terminology, spotting examples that violate rules, and preferring mechanical checks over duplicated prose. Use when editing AGENTS, skills, or repository guidance.
contract-testing
Applies consumer-driven contract testing to verify API compatibility between packages or services without full E2E tests. Use when designing or evolving API boundaries between loosely coupled modules.
web-design-guidelines
Review UI code for Web Interface Guidelines compliance. Use when asked to "review my UI", "check accessibility", "audit design", "review UX", or "check my site against best practices".
version-management
All packages must have the same version. Use changesets for coordinated version bumps. Never version packages independently.
vercel-react-native-skills
React Native and Expo best practices for building performant mobile apps. Use when building React Native components, optimizing list performance, implementing animations, or working with native modules. Triggers on tasks involving React Native, Expo, mobile performance, or native platform APIs.
vercel-react-best-practices
React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
vercel-composition-patterns
React composition patterns that scale. Use when refactoring components with boolean prop proliferation, building flexible component libraries, or designing reusable APIs. Triggers on tasks involving compound components, render props, context providers, or component architecture. Includes React 19 API changes.
user-request-gate
Use immediately when the user requests any implementation, code change, feature addition, fix, or modification. Gates code writing behind a backlog draft document. Read-only exploration is always permitted.
type-boundary-and-ssot
Applies Robota's preferred workflow for trust-boundary validation, strict typing, quality gates, and owner-based SSOT reuse. Use when adding or reviewing type contracts, boundary parsing, shared contract ownership, or running quality checks.