Phase: 2 (Complete)
Status: ✅ Production Ready
Last Updated: 2026-08-21
The Metrics Agent is an automated system for collecting, analyzing, and reporting on repository metrics. It runs daily, aggregates GitHub data, detects anomalies, and generates actionable reports for stakeholders.
┌─────────────────────────────────────────────────────┐
│ REPORTING LAYER (Task 2.4) │
│ - Markdown report generation │
│ - GitHub issue creation │
│ - Health score calculation │
└─────────────────────────────────────────────────────┘
↑
┌─────────────────────────────────────────────────────┐
│ ANALYSIS LAYER (Task 2.2) │
│ - Trend analysis │
│ - Anomaly detection │
│ - Time-series storage │
└─────────────────────────────────────────────────────┘
↑
┌─────────────────────────────────────────────────────┐
│ COLLECTION LAYER (Task 2.1 & 2.3) │
│ - GitHub API integration │
│ - Metrics collection │
│ - Pagination & error handling │
└─────────────────────────────────────────────────────┘
Purpose: GitHub API client with full metrics collection
Key Methods:
fetchMetrics()— Retrieves comprehensive metrics from GitHub APIfetchIssues()— Gets issue data with paginationfetchPullRequests()— Retrieves PR metricsfetchContributors()— Collects contributor informationhandleRateLimit()— Manages API rate limits
Features:
- Pagination support (per_page up to 100)
- Automatic retry with exponential backoff
- Rate limit awareness
- Comprehensive error handling
Purpose: Persistent time-series storage for historical data
Key Methods:
saveMetrics(repository, metrics)— Persists daily metricsgetLatestMetrics(repository)— Retrieves most recent datagetMetricsHistory(repository)— Gets historical data for trendsgetMetricsRange(repository, startDate, endDate)— Range queries
Storage Structure:
.github/reports/metrics/
├── lightspeedwp-github/
│ ├── 2026-08-21.json # Daily snapshot
│ ├── 2026-08-20.json
│ └── ...
└── time-series.json # Consolidated history
Purpose: Calculates trends and patterns
Key Methods:
analyzeTrends(repository, storage)— Computes trend metricscalculateWeekOverWeek()— Weekly change analysiscalculateMonthOverMonth()— Monthly patternsforecastNextPeriod()— Predicts future trends
Trend Metrics:
- Issue closure rate trends
- PR merge rate velocity
- Contributor growth
- Stability indicators
Purpose: Identifies unusual patterns
Key Methods:
detectAnomalies(repository, metrics, trends)— Finds outlierscompareToBaseline(current, baseline)— Deviation detectioncalculateSeverity(deviation)— Impact assessment
Detection Types:
- Issue closure rate drops
- PR review time increases
- Unexpected contributor changes
- CI failure rate spikes
Purpose: Generates markdown reports
Key Methods:
generateReport(repository, options)— Creates full reportcalculateHealthScore(metrics, trends)— 0-100 scoregenerateChart(label, data)— ASCII visualizations
Report Sections:
- Header (title, date)
- Summary (health score, key metrics)
- Issues (total, closed, closure rate)
- Pull Requests (merge stats, review time)
- Contributors (active, new, returning)
- Health Status (assessment)
- Anomalies (detected issues)
- Trends (historical patterns)
- Footer (metadata)
Purpose: Manages metrics issues on GitHub
Key Methods:
createMetricsIssue()— Creates new report issuecreateWeeklyMetricsIssue()— Weekly wrappercreateMonthlyMetricsIssue()— Monthly wrappercloseOldReports()— Cleanup (>90 days)getMetricsIssues()— RetrievalcreateMetricsIssueWithRetry()— Resilient creation
Labels Applied:
type:metrics— Issue typearea:monitoring— Areaperiod:weeklyorperiod:monthly— Period
Schedule: Daily at 2 AM UTC (configurable)
Jobs:
-
collect-metrics
- Validates config
- Calls orchestrator
- Commits results
- Pushes to develop
-
validate-results
- Verifies data integrity
- Checks storage validity
Execution Time: < 1 minute
Schedule: Weekly on Monday 2:30 AM UTC (configurable)
Jobs:
-
generate-report
- Generates markdown reports
- Creates GitHub issues
- Closes old reports
- Uploads artifacts
-
validate-issues
- Verifies issue creation
- Reports statistics
Execution Time: < 1 minute
# Trigger collection workflow
gh workflow run metrics-collection.yml \
-f context=github-control-plane \
-f dryRun=false# Trigger reporting workflow
gh workflow run metrics-reporting.yml \
-f reportType=weekly \
-f includeArchive=false# In your workflow
- name: Trigger Metrics Collection
run: |
gh workflow run metrics-collection.yml \
-f context=${{ github.repository }}# Run all metrics tests
npm test -- scripts/metrics/__tests__/
# Integration tests only
npm test -- scripts/metrics/__tests__/integration.test.js
# Performance benchmarks
npm test -- scripts/metrics/__tests__/performance.test.js
# Security validation
npm test -- scripts/metrics/__tests__/security.test.jsFile: .github/scripts/workflows/metrics-config.json
{
"schedule": {
"cron": "0 2 * * *",
"timezone": "UTC"
},
"execution": {
"parallelJobs": 1,
"timeoutMinutes": 30
},
"repositories": [
{
"owner": "lightspeedwp",
"repo": ".github",
"context": "github-control-plane",
"enabled": true
}
],
"storage": {
"basePath": ".github/reports/metrics",
"retention": { "days": 365 }
}
}The health score (0-100) is calculated as:
Score = 50 (base)
+ (issue_closure_rate × 25%) [0-25 points]
+ (pr_merge_rate × 25%) [0-25 points]
+ min(active_contributors/10 × 20%, 20%) [0-20 points]
- min(anomaly_count × 5, 30%) [-0 to -30 points]
Interpretation:
- 80-100: ✅ Healthy
- 60-80:
⚠️ Fair - 0-60: ❌ Needs Attention
- Single repository: < 30 seconds
- 10 repositories (parallel): < 5 minutes
- Per-repo enrichment: < 100ms
- Write: < 1 second
- Read (52 weeks): < 500ms
- Trend calculation: < 100ms/repo
- Anomaly detection: < 50ms/repo
- Report generation: < 2 seconds/repo
- Issue creation: < 5 seconds/repo
- Workflow total: < 5 minutes
- Linear scaling with repository count
- Parallel execution: 2-4x speedup
- Memory: < 10MB for 10 repos/year
- ✅ Never logged or exposed
- ✅ Masked in error messages
- ✅ Minimum scope:
repo:read,issues:write
- ✅ Repository name validation
- ✅ Path traversal prevention
- ✅ Period parameter validation
- ✅ Metrics structure validation
- ✅ XSS prevention in reports
- ✅ No personal information exposure
- ✅ No internal system data
- ✅ Markdown escaping
- ✅ GitHub API rate limit respect
- ✅ Exponential backoff on errors
- ✅ Concurrent request limiting
- ✅ Automatic retry logic
- Unit Tests: 96 tests across all components
- Integration Tests: 15+ end-to-end scenarios
- Performance Tests: 20+ benchmarks
- Security Tests: 25+ validation checks
-
Metrics Agent Tests (30 tests)
- GitHub API integration
- Pagination handling
- Error scenarios
- Rate limit management
-
Storage Tests (25 tests)
- Data persistence
- Retrieval accuracy
- History management
- Cleanup operations
-
Analysis Tests (20 tests)
- Trend calculation
- Anomaly detection
- Baseline comparison
- Forecast generation
-
Reporter Tests (14 tests)
- Report generation
- Health score calculation
- Section rendering
- Error handling
-
Issue Creator Tests (34 tests)
- Issue creation
- Label management
- Old report closure
- Retry logic
-
Integration Tests (15 tests)
- Full pipeline
- Data consistency
- Error recovery
- Concurrent operations
-
Performance Tests (20 tests)
- Collection benchmarks
- Storage performance
- Analysis speed
- Workflow timing
-
Security Tests (25 tests)
- Token security
- Input validation
- Output sanitization
- Rate limiting
- Data privacy
Issue: GitHub API rate limit exceeded
Solution: Check rate limit status
gh api rate_limit
Workflow: Automatic backoff with exponential delay
Issue: Metrics data not persisting
Solution: Verify .github/reports/metrics/ permissions
ls -la .github/reports/metrics/
Action: Ensure Git tracks the directory
git add .github/reports/metrics/.gitkeep
- Specification:
.github/projects/active/metrics-agent-specification-2026-08-12/SPECIFICATION.md - Architecture:
.github/projects/active/metrics-agent-specification-2026-08-12/ARCHITECTURE.md - Test Plan:
.github/projects/active/metrics-agent-specification-2026-08-12/TEST_PLAN.md - Progress Tracking:
scripts/metrics/PROGRESS.md
Issue: Reports not creating GitHub issues
Solution: Verify GITHUB_TOKEN secret
gh secret list
Action: Ensure token has issues:write scope
Issue: Workflow timeout
Solution: Check workflow execution time
gh run view <run-id> --log
Action: Increase timeout in workflow config
- Extend
MetricsAgent.fetchMetrics() - Add fields to metrics structure
- Update storage schema
- Add trend calculation in
TrendAnalyzer - Update report sections in
MetricsReporter - Add tests for new metrics
- Extend
MetricsReporterclass - Add new
generateXSection()methods - Customize health score calculation
- Update report template
- Use GitHub Actions webhook events
- Post reports to Slack/Discord via Actions
- Export metrics to external dashboards
- Create custom workflows using reports
- GitHub API: https://docs.github.com/en/rest
- GitHub Actions: https://docs.github.com/en/actions
- Octokit JS: https://octokit.github.io/rest.js/
- Markdown: https://guides.github.com/features/mastering-markdown/
- Weekly: Review generated reports for accuracy
- Monthly: Check old report closure (90+ day auto-close)
- Quarterly: Review and update trend baselines
- Annually: Archive old metrics, plan improvements
- Watch workflow runs for failures
- Monitor GitHub API usage
- Track storage growth
- Validate report accuracy
See CLAUDE.md for contribution guidelines and coding standards.
- Update metrics-agent.js
- Add corresponding tests in metrics-agent.test.js
- Update PROGRESS.md
- Run tests:
npm test -- scripts/metrics/__tests__/metrics-agent.test.js - Ensure >80% coverage
For issues or questions:
- Check troubleshooting section above
- Review workflow logs:
gh run view <run-id> --log - Check test results:
npm test -- scripts/metrics/__tests__/ - File GitHub issue with details
Metrics Agent Phase 2 | Complete | Production Ready | 2026-08-21
Docs signed by 🤖 Copilot for LightSpeedWP – always fresh!