sf-agent-framework
Version:
AI Agent Orchestration Framework for Salesforce Development - Two-phase architecture with 70% context reduction
416 lines (303 loc) • 8.72 kB
Markdown
# Analyze Codebase Task
---
task: analyze-codebase
agent: sf-architect
priority: high
estimated_time: 2-4 hours
requires_tools:
- sf
- pmd
- eslint
---
# Task Overview
Perform comprehensive analysis of the Salesforce codebase to understand its structure, complexity, quality, and dependencies. This analysis provides the foundation for technical decisions and improvements.
# Pre-requisites
- [ ] Access to Salesforce org or repository
- [ ] SF CLI installed and authenticated
- [ ] PMD (Apex static analysis) configured
- [ ] ESLint (LWC analysis) configured
- [ ] Code coverage reports available
# Instructions
## Phase 1: Inventory Collection
### 1.1 Component Inventory
```bash
# Count Apex Classes
sf project retrieve start --metadata ApexClass --target-org <alias>
find force-app -name "*.cls" | wc -l
# Count Triggers
sf project retrieve start --metadata ApexTrigger --target-org <alias>
find force-app -name "*.trigger" | wc -l
# Count LWC Components
find force-app -type d -name "lwc" -exec ls {} \; | wc -l
# Count Aura Components
find force-app -type d -name "aura" -exec ls {} \; | wc -l
# Count Flows
sf project retrieve start --metadata Flow --target-org <alias>
find force-app -name "*.flow-meta.xml" | wc -l
```
### 1.2 Metrics Collection
- Total lines of code (LOC)
- Lines of Apex code
- Lines of JavaScript code
- Lines of configuration (XML)
- Number of custom objects
- Number of custom fields
- Number of validation rules
- Number of process builders/flows
## Phase 2: Code Quality Analysis
### 2.1 Apex Analysis with PMD
```bash
# Run PMD analysis
pmd check -d force-app/main/default/classes -R category/apex/bestpractices.xml -f json -r pmd-report.json
# Check for:
- Cyclomatic complexity
- Cognitive complexity
- Method length
- Class cohesion
- SOQL/DML in loops
- Hardcoded IDs
- Missing assertions in tests
```
### 2.2 LWC Analysis with ESLint
```bash
# Run ESLint analysis
eslint force-app/main/default/lwc --format json --output-file eslint-report.json
# Check for:
- Component complexity
- Unused variables
- Console statements
- Async/await usage
- Error handling
```
### 2.3 Code Coverage Analysis
```bash
# Retrieve test coverage
sf apex test run --code-coverage --result-format json --target-org <alias>
# Analyze:
- Overall org coverage
- Per-class coverage
- Uncovered lines identification
- Test quality metrics
```
## Phase 3: Dependency Analysis
### 3.1 Component Dependencies
Create dependency map showing:
```
ApexClass -> ApexClass dependencies
ApexClass -> Object dependencies
LWC -> Apex dependencies
Flow -> Object/Apex dependencies
Trigger -> Class dependencies
```
### 3.2 External Dependencies
Identify:
- Managed package dependencies
- External service integrations
- Third-party libraries
- API dependencies
### 3.3 Data Dependencies
Map:
- Parent-child relationships
- Lookup relationships
- Master-detail relationships
- External ID relationships
## Phase 4: Architecture Analysis
### 4.1 Layer Analysis
```
Presentation Layer:
- LWC Components: [count]
- Aura Components: [count]
- Visualforce Pages: [count]
Business Logic Layer:
- Apex Classes: [count]
- Triggers: [count]
- Flows: [count]
Data Layer:
- Custom Objects: [count]
- Custom Settings: [count]
- Platform Events: [count]
```
### 4.2 Pattern Detection
Identify usage of:
- Trigger framework pattern
- Service layer pattern
- Repository pattern
- Factory pattern
- Singleton pattern
- Builder pattern
### 4.3 Integration Points
Document:
- REST API endpoints
- SOAP API endpoints
- Platform Events
- Streaming API usage
- Bulk API usage
## Phase 5: Performance Analysis
### 5.1 Query Analysis
```sql
-- Find expensive SOQL queries
SELECT COUNT(*) FROM ApexClass WHERE Body LIKE '%SELECT%FROM%'
-- Identify queries without limits
-- Identify queries without selective filters
-- Find queries in loops
```
### 5.2 Governor Limit Risks
Identify code at risk of hitting:
- SOQL query limits
- DML statement limits
- CPU time limits
- Heap size limits
- Callout limits
### 5.3 Bulk Processing Capability
Assess:
- Trigger bulkification
- Batch apex usage
- Queueable apex usage
- Platform Events for async
## Phase 6: Security Analysis
### 6.1 CRUD/FLS Checks
```apex
// Scan for:
- Missing CRUD checks
- Missing FLS checks
- Without sharing usage
- System mode operations
```
### 6.2 Vulnerability Scan
Check for:
- SOQL injection risks
- XSS vulnerabilities
- Insecure endpoints
- Hardcoded credentials
- Excessive permissions
## Phase 7: Report Generation
### 7.1 Executive Summary
```markdown
# Codebase Analysis Report
## Executive Summary
- **Analysis Date**: [DATE]
- **Org/Repository**: [NAME]
- **Total Components**: [COUNT]
- **Overall Health Score**: [SCORE]/100
## Key Findings
1. [Major finding 1]
2. [Major finding 2]
3. [Major finding 3]
## Recommendations Priority
- 🔴 Critical: [count] issues
- 🟠 High: [count] issues
- 🟡 Medium: [count] issues
- 🟢 Low: [count] issues
```
### 7.2 Detailed Metrics
```markdown
## Component Inventory
| Component Type | Count | Lines of Code | Complexity |
| -------------- | ----- | ------------- | ---------- |
| Apex Classes | XXX | XXXXX | X.X |
| Triggers | XXX | XXXXX | X.X |
| LWC | XXX | XXXXX | X.X |
| Flows | XXX | N/A | X.X |
## Code Quality Metrics
| Metric | Value | Target | Status |
| --------------- | ------- | ------ | ------ |
| Code Coverage | XX% | 85% | ⚠️ |
| Avg Complexity | X.X | <10 | ✅ |
| Technical Debt | XX days | <30 | ⚠️ |
| Duplicated Code | XX% | <5% | ❌ |
## Dependency Matrix
[Include visual representation or table]
## Risk Assessment
### High Risk Areas
1. **Component**: [Name]
- **Issue**: [Description]
- **Impact**: [High/Medium/Low]
- **Recommendation**: [Action]
```
### 7.3 Actionable Recommendations
```markdown
## Immediate Actions (Week 1)
- [ ] Fix critical security vulnerabilities in [components]
- [ ] Address governor limit risks in [classes]
- [ ] Improve test coverage for [critical classes]
## Short-term Improvements (Month 1)
- [ ] Refactor complex methods in [classes]
- [ ] Implement proper error handling in [components]
- [ ] Consolidate duplicate code in [areas]
## Long-term Enhancements (Quarter)
- [ ] Migrate to LWC from Aura components
- [ ] Implement service layer pattern
- [ ] Optimize data model relationships
```
## Output Artifacts
Generate the following files:
1. `docs/analysis/codebase-analysis.md` - Main report
2. `docs/analysis/dependency-graph.json` - Component dependencies
3. `docs/analysis/metrics-dashboard.json` - Metrics data
4. `docs/analysis/security-findings.md` - Security issues
5. `docs/analysis/performance-bottlenecks.md` - Performance issues
## Automation Script
```javascript
// analyze-codebase.js
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
class CodebaseAnalyzer {
async analyze() {
const metrics = await this.collectMetrics();
const quality = await this.analyzeQuality();
const dependencies = await this.analyzeDependencies();
const security = await this.analyzeSecurity();
const performance = await this.analyzePerformance();
const report = this.generateReport({
metrics,
quality,
dependencies,
security,
performance,
});
this.saveReport(report);
return report;
}
async collectMetrics() {
// Implementation
}
async analyzeQuality() {
// Run PMD, ESLint, etc.
}
async analyzeDependencies() {
// Map component relationships
}
async analyzeSecurity() {
// Security scanning
}
async analyzePerformance() {
// Performance analysis
}
generateReport(data) {
// Format markdown report
}
saveReport(report) {
fs.writeFileSync('docs/analysis/codebase-analysis.md', report);
}
}
// Execute analysis
const analyzer = new CodebaseAnalyzer();
analyzer.analyze().then(console.log).catch(console.error);
```
## Success Criteria
- [ ] All components inventoried
- [ ] Code metrics calculated
- [ ] Dependencies mapped
- [ ] Security vulnerabilities identified
- [ ] Performance bottlenecks found
- [ ] Report generated and saved
- [ ] Recommendations prioritized
- [ ] Action plan created
## Follow-up Tasks
After completing this analysis:
1. Run `identify-technical-debt` task for detailed debt assessment
2. Run `recommend-refactoring` task for specific improvements
3. Create Jira tickets for critical issues
4. Schedule review meeting with team
5. Plan remediation sprint