Standard Operating Procedure for /optimize phase. Covers performance benchmarking, accessibility audit, security review, and code quality checks.
Training Guide: Step-by-step procedures for executing the
/optimizecommand to ensure production readiness.
Supporting references:
Purpose: Validate feature meets performance, accessibility, security, and code quality standards before deployment.
:
Outputs:
specs/NNN-slug/optimization-report.md - Performance, accessibility, security audit resultsspecs/NNN-slug/code-review-report.md - Code quality review findingsworkflow-state.yamlExpected duration: 1-2 hours
Environment checks:
Knowledge requirements:
Actions:
Backend performance (if applicable):
# API endpoint response times
curl -w "%{time_total}\n" -o /dev/null -s http://localhost:3000/api/endpoint
# Target: <500ms (95th percentile)
# Database query performance
# Run EXPLAIN ANALYZE on slow queries
# Target: <100ms per query
Frontend performance (if HAS_UI=true):
# Lighthouse performance audit
npx lighthouse http://localhost:3000 --only-categories=performance --output=json
# Target: Score ≥85
# Core Web Vitals
# - FCP (First Contentful Paint): <1.5s
# - LCP (Largest Contentful Paint): <2.5s
# - CLS (Cumulative Layout Shift): <0.1
# - FID (First Input Delay): <100ms
Document results:
## Performance Results
**Backend**:
- API response time: 287ms (95th percentile) ✓ Target: <500ms
- Database queries: 45ms average ✓ Target: <100ms
- No N+1 query problems ✓
**Frontend** (if applicable):
- Lighthouse Performance: 92/100 ✓ Target: ≥85
- FCP: 1.2s ✓ Target: <1.5s
- LCP: 2.1s ✓ Target: <2.5s
- CLS: 0.05 ✓ Target: <0.1
Quality check: All performance targets met, documented in optimization-report.md.
Actions:
Automated accessibility scan:
# Lighthouse accessibility audit
npx lighthouse http://localhost:3000 --only-categories=accessibility --output=json
# Target: Score ≥95
# axe-core scan
npm run test:a11y
# Target: 0 violations
Manual accessibility checks:
Document results:
## Accessibility Results
**Automated scans**:
- Lighthouse Accessibility: 98/100 ✓ Target: ≥95
- axe-core violations: 0 ✓ Target: 0
**Manual checks**:
- Keyboard navigation: ✓ All interactive elements accessible
- Focus indicators: ✓ Visible on all focusable elements
- Screen reader: ✓ Tested with NVDA, all content announced correctly
- Color contrast: ✓ All text meets WCAG AA standards (≥4.5:1)
- ARIA labels: ✓ All buttons and inputs properly labeled
Quality check: Lighthouse ≥95, all manual checks passed, documented in optimization-report.md.
Actions:
Authentication/Authorization:
Input Validation:
Data Protection:
Security headers (if HAS_UI=true):
# Check security headers
curl -I http://localhost:3000
# Expected headers:
# - Content-Security-Policy
# - X-Frame-Options: DENY
# - X-Content-Type-Options: nosniff
# - Strict-Transport-Security
Document results:
## Security Results
**Authentication/Authorization**: ✓ All protected endpoints require authentication
**Input Validation**: ✓ All inputs validated, SQL injection prevented
**Data Protection**: ✓ TLS enabled, no secrets in code
**Security Headers**: ✓ CSP, X-Frame-Options, HSTS configured
**Vulnerabilities found**: None
Quality check: No security vulnerabilities, documented in optimization-report.md.
Actions:
Code duplication check:
# Check for duplicate code
npx jscpd src/
# Target: <5% duplication
# Or manual review of plan.md reuse strategy
Code coverage:
# Backend coverage
pytest --cov=api --cov-report=term-missing
# Target: ≥80% for business logic
# Frontend coverage
npm test -- --coverage
# Target: ≥80% for business logic
Linting and formatting:
# Run linters
npm run lint
pylint api/
# Target: 0 errors
# Check formatting
npm run format:check
black --check api/
# Target: All files formatted
Code complexity:
Documentation:
Document results:
## Code Quality Results
**Code Duplication**: 2.3% ✓ Target: <5%
**Test Coverage**:
- Backend: 87% ✓ Target: ≥80%
- Frontend: 82% ✓ Target: ≥80%
**Linting**: 0 errors ✓
**Formatting**: All files formatted ✓
**Complexity**: All functions <50 lines ✓
**Documentation**: All public APIs documented ✓
Quality check: Code quality meets standards, documented in code-review-report.md.
Actions:
## Success Criteria Validation
### From spec.md
1. "User can complete registration in <3 minutes"
- **Measured**: Average 2.1 minutes (PostHog funnel) ✓
- **Evidence**: e2e/registration.spec.ts passes
2. "API response time <500ms for 95th percentile"
- **Measured**: 287ms (95th percentile) ✓
- **Evidence**: Performance benchmark results above
3. "Lighthouse accessibility score ≥95"
- **Measured**: 98/100 ✓
- **Evidence**: Accessibility audit results above
4. "95% of user searches return results in <1 second"
- **Measured**: 97% of searches <1s ✓
- **Evidence**: Search performance logs
Quality check: All success criteria from spec.md are met with evidence.
Actions:
Render optimization-report.md from template with:
Include recommendations (if any):
## Recommendations
**Optional optimizations** (can defer to future):
- Cache dashboard data for 10 minutes (would reduce DB queries by 80%)
- Add database index on `student_id, lesson_id` (would improve query time from 45ms to 15ms)
- Implement image lazy loading (would improve LCP by ~200ms)
**Required fixes** (blocking deployment):
- None
Quality check: optimization-report.md is complete and comprehensive.
Actions: Run through comprehensive code review checklist:
Architecture:
Code Quality:
Testing:
Performance:
Security:
Accessibility (if HAS_UI):
Quality check: All checklist items satisfied or documented exceptions.
Actions:
Run full test suite one last time:
# Backend tests
pytest
# Frontend tests
npm test
# E2E tests
npx playwright test
Verify all quality gates passed:
Update workflow-state.yaml:
currentPhase: optimization
status: completed
qualityGates:
performance: passed
accessibility: passed
security: passed
codeQuality: passed
Quality check: All quality gates passed, ready for preview/deployment.
Actions:
git add specs/NNN-slug/optimization-report.md specs/NNN-slug/code-review-report.md
git commit -m "docs: complete optimization for <feature-name>
Performance:
- API response: 287ms ✓ Target: <500ms
- Lighthouse: 92/100 ✓ Target: ≥85
- FCP: 1.2s ✓ Target: <1.5s
Accessibility:
- Lighthouse: 98/100 ✓ Target: ≥95
- Manual checks: All passed ✓
Security:
- No vulnerabilities found ✓
- All endpoints protected ✓
Code Quality:
- Test coverage: 87% ✓ Target: ≥80%
- Code duplication: 2.3% ✓ Target: <5%
- Linting: 0 errors ✓
All quality gates passed - ready for deployment
"
Quality check: Optimization committed, ready for next phase (preview or deployment).
Impact: Poor UX, user churn, production issues
Scenario:
API response time: 1.2s (target: <500ms)
Lighthouse Performance: 45/100 (target: ≥85)
Result: Feature deployed, users complain about slowness
Prevention:
Tools:
# Profile slow API endpoints
time curl http://localhost:3000/api/slow-endpoint
# Profile database queries
EXPLAIN ANALYZE SELECT ...
# Profile frontend performance
npx lighthouse http://localhost:3000 --view
Impact: Excludes users with disabilities, legal/compliance risk
Scenario:
Lighthouse Accessibility: 72/100 (target: ≥95)
Issues:
- No ARIA labels on buttons
- Color contrast too low (2.8:1, need 4.5:1)
- Keyboard navigation broken
Prevention:
Impact: Data breaches, legal liability, reputation damage
Scenario:
SQL injection vulnerability in search endpoint
XSS vulnerability in user profile
No authentication on admin endpoints
Prevention:
Impact: Undetected bugs, regression risk
Scenario:
Test coverage: 45% (target: ≥80%)
Critical business logic untested
Prevention:
Impact: Wasted time, increased complexity
Scenario:
Spent 2 days optimizing function that runs once per day
Added complex caching layer for infrequently accessed data
Prevention:
Use systematic approach:
## Optimization Checklist
**Performance**:
- [ ] API <500ms (95th percentile)
- [ ] Frontend FCP <1.5s
- [ ] Database queries optimized
- [ ] No N+1 queries
**Accessibility** (if HAS_UI):
- [ ] Lighthouse ≥95
- [ ] Keyboard nav works
- [ ] Screen reader compatible
- [ ] Color contrast meets WCAG AA
**Security**:
- [ ] No SQL injection
- [ ] No XSS vulnerabilities
- [ ] Authentication/authorization
- [ ] No secrets in code
**Code Quality**:
- [ ] Test coverage ≥80%
- [ ] Code duplication <5%
- [ ] Linting passes
- [ ] All tests pass
Result: Systematic validation, nothing missed
For each success criterion, provide evidence:
## Success Criteria Validation
1. "API response <500ms"
- Measured: 287ms ✓
- Tool: curl -w "%{time_total}"
- Sample size: 100 requests
2. "Lighthouse ≥95"
- Measured: 98/100 ✓
- Tool: npx lighthouse
- URL: http://localhost:3000
Result: Objective proof all criteria met
Separate required fixes from nice-to-haves:
## Required Fixes (Blocking):
- None
## Optional Improvements (Future):
- Cache dashboard data (80% query reduction)
- Add lazy loading (200ms LCP improvement)
Result: Clear next steps, deployment not blocked by nice-to-haves
Pre-phase checks:
During phase:
Post-phase validation:
Optimization quality targets:
What makes good optimization:
What makes bad optimization:
Phase is complete when:
currentPhase: optimization and status: completedReady to proceed to next phase (/preview):
Issue: Performance targets not met Solution: Profile code, add indexes, implement caching, use pagination, optimize queries
Issue: Accessibility score <95 Solution: Run axe-core for specific issues, add ARIA labels, fix color contrast, test keyboard nav
Issue: Security vulnerabilities found Solution: Use parameterized queries, sanitize inputs, add authentication, enable security headers
Issue: Test coverage <80% Solution: Identify untested code with coverage report, add missing tests, focus on business logic
This SOP guides the optimization phase. Refer to reference.md for benchmarking details and examples.md for optimization patterns.