Clean Architecture Audit & Refactor
Analyze a repository's architecture through the lens of Clean Architecture principles, then suggest concrete fixes at a user-chosen scope level.
How This Skill Works
digraph clean_arch_flow {
rankdir=TB;
"Skill invoked" [shape=doublecircle];
"Load reference doc" [shape=box];
"Scan repo architecture" [shape=box];
"Map current layers & deps" [shape=box];
"Architecture healthy?" [shape=diamond];
"Report: architecture is solid" [shape=box];
"Ask user: scope level?" [shape=diamond];
"Cleanup" [shape=box];
"Medium" [shape=box];
"Major" [shape=box];
"Drastic" [shape=box];
"Generate findings + fixes" [shape=box];
"Present prioritized report" [shape=doublecircle];
"Skill invoked" -> "Load reference doc";
"Load reference doc" -> "Scan repo architecture";
"Scan repo architecture" -> "Map current layers & deps";
"Map current layers & deps" -> "Architecture healthy?";
"Architecture healthy?" -> "Report: architecture is solid" [label="yes"];
"Architecture healthy?" -> "Ask user: scope level?" [label="issues found"];
"Report: architecture is solid" -> "Present prioritized report";
"Ask user: scope level?" -> "Cleanup" [label="cleanup"];
"Ask user: scope level?" -> "Medium" [label="medium"];
"Ask user: scope level?" -> "Major" [label="major"];
"Ask user: scope level?" -> "Drastic" [label="drastic"];
"Cleanup" -> "Generate findings + fixes";
"Medium" -> "Generate findings + fixes";
"Major" -> "Generate findings + fixes";
"Drastic" -> "Generate findings + fixes";
"Generate findings + fixes" -> "Present prioritized report";
}
Phase 1: Load Clean Architecture Reference
Read the reference document located in the same directory as this skill:
clean-architecture-reference.md
This contains all principles you need: Dependency Rule, 4 layers, SOLID at architecture scale, component cohesion (REP/CCP/CRP), component coupling (ADP/SDP/SAP), Screaming Architecture, boundaries, anti-patterns, and the practical checklist.
Internalize these before scanning. Every finding must map to a named principle.
Important: Not every codebase needs fixing. If the architecture is already well-structured, say so clearly instead of inventing problems. The goal is honest assessment, not a guaranteed list of complaints.
Phase 2: Deep Architecture Scan
Use the Explore agent (subagent_type=Explore, thoroughness=very thorough) to analyze the target repo. Use the current working directory unless a different repo path is given.
Scan checklist — the agent must map:
| Area |
What to find |
| Directory structure |
Top-level dirs, does it scream domain or framework? |
| Server layers |
API routes -> services -> DB. Are they clean or leaking? |
| Client layers |
Pages -> components -> composables -> stores. Where's business logic? |
| Dependency flow |
Do routes call DB directly? Is there an abstraction layer? |
| Type sharing |
Where are types? Shared across layers properly? |
| Feature boundaries |
Are features isolated or interleaved? |
| God files |
Files >500 lines with mixed concerns |
| Dead code |
Unused exports, unreachable branches, orphaned files |
| Circular deps |
Services that call each other in cycles |
| External API access |
Direct calls or through adapters/interfaces? |
| Error handling |
Consistent patterns or scattered approaches? |
For each issue found, tag it with the Clean Architecture principle it violates.
Phase 3: Assess Health & Ask User for Scope
If the architecture is healthy
If the scan reveals a well-structured codebase with no significant violations — clean dependency flow, proper layer separation, no god files, consistent patterns — say so honestly. Present a health report:
Architecture Health: Good
The codebase follows clean architecture principles well. Dependencies flow inward, business logic lives in the right layers, boundaries are clear, and patterns are consistent.
[List 2-3 specific strengths observed]
Minor suggestions (if any): [only truly minor items, or "None — keep doing what you're doing."]
Do not invent problems to fill a report. A clean bill of health is a valid and valuable outcome. The user deserves to know their architecture is solid, not be handed busywork.
If issues are found
Present the scan summary with a brief overview of what was found, then ask:
What level of changes do you want?
Cleanup — Low risk, high confidence. No architecture changes.
- Remove dead code (unused exports, unreachable branches, orphaned files)
- Combine redundant implementations into single shared versions
- Fix inconsistent naming/patterns across similar code
- Remove duplicate type definitions
- Clean up unused imports and dependencies
Medium — Moderate risk, clear benefit. Moves logic to correct layers.
- Extract business logic from route handlers into dedicated services
- Move scattered validation into centralized service methods
- Break up god files (>500 lines) into focused, single-responsibility modules
- Standardize error handling patterns across the codebase
- Consolidate overlapping stores/state management
- Create missing abstractions for direct external API calls
Major — High impact, requires planning. Restructures toward Clean Architecture.
- Encapsulate use-case-specific logic into dedicated Use Case classes/functions
- Introduce interface-based adapters for all external dependencies (DB, LLM, external APIs)
- Restructure directories to scream domain instead of framework (Screaming Architecture)
- Establish explicit boundaries between feature domains
- Apply Dependency Inversion at all layer boundaries
- Create a proper "Main" component that wires concrete implementations to interfaces
Drastic — Full rethink. Considers technology replacement and parallel rewrite.
- Evaluate whether the current tech stack is fundamentally limiting the architecture
- Propose a target architecture with potentially different frameworks, languages, or infrastructure
- Design a parallel rewrite strategy: build the new system alongside the old one
- Plan incremental migration: identify which modules to migrate first (lowest coupling, highest pain)
- Define the strangler fig pattern — new features go to the new system, old features migrate over time
- Establish a compatibility layer / API gateway so both old and new coexist during transition
- Estimate effort and risk for the full migration path
- Only recommend this when the existing stack has fundamental constraints (e.g., framework is abandoned, language ecosystem is dying, performance ceiling is structural, or the codebase has grown beyond what incremental refactoring can fix)
Wait for the user's choice before generating the report.
Phase 4: Generate Findings Report
Structure the report as:
# Clean Architecture Audit — [Repo Name]
## Scope: [Cleanup | Medium | Major | Drastic]
## Executive Summary
[2-3 sentences: overall health, biggest issue, recommended priority]
## Findings
### Finding 1: [Short title]
- **Principle violated:** [Named principle from reference doc]
- **Where:** [Specific file paths and line ranges]
- **What's wrong:** [Concrete description with code snippets]
- **Fix:** [Specific, actionable fix with code example]
- **Risk:** [Low/Medium/High — what could break]
- **Effort:** [S/M/L]
### Finding 2: ...
[Repeat for each finding]
## Dependency Map
[ASCII diagram showing current dependency flow between major components]
## Priority Order
[Numbered list — which fixes to do first based on risk/effort/impact]
Scope-Specific Focus
Cleanup scope — focus on:
- Dead code: grep for unused exports, check import counts
- Redundancy: find functions/utilities that do the same thing
- Inconsistency: naming patterns, error handling styles, response formats
- Do NOT suggest moving code between layers or changing architecture
Medium scope — focus on:
- Everything in Cleanup, PLUS:
- Business logic in wrong layer (routes doing business logic -> move to services)
- God files that need splitting (identify clear split boundaries)
- Missing service abstractions (direct DB calls in handlers)
- Inconsistent patterns that should be unified (error handling, validation)
- Map each fix to: SRP, CCP, or ISP principle
Major scope — focus on:
- Everything in Medium, PLUS:
- Use Case encapsulation (identify distinct use cases, propose class/function boundaries)
- Adapter pattern for externals (define interfaces, show concrete impls)
- Screaming Architecture restructure (propose new directory layout)
- Boundary definitions (where to draw lines, what crosses them)
- Dependency Inversion opportunities (where control flow opposes desired dependency direction)
- Map each fix to: Dependency Rule, DIP, ADP, SDP, SAP, Screaming Architecture
Drastic scope — focus on:
- Everything in Major as the baseline assessment, PLUS:
- Tech stack evaluation: Is the current framework/language/infrastructure fundamentally constraining the architecture? Be specific — "Nuxt SSR limitations force X" not just "consider alternatives"
- Target architecture design: Propose a concrete target stack with rationale. Why this stack? What Clean Architecture problems does it solve that refactoring can't?
- Strangler fig migration plan: Don't suggest a big-bang rewrite. Design an incremental migration:
- Identify the module with the worst architecture AND lowest coupling — migrate that first
- Define an API gateway or compatibility layer so old and new systems coexist
- New features go to the new system; old features migrate in priority order
- Each migration step must leave the system fully functional
- Effort and risk matrix: For each migration phase, estimate effort (weeks/months) and risk (what breaks if it goes wrong)
- Decision criteria: Be explicit about when Drastic is warranted vs. when Major would suffice. Drastic is for: abandoned frameworks, structural performance ceilings, ecosystem dead-ends, or when cumulative tech debt makes incremental refactoring more expensive than replacement
- When NOT to recommend Drastic: If the problems are solvable with Major-level refactoring, say so. A parallel rewrite is enormously expensive — only recommend it when you genuinely believe incremental changes can't get there
- Map each fix to: all principles from Major, plus Plugin Architecture (swappability), Boundaries (migration seams), Main Component (rewiring)
Important Rules
- Every finding must cite a specific Clean Architecture principle. No vague "this could be better."
- Every fix must include concrete file paths and code. No hand-wavy suggestions.
- Respect the chosen scope. Don't suggest Major changes when user chose Cleanup.
- Prioritize by risk/effort ratio. Low-risk, high-impact first.
- Flag breaking changes explicitly. If a fix could break existing functionality, say so with the specific risk.
- Don't over-abstract. Three similar lines of code is better than a premature abstraction. Only suggest abstractions when there are 3+ concrete instances that would benefit.
- Consider framework conventions. Some "violations" are framework conventions (e.g., auto-imported composables, file-based routing). Don't fight the framework where it provides genuine value — flag where framework conventions hurt architecture.
Quick Reference: Principle -> Symptom
| Symptom |
Likely Principle Violated |
| Business logic in route handler |
SRP, Dependency Rule |
| Route handler calls DB directly |
Dependency Rule, missing adapter |
| File >500 lines with mixed concerns |
SRP, CCP |
| Same logic in 3+ places |
DRY (extract, apply CCP) |
| Circular imports between services |
ADP |
| Concrete external API calls with no interface |
DIP, Plugin Architecture |
| Directory named by tech not domain |
Screaming Architecture |
| DTO/DB entity used as domain model |
Dependency Rule (data crossing boundaries) |
| Tests require full framework to run |
Test Boundary violation |
| Changing one feature breaks another |
Missing boundary, CCP violation |
| Unused exports, dead functions |
Component hygiene (CRP) |
| Inconsistent error handling |
Missing adapter pattern |
| Framework workarounds everywhere |
Consider Drastic — framework may be the constraint |
| Performance ceiling despite optimization |
Structural limitation — evaluate stack replacement |
| Can't add features without touching 10+ files |
Missing boundaries, possibly beyond Major-level fix |
1---2name: clean-arch3description: Use when refactoring, reviewing architecture, or improving code structure in a Nuxt/TypeScript/full-stack repo. Triggers on architecture review, dependency cleanup, code organization, refactoring suggestions, dead code removal, layer violations, god files, scattered business logic.4---56# Clean Architecture Audit & Refactor78Analyze a repository's architecture through the lens of Clean Architecture principles, then suggest concrete fixes at a user-chosen scope level.910## How This Skill Works1112```dot13digraph clean_arch_flow {14 rankdir=TB;15 "Skill invoked" [shape=doublecircle];16 "Load reference doc" [shape=box];17 "Scan repo architecture" [shape=box];18 "Map current layers & deps" [shape=box];19 "Architecture healthy?" [shape=diamond];20 "Report: architecture is solid" [shape=box];21 "Ask user: scope level?" [shape=diamond];22 "Cleanup" [shape=box];23 "Medium" [shape=box];24 "Major" [shape=box];25 "Drastic" [shape=box];26 "Generate findings + fixes" [shape=box];27 "Present prioritized report" [shape=doublecircle];2829 "Skill invoked" -> "Load reference doc";30 "Load reference doc" -> "Scan repo architecture";31 "Scan repo architecture" -> "Map current layers & deps";32 "Map current layers & deps" -> "Architecture healthy?";33 "Architecture healthy?" -> "Report: architecture is solid" [label="yes"];34 "Architecture healthy?" -> "Ask user: scope level?" [label="issues found"];35 "Report: architecture is solid" -> "Present prioritized report";36 "Ask user: scope level?" -> "Cleanup" [label="cleanup"];37 "Ask user: scope level?" -> "Medium" [label="medium"];38 "Ask user: scope level?" -> "Major" [label="major"];39 "Ask user: scope level?" -> "Drastic" [label="drastic"];40 "Cleanup" -> "Generate findings + fixes";41 "Medium" -> "Generate findings + fixes";42 "Major" -> "Generate findings + fixes";43 "Drastic" -> "Generate findings + fixes";44 "Generate findings + fixes" -> "Present prioritized report";45}46```4748## Phase 1: Load Clean Architecture Reference4950Read the reference document located in the same directory as this skill:51```52clean-architecture-reference.md53```5455This contains all principles you need: Dependency Rule, 4 layers, SOLID at architecture scale, component cohesion (REP/CCP/CRP), component coupling (ADP/SDP/SAP), Screaming Architecture, boundaries, anti-patterns, and the practical checklist.5657**Internalize these before scanning.** Every finding must map to a named principle.5859**Important:** Not every codebase needs fixing. If the architecture is already well-structured, say so clearly instead of inventing problems. The goal is honest assessment, not a guaranteed list of complaints.6061## Phase 2: Deep Architecture Scan6263Use the Explore agent (subagent_type=Explore, thoroughness=very thorough) to analyze the target repo. Use the current working directory unless a different repo path is given.6465**Scan checklist — the agent must map:**6667| Area | What to find |68|------|-------------|69| **Directory structure** | Top-level dirs, does it scream domain or framework? |70| **Server layers** | API routes -> services -> DB. Are they clean or leaking? |71| **Client layers** | Pages -> components -> composables -> stores. Where's business logic? |72| **Dependency flow** | Do routes call DB directly? Is there an abstraction layer? |73| **Type sharing** | Where are types? Shared across layers properly? |74| **Feature boundaries** | Are features isolated or interleaved? |75| **God files** | Files >500 lines with mixed concerns |76| **Dead code** | Unused exports, unreachable branches, orphaned files |77| **Circular deps** | Services that call each other in cycles |78| **External API access** | Direct calls or through adapters/interfaces? |79| **Error handling** | Consistent patterns or scattered approaches? |8081**For each issue found, tag it with the Clean Architecture principle it violates.**8283## Phase 3: Assess Health & Ask User for Scope8485### If the architecture is healthy8687If the scan reveals a well-structured codebase with no significant violations — clean dependency flow, proper layer separation, no god files, consistent patterns — **say so honestly**. Present a health report:8889> **Architecture Health: Good**90>91> The codebase follows clean architecture principles well. Dependencies flow inward, business logic lives in the right layers, boundaries are clear, and patterns are consistent.92>93> [List 2-3 specific strengths observed]94>95> Minor suggestions (if any): [only truly minor items, or "None — keep doing what you're doing."]9697Do not invent problems to fill a report. A clean bill of health is a valid and valuable outcome. The user deserves to know their architecture is solid, not be handed busywork.9899### If issues are found100101Present the scan summary with a brief overview of what was found, then ask:102103> **What level of changes do you want?**104>105> 1. **Cleanup** — Low risk, high confidence. No architecture changes.106> - Remove dead code (unused exports, unreachable branches, orphaned files)107> - Combine redundant implementations into single shared versions108> - Fix inconsistent naming/patterns across similar code109> - Remove duplicate type definitions110> - Clean up unused imports and dependencies111>112> 2. **Medium** — Moderate risk, clear benefit. Moves logic to correct layers.113> - Extract business logic from route handlers into dedicated services114> - Move scattered validation into centralized service methods115> - Break up god files (>500 lines) into focused, single-responsibility modules116> - Standardize error handling patterns across the codebase117> - Consolidate overlapping stores/state management118> - Create missing abstractions for direct external API calls119>120> 3. **Major** — High impact, requires planning. Restructures toward Clean Architecture.121> - Encapsulate use-case-specific logic into dedicated Use Case classes/functions122> - Introduce interface-based adapters for all external dependencies (DB, LLM, external APIs)123> - Restructure directories to scream domain instead of framework (Screaming Architecture)124> - Establish explicit boundaries between feature domains125> - Apply Dependency Inversion at all layer boundaries126> - Create a proper "Main" component that wires concrete implementations to interfaces127>128> 4. **Drastic** — Full rethink. Considers technology replacement and parallel rewrite.129> - Evaluate whether the current tech stack is fundamentally limiting the architecture130> - Propose a target architecture with potentially different frameworks, languages, or infrastructure131> - Design a parallel rewrite strategy: build the new system alongside the old one132> - Plan incremental migration: identify which modules to migrate first (lowest coupling, highest pain)133> - Define the strangler fig pattern — new features go to the new system, old features migrate over time134> - Establish a compatibility layer / API gateway so both old and new coexist during transition135> - Estimate effort and risk for the full migration path136> - **Only recommend this when the existing stack has fundamental constraints** (e.g., framework is abandoned, language ecosystem is dying, performance ceiling is structural, or the codebase has grown beyond what incremental refactoring can fix)137138Wait for the user's choice before generating the report.139140## Phase 4: Generate Findings Report141142Structure the report as:143144```markdown145# Clean Architecture Audit — [Repo Name]146147## Scope: [Cleanup | Medium | Major | Drastic]148149## Executive Summary150[2-3 sentences: overall health, biggest issue, recommended priority]151152## Findings153154### Finding 1: [Short title]155- **Principle violated:** [Named principle from reference doc]156- **Where:** [Specific file paths and line ranges]157- **What's wrong:** [Concrete description with code snippets]158- **Fix:** [Specific, actionable fix with code example]159- **Risk:** [Low/Medium/High — what could break]160- **Effort:** [S/M/L]161162### Finding 2: ...163[Repeat for each finding]164165## Dependency Map166[ASCII diagram showing current dependency flow between major components]167168## Priority Order169[Numbered list — which fixes to do first based on risk/effort/impact]170```171172### Scope-Specific Focus173174**Cleanup scope — focus on:**175- Dead code: grep for unused exports, check import counts176- Redundancy: find functions/utilities that do the same thing177- Inconsistency: naming patterns, error handling styles, response formats178- **Do NOT suggest moving code between layers or changing architecture**179180**Medium scope — focus on:**181- Everything in Cleanup, PLUS:182- Business logic in wrong layer (routes doing business logic -> move to services)183- God files that need splitting (identify clear split boundaries)184- Missing service abstractions (direct DB calls in handlers)185- Inconsistent patterns that should be unified (error handling, validation)186- **Map each fix to: SRP, CCP, or ISP principle**187188**Major scope — focus on:**189- Everything in Medium, PLUS:190- Use Case encapsulation (identify distinct use cases, propose class/function boundaries)191- Adapter pattern for externals (define interfaces, show concrete impls)192- Screaming Architecture restructure (propose new directory layout)193- Boundary definitions (where to draw lines, what crosses them)194- Dependency Inversion opportunities (where control flow opposes desired dependency direction)195- **Map each fix to: Dependency Rule, DIP, ADP, SDP, SAP, Screaming Architecture**196197**Drastic scope — focus on:**198- Everything in Major as the baseline assessment, PLUS:199- **Tech stack evaluation:** Is the current framework/language/infrastructure fundamentally constraining the architecture? Be specific — "Nuxt SSR limitations force X" not just "consider alternatives"200- **Target architecture design:** Propose a concrete target stack with rationale. Why this stack? What Clean Architecture problems does it solve that refactoring can't?201- **Strangler fig migration plan:** Don't suggest a big-bang rewrite. Design an incremental migration:202 1. Identify the module with the worst architecture AND lowest coupling — migrate that first203 2. Define an API gateway or compatibility layer so old and new systems coexist204 3. New features go to the new system; old features migrate in priority order205 4. Each migration step must leave the system fully functional206- **Effort and risk matrix:** For each migration phase, estimate effort (weeks/months) and risk (what breaks if it goes wrong)207- **Decision criteria:** Be explicit about when Drastic is warranted vs. when Major would suffice. Drastic is for: abandoned frameworks, structural performance ceilings, ecosystem dead-ends, or when cumulative tech debt makes incremental refactoring more expensive than replacement208- **When NOT to recommend Drastic:** If the problems are solvable with Major-level refactoring, say so. A parallel rewrite is enormously expensive — only recommend it when you genuinely believe incremental changes can't get there209- **Map each fix to: all principles from Major, plus Plugin Architecture (swappability), Boundaries (migration seams), Main Component (rewiring)**210211## Important Rules2122131. **Every finding must cite a specific Clean Architecture principle.** No vague "this could be better."2142. **Every fix must include concrete file paths and code.** No hand-wavy suggestions.2153. **Respect the chosen scope.** Don't suggest Major changes when user chose Cleanup.2164. **Prioritize by risk/effort ratio.** Low-risk, high-impact first.2175. **Flag breaking changes explicitly.** If a fix could break existing functionality, say so with the specific risk.2186. **Don't over-abstract.** Three similar lines of code is better than a premature abstraction. Only suggest abstractions when there are 3+ concrete instances that would benefit.2197. **Consider framework conventions.** Some "violations" are framework conventions (e.g., auto-imported composables, file-based routing). Don't fight the framework where it provides genuine value — flag where framework conventions hurt architecture.220221## Quick Reference: Principle -> Symptom222223| Symptom | Likely Principle Violated |224|---------|--------------------------|225| Business logic in route handler | SRP, Dependency Rule |226| Route handler calls DB directly | Dependency Rule, missing adapter |227| File >500 lines with mixed concerns | SRP, CCP |228| Same logic in 3+ places | DRY (extract, apply CCP) |229| Circular imports between services | ADP |230| Concrete external API calls with no interface | DIP, Plugin Architecture |231| Directory named by tech not domain | Screaming Architecture |232| DTO/DB entity used as domain model | Dependency Rule (data crossing boundaries) |233| Tests require full framework to run | Test Boundary violation |234| Changing one feature breaks another | Missing boundary, CCP violation |235| Unused exports, dead functions | Component hygiene (CRP) |236| Inconsistent error handling | Missing adapter pattern |237| Framework workarounds everywhere | Consider Drastic — framework may be the constraint |238| Performance ceiling despite optimization | Structural limitation — evaluate stack replacement |239| Can't add features without touching 10+ files | Missing boundaries, possibly beyond Major-level fix |