tdd-refactor-guard

Pre-refactor safety checklist. Verifies test coverage exists before AI modifies existing code. Use before asking AI to refactor anything.

110 stars

Best use case

tdd-refactor-guard is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Pre-refactor safety checklist. Verifies test coverage exists before AI modifies existing code. Use before asking AI to refactor anything.

Teams using tdd-refactor-guard 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

$curl -o ~/.claude/skills/tdd-refactor-guard/SKILL.md --create-dirs "https://raw.githubusercontent.com/gustavscirulis/snapgrid/main/.claude/skills/skills/testing/tdd-refactor-guard/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/tdd-refactor-guard/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How tdd-refactor-guard Compares

Feature / Agenttdd-refactor-guardStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Pre-refactor safety checklist. Verifies test coverage exists before AI modifies existing code. Use before asking AI to refactor anything.

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

# TDD Refactor Guard

A safety gate that runs before any AI-assisted refactoring. Ensures tests exist to catch regressions. If coverage is insufficient, generates characterization tests first.

## When This Skill Activates

Use this skill when the user:
- Says "refactor this" or "clean this up"
- Wants AI to "restructure" or "reorganize" code
- Asks to "extract", "inline", "rename", or "simplify" existing code
- Plans to migrate between patterns (e.g., MVC → MVVM, CoreData → SwiftData)
- Wants AI to "improve" or "modernize" existing code

## Why This Guard Exists

```
Without guard:               With guard:
"Claude, refactor this"      "Claude, refactor this"
  → AI rewrites code           → Guard checks for tests
  → Something breaks           → Tests missing → generate them
  → You don't know what        → Tests pass → proceed with refactor
  → Debugging nightmare         → Tests fail → exact regression found
```

## Process

### Step 1: Identify Scope

What code is being refactored?

```
Ask user: "Which files/classes are you planning to refactor?"
```

Or detect from context:
```
Glob: [files mentioned in conversation]
Read: each file to understand scope
```

Determine:
- [ ] Files involved
- [ ] Public API surface (methods, properties)
- [ ] Dependencies (what calls this code, what it calls)
- [ ] Side effects (network, disk, notifications, UI updates)

### Step 2: Check Existing Test Coverage

```
Grep: "class.*Tests.*XCTestCase|@Suite.*Tests|struct.*Tests" in test targets
Grep: "@Test|func test" that reference the classes being refactored
```

#### Coverage Assessment

| Level | Criteria | Action |
|-------|----------|--------|
| Good (> 80%) | Most public methods have tests for happy + error paths | Proceed with refactoring |
| Partial (40-80%) | Some methods tested, missing edge cases | Add characterization tests for uncovered methods |
| Minimal (< 40%) | Few or no tests | Generate full characterization test suite first |
| None (0%) | No test file exists | STOP — create characterization tests before any refactoring |

### Step 3: Evaluate Test Quality

Even if tests exist, check quality:

```swift
// ❌ Low-quality test — doesn't actually verify behavior
@Test("test items")
func testItems() {
    let vm = ViewModel()
    vm.loadItems()
    #expect(true)  // Always passes, tests nothing
}

// ❌ Tests implementation, not behavior
@Test("calls repository")
func testCallsRepo() {
    let vm = ViewModel()
    vm.loadItems()
    #expect(mockRepo.fetchCallCount == 1)  // Brittle
}

// ✅ Tests observable behavior
@Test("loads items into published array")
func testLoadsItems() async {
    let vm = ViewModel(repo: MockRepo(items: [.sample]))
    await vm.loadItems()
    #expect(vm.items.count == 1)
    #expect(vm.items.first?.title == "Sample")
}
```

**Quality checklist:**
- [ ] Tests verify **outputs/state**, not implementation details
- [ ] Both happy path and error paths covered
- [ ] Edge cases (empty, nil, boundary) tested
- [ ] Async behavior properly awaited
- [ ] No `#expect(true)` or always-passing assertions

### Step 4: Generate Missing Tests

If coverage is insufficient, use `characterization-test-generator/`:

```markdown
Before refactoring [ClassName], generate characterization tests:
1. Read the source file
2. Identify all public methods
3. Generate tests that capture CURRENT behavior
4. Run and verify all pass
```

### Step 5: Green Light / Red Light

#### Green Light — Proceed

```markdown
## Refactor Guard: ✅ PROCEED

**Files**: ItemManager.swift, ItemRepository.swift
**Test coverage**: Good (12 tests covering 8/9 public methods)
**Test quality**: Adequate — tests verify behavior, not implementation

Safe to refactor. Run tests after each change:
`xcodebuild test -scheme YourApp`
```

#### Yellow Light — Needs Work

```markdown
## Refactor Guard: ⚠️ NEEDS TESTS

**Files**: ItemManager.swift, ItemRepository.swift
**Test coverage**: Partial (5 tests covering 4/9 public methods)
**Missing coverage**:
- `ItemManager.sort()` — no test
- `ItemManager.filter(by:)` — no test
- `ItemRepository.sync()` — no test
- Error paths for `save()` and `delete()` — not tested

**Action**: Generate characterization tests for uncovered methods before refactoring.
Use `characterization-test-generator` skill.
```

#### Red Light — Stop

```markdown
## Refactor Guard: 🔴 STOP

**Files**: ItemManager.swift, ItemRepository.swift
**Test coverage**: None (0 tests found)

**Action**: Do NOT refactor until characterization tests exist.
Refactoring without tests is like surgery without monitoring —
you won't know if you killed the patient.

Run `characterization-test-generator` on:
1. ItemManager (7 public methods)
2. ItemRepository (5 public methods)

Then re-run this guard.
```

### Step 6: Post-Refactor Verification

After refactoring is complete:

```bash
# Run all tests
xcodebuild test -scheme YourApp

# Check specifically for regressions
xcodebuild test -scheme YourApp \
  -only-testing "YourAppTests/ItemManagerCharacterizationTests"
```

- [ ] All pre-existing tests still pass
- [ ] Characterization tests still pass
- [ ] No new warnings or errors
- [ ] Public API surface unchanged (unless intentionally changed)

## Refactoring Safeguards

### Safe Refactorings (Low Risk)

These typically don't change behavior:
- Rename variable/method/type
- Extract method/function
- Inline temporary variable
- Move method to another type (keeping same behavior)
- Extract protocol from class

### Risky Refactorings (Need Good Coverage)

These can change behavior:
- Change method signature
- Reorder operations
- Replace algorithm
- Merge/split classes
- Change data structure
- Introduce async/await to sync code
- Migration between frameworks (CoreData → SwiftData)

### Migration Refactorings (Need Comprehensive Coverage)

Full contract tests recommended:
- Architecture change (MVC → MVVM)
- Framework migration (UIKit → SwiftUI)
- Storage migration (UserDefaults → SwiftData)
- Concurrency model change (GCD → async/await)

## Output Format

```markdown
## Refactor Guard Report

**Scope**: [Files/classes to be refactored]
**Verdict**: ✅ PROCEED / ⚠️ NEEDS TESTS / 🔴 STOP

### Coverage Summary
| Class | Public Methods | Tests | Coverage | Verdict |
|-------|---------------|-------|----------|---------|
| ItemManager | 9 | 12 | 89% | ✅ |
| ItemRepository | 5 | 2 | 40% | ⚠️ |

### Missing Coverage
- [ ] `ItemRepository.sync()` — needs characterization test
- [ ] Error path for `ItemRepository.delete()` — untested

### Recommendations
1. [Action item]
2. [Action item]
```

## References

- `testing/characterization-test-generator/` — generates tests this guard may require
- `testing/tdd-feature/` — for building new code during refactor
- Martin Fowler, *Refactoring: Improving the Design of Existing Code*

Related Skills

swiftui-ui-patterns

110
from gustavscirulis/snapgrid

Best practices and example-driven guidance for building SwiftUI views and components. Use when creating or refactoring SwiftUI UI, designing tab architecture with TabView, composing screens, or needing component-specific patterns and examples.

watchOS

110
from gustavscirulis/snapgrid

watchOS development guidance including SwiftUI for Watch, Watch Connectivity, complications, and watch-specific UI patterns. Use for watchOS code review, best practices, or Watch app development.

visionos-widgets

110
from gustavscirulis/snapgrid

visionOS widget patterns including mounting styles, glass/paper textures, proximity-aware layouts, and spatial widget families. Use when creating or adapting widgets for visionOS.

test-data-factory

110
from gustavscirulis/snapgrid

Generate test fixture factories for your models. Builder pattern and static factories for zero-boilerplate test data. Use when tests need sample data setup.

test-contract

110
from gustavscirulis/snapgrid

Generate protocol/interface test suites that any implementation must pass. Define the contract once, test every implementation. Use when designing protocols or swapping implementations.

tdd-feature

110
from gustavscirulis/snapgrid

Red-green-refactor scaffold for building new features with TDD. Write failing tests first, then implement to pass. Use when building new features test-first.

tdd-bug-fix

110
from gustavscirulis/snapgrid

Fix bugs using red-green-refactor — reproduce the bug as a failing test first, then fix it. Use when fixing bugs to ensure they never regress.

snapshot-test-setup

110
from gustavscirulis/snapgrid

Set up SwiftUI visual regression testing with swift-snapshot-testing. Generates snapshot test boilerplate and CI configuration. Use for UI regression prevention.

integration-test-scaffold

110
from gustavscirulis/snapgrid

Generate cross-module test harness with mock servers, in-memory stores, and test configuration. Use when testing networking + persistence + business logic together.

characterization-test-generator

110
from gustavscirulis/snapgrid

Generates tests that capture current behavior of existing code before refactoring. Use when you need a safety net before AI-assisted refactoring or modifying legacy code.

testing

110
from gustavscirulis/snapgrid

TDD and testing skills for iOS/macOS apps. Covers characterization tests, TDD workflows, test contracts, snapshot tests, and test infrastructure. Use for test-driven development, adding tests to existing code, or building test infrastructure.

webkit-integration

110
from gustavscirulis/snapgrid

WebKit integration in SwiftUI using WebView and WebPage for embedding web content, navigation, JavaScript interop, and customization. Use when embedding web content in SwiftUI apps.