UNPKG

sf-agent-framework

Version:

AI Agent Orchestration Framework for Salesforce Development - Two-phase architecture with 70% context reduction

478 lines (367 loc) 10.9 kB
# Identify Technical Debt Task --- task: identify-technical-debt agent: sf-architect priority: high estimated_time: 3-5 hours requires_tools: - sfdx - pmd - sonarqube - git depends_on: - analyze-codebase --- # Task Overview Systematically identify, categorize, and quantify technical debt across the Salesforce codebase. This analysis helps prioritize remediation efforts and plan technical improvements strategically. # Pre-requisites - [ ] Codebase analysis completed (`analyze-codebase` task) - [ ] Access to git history for age analysis - [ ] Static analysis tools configured (PMD, SonarQube) - [ ] Test coverage reports available - [ ] Performance metrics available # Technical Debt Categories ## 1. Code Debt - Complex or convoluted code - Duplicated code - Dead code - Long methods/classes - Poor naming conventions - Missing documentation ## 2. Design Debt - Architectural violations - Missing abstraction layers - Tight coupling - Lack of modularity - Pattern misuse - God classes/objects ## 3. Test Debt - Low test coverage - Missing test scenarios - Brittle tests - Test data dependencies - No integration tests - Manual testing only ## 4. Documentation Debt - Missing documentation - Outdated documentation - No API documentation - Missing architecture diagrams - No runbooks ## 5. Infrastructure Debt - Outdated dependencies - Manual deployments - No CI/CD pipeline - Environment inconsistencies - Missing monitoring # Instructions ## Phase 1: Code Quality Debt Assessment ### 1.1 Complexity Analysis ```javascript // Identify high complexity code const complexityThresholds = { cyclomatic: 10, // Methods with CC > 10 cognitive: 15, // Methods with cognitive complexity > 15 npath: 200, // Methods with NPath > 200 loc: 100, // Methods with > 100 lines }; // Find violations class ComplexityAnalyzer { analyzeClass(className) { return { class: className, methods: [ { name: 'processOrder', cyclomaticComplexity: 25, cognitiveComplexity: 30, linesOfCode: 250, debt: 'HIGH', estimatedHours: 16, }, ], }; } } ``` ### 1.2 Duplication Detection ```bash # Find duplicate code blocks pmd cpd --minimum-tokens 100 --language apex --files force-app --format json # Analyze results - Exact duplicates - Similar code patterns - Copy-paste programming - Missed abstraction opportunities ``` ### 1.3 Code Smell Detection ``` Common Code Smells to Identify: - Long Parameter Lists (>5 parameters) - Feature Envy (method uses another class extensively) - Data Clumps (same parameters repeatedly grouped) - Primitive Obsession (overuse of primitives) - Switch Statements (missing polymorphism) - Lazy Class (class doing too little) - Speculative Generality (unused flexibility) - Temporary Fields (fields only used sometimes) - Message Chains (a.getB().getC().getD()) - Middle Man (class only delegating) ``` ## Phase 2: Design & Architecture Debt ### 2.1 Architectural Violations ```yaml Architectural Rules: - Controllers should not contain business logic - Services should not access database directly - Triggers should delegate to handler classes - No circular dependencies between packages - Separation of concerns maintained Violations Found: - AccountController: Contains 500+ lines of business logic - OrderService: Direct SOQL queries (should use repository) - OpportunityTrigger: All logic in trigger (no handler) ``` ### 2.2 Coupling Analysis ``` High Coupling Indicators: - Classes with >10 dependencies - Circular dependencies between classes - Direct field access instead of methods - Hardcoded class references - Missing interfaces/abstractions Example: Class: OrderProcessor Dependencies: 15 classes Coupled to: Database, UI, External Services Recommendation: Apply Dependency Injection ``` ### 2.3 Pattern Violations ``` Expected Patterns vs Reality: Trigger Framework: Expected: All triggers use framework Reality: 30% using framework, 70% ad-hoc Debt: HIGH - Inconsistent error handling Service Layer: Expected: All business logic in services Reality: Logic scattered across triggers, controllers Debt: MEDIUM - Difficult to test and maintain ``` ## Phase 3: Test Debt Analysis ### 3.1 Coverage Gaps ```javascript class TestDebtAnalyzer { analyzeCoverage() { return { overall: 72, // Below 85% target uncoveredClasses: [ { name: 'PaymentProcessor', coverage: 0, risk: 'CRITICAL' }, { name: 'TaxCalculator', coverage: 45, risk: 'HIGH' }, { name: 'EmailService', coverage: 60, risk: 'MEDIUM' }, ], missingScenarios: [ 'Bulk operations (>200 records)', 'Negative test cases', 'Governor limit testing', 'Integration scenarios', ], }; } } ``` ### 3.2 Test Quality Issues ``` Test Antipatterns Found: - Tests without assertions (30 cases) - Hardcoded IDs in tests (45 cases) - Tests depending on org data (20 cases) - Non-deterministic tests (15 cases) - Tests not testing actual functionality (25 cases) Example: @isTest static void testMethod1() { // Poor naming Account a = new Account(Name='Test'); // No assertion insert a; } ``` ## Phase 4: Documentation Debt ### 4.1 Missing Documentation ```markdown Documentation Coverage: - Apex Classes: 30% documented - Methods: 15% have comments - Complex Logic: 5% explained - APIs: 0% have documentation - Workflows: No documentation Critical Gaps: 1. PaymentGateway integration - No docs 2. Tax calculation algorithm - No explanation 3. Order fulfillment process - No flow diagram ``` ### 4.2 Outdated Documentation ``` Age Analysis: - 60% of docs > 1 year old - 30% reference deprecated features - 50% have incorrect examples - Architecture diagrams don't match current state ``` ## Phase 5: Quantify Technical Debt ### 5.1 Debt Calculation ```javascript class TechnicalDebtCalculator { calculate(issue) { const hourRates = { TRIVIAL: 0.5, MINOR: 2, MAJOR: 8, CRITICAL: 24, BLOCKER: 40, }; return { issue: issue.description, severity: issue.severity, estimatedHours: hourRates[issue.severity], cost: hourRates[issue.severity] * 150, // $150/hour risk: this.calculateRisk(issue), }; } calculateRisk(issue) { // Business impact * Probability of failure return issue.businessImpact * issue.failureProbability; } } ``` ### 5.2 Debt Interest ``` Debt Interest Calculation: - Time added to new features: +30% - Bug rate increase: +45% - Onboarding time for new devs: +2 weeks - Production incident rate: 2x baseline Monthly Interest Cost: $25,000 ``` ## Phase 6: Generate Technical Debt Report ### 6.1 Executive Summary ```markdown # Technical Debt Report ## Executive Summary **Total Technical Debt**: 2,450 hours (~15 person-months) **Estimated Cost**: $367,500 **Monthly Interest**: $25,000 **Risk Level**: HIGH ## Debt Distribution - Code Quality: 35% (857 hours) - Design/Architecture: 25% (612 hours) - Test Coverage: 20% (490 hours) - Documentation: 15% (367 hours) - Infrastructure: 5% (122 hours) ## Critical Items (Must Fix) 1. **Payment Processing**: No test coverage, high complexity 2. **Order Management**: Circular dependencies, 15K LOC class 3. **Security**: SOQL injection vulnerabilities in 5 classes ``` ### 6.2 Detailed Findings ```markdown ## Code Quality Debt ### High Complexity Classes | Class | CC | LOC | Methods | Debt (hrs) | Priority | | -------------- | --- | ---- | ------- | ---------- | -------- | | OrderProcessor | 45 | 2500 | 35 | 40 | CRITICAL | | AccountManager | 38 | 1800 | 28 | 32 | HIGH | | PaymentGateway | 35 | 1500 | 22 | 24 | HIGH | ### Code Duplication - **Total Duplicated Lines**: 5,420 (12% of codebase) - **Duplication Hotspots**: - Validation logic (repeated 8 times) - Error handling (repeated 15 times) - Data transformation (repeated 6 times) ## Design Debt ### Architectural Violations 1. **Layering Violations**: 23 cases - Controllers accessing database directly - Triggers containing business logic - UI components calling external services 2. **Coupling Issues**: - Average coupling: 8.5 (target: <5) - Circular dependencies: 5 cycles detected - God classes: 3 identified ## Test Debt ### Coverage Gaps - **Current Coverage**: 72% - **Target Coverage**: 85% - **Gap**: 13% - **Critical Uncovered**: - Payment processing (0%) - Tax calculations (45%) - Integration points (30%) ### Test Quality Issues - Tests without assertions: 30 - Hardcoded test data: 45 - Flaky tests: 15 - Missing scenarios: Bulk, Negative, Limits ``` ### 6.3 Remediation Plan ```markdown ## Remediation Roadmap ### Phase 1: Critical Fixes (Month 1) - [ ] Add tests for PaymentProcessor (40 hrs) - [ ] Fix SOQL injection vulnerabilities (16 hrs) - [ ] Refactor OrderProcessor god class (32 hrs) **Total: 88 hours** ### Phase 2: High Priority (Month 2-3) - [ ] Implement trigger framework (40 hrs) - [ ] Extract service layer (60 hrs) - [ ] Improve test coverage to 80% (80 hrs) **Total: 180 hours** ### Phase 3: Medium Priority (Quarter 2) - [ ] Reduce code duplication (60 hrs) - [ ] Update documentation (40 hrs) - [ ] Implement CI/CD pipeline (30 hrs) **Total: 130 hours** ### Phase 4: Ongoing Improvements - [ ] Refactor complex methods (ongoing) - [ ] Maintain documentation (ongoing) - [ ] Code review process (ongoing) ``` ### 6.4 Debt Prevention Strategy ```markdown ## Prevention Measures ### Development Standards 1. Enforce complexity limits (CC < 10) 2. Mandatory code reviews 3. Test coverage minimum 85% 4. Documentation requirements ### Tooling 1. Pre-commit hooks for static analysis 2. Automated test execution 3. Coverage gates in CI/CD 4. Architecture validation tools ### Process Improvements 1. Regular refactoring sprints (20% capacity) 2. Technical debt review meetings 3. Architecture review board 4. Documentation days ``` ## Output Artifacts 1. `docs/analysis/technical-debt-report.md` - Main report 2. `docs/analysis/debt-inventory.json` - Detailed debt items 3. `docs/analysis/remediation-plan.md` - Action plan 4. `docs/analysis/debt-metrics.json` - Metrics and trends 5. `docs/analysis/debt-heatmap.html` - Visual representation ## Success Criteria - [ ] All debt categories assessed - [ ] Debt quantified in hours/cost - [ ] Risk levels assigned - [ ] Remediation plan created - [ ] Prevention strategy defined - [ ] Report generated and reviewed - [ ] Backlog items created ## Follow-up Actions 1. Present findings to stakeholders 2. Get approval for remediation plan 3. Allocate capacity for debt reduction 4. Set up debt tracking dashboard 5. Schedule regular debt reviews 6. Run `recommend-refactoring` for specific solutions