# architecture-explainer > This skill should be used when the user asks to 'explain architecture', 'show system design', 'diagram the feature', 'how does this feature work', or needs comprehensive understanding of a feature's architecture including components, data flow, API contracts, and design decisions. - Author: Ngoc - Repository: Vegarnom/mega-team-v4 - Version: 20260202115326 - Stars: 0 - Forks: 0 - Last Updated: 2026-02-06 - Source: https://github.com/Vegarnom/mega-team-v4 - Web: https://mule.run/skillshub/@@Vegarnom/mega-team-v4~architecture-explainer:20260202115326 --- --- name: architecture-explainer description: This skill should be used when the user asks to 'explain architecture', 'show system design', 'diagram the feature', 'how does this feature work', or needs comprehensive understanding of a feature's architecture including components, data flow, API contracts, and design decisions. allowed-tools: Read, Glob, Grep, Task, Write version: 1.1 --- # Architecture Explainer v1.0 Trình bày thiết kế kiến trúc hệ thống của một chức năng, giúp developer hiểu rộng và sâu hơn về feature thông qua visualizations, diagrams, và detailed explanations. --- ## WHAT'S NEW IN v1.0 - **Multi-level Architecture Views**: System overview, component level, code level - **Visual Diagrams**: Component diagrams, sequence diagrams, data flow diagrams - **API Contract Documentation**: Request/response schemas, authentication, error handling - **Database Schema Analysis**: Entity relationships, indexes, migration history - **Design Decision Documentation**: Why architecture decisions were made - **Technology Stack Breakdown**: Frontend, backend, database, infrastructure - **Integration Points**: External services, message queues, webhooks - **UI & Branding Analysis**: Brand guidelines, theme schemes, UI mockups logic - **Progressive Disclosure**: High-level → Mid-level → Deep-dive --- ## WHEN TO USE | Use Case | Example | |----------|---------| | Onboarding new developers | "Explain the authentication architecture" | | Feature documentation | "Show me how the payment system works" | | Code review preparation | "Diagram the notification flow" | | Refactoring planning | "Map out the user management architecture" | | Technical debt analysis | "Explain how the legacy API integrates" | | System design interview prep | "Walk through the alert escalation system" | | Before major changes | "Show the current architecture of order processing" | --- ## USAGE ```bash # Basic usage /architecture-explainer "feature-name" # Specify feature path /architecture-explainer src/modules/payment # Focus on specific aspect /architecture-explainer "authentication" --focus api-contracts /architecture-explainer "notifications" --focus data-flow /architecture-explainer "alerts" --focus database # Include code examples /architecture-explainer "user-registration" --with-code # Compare with best practices /architecture-explainer "file-upload" --compare-best-practices ``` --- ## OUTPUT STRUCTURE ``` ┌─────────────────────────────────────────────────────────────┐ │ ARCHITECTURE EXPLANATION REPORT │ ├─────────────────────────────────────────────────────────────┤ │ 1. System Overview (What, Why, Scope) │ │ 2. Technology Stack (Frontend, Backend, Database) │ │ 3. Component Architecture (Layers, Services, Modules) │ │ 4. Data Flow Diagrams (Request → Response) │ │ 5. API Contracts (Endpoints, DTOs, Authentication) │ │ 6. Database Schema (Entities, Relations, Indexes) │ │ 7. Sequence Diagrams (Critical Flows) │ │ 8. Integration Points (External Services, Queues) │ │ 9. UI & Branding (Brand colors, Theme, Mockups) │ │ 10. Key Design Decisions (Why this approach?) │ │ 11. Files Map (Where to find what) │ └─────────────────────────────────────────────────────────────┘ ``` --- ## PHASE 0: Dynamic Stack Detection (NEW v1.1) ```bash # Auto-detect stack and cache result STACK=$(~/.claude/scripts/detect-stack.sh "$(pwd)" --cache) # Get recommended agents for this project BACKEND_AGENT=$(~/.claude/scripts/agent-router.sh backend) FRONTEND_AGENT=$(~/.claude/scripts/agent-router.sh frontend) MOBILE_AGENT=$(~/.claude/scripts/agent-router.sh mobile) DEVOPS_AGENT=$(~/.claude/scripts/agent-router.sh devops) # Load relevant skill context source ~/.claude/scripts/load-skill-context.sh echo "Stack detected:" echo " Backend: $BACKEND_AGENT" echo " Frontend: $FRONTEND_AGENT" echo " Mobile: $MOBILE_AGENT" echo " DevOps: $DEVOPS_AGENT" ``` --- ## PHASE 1: DISCOVER FEATURE SCOPE ### Step 1.1: Identify Feature Boundaries ```typescript // Parse input feature_input = args[0] // "payment" or "src/modules/payment" IF feature_input.includes("/"): FEATURE_PATH = feature_input FEATURE_NAME = extractNameFromPath(feature_input) ELSE: FEATURE_NAME = feature_input // Search for feature Find all files related to feature: ${FEATURE_NAME} Look in: - src/modules/ - src/services/ - src/components/ - packages/ Include: - Controllers, services, entities, DTOs - Components, pages, stores - Tests, migrations - Config files Output: Structured file list with categorization FEATURE_PATH = discovered_path ``` ### Step 1.2: Map All Related Files ```typescript ## Comprehensive Feature File Mapping Feature: ${FEATURE_NAME} Base Path: ${FEATURE_PATH} Categorize ALL files: ### Backend - Controllers (*.controller.ts) - Services (*.service.ts) - Entities (*.entity.ts) - DTOs (*.dto.ts) - Repositories (*.repository.ts) - Modules (*.module.ts) - Guards/Middleware (*.guard.ts, *.middleware.ts) ### Frontend - Pages/Views (*.vue, *.tsx, *.jsx) - Components (*.component.ts, *.tsx) - State Management (*.store.ts, *.slice.ts) - API Clients (*.api.ts, *.service.ts) - Types (*.types.ts, *.d.ts) ### Database - Migrations (timestamp_*.ts) - Seeds (*.seed.ts) - Schema definitions ### Tests - Unit tests (*.spec.ts, *.test.ts) - Integration tests (*.integration.spec.ts) - E2E tests (*.e2e.spec.ts) ### Config - Environment configs - Module configs Output: File map with line counts and brief descriptions feature_files = parseExploreResult() ``` --- ## PHASE 2: ANALYZE ARCHITECTURE ### Step 2.1: Technology Stack Analysis (Using Dynamic Detection) ```typescript // Use pre-detected stack from Phase 0 // BACKEND_AGENT, FRONTEND_AGENT already set from detect-stack.sh console.log(` ## Technology Stack (Auto-Detected) ### Backend: ${BACKEND_AGENT || 'Not detected'} ### Frontend: ${FRONTEND_AGENT || 'Not detected'} ### Mobile: ${MOBILE_AGENT || 'Not detected'} ### DevOps: ${DEVOPS_AGENT || 'Not detected'} ### Full Stack Details \`\`\`bash # Run for detailed stack info ~/.claude/scripts/detect-stack.sh "$(pwd)" \`\`\` `) ``` ### Step 2.2: Component Architecture Diagram ```typescript // Read key files to understand structure controllers = feature_files.filter(f => f.endsWith('.controller.ts')) services = feature_files.filter(f => f.endsWith('.service.ts')) entities = feature_files.filter(f => f.endsWith('.entity.ts')) modules = feature_files.filter(f => f.endsWith('.module.ts')) // Parse dependencies dependencies = {} for (file of [...controllers, ...services, ...modules]) { dependencies[file] = extractImports(file_content) } // Generate component diagram component_diagram = ` \`\`\` ┌─────────────────────────────────────────────────────────────────┐ │ ${FEATURE_NAME.toUpperCase()} ARCHITECTURE │ ├─────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ PRESENTATION LAYER │ │ │ │ │ │ │ │ ${controllers.map(c => basename(c)).join(' ')} │ │ │ └────────────────────┬─────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ BUSINESS LOGIC LAYER │ │ │ │ │ │ │ │ ${services.map(s => basename(s)).join(' ')} │ │ │ └────────────────────┬─────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ DATA ACCESS LAYER │ │ │ │ │ │ │ │ ${entities.map(e => basename(e)).join(' ')} │ │ │ └────────────────────┬─────────────────────────────────────┘ │ │ │ │ │ ▼ │ │ ┌──────────────────────────────────────────────────────────┐ │ │ │ DATABASE │ │ │ │ PostgreSQL │ │ │ └──────────────────────────────────────────────────────────┘ │ │ │ └─────────────────────────────────────────────────────────────────┘ \`\`\` ` console.log(component_diagram) ``` ### Step 2.3: Dependency Graph ```typescript // Analyze imports/exports dependency_graph = buildDependencyGraph(dependencies) console.log(` ## Dependency Graph \`\`\` ${generateDependencyDiagram(dependency_graph)} \`\`\` ### Key Dependencies ${Object.entries(dependency_graph) .map(([file, deps]) => `**${basename(file)}**\n${deps.map(d => ` - ${d}`).join('\n')}`) .join('\n\n')} `) ``` --- ## PHASE 3: DATA FLOW ANALYSIS ### Step 3.1: Request/Response Flow ```typescript // For each controller endpoint for (controller of controllers) { endpoints = extractEndpoints(controller_content) for (endpoint of endpoints) { flow_diagram = ` ### ${endpoint.method} ${endpoint.path} \`\`\` Client Request │ ├─→ HTTP ${endpoint.method} ${endpoint.path} │ Headers: ${endpoint.auth ? 'Authorization: Bearer ' : 'None'} │ Body: ${endpoint.dto || 'None'} │ ▼ ┌────────────────────────────────────┐ │ ${controller.name} │ │ └── ${endpoint.handler}() │ └────────┬───────────────────────────┘ │ ├─→ Validate DTO │ ▼ ┌────────────────────────────────────┐ │ ${endpoint.service} │ │ └── ${endpoint.serviceMethod}() │ └────────┬───────────────────────────┘ │ ├─→ Business Logic │ ▼ ┌────────────────────────────────────┐ │ Database / External API │ │ └── Query/Mutation │ └────────┬───────────────────────────┘ │ ▼ Response │ └─→ ${endpoint.responseType} \`\`\` ` console.log(flow_diagram) } } ``` ### Step 3.2: Data Transformation Pipeline ```typescript // Track data transformations transformations = [] for (service of services) { transformations.push(...extractDataTransformations(service_content)) } console.log(` ## Data Transformation Pipeline ${transformations.map(t => ` ### ${t.methodName} \`\`\`typescript Input: ${t.inputType} ↓ Transform: ${t.transformation} ↓ Output: ${t.outputType} \`\`\` **Location**: ${t.file}:${t.line} `).join('\n')} `) ``` --- ## PHASE 4: API CONTRACT DOCUMENTATION ### Step 4.1: Extract All Endpoints ```typescript all_endpoints = [] for (controller of controllers) { endpoints = extractEndpoints(controller_content) all_endpoints.push(...endpoints) } console.log(` ## API Contracts ### Base URL \`\`\` ${detectBaseUrl(feature_files)} \`\`\` ### Authentication ${detectAuthMethod(controllers)} ### Endpoints ${all_endpoints.map(ep => ` #### ${ep.method} ${ep.path} **Description**: ${ep.description || 'N/A'} **Request**: \`\`\`typescript // Headers ${ep.headers} // Query Parameters ${ep.queryParams || 'None'} // Body ${ep.requestBody || 'None'} \`\`\` **Response**: \`\`\`typescript // Success (${ep.successStatus || 200}) ${ep.responseType} // Errors ${ep.errorResponses.map(e => `// ${e.status}: ${e.description}`).join('\n')} \`\`\` **Example**: \`\`\`bash curl -X ${ep.method} \\ ${ep.fullUrl} \\ ${ep.auth ? `-H "Authorization: Bearer " \\` : ''} ${ep.requestBody ? `-d '${ep.exampleBody}'` : ''} \`\`\` `).join('\n---\n')} `) ``` ### Step 4.2: DTO Schemas ```typescript dtos = feature_files.filter(f => f.endsWith('.dto.ts')) for (dto_file of dtos) { schemas = extractDTOSchemas(dto_content) console.log(` ### ${basename(dto_file)} ${schemas.map(schema => ` #### ${schema.name} \`\`\`typescript ${schema.definition} \`\`\` **Validation Rules**: ${schema.validations.map(v => `- ${v.field}: ${v.rules.join(', ')}`).join('\n')} **Example**: \`\`\`json ${schema.example} \`\`\` `).join('\n')} `) } ``` --- ## PHASE 5: DATABASE SCHEMA ANALYSIS ### Step 5.1: Entity Relationships ```typescript entities = feature_files.filter(f => f.endsWith('.entity.ts')) entity_definitions = [] for (entity_file of entities) { entity_definitions.push(parseEntity(entity_content)) } console.log(` ## Database Schema ### Entity Relationship Diagram \`\`\` ${generateERDiagram(entity_definitions)} \`\`\` ### Tables ${entity_definitions.map(entity => ` #### ${entity.tableName} **Columns**: | Column | Type | Nullable | Default | Index | |--------|------|----------|---------|-------| ${entity.columns.map(col => `| ${col.name} | ${col.type} | ${col.nullable ? 'Yes' : 'No'} | ${col.default || '-'} | ${col.indexed ? '✓' : ''} |` ).join('\n')} **Relations**: ${entity.relations.map(rel => `- ${rel.type} with \`${rel.target}\` via \`${rel.joinColumn}\`` ).join('\n')} **Indexes**: ${entity.indexes.map(idx => `- \`${idx.name}\`: [${idx.columns.join(', ')}] ${idx.unique ? '(UNIQUE)' : ''}` ).join('\n')} `).join('\n---\n')} `) ``` ### Step 5.2: Migration History ```typescript migrations = feature_files.filter(f => f.includes('migrations/')) console.log(` ### Migration History ${migrations.map(mig => { return ` #### ${basename(mig)} **Date**: ${extractMigrationDate(mig)} **Changes**: ${extractMigrationChanges(mig_content)} **Rollback**: \`\`\`typescript ${extractRollbackSQL(mig_content)} \`\`\` ` }).join('\n')} `) ``` --- ## PHASE 6: SEQUENCE DIAGRAMS ### Step 6.1: Critical Flow Sequences ```typescript // Identify critical flows critical_flows = identifyCriticalFlows(feature_files) for (flow of critical_flows) { sequence = generateSequenceDiagram(flow) console.log(` ### ${flow.name} \`\`\`mermaid sequenceDiagram participant Client participant Controller participant Service participant Database participant External ${sequence.steps.map(step => `${step.from}->>${step.to}: ${step.action}` ).join('\n ')} \`\`\` **Trigger**: ${flow.trigger} **Success Path**: ${flow.successPath} **Error Handling**: ${flow.errorHandling} `) } ``` --- ## PHASE 7: INTEGRATION POINTS ### Step 7.1: External Services ```typescript integrations = detectIntegrations(feature_files) console.log(` ## Integration Points ### External Services ${integrations.external.map(ext => ` #### ${ext.name} **Type**: ${ext.type} (REST API, SDK, Webhook) **Purpose**: ${ext.purpose} **Authentication**: ${ext.auth} **Endpoints Used**: ${ext.endpoints.map(ep => `- \`${ep.method} ${ep.url}\``).join('\n')} **Configuration**: \`\`\`typescript ${ext.config} \`\`\` **Error Handling**: ${ext.errorHandling} `).join('\n---\n')} `) ``` ### Step 7.2: Message Queues ```typescript queues = detectQueues(feature_files) console.log(` ### Message Queues ${queues.map(q => ` #### ${q.name} **Type**: ${q.type} (BullMQ, RabbitMQ, Kafka) **Jobs**: ${q.jobs.map(job => `- \`${job.name}\`: ${job.description}`).join('\n')} **Processors**: \`\`\`typescript ${q.processor} \`\`\` **Retry Strategy**: ${q.retryStrategy} `).join('\n---\n')} `) ``` --- ## PHASE 8: UI & BRANDING ANALYSIS (NEW) ### Step 8.1: Brand & Theme Factory Tích hợp logic từ `brand-guidelines` và `theme-factory`: 1. Phân tích màu sắc chủ đạo từ CSS/Tailwind config. 2. Đề xuất UI palette phù hợp với thương hiệu. 3. Tạo mô tả mô hình UI (Mockups) dựa trên architecture. ```typescript Analyze the frontend components for: 1. Consistency with Brand Guidelines. 2. Color palette and Theme usage. 3. UI component reusability. Generate: - Theme JSON (primary, secondary, accent colors) - UI Mockup description (in Markdown/ASCII) ``` --- ## PHASE 9: KEY DESIGN DECISIONS ### Step 8.1: Architecture Decisions Records (ADR) ```typescript // Search for ADRs or extract from code comments adrs = findArchitectureDecisions(feature_files) console.log(` ## Key Design Decisions ${adrs.map((adr, idx) => ` ### Decision ${idx + 1}: ${adr.title} **Context**: ${adr.context} **Decision**: ${adr.decision} **Rationale**: ${adr.rationale} **Consequences**: - Pros: ${adr.pros.join(', ')} - Cons: ${adr.cons.join(', ')} **Alternatives Considered**: ${adr.alternatives.map(alt => `- ${alt.name}: ${alt.reason}`).join('\n')} **References**: ${adr.references || 'None'} `).join('\n---\n')} `) ``` ### Step 8.2: Pattern Analysis ```typescript patterns = detectPatterns(feature_files) console.log(` ## Design Patterns Used ${patterns.map(p => ` ### ${p.name} **Type**: ${p.type} (Creational, Structural, Behavioral) **Location**: ${p.location} **Purpose**: ${p.purpose} **Implementation**: \`\`\`typescript ${p.codeSnippet} \`\`\` **Benefits**: ${p.benefits} **Trade-offs**: ${p.tradeoffs} `).join('\n---\n')} `) ``` --- ## PHASE 9: FILES MAP ```typescript console.log(` ## Files Map ### Where to Find What | What | Where | Purpose | |------|-------|---------| ${createFilesMap(feature_files)} ### File Tree \`\`\` ${generateFileTree(feature_files)} \`\`\` ### Key Files ${identifyKeyFiles(feature_files).map(f => ` #### ${f.path} **Purpose**: ${f.purpose} **Lines**: ${f.lines} **Dependencies**: ${f.dependencies.length} **Complexity**: ${f.complexity} **Last Modified**: ${f.lastModified} `).join('\n')} `) ``` --- ## PHASE 10: GENERATE REPORT ```typescript report = ` # Architecture Explanation: ${FEATURE_NAME} **Generated**: ${new Date().toISOString().split('T')[0]} **Author**: AI Architecture Explainer **Version**: 1.0 --- ## Executive Summary ### What is ${FEATURE_NAME}? ${generateSummary(feature_files)} ### Scope - **Files**: ${feature_files.length} - **Components**: ${components.length} - **API Endpoints**: ${all_endpoints.length} - **Database Tables**: ${entity_definitions.length} ### Technology Stack ${tech_stack_summary} --- ${component_diagram} --- ${data_flow_diagrams} --- ${api_contracts} --- ${database_schema} --- ${sequence_diagrams} --- ${integration_points} --- ${design_decisions} --- ${files_map} --- ## Next Steps ### For New Developers 1. Read this document from top to bottom 2. Review key files: ${key_files.slice(0, 3).join(', ')} 3. Set up local environment 4. Run tests to verify setup ### For Code Review 1. Check API contracts match implementation 2. Verify database schema migrations 3. Review error handling in critical paths 4. Validate integration points ### For Refactoring 1. Identify tech debt areas (see Files Map) 2. Review design decisions for outdated choices 3. Check for pattern violations 4. Plan migration strategy ` REPORT_FILE = ".claude/architecture/${FEATURE_NAME}-architecture.md" ${report} console.log(` ════════════════════════════════════════════════════════════ ✅ ARCHITECTURE EXPLANATION COMPLETE ════════════════════════════════════════════════════════════ 📄 Report: ${REPORT_FILE} ## Quick Summary | Aspect | Count | |--------|-------| | Files | ${feature_files.length} | | Components | ${components.length} | | API Endpoints | ${all_endpoints.length} | | Database Tables | ${entity_definitions.length} | | External Services | ${integrations.external.length} | ## Key Sections 1. ✓ System Overview 2. ✓ Technology Stack 3. ✓ Component Architecture 4. ✓ Data Flow Diagrams 5. ✓ API Contracts 6. ✓ Database Schema 7. ✓ Sequence Diagrams 8. ✓ Integration Points 9. ✓ Design Decisions 10. ✓ Files Map ## Next Actions - Review report: ${REPORT_FILE} - Share with team for onboarding - Use as reference for refactoring `) ``` --- ## FOCUS MODES ```bash # API-focused /architecture-explainer --focus api-contracts payment # → Deep dive into API endpoints, DTOs, validation, authentication # Data flow focused /architecture-explainer --focus data-flow notifications # → Detailed request/response flows, data transformations # Database focused /architecture-explainer --focus database user-management # → ERD, migrations, indexes, relations # Integration focused /architecture-explainer --focus integrations billing # → External services, webhooks, queues # Full analysis /architecture-explainer --full alerts # → All sections with maximum detail ``` --- ## STRICT RULES 1. **ALWAYS start with high-level overview** before diving into details 2. **USE visual diagrams** (ASCII art, Mermaid) for all flows 3. **EXPLAIN WHY**, not just WHAT - document design decisions 4. **PROGRESSIVE DISCLOSURE** - summary → details → deep-dive 5. **CODE EXAMPLES** only for complex or non-obvious patterns 6. **KEEP DIAGRAMS SIMPLE** - maximum 7±2 components per diagram 7. **LINK EVERYTHING** - file paths, line numbers for traceability 8. **VALIDATE** diagrams match actual code implementation 9. **HIGHLIGHT GOTCHAS** - non-obvious behaviors, edge cases 10. **SUGGEST IMPROVEMENTS** only if explicitly requested --- ## EXECUTION SUMMARY ``` ARCHITECTURE EXPLAINER FLOW: Phase 1: Discovery (2-3 min) ├── Identify feature scope └── Map all related files Phase 2: Architecture Analysis (3-5 min) ├── Technology stack ├── Component diagram └── Dependency graph Phase 3: Data Flow (3-5 min) ├── Request/response flows └── Data transformations Phase 4: API Contracts (3-5 min) ├── Endpoints └── DTOs & validation Phase 5: Database (2-3 min) ├── ERD ├── Migrations └── Indexes Phase 6: Sequences (2-3 min) └── Critical flow diagrams Phase 7: Integrations (2-3 min) ├── External services └── Message queues Phase 8: Design Decisions (2-3 min) ├── ADRs └── Patterns Phase 9: Files Map (1-2 min) └── Where to find what Phase 10: Report (1 min) └── Generate markdown document TOTAL: 20-35 min ``` --- ## Additional Resources ### References - **`references/diagram-templates.md`** - ASCII art and Mermaid diagram templates - **`references/tech-stack-patterns.md`** - Common architecture patterns per stack - **`references/api-documentation.md`** - API documentation best practices ### Examples - **`examples/nestjs-feature.md`** - NestJS module architecture example - **`examples/react-feature.md`** - React component architecture example - **`examples/flutter-feature.md`** - Flutter feature architecture example --- ## INTEGRATION WITH OTHER SKILLS ```bash # After architecture explanation /refactor ${FEATURE_NAME} --based-on .claude/architecture/${FEATURE_NAME}-architecture.md # Use architecture for audit /audit-feature ${FEATURE_NAME} # Will reference architecture doc # Generate tests based on architecture /test --based-on-architecture ${FEATURE_NAME} # Create documentation /docs api --from-architecture ${FEATURE_NAME} ```