# Codebase Analyzer

## ⚠️ CRITICAL EXECUTION NOTICE ⚠️

**THIS IS AN EXECUTABLE WORKFLOW - NOT REFERENCE MATERIAL**

When this task is invoked:
1. **CODEBASE STRUCTURE ANALYSIS** - Understand current project architecture and patterns
2. **DOMAIN MAPPING** - Map business domains to code structure
3. **CHANGE IMPACT ANALYSIS** - Identify where new features should be implemented
4. **PATTERN RECOGNITION** - Identify existing patterns and conventions to follow

## Overview

This workflow analyzes the current codebase to provide dev agents with comprehensive understanding of where and how to implement new features, following existing patterns and conventions rather than creating files arbitrarily.

## Input Parameters

### Required Parameters
- **project_root**: Root directory of the project to analyze
- **task_context**: Context about the tasks being implemented

### Optional Parameters
- **analysis_depth**: "surface" | "detailed" | "comprehensive" (default: "detailed")
- **focus_domains**: Array of specific business domains to focus analysis on
- **include_tests**: boolean (default: true) - Include test structure analysis

## Execution Steps

### Phase 1: Project Structure Discovery

```yaml
step: project_structure_analysis
description: Analyze overall project structure and architecture patterns
actions:
  - scan_directory_structure: Map out complete directory hierarchy
  - identify_architecture_patterns: Detect MVC, Clean Architecture, Domain-Driven Design, etc.
  - map_technology_stack: Identify frameworks, libraries, and tools in use
  - analyze_configuration_files: Examine package.json, appsettings.json, etc.
  - identify_build_patterns: Understand build and deployment structure
structure_analysis:
  backend_structure:
    - controllers_location: "Where API controllers are located"
    - services_location: "Where business logic services reside"
    - models_location: "Where data models and entities are defined"
    - repositories_location: "Where data access layer is implemented"
    - configuration_location: "Where configuration and startup logic resides"
  frontend_structure:
    - components_location: "Where reusable components are stored"
    - pages_location: "Where page components and routing is defined"
    - services_location: "Where API integration and business logic resides"
    - styles_location: "Where styling and theme definitions are kept"
    - utilities_location: "Where utility functions and helpers are stored"
  shared_structure:
    - interfaces_location: "Where TypeScript interfaces and contracts are defined"
    - constants_location: "Where application constants are stored"
    - configurations_location: "Where shared configuration is managed"
    - documentation_location: "Where project documentation resides"
```

### Phase 2: Domain Mapping & Business Logic Analysis

```yaml
step: domain_business_analysis
description: Map business domains to code structure and identify domain boundaries
actions:
  - identify_business_domains: Discover existing business domains in codebase
  - map_domain_boundaries: Understand how domains are separated in code
  - analyze_domain_models: Examine domain entities and business objects
  - trace_feature_implementations: Follow how existing features are implemented
  - identify_cross_cutting_concerns: Find shared functionality across domains
domain_mapping:
  business_domains:
    - user_management: "User registration, authentication, profile management"
    - payments: "Payment processing, billing, transaction management"
    - notifications: "Email, SMS, push notifications, communication"
    - reporting: "Analytics, reporting, dashboard functionality"
    - administration: "Admin panels, system configuration, user management"
  domain_code_mapping:
    - domain_controllers: "Which controllers handle which business domains"
    - domain_services: "How business logic is organized by domain"
    - domain_models: "How data models are structured by business area"
    - domain_frontend: "How frontend is organized by user-facing features"
  implementation_patterns:
    - naming_conventions: "How files, classes, and methods are named"
    - folder_organization: "How code is organized within each domain"
    - dependency_patterns: "How dependencies flow between layers"
    - error_handling_patterns: "How errors are handled consistently"
```

### Phase 3: Change Impact Analysis

```yaml
step: change_impact_analysis
description: Identify optimal locations for implementing new features
actions:
  - analyze_existing_patterns: Study how similar features were implemented
  - identify_extension_points: Find where new functionality should be added
  - assess_modification_requirements: Determine what existing code needs changes
  - plan_integration_strategy: Plan how new code integrates with existing systems
  - identify_potential_conflicts: Spot areas where changes might cause issues
change_strategy:
  new_feature_placement:
    - follow_existing_patterns: "Place new code following established patterns"
    - respect_domain_boundaries: "Keep business logic within appropriate domains"
    - minimize_cross_cutting_changes: "Avoid changes that affect multiple domains"
    - leverage_existing_infrastructure: "Use existing services and utilities"
  modification_approach:
    - extend_existing_classes: "Extend rather than modify when possible"
    - use_established_interfaces: "Implement existing interfaces and contracts"
    - follow_naming_conventions: "Use consistent naming with existing code"
    - maintain_architectural_integrity: "Preserve existing architectural decisions"
  integration_points:
    - api_endpoints: "Where to add new API endpoints"
    - database_schema: "How to extend database schema appropriately"
    - frontend_routing: "Where to add new routes and navigation"
    - authentication_integration: "How to integrate with existing auth systems"
```

### Phase 4: Pattern Recognition & Convention Mapping

```yaml
step: pattern_convention_analysis
description: Identify and document existing patterns and conventions to follow
actions:
  - analyze_coding_patterns: Study existing code patterns and styles
  - document_architectural_decisions: Record architectural patterns in use
  - identify_testing_patterns: Understand how testing is structured
  - map_configuration_patterns: Document configuration and dependency injection
  - analyze_error_handling: Study error handling and logging patterns
pattern_documentation:
  coding_conventions:
    - class_naming: "How classes are named (PascalCase, prefixes, suffixes)"
    - method_naming: "How methods are named (camelCase, verb patterns)"
    - variable_naming: "How variables are named (camelCase, descriptive names)"
    - file_organization: "How files are organized within directories"
  architectural_patterns:
    - controller_patterns: "How controllers are structured and organized"
    - service_patterns: "How services are implemented and injected"
    - repository_patterns: "How data access is implemented"
    - dto_patterns: "How data transfer objects are structured"
  testing_conventions:
    - test_file_naming: "How test files are named and organized"
    - test_method_naming: "How test methods are structured"
    - mock_patterns: "How mocking and test doubles are used"
    - test_data_patterns: "How test data is created and managed"
```

### Phase 5: Implementation Guidance Generation

```yaml
step: implementation_guidance
description: Generate specific guidance for implementing new features
actions:
  - create_implementation_roadmap: Provide step-by-step implementation guidance
  - identify_required_files: List exactly which files need to be created or modified
  - provide_code_templates: Generate templates following existing patterns
  - specify_integration_points: Detail how new code integrates with existing systems
  - create_testing_strategy: Outline testing approach following existing patterns
guidance_output:
  file_modification_plan:
    - files_to_create: "New files to create with exact paths and purposes"
    - files_to_modify: "Existing files to modify with specific change locations"
    - configuration_updates: "Configuration files that need updates"
    - database_changes: "Database schema changes required"
  implementation_templates:
    - controller_template: "Template for new controllers following existing patterns"
    - service_template: "Template for new services with proper dependency injection"
    - model_template: "Template for new models with validation and mapping"
    - component_template: "Template for new frontend components"
  integration_checklist:
    - dependency_injection: "How to register new services in DI container"
    - routing_updates: "How to add new routes following existing patterns"
    - authentication_integration: "How to integrate with existing auth middleware"
    - logging_integration: "How to add logging following existing patterns"
```

## Output Format

### Codebase Analysis Results
```yaml
codebase_analysis:
  project_overview:
    architecture_pattern: "Clean Architecture with Domain-Driven Design"
    technology_stack:
      backend: [".NET Core 8", "Entity Framework Core", "PostgreSQL"]
      frontend: ["Next.js 14", "TypeScript", "Tailwind CSS"]
      testing: ["NUnit", "Vitest", "Playwright"]
    project_structure:
      backend_root: "src/Api"
      frontend_root: "src/Web"
      shared_root: "src/Shared"
      tests_root: "tests"
  
  domain_mapping:
    identified_domains:
      - domain: "UserManagement"
        location: "src/Api/Features/Users"
        frontend_location: "src/Web/features/users"
        responsibilities: ["User registration", "Profile management", "Authentication"]
      
      - domain: "Payments"
        location: "src/Api/Features/Payments"
        frontend_location: "src/Web/features/payments"
        responsibilities: ["Payment processing", "Transaction history", "Billing"]
      
      - domain: "Notifications"
        location: "src/Api/Features/Notifications"
        frontend_location: "src/Web/features/notifications"
        responsibilities: ["Email notifications", "SMS alerts", "Push notifications"]
  
  implementation_patterns:
    controller_pattern:
      location: "src/Api/Features/{Domain}/Controllers"
      naming_convention: "{Domain}Controller.cs"
      base_class: "ApiControllerBase"
      example: "src/Api/Features/Users/Controllers/UsersController.cs"
    
    service_pattern:
      location: "src/Api/Features/{Domain}/Services"
      naming_convention: "I{Domain}Service.cs (interface), {Domain}Service.cs (implementation)"
      dependency_injection: "Registered in Program.cs using service extensions"
      example: "src/Api/Features/Users/Services/IUserService.cs"
    
    frontend_pattern:
      components_location: "src/Web/features/{domain}/components"
      pages_location: "src/Web/features/{domain}/pages"
      services_location: "src/Web/features/{domain}/services"
      naming_convention: "PascalCase for components, kebab-case for files"
```

### Implementation Guidance
```yaml
implementation_guidance:
  for_task_group: "user-profile-management"
  
  backend_implementation:
    files_to_create:
      - path: "src/Api/Features/Users/Controllers/ProfileController.cs"
        purpose: "Handle profile management API endpoints"
        template: "Standard controller with CRUD operations"
      
      - path: "src/Api/Features/Users/Services/IProfileService.cs"
        purpose: "Profile management business logic interface"
        template: "Service interface with async methods"
      
      - path: "src/Api/Features/Users/Services/ProfileService.cs"
        purpose: "Profile management business logic implementation"
        template: "Service with repository injection and validation"
    
    files_to_modify:
      - path: "src/Api/Features/Users/Models/UserProfile.cs"
        changes: ["Add new profile fields", "Update validation attributes"]
        location: "Extend existing UserProfile class"
      
      - path: "src/Api/Program.cs"
        changes: ["Register new ProfileService in DI container"]
        location: "Add to service registration section"
    
    database_changes:
      - migration_name: "AddProfileFields"
        changes: ["Add ProfilePicture column", "Add Bio column", "Add LastUpdated column"]
        entity: "UserProfile"
  
  frontend_implementation:
    files_to_create:
      - path: "src/Web/features/users/components/ProfileEditor.tsx"
        purpose: "Profile editing form component"
        template: "Form component with validation using react-hook-form"
      
      - path: "src/Web/features/users/services/profileService.ts"
        purpose: "API integration for profile operations"
        template: "Service with typed API calls using fetch wrapper"
    
    files_to_modify:
      - path: "src/Web/features/users/pages/ProfilePage.tsx"
        changes: ["Add ProfileEditor component", "Add profile update handling"]
        location: "Integrate new editor in existing profile page"
    
    routing_updates:
      - path: "src/Web/app/users/profile/edit/page.tsx"
        purpose: "Profile editing page route"
        integration: "Add to existing user profile routing structure"
  
  testing_strategy:
    backend_tests:
      - path: "tests/Api.Tests/Features/Users/ProfileControllerTests.cs"
        purpose: "Unit tests for profile controller"
        template: "Controller tests with mocked dependencies"
      
      - path: "tests/Api.Tests/Features/Users/ProfileServiceTests.cs"
        purpose: "Unit tests for profile service"
        template: "Service tests with repository mocks"
    
    frontend_tests:
      - path: "tests/Web.Tests/features/users/ProfileEditor.test.tsx"
        purpose: "Component tests for profile editor"
        template: "Vitest component tests with user interaction"
      
      - path: "tests/E2E/features/profile-management.spec.ts"
        purpose: "End-to-end profile management tests"
        template: "Playwright E2E tests covering full user journey"
```

### Pattern Templates
```yaml
pattern_templates:
  controller_template: |
    using Microsoft.AspNetCore.Mvc;
    using {ProjectName}.Api.Features.{Domain}.Services;
    using {ProjectName}.Api.Features.{Domain}.Models;
    
    namespace {ProjectName}.Api.Features.{Domain}.Controllers;
    
    [ApiController]
    [Route("api/[controller]")]
    public class {Domain}Controller : ApiControllerBase
    {
        private readonly I{Domain}Service _{domain}Service;
        
        public {Domain}Controller(I{Domain}Service {domain}Service)
        {
            _{domain}Service = {domain}Service;
        }
        
        // Follow existing controller patterns from UserController
    }
  
  service_template: |
    using {ProjectName}.Api.Features.{Domain}.Models;
    
    namespace {ProjectName}.Api.Features.{Domain}.Services;
    
    public interface I{Domain}Service
    {
        Task<{Domain}Response> GetAsync(int id);
        Task<{Domain}Response> CreateAsync({Domain}Request request);
        Task<{Domain}Response> UpdateAsync(int id, {Domain}Request request);
        Task<bool> DeleteAsync(int id);
    }
  
  frontend_component_template: |
    'use client';
    
    import { useState } from 'react';
    import { useForm } from 'react-hook-form';
    import { {domain}Service } from '../services/{domain}Service';
    
    interface {Component}Props {
      // Define props following existing component patterns
    }
    
    export function {Component}({ }: {Component}Props) {
      // Follow existing component patterns from UserProfile component
      return (
        <div className="space-y-4">
          {/* Component implementation */}
        </div>
      );
    }
```

## Integration Points

### Dev Agent Integration
- **Codebase Context**: Provides comprehensive codebase understanding to dev agents
- **Implementation Guidance**: Specific instructions on where and how to implement features
- **Pattern Following**: Ensures new code follows existing patterns and conventions

### Workflow Integration
- **Pre-Implementation**: Runs before dev agents start implementation
- **Context Sharing**: Shares analysis results with all development agents
- **Quality Assurance**: Ensures implementations maintain architectural integrity

### Quality Standards
- **Pattern Consistency**: Maintains consistent patterns across codebase
- **Architectural Integrity**: Preserves existing architectural decisions
- **Domain Boundaries**: Respects business domain boundaries and separation