Skip to content
Back to skills

Refactor

ASecurity

Structured code refactoring with dependency-safe execution and behavior preservation. Maps all dependents before touching any file. Refactoring changes structure without changing observable behavior. Tests must pass before and after every step.

  • 7 stars
  • 0 votes
  • 0 copies
  • 2 views
  • Added November 9, 2026
ai-agentstypescriptgobashrefactoringgitapidatabaseperformance

Works with

  • api

Security analysis

A100/100

Scanned November 9, 2026

npx -y skills add Harmitx7/tribunal-kit --skill refactor --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Refactor?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Refactor
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/harmitx7-refactor/badge)](https://www.skillsdirectory.com/skills/harmitx7-refactor)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: refactor
description: Structured code refactoring with dependency-safe execution and behavior preservation. Maps all dependents before touching any file. Refactoring changes structure without changing observable behavior. Tests must pass before and after every step.
tools: Read, Grep, Glob, Bash, Edit, Write
version: 3.0.0
last-updated: 2026-07-30
required-skills:
  - clean-code
  - architecture
  - codebase-design
  - tdd-workflow
scripts-binding:
  - .agent/scripts/test_runner.js
  - .agent/scripts/lint_runner.js
---

# /refactor — Dependency-Safe Structural Improvement

$ARGUMENTS

---

## Mandatory Pre-Flight Context Inspection

Before executing structural refactoring or extracting interfaces, you MUST inspect:

1. Complete Dependent Map (Grep Importers) → Identify every file importing the target module before touching a single line
2. Baseline Test Suite Verification (`test_runner.js`) → Ensure all unit and integration tests pass BEFORE initiating refactor steps
3. Observable Behavior Preservation → Enforce zero change in public function behavior or API contracts; verify tests pass cleanly after every step

4. Required Skills → Before executing, load and follow procedural rules from:
   - `clean-code` (.agent/skills/clean-code/SKILL.md): Self-documenting naming, no over-engineering, error handling patterns
   - `architecture` (.agent/skills/architecture/SKILL.md): System architecture, module boundaries, and dependency management
   - `codebase-design` (.agent/skills/codebase-design/SKILL.md): Deep module design with small interfaces and clean seams
   - `tdd-workflow` (.agent/skills/tdd-workflow/SKILL.md): Red-Green-Refactor TDD cycle and test-first development

---

## The Refactoring Contract

"Refactoring means changing the structure of code without changing its observable behavior."
If observable behavior changes, it's an enhancement — use `/enhance`.

---

## When to Use /refactor

| Use `/refactor` when...              | Use something else when...                         |
| :----------------------------------- | :------------------------------------------------- |
| Code structure is hard to understand | Adding new functionality → `/enhance`              |
| Repeated logic should be extracted   | Fixing a bug → `/debug`                            |
| Naming is unclear or misleading      | Performance improvements → `/tribunal-performance` |
| TypeScript types need tightening     | Full rebuild needed → `/create`                    |
| Dead code needs removal              |                                                    |

---

## Phase 1 — Pre-Refactor Checklist (Non-Negotiable)

Before touching any file:

```
□ Tests exist and pass (npm test passes clean)
□ If no tests exist → write tests FIRST using /test
□ Impact zone mapped (all importers identified)
□ Behavior contract documented (what must remain identical)
□ Rollback plan confirmed (git branch or stash)
```

**If tests don't exist: STOP. Write tests first. Tests are the safety net for refactoring.**

---

## Phase 2 — Impact Zone Mapping

```bash
# Map every file that will need to change
grep -r "from '.*target-module'" src/ --include="*.ts" --include="*.tsx"

# Check for dynamic imports that grep might miss
grep -r "import(" src/ --include="*.ts" --include="*.tsx"

# Check for re-exports
grep -r "export \* from" src/ --include="*.ts"
```

Build the full change list before making any modification:

```
Refactoring: rename getUserById → fetchUserById

Files affected:
- src/lib/users.ts              [RENAME function definition]
- src/app/api/users/[id]/route.ts [UPDATE callers]
- src/app/dashboard/page.tsx    [UPDATE callers]
- src/lib/users.test.ts         [UPDATE test references]
```

---

## Phase 3 — Dependency-Safe Execution Order

Refactoring order must follow the dependency graph:

```
Rule: Always update the definition FIRST, then update callers.
      Never update a caller before the definition is updated.

Dependency order (example: extracting a shared utility):
1. Create src/lib/shared-utility.ts (new definition)
2. Update the original file to import from shared-utility (definition update)
3. Update all other callers to import from shared-utility
4. Run tests — verify all pass
5. Remove old inline code

Database refactoring order:
1. Write migration (expand: add new column)
2. Update ORM schema
3. Update application code to write to new column
4. Backfill existing data
5. Update application code to read from new column
6. Write second migration (contract: remove old column)
```

---

## Phase 4 — Behavior Verification After Each Step

After every file change in the refactoring sequence:

```bash
npx tsc --noEmit   # TypeScript types must remain valid
npm test           # All tests must still pass
```

**If any step causes a type error or test failure → STOP and fix before proceeding.**

Rolling forward with broken tests is not refactoring — it's breaking code.

---

## Phase 5 — Common Safe Refactoring Patterns

### Extract Function

```typescript
// Before: inline logic in handler
app.post('/orders', async (req, res) => {
  const discount = amount > 100 ? amount * 0.9 : amount; // inline
  // ...
});

// After: extracted pure function with tests
const applyDiscount = (amount: number): number => (amount > 100 ? amount * 0.9 : amount);
app.post('/orders', async (req, res) => {
  const discount = applyDiscount(amount); // single responsibility
  // ...
});
```

### Remove Dead Code

```bash
# Verify zero callers BEFORE deleting
grep -r "OldFunction\|oldFunction" src/ --include="*.ts" # Must return: 0 results
# Then delete
```

### Tighten Types

```typescript
// Before: any loses all type checking
function process(data: any) {
  data.unknownProp;
} // No error

// After: explicit interface — all callers must provide correct shape
function process(data: { id: string; name: string }) {
  data.id;
} // Typed
```

---

## Refactor Guard

```
❌ Never refactor without tests passing before AND after
❌ Never rename an exported symbol without updating ALL importers
❌ Never remove "dead code" without grepping to confirm zero usages
❌ Never mix refactoring and new feature in the same commit
❌ Never refactor database columns without expand-and-contract migration
❌ Never change function signatures without updating all callers simultaneously
```

---

## After /refactor — Next Steps

| Outcome                       | Next Command                    |
| :---------------------------- | :------------------------------ |
| Refactor complete, tests pass | → `/tribunal-full` or `/deploy` |
| Need to improve performance   | → `/tribunal-performance`       |
| Want to add features now      | → `/enhance`                    |

---

---

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.