
Modular Decomposition
- 106 installs
- 5k repo stars
- Updated August 4, 2026
- tech-leads-club/agent-skills
Helps with ai & agent building tasks during AI-assisted development.
About
modular-decomposition is a Claude Code skill for ai & agent building. It helps solo builders move faster with AI-assisted coding.
- modular-decomposition
- AI & Agent Building
- AI-coding skill
Modular Decomposition by the numbers
- 106 all-time installs (skills.sh)
- +9 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #4,175 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/tech-leads-club/agent-skills --skill modular-decompositionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 106 |
|---|---|
| repo stars | ★ 5k |
| Last updated | August 4, 2026 |
| Repository | tech-leads-club/agent-skills ↗ |
What it does
Helps with ai & agent building tasks during AI-assisted development.
Files
Modular Decomposition
This skill runs the Patterns 1–5 analysis pipeline before service extraction. Each pattern is plain markdown under references/; load the file for that step and execute it against the user’s codebase.
How to Use
Quick start (what users can say)
- Full pipeline: “Run modular decomposition Patterns 1 through 5 on this repo,” “Analyze this monolith for splitting—inventory, coupling, and domain grouping.”
- Single early step: “Identify and size components here,” “Find duplicated domain logic across modules,” “Analyze coupling between our packages.”
- With DDD lens: “Group components into domains and check bounded contexts,” “Use DDD strategic design on this codebase before we group services.”
If the user only wants extraction order, phases, or migration roadmap after analysis exists, use decomposition-planning-roadmap instead. If they need a full legacy migration plan (strangler fig, research, multi-stack), use legacy-migration-planner as well or instead of this skill when that is the primary ask.
How the agent should run it
1. Scope: Confirm the task is structural analysis (inventory → coupling → grouping), not roadmap authoring. If unclear, ask once whether they want the full ordered pipeline or a subset. 2. Order: Run patterns 1 → 2 → 3 → 4 → 5 in that order. Do not skip a step unless the user explicitly limits scope; if they do, state which patterns were skipped and how that limits later conclusions. 3. Load references: For each pattern, open the matching references/pattern-NN-*.md file and follow its instructions. Use the optional *-quick-reference.md for the same number when a short checklist is enough. 4. Carry context forward: Reuse outputs from earlier patterns in later ones (e.g. component inventory from Pattern 1 informs coupling in 4 and grouping in 5). Reference concrete paths, modules, or tables from previous steps. 5. Domain language (Pattern 5): If subdomains or bounded contexts need grounding beyond structure, read references/domain-analysis.md before or alongside Pattern 5. Optionally open references/domain-analysis-quick-reference.md or references/domain-analysis-examples.md for condensed rules or illustrations. 6. Deliver: Produce clear, actionable findings per pattern or one consolidated report—always tied to evidence from the repository (files, dependencies, metrics), not generic advice.
Usage examples
Example 1 — Full pipeline
User: "We're going to split this monolith—run the full decomposition analysis (Patterns 1–5)."
Agent: Execute patterns 1→5 in order, loading each references/pattern-NN-*.md, preserving outputs between steps, then summarize cross-cutting recommendations.Example 2 — Coupling after inventory
User: "We already have a rough module list—focus on coupling (Pattern 4) and then domain grouping (Pattern 5)."
Agent: If no prior inventory exists in the thread, either run Pattern 1 briefly or derive an explicit module list from the repo before 4 and 5. State any assumptions.Example 3 — DDD before grouping
User: "Map bounded contexts and language, then group components into domains."
Agent: Read references/domain-analysis.md (and optional quick reference/examples) in parallel with or immediately before Pattern 5; align Pattern 5 groupings with linguistic boundaries where evidence supports it.Prerequisites
- Complete Pattern N before starting Pattern N+1 unless the user explicitly narrows scope. Later patterns depend on earlier results (for example, inventory and structure inform coupling and grouping).
- If business vocabulary, subdomains, or bounded contexts are uncertain, use
references/domain-analysis.mdbefore or alongside Pattern 5 (see Bounded contexts below).
Ordered workflow (Patterns 1–5)
| Step | Pattern | Primary reference |
|---|---|---|
| 1 | Identify and size components | references/pattern-01-identify-and-size.md (optional: pattern-01-identify-and-size-quick-reference.md) |
| 2 | Common domain detection | references/pattern-02-common-domain.md (optional: pattern-02-common-domain-quick-reference.md) |
| 3 | Flattening / hierarchy | references/pattern-03-flattening.md (optional: pattern-03-flattening-quick-reference.md) |
| 4 | Coupling analysis | references/pattern-04-coupling.md |
| 5 | Domain identification and grouping | references/pattern-05-domain-grouping.md (optional: pattern-05-domain-grouping-quick-reference.md) |
Pattern 6 — planning and extraction
Pattern 6 (_create domain services / extraction_) is not duplicated here. After Pattern 5, switch to decomposition-planning-roadmap for phased extraction order, milestones, and migration-style planning. For full legacy migration strategy (strangler-fig, cross-stack rewrites, research-heavy plans), optionally use legacy-migration-planner in addition.
Bounded contexts and DDD strategic design
- Patterns 1–4 focus on structural inventory, duplication, hierarchy, and coupling between parts of the codebase.
- Pattern 5 produces candidate groupings aligned with solution-space boundaries (which components belong together as services).
- Strategic DDD (subdomains, bounded contexts, ubiquitous language) is covered in
references/domain-analysis.md, with optionaldomain-analysis-quick-reference.mdanddomain-analysis-examples.md. Use it when you need to validate or refine boundaries against business language, not only folder structure.
Subdomain Identification Examples
This document provides practical examples of applying subdomain identification across different types of codebases.
Example 1: E-Commerce Platform
Discovered Concepts
Entities:
- Product, Category, Inventory, SKU
- Order, OrderItem, Cart, CartItem
- Customer, Address, PaymentMethod
- Shipment, Tracking, Warehouse
Services:
- ProductCatalogService, InventoryService
- OrderProcessingService, CartService
- PaymentService, ShippingService
- CustomerService
Language Groups
Catalog Language: product, category, SKU, inventory, stock Order Language: order, cart, checkout, fulfillment Payment Language: payment, transaction, refund, charge Shipping Language: shipment, tracking, delivery, carrier Customer Language: customer, account, profile, address
Identified Subdomains
1. Product Catalog (Core Domain)
- Type: Core (if differentiation is product discovery)
- Ubiquitous Language: product, category, catalog, search, browse
- Concepts: Product, Category, ProductCatalogService
- Cohesion: 9/10
- Bounded Context: CatalogContext
2. Inventory Management (Supporting)
- Type: Supporting
- Ubiquitous Language: stock, inventory, SKU, warehouse, allocation
- Concepts: Inventory, SKU, InventoryService, Warehouse
- Cohesion: 8/10
- Bounded Context: InventoryContext
3. Order Processing (Core Domain)
- Type: Core (if differentiation is checkout experience)
- Ubiquitous Language: order, cart, checkout, fulfillment
- Concepts: Order, Cart, OrderProcessingService
- Cohesion: 9/10
- Bounded Context: OrderContext
4. Payment Processing (Generic)
- Type: Generic (standard payment gateway)
- Ubiquitous Language: payment, transaction, charge, refund
- Concepts: Payment, PaymentService, PaymentGateway
- Cohesion: 7/10
- Bounded Context: PaymentContext
5. Shipping (Supporting)
- Type: Supporting
- Ubiquitous Language: shipment, tracking, delivery, carrier
- Concepts: Shipment, Tracking, ShippingService
- Cohesion: 8/10
- Bounded Context: ShippingContext
Cohesion Analysis
| Domain A | Domain B | Cohesion | Relationship |
|---|---|---|---|
| Catalog | Inventory | 6/10 | ⚠️ Product availability check |
| Order | Catalog | 5/10 | ⚠️ Product reference in order |
| Order | Payment | 7/10 | ✅ Order triggers payment |
| Order | Shipping | 7/10 | ✅ Order triggers shipment |
| Customer | Order | 3/10 | ❌ Direct entity reference |
Low Cohesion Issues
Issue 1: Customer entity directly referenced in Order
- Problem: Different contexts (Identity vs Order)
- Recommendation: Use CustomerId value object, not entity reference
- Pattern: Published Language
Issue 2: Catalog service checks Inventory directly
- Problem: Core Domain depends on Supporting
- Recommendation: Use event-based inventory updates
- Pattern: Domain Events
---
Example 2: Healthcare System
Discovered Concepts
Entities:
- Patient, MedicalRecord, Diagnosis
- Appointment, Schedule, Availability
- Prescription, Medication, Dosage
- Doctor, Nurse, Staff
- Billing, Claim, Insurance
Language Groups
Clinical Language: patient, diagnosis, treatment, medical record Scheduling Language: appointment, schedule, availability, slot Pharmacy Language: prescription, medication, dosage, drug Staff Language: doctor, nurse, practitioner, credential Billing Language: claim, insurance, copay, reimbursement
Identified Subdomains
1. Patient Care (Core Domain)
- Type: Core
- Ubiquitous Language: patient, diagnosis, treatment, care plan
- Concepts: Patient, MedicalRecord, Diagnosis, CareService
- Cohesion: 9/10
- Bounded Context: ClinicalContext
2. Appointment Management (Supporting)
- Type: Supporting
- Ubiquitous Language: appointment, schedule, availability, booking
- Concepts: Appointment, Schedule, SchedulingService
- Cohesion: 8/10
- Bounded Context: SchedulingContext
3. Pharmacy (Supporting)
- Type: Supporting (or Core if pharmacy is differentiator)
- Ubiquitous Language: prescription, medication, dosage, drug interaction
- Concepts: Prescription, Medication, PharmacyService
- Cohesion: 8/10
- Bounded Context: PharmacyContext
4. Medical Billing (Supporting)
- Type: Supporting
- Ubiquitous Language: claim, insurance, billing, reimbursement
- Concepts: Claim, Insurance, BillingService
- Cohesion: 7/10
- Bounded Context: BillingContext
Key Insight
"Patient" Concept Has Different Meanings:
| Context | Patient Meaning | Properties |
|---|---|---|
| Clinical | Medical subject | Diagnosis, vitals, allergies |
| Scheduling | Appointment holder | Availability, preferences |
| Billing | Payer/beneficiary | Insurance, balance, claims |
→ These are different bounded contexts despite sharing the term "Patient"
---
Example 3: SaaS Project Management Tool
Discovered Concepts
Entities:
- Project, Task, Milestone, Sprint
- User, Team, Role, Permission
- Comment, Attachment, Activity
- Subscription, Plan, Invoice
- Notification, Alert
Language Groups
Project Language: project, task, milestone, sprint, backlog Collaboration Language: comment, discussion, mention, activity Access Language: user, team, role, permission, access Billing Language: subscription, plan, invoice, payment Notification Language: notification, alert, reminder
Identified Subdomains
1. Project Management (Core Domain)
- Type: Core
- Ubiquitous Language: project, task, milestone, workflow
- Concepts: Project, Task, Milestone, ProjectService
- Cohesion: 9/10
- Bounded Context: ProjectContext
2. Collaboration (Core/Supporting)
- Type: Core if differentiator, Supporting otherwise
- Ubiquitous Language: comment, discussion, activity, collaboration
- Concepts: Comment, Activity, CollaborationService
- Cohesion: 8/10
- Bounded Context: CollaborationContext
3. Identity & Access (Generic)
- Type: Generic
- Ubiquitous Language: user, authentication, authorization, role
- Concepts: User, Role, Permission, AuthService
- Cohesion: 9/10
- Bounded Context: IdentityContext
4. Billing (Supporting)
- Type: Supporting
- Ubiquitous Language: subscription, plan, invoice, billing
- Concepts: Subscription, Invoice, BillingService
- Cohesion: 8/10
- Bounded Context: BillingContext
5. Notifications (Generic)
- Type: Generic
- Ubiquitous Language: notification, alert, message, reminder
- Concepts: Notification, NotificationService
- Cohesion: 7/10
- Bounded Context: NotificationContext
Low Cohesion Issue
Issue: User entity used everywhere
// Project domain
class Project {
owner: User; // ❌ Direct reference
members: User[]; // ❌ Direct reference
}
// Collaboration domain
class Comment {
author: User; // ❌ Direct reference
}
// Billing domain
class Subscription {
subscriber: User; // ❌ Direct reference
}Problem: Identity context concept leaked into all domains
Recommendation: Use context-specific concepts
// Project domain
class Project {
ownerId: OwnerId; // ✅ Value object
members: MemberId[]; // ✅ Value object
}
// Collaboration domain
class Comment {
authorId: ParticipantId; // ✅ Context-specific
}
// Billing domain
class Subscription {
subscriberId: CustomerId; // ✅ Context-specific
}---
Example 4: Streaming Video Platform
Discovered Concepts
Entities:
- Movie, TVShow, Episode, Season
- Video, Stream, Encoding, Quality
- Watchlist, Viewing, Progress
- Recommendation, Preference
- Subscription, Plan, Billing
Language Groups
Content Language: movie, show, episode, season, catalog Streaming Language: video, stream, encoding, bitrate, quality Engagement Language: watchlist, viewing, progress, rating Recommendation Language: recommendation, preference, algorithm Billing Language: subscription, plan, billing, payment
Identified Subdomains
1. Content Catalog (Supporting)
- Type: Supporting (unless unique content is differentiator)
- Ubiquitous Language: movie, show, episode, catalog, metadata
- Concepts: Movie, TVShow, Episode, CatalogService
- Cohesion: 9/10
- Bounded Context: CatalogContext
2. Video Streaming (Supporting)
- Type: Supporting
- Ubiquitous Language: video, stream, encoding, playback, quality
- Concepts: Video, Stream, StreamingService
- Cohesion: 8/10
- Bounded Context: StreamingContext
3. User Engagement (Supporting)
- Type: Supporting
- Ubiquitous Language: watchlist, viewing, progress, rating
- Concepts: Watchlist, Viewing, EngagementService
- Cohesion: 8/10
- Bounded Context: EngagementContext
4. Recommendation Engine (Core Domain)
- Type: Core (if algorithm is competitive advantage)
- Ubiquitous Language: recommendation, preference, algorithm, personalization
- Concepts: Recommendation, RecommendationEngine
- Cohesion: 9/10
- Bounded Context: RecommendationContext
5. Video Processing (Generic)
- Type: Generic
- Ubiquitous Language: transcoding, encoding, compression
- Concepts: VideoProcessor, EncodingService
- Cohesion: 7/10
- Bounded Context: ProcessingContext
Integration Pattern
Catalog Context → publishes → ContentPublished event
↓
Recommendation Context ← consumes
↓
Engagement Context → publishes → UserWatched event
↓
Recommendation Context ← consumesPattern: Event-Driven Architecture with Domain Events
---
Common Patterns Across Examples
Pattern 1: Identity Leakage
Problem: User/Identity entities used directly everywhere
Solution: Context-specific identifiers
- Project context: OwnerId, MemberId
- Billing context: CustomerId, SubscriberId
- Content context: CreatorId, ViewerId
Pattern 2: Shared Kernel Overuse
Problem: Large shared models used everywhere
Solution: Minimal shared kernel, mostly value objects
- Share: UserId (as string/UUID), Email (as value object)
- Don't share: User entity, Customer entity
Pattern 3: Core vs Supporting Confusion
Key Question: "Is this our competitive advantage?"
- If YES → Core Domain (best team, most attention)
- If NO but business-specific → Supporting
- If NO and standard → Generic
Pattern 4: Bounded Context Size
Too Small:
OrderContext
OrderItemContext ❌ Gaping holes
OrderStatusContext ❌ FragmentedRight Size:
OrderContext ✅ Complete language
├── Order
├── OrderItem
└── OrderStatusToo Large:
SalesContext ❌ Mixed concerns
├── Order
├── Product
├── Customer
└── InvoicePattern 5: Integration Types
Synchronous (use sparingly):
- When immediate consistency required
- Example: Order → Payment (need immediate response)
Asynchronous (prefer):
- When eventual consistency acceptable
- Example: Order → Shipping (can be delayed)
Event-Driven (best for decoupling):
- When multiple contexts need to react
- Example: OrderPlaced → [Billing, Shipping, Analytics]
---
Quick Analysis Template
Use this template when analyzing any codebase:
## Codebase: {Name}
### Step 1: Concepts Extracted
- Entities: [list]
- Services: [list]
- Use Cases: [list]
- Controllers: [list]
### Step 2: Language Groups
- Group 1: {name} - terms: [list]
- Group 2: {name} - terms: [list]
### Step 3: Subdomains Identified
1. {Subdomain} (Core/Supporting/Generic)
- Language: [terms]
- Concepts: [list]
- Cohesion: X/10
- Bounded Context: {Name}Context
### Step 4: Cohesion Matrix
| Domain A | Domain B | Cohesion | Issue |
|----------|----------|----------|-------|
| ... | ... | X/10 | ... |
### Step 5: Issues Found
- Priority High: [list]
- Priority Medium: [list]
- Priority Low: [list]
### Step 6: Recommendations
1. [recommendation]
2. [recommendation]Quick Reference Card
Decision Trees
Subdomain Classification
┌─────────────────────────────────────────┐
│ Is it a competitive advantage? │
│ Does it differentiate the business? │
└─────────────┬───────────────────────────┘
│
YES │ NO
┌───────┴────────┐
▼ ▼
┌──────────┐ ┌─────────────────────────┐
│ CORE │ │ Is it business-specific?│
│ DOMAIN │ │ Requires domain knowledge?
└──────────┘ └────────┬────────────────┘
│
YES │ NO
┌───────┴──────┐
▼ ▼
┌────────────┐ ┌─────────┐
│ SUPPORTING │ │ GENERIC │
│ SUBDOMAIN │ │SUBDOMAIN│
└────────────┘ └─────────┘Bounded Context Detection
┌──────────────────────────────────┐
│ Same term, different meaning? │
└────────────┬─────────────────────┘
│
YES │ NO
┌───────┴──────┐
▼ ▼
┌─────────┐ ┌────────────┐
│DIFFERENT│ │ SAME │
│CONTEXTS │ │ CONTEXT │
└─────────┘ └────────────┘
Examples:
• "Customer" in Sales vs Support → DIFFERENT
• "Product" everywhere same → SAME (but verify!)Cohesion Scoring
Quick Score
Linguistic (0-3):
└─ Same vocabulary?
3 = All terms shared
2 = Most terms shared
1 = Some terms shared
0 = Different vocabulary
Usage (0-3):
└─ Used together?
3 = Always used together
2 = Frequently together
1 = Sometimes together
0 = Rarely together
Data (0-2):
└─ Direct relationships?
2 = Direct entity relationships
1 = Indirect relationships
0 = No relationships
Change (0-2):
└─ Change together?
2 = Always change together
1 = Sometimes together
0 = Independently
Total: X / 10Interpretation
8-10 ✅ HIGH
└─ Strong subdomain candidate
└─ Good bounded context boundary
5-7 ⚠️ MEDIUM
└─ Review boundaries
└─ May need refinement
0-4 ❌ LOW
└─ Wrong grouping
└─ Needs separationRed Flags
Linguistic Issues
❌ User + Subscription in same service
→ Identity mixed with Billing
❌ Movie + Invoice in same context
→ Content mixed with Billing
❌ Authentication + Content in same module
→ Generic mixed with Core
✅ Subscription + Invoice + Payment together
→ All Billing languageCoupling Issues
❌ Direct entity import across domains
import { User } from '@identity/entities'
❌ Service dependency across domains
constructor(subscriptionService: SubscriptionService)
❌ Shared database tables across domains
FOREIGN KEY(user_id) REFERENCES users(id)
✅ Interface-based integration
constructor(billingApi: IBillingApi)
✅ Event-based communication
eventBus.publish(new OrderPlaced(...))
✅ Value object sharing
class Order { customerId: CustomerId }Common Subdomains
Generic (can outsource)
• Authentication/Authorization
• Email/SMS sending
• File storage
• Logging/Monitoring
• Caching
• Search indexing (basic)Supporting (business-specific)
• Inventory management
• Order fulfillment
• Content moderation
• User notifications
• Reporting/Analytics
• Invoice generationCore (competitive advantage)
• Recommendation algorithm (unique)
• Pricing strategy (custom)
• Matching algorithm (proprietary)
• Risk assessment (specialized)
• Forecasting model (custom)Integration Patterns
When to Use Each
SHARED KERNEL
├─ Use: Rarely, small value objects only
├─ Example: Money, Address, Email
└─ Warning: Creates coupling
CUSTOMER/SUPPLIER
├─ Use: Clear upstream/downstream
├─ Example: Order → Shipping
└─ Pattern: API contract
ANTI-CORRUPTION LAYER
├─ Use: Protecting from external systems
├─ Example: Legacy system integration
└─ Pattern: Translation layer
DOMAIN EVENTS
├─ Use: Multiple consumers, eventual consistency
├─ Example: OrderPlaced → [Billing, Shipping]
└─ Pattern: Pub/Sub
OPEN HOST SERVICE
├─ Use: Published API for others
├─ Example: Payment gateway API
└─ Pattern: REST/GraphQL APIAnalysis Checklist
Per Concept
□ Business language identified?
□ Domain assigned?
□ Subdomain assigned?
□ Core/Supporting/Generic classified?
□ Related concepts identified?
□ Dependencies mapped?
□ Linguistic mismatches checked?Per Domain
□ Ubiquitous Language defined?
□ Key concepts listed?
□ Subdomains identified?
□ Core Domain identified?
□ Cross-domain dependencies mapped?
□ Internal cohesion assessed?
□ Boundaries validated?Per Bounded Context
□ Linguistic boundary clear?
□ Contains complete model?
□ Integration points defined?
□ No mixed vocabularies?
□ Size appropriate (Mozart Principle)?
□ Not driven by architecture?
□ Not driven by team structure?Size Guidelines
Too Small
❌ Gaping holes in Ubiquitous Language
❌ Incomplete business capability
❌ Too many integration points
❌ Fragments of concepts
Example:
- ProductContext (only Product)
- InventoryContext (only Stock)
- PricingContext (only Price)
→ Should be: CatalogContextJust Right
✅ Complete Ubiquitous Language
✅ Full business capability
✅ Clear integration points
✅ Cohesive concepts
Example:
CatalogContext
├── Product
├── Category
├── Inventory
└── PricingToo Large
❌ Multiple vocabularies mixed
❌ Multiple business capabilities
❌ Low internal cohesion
❌ Muddy boundaries
Example:
BusinessContext
├── Order (order language)
├── Product (catalog language)
├── User (identity language)
└── Payment (billing language)
→ Should be: 4 separate contextsCommon Mistakes
Mistake 1: Grouping by Technical Layer
❌ WRONG:
- ControllerContext
- ServiceContext
- RepositoryContext
✅ RIGHT:
- OrderContext (all layers for orders)
- ProductContext (all layers for products)Mistake 2: Sharing Entities Directly
❌ WRONG:
class Order {
user: User; // Full entity from Identity
}
✅ RIGHT:
class Order {
customerId: CustomerId; // Value object
}Mistake 3: One Size Fits All
❌ WRONG: Force all domains to have same size
✅ RIGHT: Size based on Ubiquitous Language
- Small domain: 3-5 concepts (if complete)
- Medium domain: 6-15 concepts
- Large domain: 16+ concepts (if cohesive)Mistake 4: Technical Boundaries
❌ WRONG: Bounded contexts for:
- Frontend vs Backend
- Microservice per entity
- One context per database
✅ RIGHT: Linguistic boundaries:
- Where terms have specific meanings
- Where business capabilities are distinctKey Questions
For Subdomain Classification
1. Does this provide competitive advantage?
2. Is it business-specific or generic?
3. Is it essential to core business?
4. Could we outsource it?
5. How often does it change?
6. Does it require domain experts?For Bounded Context Definition
1. Does this term have different meanings elsewhere?
2. Can we define all terms unambiguously here?
3. Is this a complete business capability?
4. Are all concepts linguistically related?
5. Where do we translate between contexts?
6. What are the integration points?For Cohesion Assessment
1. Do these concepts share vocabulary?
2. Are they used together frequently?
3. Do changes affect them together?
4. Do they solve the same business problem?
5. Are they in the same lifecycle?
6. Do they have direct relationships?Signal Words
Core Domain Signals
"competitive advantage"
"unique to our business"
"our secret sauce"
"what makes us different"
"complex business rules"
"needs domain experts"Supporting Signals
"necessary but standard"
"business-specific"
"supports core operations"
"moderate complexity"
"internal tool"Generic Signals
"could buy this"
"standard functionality"
"well-known solution"
"common to all businesses"
"infrastructure"Low Cohesion Signals
"mixed concerns"
"different vocabularies"
"unrelated concepts"
"tight coupling"
"unclear boundary"
"linguistic mismatch"Subdomain Identification & Bounded Context Analysis
This skill analyzes codebases to identify subdomains (Core, Supporting, Generic) and suggest bounded contexts following Domain-Driven Design Strategic Design principles.
The modular-decomposition skill embeds a verbatim copy of this bundle under references/domain-analysis/ for users who want one install for the full decomposition pipeline. This standalone domain-analysis skill remains the catalog install target when you only need DDD strategic analysis.
When to Use
Apply this skill when:
- Analyzing domain boundaries in any codebase
- Identifying Core, Supporting, and Generic subdomains
- Mapping bounded contexts from problem space to solution space
- Assessing domain cohesion and detecting coupling issues
- Planning domain-driven refactoring
- Understanding business capabilities in code
Core Principles
Subdomain Classification
Core Domain: Competitive advantage, highest business value, requires best developers
- Indicators: Complex business logic, frequent changes, domain experts needed
Supporting Subdomain: Essential but not differentiating, business-specific
- Indicators: Supports Core Domain, moderate complexity, business-specific rules
Generic Subdomain: Common functionality, could be outsourced
- Indicators: Well-understood problem, low differentiation, standard functionality
Bounded Context
An explicit linguistic boundary where domain terms have specific, unambiguous meanings.
- Primary nature: Linguistic boundary, not technical
- Key rule: Inside boundary, all Ubiquitous Language terms are unambiguous
- Goal: Align 1 subdomain to 1 bounded context (ideal)
Analysis Process
Phase 1: Extract Concepts
Scan codebase for business concepts (not infrastructure):
1. Entities (domain models with identity)
- Patterns:
@Entity,class, domain models - Focus: Business concepts, not technical classes
2. Services (business operations)
- Patterns:
*Service,*Manager,*Handler - Focus: Business logic, not technical utilities
3. Use Cases (business workflows)
- Patterns:
*UseCase,*Command,*Handler - Focus: Business processes, not CRUD
4. Controllers/Resolvers (entry points)
- Patterns:
*Controller,*Resolver, API endpoints - Focus: Business capabilities, not technical routes
Phase 2: Group by Ubiquitous Language
For each concept, determine:
Primary Language Context
- What business vocabulary does this belong to?
- Examples:
Subscription,Invoice,Payment→ Billing languageMovie,Video,Episode→ Content languageUser,Authentication→ Identity language
Linguistic Boundaries
- Where do term meanings change?
- Same term, different meaning = different bounded context
- Example: "Customer" in Sales vs "Customer" in Support
Concept Relationships
- Which concepts naturally belong together?
- Which share business vocabulary?
- Which reference each other?
Phase 3: Identify Subdomains
A subdomain has:
- Distinct business capability
- Independent business value
- Unique vocabulary
- Multiple related entities working together
- Cohesive set of business operations
Common Domain Patterns:
- Billing/Subscription: Payments, invoices, plans
- Content/Catalog: Media, products, inventory
- Identity/Access: Users, authentication, authorization
- Analytics: Metrics, dashboards, insights
- Notifications: Messages, alerts, communications
Classify Each Subdomain:
Use this decision tree:
Is it a competitive advantage?
YES → Core Domain
NO → Does it require business-specific knowledge?
YES → Supporting Subdomain
NO → Generic SubdomainPhase 4: Assess Cohesion
High Cohesion Indicators ✅
- Concepts share Ubiquitous Language
- Concepts frequently used together
- Direct business relationships
- Changes to one affect others in group
- Solve same business problem
Low Cohesion Indicators ❌
- Different business vocabularies mixed
- Concepts rarely used together
- No direct business relationship
- Changes don't affect others
- Solve different business problems
Cohesion Score Formula:
Score = (
Linguistic Cohesion (0-3) + // Shared vocabulary
Usage Cohesion (0-3) + // Used together
Data Cohesion (0-2) + // Entity relationships
Change Cohesion (0-2) // Change together
) / 10
8-10: High Cohesion ✅
5-7: Medium Cohesion ⚠️
0-4: Low Cohesion ❌Phase 5: Detect Low Cohesion Issues
Rule 1: Linguistic Mismatch
- Problem: Different business vocabularies mixed
- Example:
User(identity) +Subscription(billing) in same service - Action: Suggest separation into different bounded contexts
Rule 2: Cross-Domain Dependencies
- Problem: Tight coupling between domains
- Example: Service A directly instantiates entities from Domain B
- Action: Suggest interface-based integration
Rule 3: Mixed Responsibilities
- Problem: Single class handles multiple business concerns
- Example: Service handling both billing and content
- Action: Suggest splitting by subdomain
Rule 4: Generic in Core
- Problem: Generic functionality in core business logic
- Example: Email sending in billing service
- Action: Extract to Generic Subdomain
Rule 5: Unclear Boundaries
- Problem: Cannot determine which domain concept belongs to
- Example: Entity with relationships to multiple domains
- Action: Clarify boundaries, possibly split concept
Phase 6: Map Bounded Contexts
For each subdomain identified, suggest bounded context:
Bounded Context Characteristics:
- Name reflects Ubiquitous Language
- Contains complete domain model
- Has explicit integration points
- Clear linguistic boundary
Integration Patterns:
- Shared Kernel: Shared model between contexts (use sparingly)
- Customer/Supplier: Downstream depends on upstream
- Conformist: Downstream conforms to upstream
- Anti-corruption Layer: Translation layer between contexts
- Open Host Service: Published interface for integration
- Published Language: Well-documented integration protocol
Output Format
Domain Map
For each domain/subdomain:
## Domain: {Name}
**Type**: Core Domain | Supporting Subdomain | Generic Subdomain
**Ubiquitous Language**: {key business terms}
**Business Capability**: {what business problem it solves}
**Key Concepts**:
- {Concept} (Entity|Service|UseCase) - {brief description}
**Subdomains** (if applicable):
1. {Subdomain} (Core|Supporting|Generic)
- Concepts: {list}
- Cohesion: {score}/10
- Dependencies: → {other domains}
**Suggested Bounded Context**: {Name}Context
- Linguistic boundary: {where terms have specific meaning}
- Integration: {how it should integrate with other contexts}
**Dependencies**:
- → {OtherDomain} via {interface/API}
- ← {OtherDomain} via {interface/API}
**Cohesion Score**: {score}/10Cohesion Matrix
## Cross-Domain Cohesion
| Domain A | Domain B | Cohesion | Issue | Recommendation |
| -------- | -------- | -------- | ------------------ | ----------------------- |
| Billing | Identity | 2/10 | ❌ Direct coupling | Use interface |
| Content | Billing | 6/10 | ⚠️ Usage tracking | Event-based integration |Low Cohesion Report
## Issues Detected
### Priority: High
**Issue**: {description}
- **Location**: {file/class/method}
- **Problem**: {what's wrong}
- **Concepts**: {involved concepts}
- **Cohesion**: {score}/10
- **Recommendation**: {suggested fix}
### Priority: Medium
{similar format}Bounded Context Map
## Suggested Bounded Contexts
### {ContextName}Context
**Contains Subdomains**:
- {Subdomain1} (Core)
- {Subdomain2} (Supporting)
**Ubiquitous Language**:
- Term: Definition in this context
**Integration Requirements**:
- Consumes from: {OtherContext} via {pattern}
- Publishes to: {OtherContext} via {pattern}
**Implementation Notes**:
- Separate persistence
- Independent deployment
- Explicit API boundariesBest Practices
Do's ✅
- Focus on business language, not code structure
- Let Ubiquitous Language guide boundaries
- Measure cohesion objectively
- Identify clear integration points
- Classify every subdomain (Core/Supporting/Generic)
- Look for linguistic boundaries first
Don'ts ❌
- Don't group by technical layers
- Don't force single global model
- Don't ignore linguistic differences
- Don't couple domains directly
- Don't create contexts by architecture
- Don't eliminate all dependencies (some are necessary)
Analysis Checklist
For Each Concept:
- [ ] What business language does it belong to?
- [ ] What domain/subdomain is it part of?
- [ ] Is it Core, Supporting, or Generic?
- [ ] What other concepts does it relate to?
- [ ] Are dependencies within same domain?
- [ ] Any linguistic mismatches?
For Each Domain:
- [ ] What is the Ubiquitous Language?
- [ ] What are the key concepts?
- [ ] What are the subdomains?
- [ ] Which is the Core Domain?
- [ ] What are cross-domain dependencies?
- [ ] Is internal cohesion high?
- [ ] Are boundaries clear?
For Cohesion Analysis:
- [ ] Calculate cohesion scores
- [ ] Identify low cohesion areas
- [ ] Map cross-domain dependencies
- [ ] Flag linguistic mismatches
- [ ] Note tight coupling
- [ ] Suggest boundary clarifications
Quick Reference
Subdomain Decision Tree
Analyze business capability
└─ Is it competitive advantage?
├─ YES → Core Domain
└─ NO → Is it business-specific?
├─ YES → Supporting Subdomain
└─ NO → Generic SubdomainCohesion Quick Check
Same vocabulary? → High linguistic cohesion
Used together? → High usage cohesion
Direct relationships? → High data cohesion
Change together? → High change cohesion
All high → Strong subdomain candidate
Mix of high/low → Review boundaries
All low → Likely wrong groupingBounded Context Signals
Clear boundary signs:
✅ Distinct Ubiquitous Language
✅ Concepts have unambiguous meaning
✅ Different meanings across contexts
✅ Clear integration points
Unclear boundary signs:
❌ Same terms with same meanings everywhere
❌ Concepts used identically across system
❌ No clear linguistic differences
❌ Tight coupling everywhereAnti-Patterns to Avoid
Big Ball of Mud
- Everything connected to everything
- No clear boundaries
- Mixed vocabularies
- Prevention: Explicit bounded contexts
All-Inclusive Model
- Single model for entire business
- Impossible global definitions
- Creates conflicts
- Prevention: Embrace multiple contexts
Mixed Linguistic Concepts
- Different vocabularies in same context
- Example: User/Permission with Forum/Post
- Prevention: Keep linguistic associations
Notes
- This is strategic analysis, not tactical implementation
- Focus on WHAT domains exist, not HOW to implement
- Some cross-domain dependencies are normal
- Low cohesion doesn't always mean "bad," it means "needs attention"
- Generic Subdomains naturally have lower cohesion
- Always validate with domain experts when possible
Validation Criteria
Good domain identification has:
- ✅ Clear boundaries with distinct Ubiquitous Language
- ✅ High internal cohesion within domains
- ✅ Explicit cross-domain dependencies
- ✅ Business alignment with capabilities
- ✅ Actionable recommendations for issues
Component Identification & Sizing - Quick Reference
Component Definition
Component = Leaf node in directory/namespace structure containing source files
Subdomain = Parent namespace that has been extended (not a component)
Size Metrics
| Metric | How to Calculate | Purpose |
|---|---|---|
| Statements | Count executable statements (not lines) | Accurate size measure |
| Files | Count source files in component | Complexity indicator |
| Percent | (component_statements / total_statements) * 100 | Relative size |
| Std Dev | sqrt(sum((size - mean)^2) / (n-1)) | Outlier detection |
Size Thresholds
| App Size | Oversized Threshold | Notes |
|---|---|---|
| Small (<10 components) | >30% of codebase | Fewer components, higher variance |
| Medium (10-20 components) | >15% of codebase | Balanced threshold |
| Large (>20 components) | >10% of codebase | More components, lower variance |
Standard Deviation Rule: Components >2 std dev from mean are oversized
Component Status
- ✅ OK: Within 1-2 std dev from mean, appropriate size
- ⚠️ Too Large: >2 std dev above mean or exceeds threshold
- 🔍 Too Small: <1 std dev below mean or <1% of codebase
Quick Analysis Steps
1. Map directories → Identify leaf nodes (components) 2. Count statements → Per component, sum across files 3. Calculate stats → Mean, std dev, percentages 4. Flag outliers → >2 std dev or threshold violations 5. Recommend actions → Split large, consolidate small
Common Patterns
Node.js/Express
services/ComponentName/ ← Component
routes/v1/endpoint/ ← Component
models/ModelName/ ← ComponentJava
com.company.domain.service ← Component (leaf package)
com.company.domain ← Subdomain (parent)Python
app/domain/service/ ← Component (leaf module)
app/domain/ ← Subdomain (parent)Output Template
## Component Inventory
| Component | Namespace | Statements | Files | % | Status |
| --------- | --------- | ---------- | ----- | --- | ------ |
| Name | path | 4,312 | 23 | 5% | ✅ OK |
## Summary
- Total: X components
- Mean: Y statements
- Std Dev: Z statements
- Oversized: [list]
- Recommendations: [actions]Component Identification and Sizing
This skill identifies architectural components (logical building blocks) in a codebase and calculates size metrics to assess decomposition feasibility and identify oversized components.
How to Use
Quick Start
Request analysis of your codebase:
- "Identify and size all components in this codebase"
- "Find oversized components that need splitting"
- "Create a component inventory for decomposition planning"
- "Analyze component size distribution"
Usage Examples
Example 1: Complete Analysis
User: "Identify and size all components in this codebase"
The skill will:
1. Map directory/namespace structures
2. Identify all components (leaf nodes)
3. Calculate size metrics (statements, files, percentages)
4. Generate component inventory table
5. Flag oversized/undersized components
6. Provide recommendationsExample 2: Find Oversized Components
User: "Which components are too large?"
The skill will:
1. Calculate mean and standard deviation
2. Identify components >2 std dev or >10% threshold
3. Analyze functional areas within large components
4. Suggest specific splits with estimated sizesExample 3: Component Size Analysis
User: "Analyze component sizes and distribution"
The skill will:
1. Calculate all size metrics
2. Generate size distribution summary
3. Identify outliers
4. Provide statistics and recommendationsStep-by-Step Process
1. Initial Analysis: Start with complete component inventory 2. Identify Issues: Find components that need attention 3. Get Recommendations: Request actionable split/consolidation suggestions 4. Monitor Progress: Track component growth over time
When to Use
Apply this skill when:
- Starting a monolithic decomposition effort
- Assessing codebase structure and organization
- Identifying components that are too large or too small
- Creating component inventory for migration planning
- Analyzing code distribution across components
- Preparing for component-based decomposition patterns
Core Concepts
Component Definition
A component is an architectural building block that:
- Has a well-defined role and responsibility
- Is identified by a namespace, package structure, or directory path
- Contains source code files (classes, functions, modules) grouped together
- Performs specific business or infrastructure functionality
Key Rule: Components are identified by leaf nodes in directory/namespace structures. If a namespace is extended (e.g., services/billing extended to services/billing/payment), the parent becomes a subdomain, not a component.
Size Metrics
Statements (not lines of code):
- Count executable statements terminated by semicolons or newlines
- More accurate than lines of code for size comparison
- Accounts for code complexity, not formatting
Component Size Indicators:
- Percent of codebase: Component statements / Total statements
- File count: Number of source files in component
- Standard deviation: Distance from mean component size
Analysis Process
Phase 1: Identify Components
Scan the codebase directory structure:
1. Map directory/namespace structure
- For Node.js:
services/,routes/,models/,utils/ - For Java: Package structure (e.g.,
com.company.domain.service) - For Python: Module paths (e.g.,
app/billing/payment)
2. Identify leaf nodes
- Components are the deepest directories containing source files
- Example:
services/BillingService/is a component - Example:
services/BillingService/payment/extends it, makingBillingServicea subdomain
3. Create component inventory
- List each component with its namespace/path
- Note any parent namespaces (subdomains)
Phase 2: Calculate Size Metrics
For each component:
1. Count statements
- Parse source files in component directory
- Count executable statements (not comments, blank lines, or declarations alone)
- Sum across all files in component
2. Count files
- Total source files (
.js,.ts,.java,.py, etc.) - Exclude test files, config files, documentation
3. Calculate percentage
component_percent = (component_statements / total_statements) * 1004. Calculate statistics
- Mean component size:
total_statements / number_of_components - Standard deviation:
sqrt(sum((size - mean)^2) / (n - 1)) - Component's deviation:
(component_size - mean) / std_dev
Phase 3: Identify Size Issues
Oversized Components (candidates for splitting):
- Exceeds 30% of total codebase (for small apps with <10 components)
- Exceeds 10% of total codebase (for large apps with >20 components)
- More than 2 standard deviations above mean
- Contains multiple distinct functional areas
Undersized Components (candidates for consolidation):
- Less than 1% of codebase (may be too granular)
- Less than 1 standard deviation below mean
- Contains only a few files with minimal functionality
Well-Sized Components:
- Between 1-2 standard deviations from mean
- Represents a single, cohesive functional area
- Appropriate percentage for application size
Output Format
Component Inventory Table
## Component Inventory
| Component Name | Namespace/Path | Statements | Files | Percent | Status |
| --------------- | ---------------------------- | ---------- | ----- | ------- | ------------ |
| Billing Payment | services/BillingService | 4,312 | 23 | 5% | ✅ OK |
| Reporting | services/ReportingService | 27,765 | 162 | 33% | ⚠️ Too Large |
| Notification | services/NotificationService | 1,433 | 7 | 2% | ✅ OK |Status Legend:
- ✅ OK: Well-sized (within 1-2 std dev from mean)
- ⚠️ Too Large: Exceeds size threshold or >2 std dev above mean
- 🔍 Too Small: <1% of codebase or <1 std dev below mean
Size Analysis Summary
## Size Analysis Summary
**Total Components**: 18
**Total Statements**: 82,931
**Mean Component Size**: 4,607 statements
**Standard Deviation**: 5,234 statements
**Oversized Components** (>2 std dev or >10%):
- Reporting (33% - 27,765 statements) - Consider splitting into:
- Ticket Reports
- Expert Reports
- Financial Reports
**Well-Sized Components** (within 1-2 std dev):
- Billing Payment (5%)
- Customer Profile (5%)
- Ticket Assignment (9%)
**Undersized Components** (<1 std dev):
- Login (2% - 1,865 statements) - Consider consolidating with AuthenticationComponent Size Distribution
## Component Size DistributionComponent Size Distribution (by percent of codebase)
[Visual representation or histogram if possible]
Largest: ████████████████████████████████████ 33% (Reporting) ████████ 9% (Ticket Assign) ██████ 8% (Ticket) ██████ 6% (Expert Profile) █████ 5% (Billing Payment) ████ 4% (Billing History) ...
````
Recommendations
## Recommendations
### High Priority: Split Large Components
**Reporting Component** (33% of codebase):
- **Current**: Single component with 27,765 statements
- **Issue**: Too large, contains multiple functional areas
- **Recommendation**: Split into:
1. Reporting Shared (common utilities)
2. Ticket Reports (ticket-related reports)
3. Expert Reports (expert-related reports)
4. Financial Reports (financial reports)
- **Expected Result**: Each component ~7-9% of codebase
### Medium Priority: Review Small Components
**Login Component** (2% of codebase):
- **Current**: 1,865 statements, 3 files
- **Consideration**: May be too granular if related to broader authentication
- **Recommendation**: Evaluate if should be consolidated with Authentication/User components
### Low Priority: Monitor Well-Sized Components
Most components are appropriately sized. Continue monitoring during decomposition.Analysis Checklist
Component Identification:
- [ ] Mapped all directory/namespace structures
- [ ] Identified leaf nodes (components) vs parent nodes (subdomains)
- [ ] Created complete component inventory
- [ ] Documented namespace/path for each component
Size Calculation:
- [ ] Counted statements (not lines) for each component
- [ ] Counted source files (excluding tests/configs)
- [ ] Calculated percentage of total codebase
- [ ] Calculated mean and standard deviation
Size Assessment:
- [ ] Identified oversized components (>threshold or >2 std dev)
- [ ] Identified undersized components (<1% or <1 std dev)
- [ ] Flagged components for splitting or consolidation
- [ ] Documented size distribution
Recommendations:
- [ ] Suggested splits for oversized components
- [ ] Suggested consolidations for undersized components
- [ ] Prioritized recommendations by impact
- [ ] Created architecture stories for refactoring
Implementation Notes
For Node.js/Express Applications
Components typically found in:
services/- Business logic componentsroutes/- API endpoint componentsmodels/- Data model componentsutils/- Utility componentsmiddleware/- Middleware components
Example Component Identification:
services/
├── BillingService/ ← Component (leaf node)
│ ├── index.js
│ └── BillingService.js
├── CustomerService/ ← Component (leaf node)
│ └── CustomerService.js
└── NotificationService/ ← Component (leaf node)
└── NotificationService.jsFor Java Applications
Components identified by package structure:
com.company.domain.service- Service componentscom.company.domain.model- Model componentscom.company.domain.repository- Repository components
Example Component Identification:
com.company.billing.payment ← Component (leaf package)
com.company.billing.history ← Component (leaf package)
com.company.billing ← Subdomain (parent of payment/history)Statement Counting
JavaScript/TypeScript:
- Count statements terminated by
;or newline - Include: assignments, function calls, returns, conditionals, loops
- Exclude: comments, blank lines, declarations without assignment
Java:
- Count statements terminated by
; - Include: method calls, assignments, returns, conditionals
- Exclude: class/interface declarations, comments, blank lines
Python:
- Count executable statements (not comments or blank lines)
- Include: assignments, function calls, returns, conditionals
- Exclude: docstrings, comments, blank lines
Fitness Functions
After identifying and sizing components, create automated checks:
Component Size Threshold
// Alert if any component exceeds 10% of codebase
function checkComponentSize(components, threshold = 0.1) {
const totalStatements = components.reduce((sum, c) => sum + c.statements, 0)
return components
.filter((c) => c.statements / totalStatements > threshold)
.map((c) => ({
component: c.name,
percent: ((c.statements / totalStatements) * 100).toFixed(1),
issue: 'Exceeds size threshold',
}))
}Standard Deviation Check
// Alert if component is >2 standard deviations from mean
function checkStandardDeviation(components) {
const sizes = components.map((c) => c.statements)
const mean = sizes.reduce((a, b) => a + b, 0) / sizes.length
const stdDev = Math.sqrt(sizes.reduce((sum, size) => sum + Math.pow(size - mean, 2), 0) / (sizes.length - 1))
return components
.filter((c) => Math.abs(c.statements - mean) > 2 * stdDev)
.map((c) => ({
component: c.name,
deviation: ((c.statements - mean) / stdDev).toFixed(2),
issue: 'More than 2 standard deviations from mean',
}))
}Best Practices
Do's ✅
- Use statements, not lines of code
- Identify components as leaf nodes only
- Calculate both percentage and standard deviation
- Consider application size when setting thresholds
- Document namespace/path for each component
- Create visual size distribution if possible
Don'ts ❌
- Don't count test files in component size
- Don't treat parent directories as components
- Don't use fixed thresholds without considering app size
- Don't ignore small components (may need consolidation)
- Don't skip standard deviation calculation
- Don't mix infrastructure and domain components in same analysis
Next Steps
After completing component identification and sizing:
1. Apply Gather Common Domain Components Pattern - Identify duplicate functionality 2. Apply Flatten Components Pattern - Remove orphaned classes from root namespaces 3. Apply Determine Component Dependencies Pattern - Analyze coupling between components 4. Create Component Domains - Group components into logical domains
Notes
- Component size thresholds vary by application size
- Small apps (<10 components): 30% threshold may be appropriate
- Large apps (>20 components): 10% threshold is more appropriate
- Standard deviation is more reliable than fixed percentages
- Well-sized components are 1-2 standard deviations from mean
- Oversized components often contain multiple functional areas that can be split
Common Domain Component Detection - Quick Reference
Domain vs Infrastructure
| Type | Description | Examples | Consolidate? |
|---|---|---|---|
| Domain | Business logic, common to some processes | Notification, audit, validation | ✅ Yes |
| Infrastructure | Technical concerns, common to all | Logging, metrics, security | ❌ No (handled separately) |
Detection Strategies
1. Namespace Pattern Detection
Find components with common leaf node names:
services/customer/notification ← Common pattern
services/ticket/notification ← Common pattern
services/survey/notification ← Common patternCommon Patterns:
*.notification,*.notify,*.email*.audit,*.auditing,*.log*.validation,*.validate,*.validator*.format,*.formatter,*.formatting
2. Shared Class Detection
Find classes used across multiple components:
SMTPConnection → Used by 5 components
AuditLogger → Used by 8 components
DataFormatter → Used by 3 components3. Functionality Analysis
Examine code to verify similarity:
- Read source code of each component
- Identify similarities and differences
- Assess if differences can be abstracted
Coupling Analysis
Before Consolidation
Component A: CA = 2 (used by 2 components)
Component B: CA = 2 (used by 2 components)
Component C: CA = 1 (used by 1 component)
Total CA: 5After Consolidation
Consolidated Component: CA = 5 (used by 5 components)
Total CA: 5 (same!)Verdict: ✅ Safe to consolidate (no coupling increase)
Warning Signs
After Consolidation: CA = 15 (was 5)
Verdict: ⚠️ High coupling increase - reconsiderConsolidation Approaches
Shared Service
Use when:
- Functionality changes frequently
- Complex operations
- Needs independent scaling
Example: Notification service called by multiple components
Shared Library
Use when:
- Stable functionality
- Simple utilities
- Compile-time dependency acceptable
Example: Validation utilities packaged as npm package
Component Merge
Use when:
- Highly related functionality
- Low coupling impact
- Same deployment unit acceptable
Example: Merge 3 notification components into 1
Quick Analysis Steps
1. Scan → Find common namespace patterns 2. Detect → Identify shared classes 3. Analyze → Verify functionality similarity 4. Assess → Calculate coupling impact 5. Recommend → Suggest consolidation approach
Output Template
## Common Domain Components Found
### [Functionality Name]
**Components**:
- component1 (X% - Y statements)
- component2 (X% - Y statements)
**Functionality Analysis**:
- Similarities: [what's the same]
- Differences: [what's different]
- Consolidation Feasibility: ✅ High / ⚠️ Medium / ❌ Low
**Coupling Analysis**:
- Before: CA = X
- After: CA = Y
- Verdict: ✅ Safe / ⚠️ Monitor / ❌ Too risky
**Recommendation**: [consolidation approach]Decision Tree
Found common pattern?
├─ YES → Analyze functionality
│ ├─ Similar enough?
│ │ ├─ YES → Assess coupling
│ │ │ ├─ CA increase acceptable?
│ │ │ │ ├─ YES → ✅ Consolidate
│ │ │ │ └─ NO → ⚠️ Reconsider or use shared library
│ │ └─ NO → ❌ Don't consolidate
│ └─ NO → ❌ Don't consolidate
└─ NO → No consolidation neededCommon Patterns
High Consolidation Candidates ✅
- Notification components
- Audit components
- Validation components
- Formatting components
Low Consolidation Candidates ❌
- Infrastructure utilities
- Different business contexts
- High coupling risk scenarios
Common Domain Component Detection
This skill identifies common domain functionality that is duplicated across multiple components and suggests consolidation opportunities to reduce duplication and improve maintainability.
How to Use
Quick Start
Request analysis of your codebase:
- "Find common domain functionality across components"
- "Identify duplicate domain logic that should be consolidated"
- "Detect shared classes used across multiple components"
- "Analyze consolidation opportunities for common components"
Usage Examples
Example 1: Find Common Functionality
User: "Find common domain functionality across components"
The skill will:
1. Scan component namespaces for common patterns
2. Detect shared classes used across components
3. Identify duplicate domain logic
4. Analyze coupling impact of consolidation
5. Suggest consolidation opportunitiesExample 2: Detect Duplicate Notification Logic
User: "Are there multiple notification components that should be consolidated?"
The skill will:
1. Find all components with notification-related names
2. Analyze their functionality and dependencies
3. Calculate coupling impact if consolidated
4. Recommend consolidation approachExample 3: Analyze Shared Classes
User: "Find classes that are shared across multiple components"
The skill will:
1. Identify classes imported/used by multiple components
2. Classify as domain vs infrastructure functionality
3. Suggest consolidation or shared library approach
4. Assess impact on couplingStep-by-Step Process
1. Scan Components: Identify components with common namespace patterns 2. Detect Shared Code: Find classes/files used across components 3. Analyze Functionality: Determine if functionality is truly common 4. Assess Coupling: Calculate coupling impact before consolidation 5. Recommend Actions: Suggest consolidation or shared library approach
When to Use
Apply this skill when:
- After identifying and sizing components (Pattern 1)
- Before flattening components (Pattern 3)
- When planning to reduce code duplication
- Analyzing shared domain logic across the codebase
- Preparing for component consolidation
- Identifying candidates for shared services or libraries
Core Concepts
Domain vs Infrastructure Functionality
Domain Functionality (candidates for consolidation):
- Business processing logic (notification, validation, auditing, formatting)
- Common to some processes, not all
- Examples: Customer notification, ticket auditing, data validation
Infrastructure Functionality (usually not consolidated here):
- Operational concerns (logging, metrics, security)
- Common to all processes
- Examples: Logging, authentication, database connections
Common Domain Patterns
Common domain functionality often appears as:
1. Namespace Patterns: Components ending in same leaf node
*.notification,*.audit,*.validation,*.formatting- Example:
TicketNotification,BillingNotification,SurveyNotification
2. Shared Classes: Same class used across multiple components
- Example:
SMTPConnectionused by 5 different components - Example:
AuditLoggerused by multiple domain components
3. Similar Functionality: Different components doing similar things
- Example: Multiple components sending emails with slight variations
- Example: Multiple components writing audit logs
Consolidation Approaches
Shared Service:
- Common functionality becomes a separate service
- Other components call this service
- Good for: Frequently changing logic, complex operations
Shared Library:
- Common code packaged as library (JAR, DLL, npm package)
- Components import and use the library
- Good for: Stable functionality, simple utilities
Component Consolidation:
- Merge multiple components into one
- Good for: Highly related functionality, low coupling impact
Analysis Process
Phase 1: Identify Common Namespace Patterns
Scan component namespaces for common leaf node names:
1. Extract leaf nodes from all component namespaces
- Example:
services/billing/notification→notification - Example:
services/ticket/notification→notification
2. Group by common leaf nodes
- Find components with same leaf node name
- Example: All components ending in
.notification
3. Filter out infrastructure patterns
- Exclude:
.util,.helper,.common(usually infrastructure) - Focus on:
.notification,.audit,.validation,.formatting
Example Output:
## Common Namespace Patterns Found
**Notification Components**:
- services/customer/notification
- services/ticket/notification
- services/survey/notification
**Audit Components**:
- services/billing/audit
- services/ticket/audit
- services/survey/auditPhase 2: Detect Shared Classes
Find classes/files used across multiple components:
1. Scan imports/dependencies in each component
- Track which classes are imported from where
- Note classes used by multiple components
2. Identify shared classes
- Classes imported by 2+ components
- Exclude infrastructure classes (Logger, Config, etc.)
3. Classify as domain vs infrastructure
- Domain: Business logic classes (SMTPConnection, AuditLogger)
- Infrastructure: Technical utilities (Logger, DatabaseConnection)
Example Output:
## Shared Classes Found
**Domain Classes**:
- `SMTPConnection` - Used by 5 components (notification-related)
- `AuditLogger` - Used by 8 components (audit-related)
- `DataFormatter` - Used by 3 components (formatting-related)
**Infrastructure Classes** (exclude from consolidation):
- `Logger` - Used by all components (infrastructure)
- `Config` - Used by all components (infrastructure)Phase 3: Analyze Functionality Similarity
For each group of common components:
1. Examine functionality
- Read source code of each component
- Identify what each component does
- Note similarities and differences
2. Assess consolidation feasibility
- Are differences minor (configurable)?
- Can differences be abstracted?
- Is functionality truly the same?
3. Calculate coupling impact
- Count incoming dependencies (afferent coupling) before consolidation
- Estimate incoming dependencies after consolidation
- Compare total coupling levels
Example Analysis:
## Functionality Analysis
**Notification Components**:
- CustomerNotification: Sends billing notifications
- TicketNotification: Sends ticket assignment notifications
- SurveyNotification: Sends survey emails
**Similarities**: All send emails to customers
**Differences**: Email content/templates, triggers
**Consolidation Feasibility**: ✅ High
- Differences are in content, not mechanism
- Can be abstracted with templates/contextPhase 4: Assess Coupling Impact
Before recommending consolidation, analyze coupling:
1. Calculate current coupling
- Count components using each notification component
- Sum total incoming dependencies
2. Estimate consolidated coupling
- Count components that would use consolidated component
- Compare to current total
3. Evaluate coupling increase
- Is consolidated component too coupled?
- Does it create a bottleneck?
- Is coupling increase acceptable?
Example Coupling Analysis:
## Coupling Impact Analysis
**Before Consolidation**:
- CustomerNotification: Used by 2 components (CA = 2)
- TicketNotification: Used by 2 components (CA = 2)
- SurveyNotification: Used by 1 component (CA = 1)
- **Total CA**: 5
**After Consolidation**:
- Notification: Used by 5 components (CA = 5)
- **Total CA**: 5 (same!)
**Verdict**: ✅ No coupling increase, safe to consolidatePhase 5: Recommend Consolidation Approach
Based on analysis, recommend approach:
Shared Service (if):
- Functionality changes frequently
- Complex operations
- Needs independent scaling
- Multiple deployment units will use it
Shared Library (if):
- Stable functionality
- Simple utilities
- Compile-time dependency acceptable
- No need for independent deployment
Component Consolidation (if):
- Highly related functionality
- Low coupling impact
- Same deployment unit acceptable
Output Format
Common Domain Components Report
## Common Domain Components Found
### Notification Functionality
**Components**:
- services/customer/notification (2% - 1,433 statements)
- services/ticket/notification (2% - 1,765 statements)
- services/survey/notification (2% - 1,299 statements)
**Shared Classes**: SMTPConnection (used by all 3)
**Functionality Analysis**:
- All send emails to customers
- Differences: Content/templates, triggers
- Consolidation Feasibility: ✅ High
**Coupling Analysis**:
- Before: CA = 2 + 2 + 1 = 5
- After: CA = 5 (no increase)
- Verdict: ✅ Safe to consolidate
**Recommendation**: Consolidate into `services/notification`
- Approach: Shared Service
- Expected Size: ~4,500 statements (5% of codebase)
- Benefits: Reduced duplication, easier maintenanceConsolidation Opportunities Table
## Consolidation Opportunities
| Common Functionality | Components | Current CA | After CA | Feasibility | Recommendation |
| -------------------- | ------------ | ---------- | -------- | ----------- | ----------------------------- |
| Notification | 3 components | 5 | 5 | ✅ High | Consolidate to shared service |
| Audit | 3 components | 8 | 12 | ⚠️ Medium | Consolidate, monitor coupling |
| Validation | 2 components | 3 | 3 | ✅ High | Consolidate to shared library |Detailed Consolidation Plan
## Consolidation Plan
### Priority: High
**Notification Components** → `services/notification`
**Steps**:
1. Create new `services/notification` component
2. Move common functionality from 3 components
3. Create abstraction for content/templates
4. Update dependent components to use new service
5. Remove old notification components
**Expected Impact**:
- Reduced code: ~4,500 statements consolidated
- Reduced duplication: 3 components → 1
- Coupling: No increase (CA stays at 5)
- Maintenance: Easier to maintain single component
### Priority: Medium
**Audit Components** → `services/audit`
**Steps**:
[Similar format]
**Expected Impact**:
- Coupling increase: CA 8 → 12 (monitor)
- Benefits: Reduced duplicationAnalysis Checklist
Common Pattern Detection:
- [ ] Scanned all component namespaces for common leaf nodes
- [ ] Identified components with same ending names
- [ ] Filtered out infrastructure patterns
- [ ] Grouped similar components
Shared Class Detection:
- [ ] Scanned imports/dependencies in each component
- [ ] Identified classes used by multiple components
- [ ] Classified as domain vs infrastructure
- [ ] Documented shared class usage
Functionality Analysis:
- [ ] Examined source code of common components
- [ ] Identified similarities and differences
- [ ] Assessed consolidation feasibility
- [ ] Determined if differences can be abstracted
Coupling Assessment:
- [ ] Calculated current coupling (CA) for each component
- [ ] Estimated consolidated coupling
- [ ] Compared total coupling levels
- [ ] Evaluated if coupling increase is acceptable
Recommendations:
- [ ] Suggested consolidation approach (service/library/merge)
- [ ] Prioritized recommendations by impact
- [ ] Created consolidation plan with steps
- [ ] Estimated expected benefits and risks
Implementation Notes
For Node.js/Express Applications
Common patterns to look for:
services/
├── CustomerService/
│ └── notification.js ← Common pattern
├── TicketService/
│ └── notification.js ← Common pattern
└── SurveyService/
└── notification.js ← Common patternShared Classes:
- Check
require()statements - Look for classes imported from other components
- Example:
const SMTPConnection = require('../shared/SMTPConnection')
For Java Applications
Common patterns:
com.company.billing.audit ← Common pattern
com.company.ticket.audit ← Common pattern
com.company.survey.audit ← Common patternShared Classes:
- Check
importstatements - Look for classes in common packages
- Example:
import com.company.shared.AuditLogger
Detection Strategies
Namespace Pattern Detection:
// Extract leaf nodes from namespaces
function extractLeafNode(namespace) {
const parts = namespace.split('/')
return parts[parts.length - 1]
}
// Group by common leaf nodes
function groupByLeafNode(components) {
const groups = {}
components.forEach((comp) => {
const leaf = extractLeafNode(comp.namespace)
if (!groups[leaf]) groups[leaf] = []
groups[leaf].push(comp)
})
return groups
}Shared Class Detection:
// Find classes used by multiple components
function findSharedClasses(components) {
const classUsage = {}
components.forEach((comp) => {
comp.imports.forEach((imp) => {
if (!classUsage[imp]) classUsage[imp] = []
classUsage[imp].push(comp.name)
})
})
return Object.entries(classUsage)
.filter(([cls, users]) => users.length > 1)
.map(([cls, users]) => ({ class: cls, usedBy: users }))
}Fitness Functions
After identifying common components, create automated checks:
Common Namespace Pattern Detection
// Alert if new components with common patterns are created
function checkCommonPatterns(components, exclusionList = []) {
const leafNodes = {}
components.forEach((comp) => {
const leaf = extractLeafNode(comp.namespace)
if (!exclusionList.includes(leaf)) {
if (!leafNodes[leaf]) leafNodes[leaf] = []
leafNodes[leaf].push(comp.name)
}
})
return Object.entries(leafNodes)
.filter(([leaf, comps]) => comps.length > 1)
.map(([leaf, comps]) => ({
pattern: leaf,
components: comps,
suggestion: 'Consider consolidating these components',
}))
}Shared Class Usage Alert
// Alert if class is used by multiple components
function checkSharedClasses(components, exclusionList = []) {
const classUsage = {}
components.forEach((comp) => {
comp.imports.forEach((imp) => {
if (!exclusionList.includes(imp)) {
if (!classUsage[imp]) classUsage[imp] = []
classUsage[imp].push(comp.name)
}
})
})
return Object.entries(classUsage)
.filter(([cls, users]) => users.length > 1)
.map(([cls, users]) => ({
class: cls,
usedBy: users,
suggestion: 'Consider extracting to shared component or library',
}))
}Best Practices
Do's ✅
- Distinguish domain from infrastructure functionality
- Analyze coupling impact before consolidating
- Consider both shared service and shared library approaches
- Look for namespace patterns AND shared classes
- Verify functionality is truly similar before consolidating
- Calculate coupling metrics (CA) before and after
Don'ts ❌
- Don't consolidate infrastructure functionality (handled separately)
- Don't consolidate without analyzing coupling impact
- Don't assume all common patterns should be consolidated
- Don't ignore differences in functionality
- Don't consolidate if coupling increase is too high
- Don't mix domain and infrastructure in same analysis
Common Patterns to Look For
High Consolidation Candidates
- Notification:
*.notification,*.notify,*.email - Audit:
*.audit,*.auditing,*.log - Validation:
*.validation,*.validate,*.validator - Formatting:
*.format,*.formatter,*.formatting - Reporting:
*.report,*.reporting(if similar functionality)
Low Consolidation Candidates
- Infrastructure:
*.util,*.helper,*.common(usually infrastructure) - Different contexts: Same name, different business meaning
- High coupling risk: Consolidation would create bottleneck
Next Steps
After identifying common domain components:
1. Apply Flatten Components Pattern - Remove orphaned classes 2. Apply Determine Component Dependencies Pattern - Analyze coupling 3. Create Component Domains - Group components into domains 4. Plan Consolidation - Execute consolidation recommendations
Notes
- Common domain functionality is different from infrastructure functionality
- Consolidation reduces duplication but may increase coupling
- Always analyze coupling impact before consolidating
- Shared services vs shared libraries have different trade-offs
- Some duplication is acceptable if it reduces coupling
- Not all common patterns should be consolidated
Component Flattening Analysis - Quick Reference
Component Definition
Component = Leaf node in directory/namespace structure containing source files
Key Rule: Components exist only as leaf nodes. If namespace is extended, parent becomes subdomain.
Root Namespace vs Component
| Type | Definition | Example | Has Code? |
|---|---|---|---|
| Component | Leaf node (deepest directory) | ss.survey.templates | ✅ Yes |
| Root Namespace | Extended by child nodes | ss.survey (has .templates) | ❌ No (orphaned if yes) |
| Subdomain | Same as root namespace | ss.survey | ❌ No |
Orphaned Classes
Orphaned Class = Source file in root namespace (non-leaf node)
Problem: No definable component associated with it
Solution: Move to leaf node namespace (component)
Detection
Root namespace extended?
├─ YES → Check for source files
│ ├─ Has files? → Orphaned classes found
│ └─ No files? → ✅ OK
└─ NO → Not a root namespaceFlattening Strategies
Strategy 1: Consolidate Down ✅
When: Leaf nodes are small, related functionality
Action: Move leaf code into root namespace
Example:
Before: ss.survey/ + ss.survey.templates/
After: ss.survey/ (single component)Strategy 2: Split Up ✅
When: Root namespace has distinct functional areas
Action: Move root code into new leaf nodes
Example:
Before: ss.ticket/ (45 orphaned files)
After: ss.ticket.maintenance/ + ss.ticket.completion/Strategy 3: Extract Shared ✅
When: Root namespace has shared utilities
Action: Move shared code to .shared component
Example:
Before: ss.survey/ (domain + shared code)
After: ss.survey/ + ss.survey.shared/Decision Tree
Found orphaned classes?
├─ YES → Analyze functionality
│ ├─ Related to leaf components?
│ │ ├─ YES → Consolidate Down
│ │ └─ NO → Distinct areas?
│ │ ├─ YES → Split Up
│ │ └─ NO → Shared code?
│ │ └─ YES → Extract Shared
│ └─ NO → ✅ No action needed
└─ NO → ✅ Structure is flatCommon Patterns
Pattern 1: Simple Consolidation
Before:
ss.survey/
├── Survey.js ← Orphaned
└── templates/ ← Component
└── Template.js
After:
ss.survey/ ← Component
├── Survey.js
└── Template.jsPattern 2: Functional Split
Before:
ss.ticket/ ← Root (45 orphaned files)
├── assign/ ← Component
└── route/ ← Component
After:
ss.ticket/ ← Subdomain
├── maintenance/ ← Component
├── completion/ ← Component
├── assign/ ← Component
└── route/ ← ComponentPattern 3: Shared Code Extraction
Before:
ss.survey/ ← Root
├── Survey.js ← Domain
├── Validator.js ← Shared
└── templates/ ← Component
After:
ss.survey/ ← Component
├── Survey.js
└── shared/ ← Component
└── Validator.jsQuick Analysis Steps
1. Map → Build namespace tree, identify root namespaces 2. Detect → Find orphaned classes in root namespaces 3. Analyze → Determine flattening strategy 4. Plan → Create refactoring steps 5. Execute → Move files, update references
Output Template
## Orphaned Classes Analysis
### Root Namespace: [name]
**Orphaned Files** (X files):
- File1.js (domain/shared code)
- File2.js (domain/shared code)
**Leaf Components**:
- [component.name] (X files)
**Issue**: [description]
**Recommendation**: [strategy]
## Flattening Plan
### Priority: High/Medium/Low
**[Namespace]** → [Strategy]
- [Steps]
- Effort: X days
- Risk: Low/Medium/HighValidation Rules
Rule 1: Components Only as Leaf Nodes
✅ Valid:
ss.survey.templates/ ← Component (leaf node)
❌ Invalid:
ss.survey/ ← Root namespace with code
├── Survey.js ← Orphaned class
└── templates/ ← ComponentRule 2: No Orphaned Classes
✅ Valid:
ss.survey/ ← Subdomain (no code)
└── templates/ ← Component (has code)
└── Template.js
❌ Invalid:
ss.survey/ ← Root namespace
├── Survey.js ← Orphaned class ❌
└── templates/ ← Component
└── Template.jsQuick Checklist
- [ ] Mapped namespace hierarchies
- [ ] Identified root namespaces
- [ ] Found orphaned classes
- [ ] Classified orphaned classes
- [ ] Selected flattening strategy
- [ ] Created refactoring plan
- [ ] Updated all references
- [ ] Verified with tests
Component Flattening Analysis
This skill identifies component hierarchy issues and ensures components exist only as leaf nodes in directory/namespace structures, removing orphaned classes from root namespaces.
How to Use
Quick Start
Request analysis of your codebase:
- "Find orphaned classes in root namespaces"
- "Flatten component hierarchies"
- "Identify components that need flattening"
- "Analyze component structure for hierarchy issues"
Usage Examples
Example 1: Find Orphaned Classes
User: "Find orphaned classes in root namespaces"
The skill will:
1. Scan component namespaces for hierarchy issues
2. Identify orphaned classes in root namespaces
3. Detect components built on top of other components
4. Suggest flattening strategies
5. Create refactoring planExample 2: Flatten Components
User: "Flatten component hierarchies in this codebase"
The skill will:
1. Identify components with hierarchy issues
2. Analyze orphaned classes
3. Suggest consolidation or splitting strategies
4. Create refactoring plan
5. Estimate effortExample 3: Component Structure Analysis
User: "Analyze component structure for hierarchy issues"
The skill will:
1. Map component namespace structure
2. Identify root namespaces with code
3. Find components built on components
4. Flag hierarchy violations
5. Provide recommendationsStep-by-Step Process
1. Scan Structure: Map component namespace hierarchies 2. Identify Issues: Find orphaned classes and component nesting 3. Analyze Options: Determine flattening strategy (consolidate vs split) 4. Create Plan: Generate refactoring plan with steps 5. Execute: Refactor components to remove hierarchy
When to Use
Apply this skill when:
- After gathering common domain components (Pattern 2)
- Before determining component dependencies (Pattern 4)
- When components have nested structures
- Finding orphaned classes in root namespaces
- Preparing for domain grouping
- Cleaning up component structure
- Ensuring components are leaf nodes only
Core Concepts
Component Definition
A component is identified by a leaf node in directory/namespace structure:
- Leaf Node: The deepest directory containing source files
- Component: Source code files in leaf node namespace
- Subdomain: Parent namespace that has been extended
Key Rule: Components exist only as leaf nodes. If a namespace is extended, the parent becomes a subdomain, not a component.
Root Namespace
A root namespace is a namespace node that has been extended:
- Extended: Another namespace node added below it
- Example:
ss.surveyextended toss.survey.templates - Result:
ss.surveybecomes a root namespace (subdomain)
Orphaned Classes
Orphaned classes are source files in root namespaces:
- Location: Root namespace (non-leaf node)
- Problem: No definable component associated with them
- Solution: Move to leaf node namespace (component)
Example:
ss.survey/ ← Root namespace (extended by .templates)
├── Survey.js ← Orphaned class (in root namespace)
└── templates/ ← Component (leaf node)
└── Template.jsFlattening Strategies
Strategy 1: Consolidate Down
- Move code from leaf nodes into root namespace
- Makes root namespace the component
- Example: Move
ss.survey.templates→ss.survey
Strategy 2: Split Up
- Move code from root namespace into new leaf nodes
- Creates new components from root namespace
- Example: Split
ss.survey→ss.survey.create+ss.survey.process
Strategy 3: Move Shared Code
- Move shared code to dedicated component
- Creates
.sharedcomponent - Example:
ss.surveyshared code →ss.survey.shared
Analysis Process
Phase 1: Map Component Structure
Scan directory/namespace structure to identify hierarchy:
1. Map Namespace Tree
- Build tree of all namespaces
- Identify parent-child relationships
- Mark leaf nodes (components)
2. Identify Root Namespaces
- Find namespaces that have been extended
- Mark as root namespaces (subdomains)
- Note which namespaces extend them
3. Locate Source Files
- Find all source files in each namespace
- Map files to their namespace location
- Identify files in root namespaces
Example Structure Mapping:
## Component Structure Mapss.survey/ ← Root namespace (extended) ├── Survey.js ← Orphaned class ├── SurveyProcessor.js ← Orphaned class └── templates/ ← Component (leaf node) ├── EmailTemplate.js └── SMSTemplate.js
ss.ticket/ ← Root namespace (extended) ├── Ticket.js ← Orphaned class ├── assign/ ← Component (leaf node) │ └── TicketAssign.js └── route/ ← Component (leaf node) └── TicketRoute.js
Phase 2: Identify Orphaned Classes
Find source files in root namespaces:
1. Scan Root Namespaces
- Check each root namespace for source files
- Identify files that are orphaned
- Count orphaned files per root namespace
2. Classify Orphaned Classes
- Shared Code: Common utilities, interfaces, abstract classes
- Domain Code: Business logic that should be in component
- Mixed: Combination of shared and domain code
3. Assess Impact
- How many files are orphaned?
- What functionality do they contain?
- What components depend on them?
Example Orphaned Class Detection:
## Orphaned Classes Found
### Root Namespace: ss.survey
**Orphaned Files** (5 files):
- Survey.js (domain code - survey creation)
- SurveyProcessor.js (domain code - survey processing)
- SurveyValidator.js (shared code - validation)
- SurveyFormatter.js (shared code - formatting)
- SurveyConstants.js (shared code - constants)
**Classification**:
- Domain Code: 2 files (should be in components)
- Shared Code: 3 files (should be in .shared component)
**Dependencies**: Used by ss.survey.templates componentPhase 3: Analyze Flattening Options
Determine best flattening strategy for each root namespace:
1. Option 1: Consolidate Down
- Move leaf node code into root namespace
- Makes root namespace the component
- Use when: Leaf nodes are small, related functionality
2. Option 2: Split Up
- Move root namespace code into new leaf nodes
- Creates multiple components from root
- Use when: Root namespace has distinct functional areas
3. Option 3: Move Shared Code
- Extract shared code to
.sharedcomponent - Keep domain code in root or split
- Use when: Root namespace has shared utilities
Example Flattening Analysis:
## Flattening Options Analysis
### Root Namespace: ss.survey
**Current State**:
- Root namespace: 5 orphaned files
- Leaf component: ss.survey.templates (7 files)
**Option 1: Consolidate Down** ✅ Recommended
- Move templates code into ss.survey
- Result: Single component ss.survey
- Effort: Low (7 files to move)
- Rationale: Templates are small, related to survey functionality
**Option 2: Split Up**
- Create ss.survey.create (2 files)
- Create ss.survey.process (1 file)
- Create ss.survey.shared (3 files)
- Keep ss.survey.templates (7 files)
- Effort: High (multiple components to create)
- Rationale: More granular, but may be over-engineering
**Option 3: Move Shared Code**
- Create ss.survey.shared (3 shared files)
- Keep domain code in root (2 files)
- Keep ss.survey.templates (7 files)
- Effort: Medium
- Rationale: Separates shared from domain, but still has hierarchyPhase 4: Create Flattening Plan
Generate refactoring plan for each root namespace:
1. Select Strategy
- Choose best flattening option
- Consider effort, complexity, maintainability
2. Plan Refactoring Steps
- List files to move
- Identify target namespaces
- Note dependencies to update
3. Estimate Effort
- Time to refactor
- Risk assessment
- Testing requirements
Example Flattening Plan:
## Flattening Plan
### Priority: High
**Root Namespace: ss.survey**
**Strategy**: Consolidate Down
**Steps**:
1. Move files from ss.survey.templates/ to ss.survey/
- EmailTemplate.js
- SMSTemplate.js
- [5 more files]
2. Update imports in dependent components
- Update references from ss.survey.templates._ to ss.survey._
3. Remove ss.survey.templates/ directory
4. Update namespace declarations
- Change namespace from ss.survey.templates to ss.survey
5. Run tests to verify changes
**Effort**: 2-3 days
**Risk**: Low (templates are self-contained)
**Dependencies**: NonePhase 5: Execute Flattening
Perform the refactoring:
1. Move Files
- Move source files to target namespace
- Update file paths and imports
2. Update References
- Update imports in dependent components
- Update namespace declarations
- Update directory structure
3. Verify Changes
- Run tests
- Check for broken references
- Validate component structure
Output Format
Orphaned Classes Report
## Orphaned Classes Analysis
### Root Namespace: ss.survey
**Status**: ⚠️ Has Orphaned Classes
**Orphaned Files** (5 files):
- Survey.js (domain code)
- SurveyProcessor.js (domain code)
- SurveyValidator.js (shared code)
- SurveyFormatter.js (shared code)
- SurveyConstants.js (shared code)
**Leaf Components**:
- ss.survey.templates (7 files)
**Issue**: Root namespace contains code but is extended by leaf component
**Recommendation**: Consolidate templates into root namespaceComponent Hierarchy Issues
## Component Hierarchy Issues
| Root Namespace | Orphaned Files | Leaf Components | Issue | Recommendation |
| -------------- | -------------- | ------------------------------- | -------------------- | ---------------- |
| ss.survey | 5 | 1 (templates) | Has orphaned classes | Consolidate down |
| ss.ticket | 45 | 2 (assign, route) | Large orphaned code | Split up |
| ss.reporting | 0 | 3 (tickets, experts, financial) | No issue | ✅ OK |Flattening Plan
## Flattening Plan
### Priority: High
**ss.survey** → Consolidate Down
- Move 7 files from templates to root
- Effort: 2-3 days
- Risk: Low
### Priority: Medium
**ss.ticket** → Split Up
- Create ss.ticket.maintenance (30 files)
- Create ss.ticket.completion (10 files)
- Create ss.ticket.shared (5 files)
- Effort: 1 week
- Risk: MediumAnalysis Checklist
Structure Mapping:
- [ ] Mapped all namespace hierarchies
- [ ] Identified root namespaces
- [ ] Located all source files
- [ ] Marked leaf nodes (components)
Orphaned Class Detection:
- [ ] Scanned root namespaces for source files
- [ ] Identified orphaned classes
- [ ] Classified orphaned classes (shared/domain/mixed)
- [ ] Assessed impact and dependencies
Flattening Analysis:
- [ ] Analyzed consolidation option
- [ ] Analyzed splitting option
- [ ] Analyzed shared code extraction option
- [ ] Selected best strategy for each root namespace
Plan Creation:
- [ ] Selected flattening strategy
- [ ] Created refactoring steps
- [ ] Estimated effort and risk
- [ ] Prioritized work
Execution:
- [ ] Moved files to target namespaces
- [ ] Updated imports and references
- [ ] Updated namespace declarations
- [ ] Verified changes with tests
Implementation Notes
For Node.js/Express Applications
Components typically in services/ directory:
services/
├── survey/ ← Root namespace (extended)
│ ├── Survey.js ← Orphaned class
│ └── templates/ ← Component (leaf node)
│ └── Template.jsFlattening:
- Consolidate: Move
templates/files tosurvey/ - Split: Create
survey/create/andsurvey/process/ - Shared: Create
survey/shared/for utilities
For Java Applications
Components identified by package structure:
com.company.survey ← Root package (extended)
├── Survey.java ← Orphaned class
└── templates/ ← Component (leaf package)
└── Template.javaFlattening:
- Consolidate: Move
templatesclasses tosurveypackage - Split: Create
survey.createandsurvey.processpackages - Shared: Create
survey.sharedpackage
Detection Strategies
Find Root Namespaces with Code:
// Find root namespaces containing source files
function findRootNamespacesWithCode(namespaces, sourceFiles) {
const rootNamespaces = namespaces.filter((ns) => {
// Check if namespace has been extended
const hasChildren = namespaces.some((n) => n.startsWith(ns + '.') || n.startsWith(ns + '/'))
// Check if namespace contains source files
const hasFiles = sourceFiles.some((f) => f.namespace === ns)
return hasChildren && hasFiles
})
return rootNamespaces
}Find Orphaned Classes:
// Find orphaned classes in root namespaces
function findOrphanedClasses(rootNamespaces, sourceFiles) {
const orphaned = []
rootNamespaces.forEach((rootNs) => {
const files = sourceFiles.filter((f) => f.namespace === rootNs)
orphaned.push({
rootNamespace: rootNs,
files: files,
count: files.length,
})
})
return orphaned
}Fitness Functions
After flattening components, create automated checks:
No Source Code in Root Namespaces
// Alert if source code exists in root namespace
function checkRootNamespaceCode(namespaces, sourceFiles) {
const violations = []
namespaces.forEach((ns) => {
// Check if namespace has been extended
const hasChildren = namespaces.some((n) => n.startsWith(ns + '.') || n.startsWith(ns + '/'))
if (hasChildren) {
// Check if namespace contains source files
const files = sourceFiles.filter((f) => f.namespace === ns)
if (files.length > 0) {
violations.push({
namespace: ns,
files: files.map((f) => f.name),
issue: 'Root namespace contains source files (orphaned classes)',
})
}
}
})
return violations
}Components Only as Leaf Nodes
// Ensure components exist only as leaf nodes
function validateComponentStructure(namespaces, sourceFiles) {
const violations = []
// Find all leaf nodes (components)
const leafNodes = namespaces.filter((ns) => {
return !namespaces.some((n) => n.startsWith(ns + '.') || n.startsWith(ns + '/'))
})
// Check that all source files are in leaf nodes
sourceFiles.forEach((file) => {
if (!leafNodes.includes(file.namespace)) {
violations.push({
file: file.name,
namespace: file.namespace,
issue: 'Source file not in leaf node (component)',
})
}
})
return violations
}Best Practices
Do's ✅
- Ensure components exist only as leaf nodes
- Remove orphaned classes from root namespaces
- Choose flattening strategy based on functionality
- Consolidate when functionality is related
- Split when functionality is distinct
- Extract shared code to
.sharedcomponents - Update all references after flattening
- Verify changes with tests
Don'ts ❌
- Don't leave orphaned classes in root namespaces
- Don't create components on top of other components
- Don't skip updating imports after moving files
- Don't flatten without analyzing impact
- Don't mix flattening strategies inconsistently
- Don't ignore shared code when flattening
- Don't skip testing after refactoring
Common Patterns
Pattern 1: Simple Consolidation
Before:
ss.survey/
├── Survey.js ← Orphaned
└── templates/ ← Component
└── Template.jsAfter:
ss.survey/ ← Component (leaf node)
├── Survey.js
└── Template.jsPattern 2: Functional Split
Before:
ss.ticket/ ← Root namespace
├── Ticket.js ← Orphaned (45 files)
├── assign/ ← Component
└── route/ ← ComponentAfter:
ss.ticket/ ← Subdomain
├── maintenance/ ← Component
│ └── Ticket.js
├── completion/ ← Component
│ └── TicketCompletion.js
├── assign/ ← Component
└── route/ ← ComponentPattern 3: Shared Code Extraction
Before:
ss.survey/ ← Root namespace
├── Survey.js ← Domain code
├── SurveyValidator.js ← Shared code
└── templates/ ← ComponentAfter:
ss.survey/ ← Component
├── Survey.js
└── shared/ ← Component
└── SurveyValidator.jsNext Steps
After flattening components:
1. Apply Determine Component Dependencies Pattern - Analyze coupling 2. Create Component Domains - Group components into domains 3. Create Domain Services - Extract domains to services
Notes
- Components must exist only as leaf nodes
- Root namespaces with code are problematic
- Flattening improves component clarity
- Choose flattening strategy based on functionality
- Shared code should be in dedicated components
- Always update references after moving files
- Test thoroughly after flattening
Coupling Analysis Skill
You are an expert software architect specializing in coupling analysis. You analyze codebases following the three-dimensional model from _Balancing Coupling in Software Design_ (Vlad Khononov):
1. Integration Strength — _what_ is shared between components 2. Distance — _where_ the coupling physically lives 3. Volatility — _how often_ components change
The guiding balance formula:
BALANCE = (STRENGTH XOR DISTANCE) OR NOT VOLATILITYA design is balanced when:
- Tightly coupled components are close together (high strength + low distance = cohesion)
- Distant components are loosely coupled (low strength + high distance = loose coupling)
- Stable components (low volatility) can tolerate stronger coupling
When to Use
Apply this skill when the user:
- Asks to "analyze coupling", "evaluate architecture", or "check dependencies"
- Wants to understand integration strength between modules or services
- Needs to identify problematic coupling or architectural smell
- Wants to know if a module should be extracted or merged
- References concepts like connascence, cohesion, or coupling from Khononov's book
- Asks why changes in one module cascade to others unexpectedly
Process
PHASE 1 — Context Gathering
Before analyzing code, collect:
1.1 Scope
- Full codebase or a specific area?
- Primary level of abstraction: methods, classes, modules/packages, services?
- Is git history available? (useful to estimate volatility)
1.2 Business context — ask the user or infer from code:
- Which parts are the business "core" (competitive differentiator)?
- Which are infrastructure/generic support (auth, billing, logging)?
- What changes most frequently according to the team?
This allows classifying subdomains (critical for volatility):
| Type | Volatility | Indicators |
|---|---|---|
| Core subdomain | High | Proprietary logic, competitive advantage, area the business most wants to evolve |
| Supporting subdomain | Low | Simple CRUD, core support, no algorithmic complexity |
| Generic subdomain | Minimal | Auth, billing, email, logging, storage |
---
PHASE 2 — Structural Mapping
2.1 Module inventory
For each module, record:
- Name and location (namespace/package/path)
- Primary responsibility
- Declared dependencies (imports, DI, HTTP calls)
2.2 Dependency graph
Build a directed graph where:
- Nodes = modules
- Edges = dependencies (A → B means "A depends on B")
- Note: the flow of _knowledge_ is OPPOSITE to the dependency arrow
- If A → B, then B is _upstream_ and exposes knowledge to A (downstream)
2.3 Distance calculation
Use the encapsulation hierarchy to measure distance. The nearest common ancestor determines distance:
| Common ancestor level | Distance | Example |
|---|---|---|
| Same method/function | Minimal | Two lines in same method |
| Same object/class | Very low | Methods on same object |
| Same namespace/package | Low | Classes in same package |
| Same library/module | Medium | Libs in same project |
| Different services | High | Distinct microservices |
| Different systems/orgs | Maximum | External APIs, different teams |
Social factor: If modules are maintained by different teams, increase the estimated distance by one level (Conway's Law).
---
PHASE 3 — Integration Strength Analysis
For each dependency in the graph, classify the Integration Strength level (strongest to weakest):
INTRUSIVE COUPLING (Strongest — Avoid)
Downstream accesses implementation details of upstream that were _not designed for integration_.
Code signals:
- Reflection to access private members
- Service directly reading another service's database
- Dependency on internal file/config structure of another module
- Monkey-patching of internals (Python/Ruby)
- Direct access to internal fields without getter
Effect: Any internal change to upstream (even without changing public interface) breaks downstream. Upstream doesn't know it's being observed.
---
FUNCTIONAL COUPLING (Second strongest)
Modules implement interrelated functionalities — shared business logic, interdependent rules, or coupled workflows.
Three degrees (weakest to strongest):
a) Sequential (Temporal) — modules must execute in specific order
connection.open() # must come first
connection.query() # depends on open
connection.close() # must come lastb) Transactional — operations must succeed or fail together
with transaction:
service_a.update(data)
service_b.update(data) # both must succeedc) Symmetric (strongest) — same business logic duplicated in multiple modules
# Module A
def is_premium_customer(c): return c.purchases > 1000
# Module B — duplicated rule! Must stay in sync
def qualifies_for_discount(c): return c.purchases > 1000Note: symmetric coupling does NOT require modules to reference each other — they can be fully independent in code yet still have this coupling.
General signals of Functional Coupling:
- Comments like "remember to update X when changing Y"
- Cascading test failures when a business rule changes
- Duplicated validation logic in multiple places
- Need to deploy multiple services simultaneously for a feature
---
MODEL COUPLING (Third level)
Upstream exposes its internal domain model as part of the public interface. Downstream knows and uses objects representing the upstream's internal model.
Code signals:
# Analysis module uses Customer from CRM directly
from crm.models import Customer # CRM's internal model
class Analysis:
def process(self, customer_id):
customer = crm_repo.get(customer_id) # returns full Customer
status = customer.status # only needs status, but knows everything// Service B consuming Service A's internal model via API
interface CustomerFromServiceA {
internalAccountCode: string; // internal detail exposed
legacyId: number; // unnecessary internal field
// ... many fields Service B doesn't need
}Degrees (via static connascence):
- _connascence of name_: knows field names of the model
- _connascence of type_: knows specific types of the model
- _connascence of meaning_: interprets specific values (magic numbers, internal enums)
- _connascence of algorithm_: must use same algorithm to interpret data
- _connascence of position_: depends on element order (tuples, unnamed arrays)
---
CONTRACT COUPLING (Weakest — Ideal)
Upstream exposes an _integration-specific model_ (contract), separate from its internal model. The contract abstracts implementation details.
Code signals:
class CustomerSnapshot: # integration DTO, not the internal model
"""Public integration contract — stable and intentional."""
id: str
status: str # enum converted to string
tier: str # only what consumers need
@staticmethod
def from_customer(customer: Customer) -> 'CustomerSnapshot':
return CustomerSnapshot(
id=str(customer.id),
status=customer.status.value,
tier=customer.loyalty_tier.display_name
)Characteristics of good Contract Coupling:
- Dedicated DTOs/ViewModels per use case (not the domain model)
- Versionable contracts (V1, V2)
- Primitive types or simple value types
- Explicit contract documentation (OpenAPI, Protobuf, etc.)
- Patterns: Facade, Adapter, Anti-Corruption Layer, Published Language (DDD)
---
PHASE 4 — Volatility Assessment
For each module, estimate volatility based on:
4.1 Subdomain type (preferred) — see table in Phase 1
4.2 Git analysis (when available):
# Commits per file in the last 6 months
git log --since="6 months ago" --format="" --name-only | sort | uniq -c | sort -rn | head -20
# Files that change together frequently (temporal coupling)
# High co-change = possible undeclared functional coupling4.3 Code signals:
- Many TODO/FIXME → area under evolution (higher volatility)
- Many API versions (V1, V2, V3) → frequently changing area
- Fragile tests that break constantly → volatile area
- Comments "business rule: ..." → business logic = probably core
4.4 Inferred volatility
Even a supporting subdomain module may have high volatility if:
- It has Intrusive or Functional coupling with core subdomain modules
- Changes in core propagate to it frequently
---
PHASE 5 — Balance Score Calculation
For each coupled pair (A → B):
Simplified scale (0 = low, 1 = high):
| Dimension | 0 (Low) | 1 (High) |
|---|---|---|
| Strength | Contract coupling | Intrusive coupling |
| Distance | Same object/namespace | Different services |
| Volatility | Generic/Supporting subdomain | Core subdomain |
Maintenance effort formula:
MAINTENANCE_EFFORT = STRENGTH × DISTANCE × VOLATILITY(0 in any dimension = low effort)
Classification table:
| Strength | Distance | Volatility | Diagnosis |
|---|---|---|---|
| High | High | High | 🔴 CRITICAL — Global complexity + high change cost |
| High | High | Low | 🟡 ACCEPTABLE — Strong but stable (e.g. legacy integration) |
| High | Low | High | 🟢 GOOD — High cohesion (change together, live together) |
| High | Low | Low | 🟢 GOOD — Strong but static |
| Low | High | High | 🟢 GOOD — Loose coupling (separate and independent) |
| Low | High | Low | 🟢 GOOD — Loose coupling and stable |
| Low | Low | High | 🟠 ATTENTION — Local complexity (mixes unrelated components) |
| Low | Low | Low | 🟡 ACCEPTABLE — May generate noise, but low cost |
---
PHASE 6 — Analysis Report
Structure the report in sections:
6.1 Executive Summary
CODEBASE: [name]
MODULES ANALYZED: N
DEPENDENCIES MAPPED: N
CRITICAL ISSUES: N
MODERATE ISSUES: N
OVERALL HEALTH SCORE: [Healthy / Attention / Critical]6.2 Dependency Map
Present the annotated graph:
[ModuleA] --[INTRUSIVE]-----------> [ModuleB]
[ModuleC] --[CONTRACT]------------> [ModuleD]
[ModuleE] --[FUNCTIONAL:symmetric]-> [ModuleF]6.3 Identified Issues (by severity)
For each critical or moderate issue:
ISSUE: [descriptive name]
────────────────────────────────────────
Modules involved: A → B
Coupling type: Functional Coupling (symmetric)
Connascence level: Connascence of Value
Evidence in code:
[snippet or description of found pattern]
Dimensions:
• Strength: HIGH (Functional - symmetric)
• Distance: HIGH (separate services)
• Volatility: HIGH (core subdomain)
Balance Score: CRITICAL 🔴
Maintenance: High — frequent changes propagate over long distance
Impact: Any change to business rule [X] requires simultaneous
update in [A] and [B], which belong to different teams.
Recommendation:
→ Extract shared logic to a dedicated module that both can
reference (DRY + contract coupling)
→ Or: Accept duplication and explicitly document the coupling
(if volatility is lower than it appears)6.4 Positive Patterns Found
✅ [ModuleX] uses dedicated integration DTOs — contract coupling well implemented
✅ [ServiceY] exposes only necessary data via API — minimizes model coupling
✅ [PackageZ] encapsulates its internal model well — low implementation leakage6.5 Prioritized Recommendations
High priority (high impact, blocking evolution):
1. ...
Medium priority (improve architectural health): 2. ...
Low priority (incremental improvements): 3. ...
---
Quick Reference: Pattern → Integration Strength
| Pattern found | Integration Strength | Action |
|---|---|---|
| Reflection to access private members | Intrusive | Refactor urgently |
| Reading another service's DB | Intrusive | Refactor urgently |
| Duplicated business logic | Functional (symmetric) | Extract to shared module |
| Distributed transaction / Saga | Functional (transactional) | Evaluate if cohesion would be better |
| Mandatory execution order | Functional (sequential) | Document protocol or encapsulate |
| Rich domain object returned | Model coupling | Create integration DTO |
| Internal enum shared externally | Model coupling | Create public contract enum |
| Use-case-specific DTO | Contract coupling | ✅ Correct pattern |
| Versioned public interface/protocol | Contract coupling | ✅ Correct pattern |
| Anti-Corruption Layer | Contract coupling | ✅ Correct pattern |
Quick Heuristics
For Integration Strength:
- "If I change an internal detail of module X, how many other modules need to change?"
- "Was the integration contract designed to be public, or is it accidental?"
- "Is there duplicated business logic that must be manually synchronized?"
For Distance:
- "What's the cost of making a change that affects both modules?"
- "Do teams maintaining these modules need to coordinate deployments?"
- "If one module fails, does the other stop working?"
For Volatility:
- "Does this module encapsulate competitive business advantage?"
- "Does the business team frequently request changes in this area?"
- "Is there a history of many refactors in this area?"
For Balance:
- "Do components that need to change together live together in the code?"
- "Are independent components well separated?"
- "Where is there strong coupling with volatile and distant components?" (→ this is the main problem)
Known Limitations
- Volatility is best estimated with real git data rather than static analysis alone
- Symmetric functional coupling requires semantic code reading — static analysis tools generally don't detect it
- Organizational distance (different teams) requires user input
- Dynamic connascence (timing, value, identity) is hard to detect without runtime observation
- Analysis is a starting point — business context always refines the conclusions
Book References
These concepts are based on _Balancing Coupling in Software Design_ by Vlad Khononov (Addison-Wesley).
Domain Identification & Grouping - Quick Reference
Domain Definition
Domain = Logical grouping of components representing a distinct business capability
Key Characteristics:
- Represents business area, not technical layer
- Contains related components
- Has clear boundaries
- Can become domain service
Domain Identification Strategies
1. Business Capability Analysis
What business capabilities does the system provide?
→ Each capability = Potential domain2. Vocabulary Analysis
What business language do components use?
→ Components sharing vocabulary = Same domain3. Relationship Analysis
Which components are frequently used together?
→ Related components = Same domain4. Stakeholder Collaboration
What do business experts say?
→ Their understanding = Domain boundariesComponent-to-Domain Assignment
Decision Process
Analyze component:
├─ What business capability does it support?
├─ What domain vocabulary does it use?
├─ What other components does it relate to?
└─ Assign to domain that best fitsEdge Cases
- Unclear assignment: Analyze more deeply, check relationships
- Multiple domains: Choose primary domain, document secondary
- Shared functionality: May belong to Shared domain
Namespace Refactoring
Pattern
Before: services/billing/payment After: services/customer/billing/payment
Rule: Add domain node to namespace
Refactoring Steps
1. Update namespace declarations 2. Update import statements 3. Update directory structure 4. Run tests 5. Update documentation
Domain Validation
Checklist
- [ ] All components assigned to a domain
- [ ] Domains have clear boundaries
- [ ] Components fit domain vocabulary
- [ ] Domains represent distinct capabilities
- [ ] Stakeholders validate groupings
Cohesion Check
High Cohesion ✅:
- Components share business language
- Components used together
- Direct relationships
Low Cohesion ❌:
- Different vocabularies
- Rarely used together
- No relationshipsDomain Size Guidelines
| Size | Component Count | Notes |
|---|---|---|
| Small | 2-4 | May need consolidation |
| Medium | 5-8 | Ideal size |
| Large | 9-15 | Monitor for splitting |
| Too Large | >15 | Consider splitting |
Common Domain Patterns
Typical Domains
- Customer: Customer management, profiles, billing
- Product: Catalog, inventory, pricing
- Order: Processing, fulfillment
- Billing: Invoicing, payments
- Reporting: Reports, analytics
- Admin: User management, config
- Shared: Common functionality
Domain Count
Ideal: 3-7 domains Too Many: >10 domains (consider merging) Too Few: <3 domains (consider splitting)
Output Template
## Domain: [Name] ([namespace])
**Business Capability**: [what it does]
**Components**:
- Component 1
- Component 2
**Component Count**: X
**Total Size**: Y statements (Z% of codebase)
**Domain Cohesion**: ✅ High / ⚠️ Medium / ❌ Low
**Boundaries**:
- Clear separation from [Domain A]
- Clear separation from [Domain B]Quick Analysis Steps
1. Identify → Analyze components, find business capabilities 2. Group → Assign components to domains 3. Validate → Check cohesion, boundaries, completeness 4. Refactor → Align namespaces with domains 5. Map → Create domain visualization
Decision Tree
Identify domains
├─ Analyze component responsibilities
├─ Identify business capabilities
├─ Group by vocabulary/relationships
└─ Validate with stakeholders
Assign components
├─ Analyze functionality
├─ Check relationships
├─ Assign to domain
└─ Handle edge cases
Refactor namespaces
├─ Compare current vs target
├─ Identify changes needed
├─ Create refactoring plan
└─ Execute refactoring