# Quality Assurance Commands - Technical Implementation Specification

**Version**: 1.0  
**Created**: October 29, 2025  
**Status**: Ready for Implementation  
**Priority**: High

---

## Executive Summary

This specification outlines the implementation of 6 quality assurance commands to complete the 05-CODE-ANALYSIS and 06-TESTING patterns:

| Command | Phase | Priority | Est. Effort | Status |
|---------|-------|----------|------------|--------|
| **review-code** | 05-CODE-ANALYSIS | 🔴 HIGH | 20-25 hours | TODO |
| **audit-security** | 05-CODE-ANALYSIS | 🔴 HIGH | 25-30 hours | TODO |
| **audit-performance** | 05-CODE-ANALYSIS | 🟡 MEDIUM | 20-25 hours | TODO |
| **audit-complexity** | 05-CODE-ANALYSIS | 🟡 MEDIUM | 15-20 hours | TODO |
| **analyze-test-coverage** | 06-TESTING | 🟡 MEDIUM | 18-22 hours | TODO |
| **code-cleanup** | 06-TESTING | 🟡 MEDIUM | 12-16 hours | TODO |

**Total Estimated Effort**: 110-138 hours (~4-5 weeks for single developer)

---

## 1. Architecture Overview

### 1.1 System Context

```
┌──────────────────────────────────────────────────────────────┐
│                    QUALITY ASSURANCE LAYER                   │
│                      (Commands 05-06)                        │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  INPUT: Generated code from 04-IMPLEMENT                    │
│         ↓                                                    │
│  ┌─────────────────────────────────────────────────────┐   │
│  │         review-code (Orchestrator)                  │   │
│  │  - Validates requirements compliance                │   │
│  │  - Checks code standards (cursorrules)             │   │
│  │  - Analyzes quota/rate limits                      │   │
│  │  - Proposes functional tests                       │   │
│  └─────────────────────────────────────────────────────┘   │
│         ↓                                                    │
│  ┌──────────────┬──────────────┬──────────────────────────┐ │
│  │              │              │                          │ │
│  │ audit-       │ audit-       │ audit-                   │ │
│  │ security     │ performance  │ complexity               │ │
│  │              │              │                          │ │
│  └──────────────┴──────────────┴──────────────────────────┘ │
│         ↓                                                    │
│  ┌─────────────────────────────────────────────────────┐   │
│  │    Testing & Coverage Analysis Layer               │   │
│  │                                                     │   │
│  │  ├─ analyze-test-coverage (metrics & gaps)        │   │
│  │  └─ code-cleanup (maintenance)                    │   │
│  └─────────────────────────────────────────────────────┘   │
│         ↓                                                    │
│  OUTPUT: Quality report → 07-PUBLISH                       │
│                                                              │
└──────────────────────────────────────────────────────────────┘
```

### 1.2 Technology Stack

**Language**: TypeScript (compiled to JavaScript)

**Core Dependencies**:
- `@octokit/rest` - GitHub API (already available)
- `@types/node` - Node.js type definitions (already available)
- Static analysis tools (external, called via `execSync`):
  - ESLint + security plugins
  - npm audit / pip safety
  - Semgrep (optional advanced scanning)

**Output Formats**:
- Markdown reports (human-readable)
- JSON reports (machine-readable)
- GitHub Issues (integration)

**Report Storage**: `config/reports/` directory (already exists)

---

## 2. Individual Command Specifications

### 2.1 review-code

**Type**: Orchestrator Command  
**File**: `scripts/review-code.ts`  
**npm run**: Add to package.json scripts  
**Input**: GitHub issue number  
**Output**: Comprehensive code review report

#### 2.1.1 Responsibilities

1. **Data Collection Phase**
   - Fetch issue details from GitHub (title, body, acceptance criteria)
   - Get current git branch and recent commits
   - Identify files changed (from git status/log)
   - Extract acceptance criteria from issue body

2. **Requirements Validation Phase**
   - Parse each acceptance criterion from issue
   - Check if changes satisfy each criterion
   - Verify scope compliance (no unrelated changes)
   - Create validation checklist

3. **Standards Review Phase**
   - Load `.cursorrules.md` for coding standards
   - Check code quality (architecture, DRY, function size)
   - Validate JavaScript/TypeScript best practices
   - Verify type safety and documentation
   - Check naming conventions and style

4. **Quota & Rate Limits Analysis Phase**
   - Parse `config/runtime.template.json` for API limits
   - Estimate API usage (Gmail, Sheets, Apps Script, Gemini)
   - Calculate execution time estimates
   - Flag potential bottlenecks

5. **Testing & Quality Validation Phase**
   - Check for test functions
   - Verify error handling
   - Validate functional test coverage

6. **Functional Testing Checklist Phase**
   - Propose 5-10 step functional test
   - Suggest DRY_RUN mode usage
   - Recommend verification steps

#### 2.1.2 Output Format

```markdown
### 1. Executive Summary
- Issue: #N - [Title]
- Files Changed: [List with line counts]
- Overall Assessment: ✅/⚠️/❌
- Key Findings: [3-5 bullets]

### 2. Requirements Compliance
[Table with criteria and status]

### 3. Cursorrules Standards Review
[Checklist of standards]

### 4. Quota & Rate Limits Analysis
[Calculations and risk assessment]

### 5. Issues Found
**BLOCKER**: [Critical issues]
**MAJOR**: [Should fix before PR]
**MINOR**: [Can fix later]

### 6. Functional Testing Checklist
[5 quick test steps]

### 7. Recommendations & Decision Point
[Approve/Fix/Reject with rationale]
```

#### 2.1.3 Implementation Details

**Data Structures**:
```typescript
interface CodeReview {
  issueNumber: number;
  issueTitle: string;
  executiveSummary: string;
  requirementsCompliance: AcceptanceCriterion[];
  standardsReview: StandardsCheckResult[];
  quotaAnalysis: QuotaAnalysisResult;
  issuesFound: CodeIssue[];
  testingChecklist: TestStep[];
  recommendation: 'APPROVE' | 'FIX_ISSUES' | 'REJECT';
  rationale: string;
}

interface AcceptanceCriterion {
  criterion: string;
  status: 'PASS' | 'FAIL' | 'PARTIAL';
  evidence: string;
}

interface CodeIssue {
  severity: 'BLOCKER' | 'MAJOR' | 'MINOR';
  description: string;
  location: string;
  remediation: string;
}
```

**Key Functions**:
- `fetchIssueDetails(issueNumber: number)` - GitHub API
- `extractAcceptanceCriteria(body: string)` - Parse markdown
- `validateRequirements(files: string[], criteria: string[])` - Code analysis
- `loadCursorrules()` - Read .cursorrules.md
- `checkCodeStandards(files: string[])` - Run linters
- `estimateQuotaUsage(code: string)` - API analysis
- `proposeTests(code: string)` - Test recommendations
- `generateReport(review: CodeReview)` - Format output

**External Integrations**:
- GitHub CLI: `gh issue view`, `gh pr view`, git commands
- ESLint: Check code style and quality
- Manual parsing: Extract criteria from issue body

---

### 2.2 audit-security

**Type**: Atomic Command  
**File**: `scripts/audit-security.ts`  
**npm run**: Add to package.json scripts  
**Input**: Optional flags (`--severity`, `--files`, `--create-issues`)  
**Output**: Security vulnerability report

#### 2.2.1 Responsibilities

1. **Setup & Integration Phase**
   - Detect project type from `memory-bank/techContext.md`
   - Select appropriate security tools:
     - TypeScript/Node.js: ESLint security plugins, npm audit, semgrep
     - Python: Bandit, safety, semgrep
     - Go: gosec, staticcheck
   - Load existing security configurations

2. **Scanning Phase**
   - Run security scanners in parallel
   - Analyze authentication patterns
   - Analyze data handling practices
   - Identify injection vulnerabilities
   - Check dependency vulnerabilities
   - Review configuration issues

3. **Analysis Phase**
   - Prioritize findings by severity:
     - 🔴 CRITICAL: RCE, SQL injection, auth bypass, exposed secrets
     - 🟠 HIGH: XSS, CSRF, unencrypted PII, weak auth
     - 🟡 MEDIUM: Insecure defaults, missing rate limiting
     - 🟢 LOW: Best practices, code hygiene

4. **Report Generation Phase**
   - Create categorized findings by type
   - Include severity, location, risk, remediation
   - Add CWE and OWASP references
   - Generate both markdown and JSON reports

5. **Integration Phase**
   - Optional: Create GitHub issues for critical/high findings
   - Compare with baseline for trend analysis
   - Generate SARIF report for GitHub Security tab

#### 2.2.2 Output Format

```markdown
# Security Audit Report

**Scan Date**: YYYY-MM-DD
**Project**: [Name]
**Severity Filter**: high+

## Summary
- 🔴 Critical Issues: N
- 🟠 High Issues: N
- 🟡 Medium Issues: N
- 🟢 Low Issues: N

## Findings by Category

### Authentication & Authorization (N issues)
**Finding 1: [Title]**
- **Severity**: 🔴 CRITICAL
- **Location**: `path/file.ts:123`
- **Issue**: [Description]
- **Risk**: [What could go wrong]
- **Remediation**: [How to fix]
- **CWE**: CWE-XXX
- **OWASP**: A01:2021 – Broken Access Control

### Data & Encryption (N issues)
...

## Improvement Priority

### Phase 1 (Critical - Fix Immediately)
...

## Metrics & Trends
- Previous: [Date] (N findings)
- Current: [Date] (N findings)
- Trend: 📈/📉/➡️

## Next Steps
1. Review findings with security engineer
2. Triage each finding
3. Create GitHub issues
4. Track remediation progress
5. Rescan after fixes
```

#### 2.2.3 Implementation Details

**Data Structures**:
```typescript
interface SecurityAudit {
  scanDate: Date;
  projectName: string;
  findings: SecurityFinding[];
  summary: SecuritySummary;
  trend: TrendAnalysis;
  baseline: SecurityBaseline;
}

interface SecurityFinding {
  id: string;
  title: string;
  severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
  category: 'AUTH' | 'DATA' | 'INJECTION' | 'DEPENDENCY' | 'CONFIG';
  location: string;
  issue: string;
  risk: string;
  remediation: string;
  cwe: string;
  owasp: string;
}

interface SecuritySummary {
  critical: number;
  high: number;
  medium: number;
  low: number;
  total: number;
}
```

**Key Functions**:
- `detectProjectType()` - Read tech-stack.md
- `selectScannerTools(type: string)` - Choose scanners
- `runESLintSecurity()` - ESLint with security plugins
- `runNpmAudit()` - Dependency scanning
- `analyzeAuthPatterns(files: string[])` - Auth analysis
- `analyzeDataHandling(files: string[])` - Data protection check
- `calculateSeverity(finding: RawFinding)` - Prioritize findings
- `generateReport(audit: SecurityAudit)` - Format output
- `compareWithBaseline(audit: SecurityAudit)` - Trend analysis
- `createGitHubIssues(findings: SecurityFinding[])` - Auto-create issues

**External Tools**:
- ESLint + `@typescript-eslint/plugin-security` (if installed)
- `npm audit` (built-in)
- Semgrep (optional, via CLI)
- GitHub API for issue creation

---

### 2.3 audit-performance

**Type**: Atomic Command  
**File**: `scripts/audit-performance.ts`  
**npm run**: Add to package.json scripts  
**Input**: Optional flags (`--threshold`, `--files`, `--compare`)  
**Output**: Performance bottleneck report

#### 2.3.1 Responsibilities

1. **Analysis Phase**
   - Identify slow-running functions
   - Detect algorithmic inefficiencies (O(n²) loops, nesting depth)
   - Analyze memory patterns
   - Check for circular dependencies
   - Review I/O and network patterns

2. **Detection Phase**
   - Static analysis: N² loops, unbounded data structures
   - Code pattern analysis: eager vs lazy loading, data copies
   - Dependency analysis: heavy imports, bloated deps
   - Load baseline metrics from previous scans

3. **Report Generation Phase**
   - List critical performance issues
   - Rank by impact (requests/day affected)
   - Estimate improvement potential
   - Provide specific optimization recommendations
   - Calculate effort estimates

4. **Trend Analysis Phase**
   - Compare with baseline
   - Calculate performance delta
   - Track optimization velocity

#### 2.3.2 Output Format

```markdown
# Performance Audit Report

**Scan Date**: YYYY-MM-DD
**Project**: [Name]
**Baseline**: [Date] (Xms avg)
**Current**: [Date] (Yms avg)
**Trend**: [±N%]

## Summary
- Slow Functions: N
- Memory Leaks: N
- Algorithmic Issues: N

## Critical Performance Issues

**Issue 1: [Title]**
- Location: `path/file.ts:123` - functionName()
- Current: Xms / YMB
- Target: Xms / YMB
- Problem: [Description]
- Root Cause: [Analysis]
- Impact: Affects N requests/day, saves Yms if fixed
- Recommendation: [Specific optimization]
- Effort: 2-4 hours
- Performance Gain: X% faster

## Improvement Priority

### Phase 1 (Critical - Blocks Scalability)
...

## Metrics & Trends
...
```

#### 2.3.3 Implementation Details

**Data Structures**:
```typescript
interface PerformanceAudit {
  scanDate: Date;
  findings: PerformanceIssue[];
  summary: PerformanceSummary;
  baseline: PerformanceBaseline;
  trend: PerformanceTrend;
}

interface PerformanceIssue {
  id: string;
  title: string;
  category: 'SLOW_FUNCTION' | 'MEMORY_LEAK' | 'ALGORITHMIC' | 'IO';
  location: string;
  functionName: string;
  currentPerf: {
    executionTime: number;
    memoryUsage: number;
  };
  targetPerf: {
    executionTime: number;
    memoryUsage: number;
  };
  problem: string;
  rootCause: string;
  impact: {
    affectedRequests: number;
    potentialSavings: number;
  };
  recommendation: string;
  effort: 'SMALL' | 'MEDIUM' | 'LARGE';
  estimatedGain: number; // percentage
}
```

**Key Functions**:
- `analyzeFunction(ast: AST)` - Extract complexity metrics
- `detectSlowLoops(code: string)` - Find O(n²) patterns
- `detectMemoryLeaks(code: string)` - Memory pattern analysis
- `findHeavyImports(files: string[])` - Dependency weight
- `estimateExecutionTime(code: string)` - Rough estimation
- `compareWithBaseline(current: Metrics)` - Trend analysis
- `generateReport(audit: PerformanceAudit)` - Format output

**Analysis Methods**:
- Abstract Syntax Tree (AST) parsing for complexity
- Regex pattern matching for common inefficiencies
- Static analysis (no runtime profiling needed)

---

### 2.4 audit-complexity

**Type**: Atomic Command  
**File**: `scripts/audit-complexity.ts`  
**npm run**: Add to package.json scripts  
**Input**: Optional flags (`--max-complexity`, `--files`, `--sort`)  
**Output**: Code complexity metrics report

#### 2.4.1 Responsibilities

1. **Analysis Phase**
   - Calculate cyclomatic complexity per function
   - Measure function size (lines of code)
   - Measure nesting depth
   - Calculate cognitive complexity
   - Generate maintainability index

2. **Evaluation Phase**
   - Compare against thresholds:
     - Cyclomatic: 1-3 ✅, 4-7 🟡, 8-10 ⚠️, 11+ 🔴
     - Function size: 1-20 ✅, 21-50 🟡, 51-100 ⚠️, 100+ 🔴
     - Nesting: 1-2 ✅, 3-4 🟡, 5+ 🔴

3. **Report Generation Phase**
   - List functions exceeding thresholds
   - Provide refactoring recommendations:
     - Extract conditions
     - Use guard clauses
     - Polymorphism over conditionals
   - Calculate effort estimates

4. **Integration Phase**
   - Optional: Create GitHub issues for critical functions

#### 2.4.2 Output Format

```markdown
# Code Complexity Audit Report

**Scan Date**: YYYY-MM-DD
**Files Analyzed**: N
**Total Functions**: N
**Average Cyclomatic Complexity**: X
**Maintainability Index**: Y/100

## Summary
- Functions Exceeding Threshold (>8): N
- Critical Functions (>15): N
- Large Functions (>100 LOC): N

## Critical Complexity (>15)

**Function 1: createIssuesInBatch()**
- Location: `scripts/core/github-issue-creator.ts:145`
- Cyclomatic Complexity: 22
- Function Size: 148 lines
- Nesting Depth: 5
- Maintainability: Poor
- Recommendation: Split into smaller functions, extract conditions

## High Complexity (10-15)
...

## Refactoring Strategies

### Strategy 1: Extract Conditions
```typescript
// Before
if (a && b) { ... }
else if (c && d) { ... }

// After
if (isConditionA()) { ... }
else if (isConditionB()) { ... }
```

### Strategy 2: Guard Clauses
### Strategy 3: Polymorphism
```

#### 2.4.3 Implementation Details

**Data Structures**:
```typescript
interface ComplexityAudit {
  scanDate: Date;
  filesAnalyzed: number;
  functions: ComplexityMetrics[];
  summary: ComplexitySummary;
}

interface ComplexityMetrics {
  functionName: string;
  location: string;
  cyclomaticComplexity: number;
  functionSize: number; // lines of code
  nestingDepth: number;
  cognitiveComplexity: number;
  maintainability: 'GOOD' | 'OK' | 'WARNING' | 'CRITICAL';
  recommendations: string[];
  refactoringStrategy: 'EXTRACT' | 'GUARDS' | 'POLYMORPHISM' | 'NONE';
}

interface ComplexitySummary {
  avgCyclomaticComplexity: number;
  maintainabilityIndex: number;
  functionsAboveThreshold: number;
  criticalFunctions: number;
}
```

**Key Functions**:
- `calculateCyclomaticComplexity(ast: AST)` - Count decision paths
- `measureFunctionSize(node: FunctionNode)` - Count LOC
- `measureNestingDepth(node: FunctionNode)` - Track nesting
- `calculateCognitiveComplexity(ast: AST)` - Mental effort
- `calculateMaintainabilityIndex(metrics: Metrics)` - Overall score
- `recommendRefactoring(metrics: ComplexityMetrics)` - Suggestions
- `generateReport(audit: ComplexityAudit)` - Format output

**Calculation Formulas**:
- Cyclomatic Complexity: Count of decision nodes + 1
- Maintainability Index: (171 - 5.2*ln(Halstead Volume) - 0.23*Cyclomatic - 50*sin(sqrt(2.4*LOC)))

---

### 2.5 analyze-test-coverage

**Type**: Atomic Command  
**File**: `scripts/analyze-test-coverage.ts`  
**npm run**: Add to package.json scripts  
**Input**: Optional flags (`--min-coverage`, `--files`, `--show-dead-code`)  
**Output**: Test coverage analysis report

#### 2.5.1 Responsibilities

1. **Coverage Analysis Phase**
   - Parse `coverage/lcov.info` (Jest coverage file)
   - Calculate overall coverage percentage
   - Break down by coverage type: lines, branches, functions, statements

2. **Gap Identification Phase**
   - Identify untested functions (0% coverage)
   - Find partially tested branches
   - Detect unreachable/dead code
   - Identify low-coverage files

3. **Prioritization Phase**
   - Rank gaps by impact:
     - Critical functions
     - High-value files
     - Frequently-changed code
   - Estimate effort to reach targets

4. **Report Generation Phase**
   - Summary of coverage metrics
   - List of untested code by file
   - Dead code identification
   - Prioritized improvement roadmap

5. **Integration Phase**
   - Compare with baseline
   - Track trends over time
   - Generate recommendations

#### 2.5.2 Output Format

```markdown
# Test Coverage Analysis Report

**Scan Date**: YYYY-MM-DD
**Coverage Report**: coverage/lcov.info
**Baseline**: 62%
**Target**: 80%

## Coverage Summary

- Overall Coverage: 62% (Target: 80%)
- Lines: 1,847 / 2,400 (77%)
- Branches: 156 / 340 (46%)
- Functions: 89 / 127 (70%)
- Statements: 1,923 / 2,450 (78%)

## Files Below Threshold
- 23 files need more test coverage

## Untested Code (0% Coverage)

**File 1: scripts/core/github-issue-creator.ts**
- Functions: 4 untested
  - createIssuesInBatch() - lines 145-295
  - validateIssueLinks() - lines 298-340
- Branches: 12 untested paths
- Estimated effort: 4-6 hours

**File 2: scripts/utils/issue-parser.ts**
- Functions: 2 untested
- Branches: 5 untested paths

## Low Coverage (<70%)
...

## Improvement Roadmap

### Phase 1 (Critical - 0% coverage functions)
- [Untested functions affecting >5 files]
- Estimated: 8-10 hours

### Phase 2 (High - Branch coverage <50%)
- [Partially tested code]
- Estimated: 6-8 hours

### Phase 3 (Medium - File coverage <70%)
- [Low-coverage files]

## Metrics & Trends
- Previous: [Date] - 58%
- Current: [Date] - 62%
- Trend: 📈 +4% (good progress)
- Velocity: 3 files improved this month
```

#### 2.5.3 Implementation Details

**Data Structures**:
```typescript
interface CoverageAnalysis {
  scanDate: Date;
  overallCoverage: number;
  byCoverageType: {
    lines: { covered: number; total: number };
    branches: { covered: number; total: number };
    functions: { covered: number; total: number };
    statements: { covered: number; total: number };
  };
  fileAnalysis: FileCoverage[];
  untestedCode: UntestedItem[];
  baseline: CoverageBaseline;
  trend: CoverageTrend;
}

interface FileCoverage {
  filePath: string;
  coverage: number;
  lines: { covered: number; total: number };
  branches: { covered: number; total: number };
  functions: { covered: number; total: number };
  untestedFunctions: UuntestedFunction[];
}

interface UntestedFunction {
  name: string;
  location: string;
  lineRange: string;
  priority: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
  estimatedEffort: number; // hours
}
```

**Key Functions**:
- `parseLcovFile()` - Read coverage/lcov.info
- `calculateCoverageMetrics()` - Summary stats
- `identifyUntestedFunctions(coverage)` - 0% functions
- `identifyPartiallyTestedBranches(coverage)` - Branch gaps
- `rankByPriority(items)` - Impact ranking
- `estimateTestEffort(functions)` - Effort calculation
- `generateReport(analysis)` - Format output
- `compareWithBaseline(current)` - Trend analysis

**Data Sources**:
- `coverage/lcov.info` - LCOV format (generated by Jest)
- `package.json` - Test configuration
- `jest.config.js` - Coverage thresholds

---

### 2.6 code-cleanup

**Type**: Maintenance Command  
**File**: `scripts/code-cleanup.ts`  
**npm run**: Add to package.json scripts  
**Input**: Context-dependent (called after new implementation confirmed)  
**Output**: Cleanup execution log + confirmation

#### 2.6.1 Responsibilities

1. **Identification Phase**
   - Identify old/deprecated files
   - Find redundant functions/aliases
   - Locate commented-out code blocks
   - Find unused imports/dependencies
   - Identify outdated configuration

2. **Verification Phase**
   - Confirm new implementation is working
   - Check for external dependencies
   - Assess backwards compatibility needs
   - Calculate impact of removal

3. **Cleanup Execution Phase**
   - Delete old files (via git rm)
   - Remove deprecated functions
   - Remove commented code
   - Update all references
   - Clean documentation

4. **Validation Phase**
   - Verify no broken references
   - Run basic tests
   - Check git diff
   - Generate cleanup report

5. **Git Operations Phase**
   - Stage all cleanup changes
   - Create clean commit with explanation
   - Push changes

#### 2.6.2 Cleanup Categories

**Category A: Immediate Cleanup**
- Old implementations replaced inline
- Temporary helper files
- Dead code paths
- Duplicate functions
- Backup files (*.backup, *.old)

**Category B: Delayed Cleanup**
- Backwards compatibility layers
- Migration paths
- Deprecation notices (keep 1 version)

**Category C: Never Delete**
- Working code with no replacement
- Code required by external systems
- Historical reference code (with comment)

#### 2.6.3 Output Format

```markdown
# Code Cleanup Report

**Execution Date**: YYYY-MM-DD
**Status**: ✅ Complete

## Summary

Old implementation confirmed working. Cleaning up:
- 3 old files deleted
- 2 deprecated functions removed
- 5 files with updated references
- 12 lines of commented code removed

## Cleanup Actions

### Files Deleted
- ❌ scripts/old-implementation.ts
- ❌ config/legacy-config.yml
- ❌ temp-helper-script.sh

### Functions Removed
- ❌ setupTaxBuddy() → replaced by createWorkingFolder()
- ❌ legacyParseIssue() → replaced by parseIssue()

### Commented Code Removed
- ❌ scripts/core/github-issue-creator.ts lines 145-195
- ❌ scripts/utils/issue-parser.ts lines 67-85

### References Updated
- ✅ README.md - Updated setup instructions
- ✅ deploy.sh - Updated function calls
- ✅ docs/architecture.md - Removed legacy diagram
- ✅ config/runtime.template.json - Removed old config keys
- ✅ 3 other files

## Git Operations

```bash
git rm scripts/old-implementation.ts
git rm config/legacy-config.yml
git rm temp-helper-script.sh
git add -A
git commit -m "cleanup: Remove old implementation (replaced by new approach)"
git push origin main
```

## Verification

- ✅ Build succeeds: npm run build
- ✅ Tests pass: npm test
- ✅ No broken imports
- ✅ All references updated
- ✅ Documentation updated

## Cleanup Complete ✅

Codebase is now clean and maintains only current implementations.
```

#### 2.6.4 Implementation Details

**Data Structures**:
```typescript
interface CleanupPlan {
  context: string; // "Old implementation confirmed working"
  filesToDelete: string[];
  functionsToRemove: {
    name: string;
    location: string;
    replacement: string;
  }[];
  commentedCodeToRemove: {
    file: string;
    lineRange: string;
  }[];
  referencesToUpdate: {
    file: string;
    oldReference: string;
    newReference: string;
  }[];
  backwardsCompatibility: {
    keep: boolean;
    reason: string;
    deprecationNotice: string;
  };
}

interface CleanupExecution {
  plan: CleanupPlan;
  startTime: Date;
  actions: CleanupAction[];
  gitOperations: GitOperation[];
  verification: VerificationResult;
  status: 'SUCCESS' | 'PARTIAL' | 'FAILED';
}
```

**Key Functions**:
- `identifyOldImplementations()` - Find cleanup candidates
- `verifyReplacement(old, new)` - Confirm new works
- `findReferences(name)` - Find all usages
- `deleteFile(path)` - Git rm operation
- `removeFunction(file, name)` - Code removal
- `removeCommentedCode(file, lines)` - Clean comments
- `updateReferences(old, new)` - Fix all usages
- `createCleanupCommit(plan)` - Git commit
- `verifyCleanup()` - Run tests and checks

**Git Integration**:
- Use `git rm` for file deletion
- Use `git add` for staged changes
- Create single, clear commit message
- Automatic push with confirmation

---

## 3. Cross-Command Architecture

### 3.1 Shared Utilities

Create shared utility modules in `scripts/utils/`:

```
scripts/utils/
├── code-analyzer.ts          # AST parsing, complexity calculation
├── github-integration.ts     # Issue creation, PR fetching
├── report-generator.ts       # Markdown/JSON formatting
├── baseline-manager.ts       # Save/load baseline metrics
├── severity-calculator.ts    # Prioritize findings
├── recommendation-engine.ts  # Generate suggestions
└── git-integration.ts        # Git operations
```

### 3.2 Shared Data Models

```typescript
// scripts/core/qa-models.ts

export interface QAFinding {
  id: string;
  title: string;
  severity: 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW';
  location: string;
  category: string;
  description: string;
  remediation: string;
  priority: number; // 1-100
}

export interface QAReport {
  commandName: string;
  scanDate: Date;
  summary: ScanSummary;
  findings: QAFinding[];
  metadata: ReportMetadata;
}

export interface Baseline {
  date: Date;
  commandName: string;
  metrics: Record<string, number>;
  findings: QAFinding[];
}
```

### 3.3 Report Output Pipeline

```
┌─────────────────┐
│  Analysis      │
│  Results       │
└────────┬────────┘
         │
    ┌────▼─────────────────────────┐
    │  Format to QAReport          │
    │  - Categorize findings       │
    │  - Calculate severity        │
    │  - Add recommendations       │
    └────┬──────────────────┬──────┘
         │                  │
    ┌────▼─────┐    ┌──────▼────────┐
    │ Markdown  │    │ JSON format   │
    │ Report    │    │ (machine read)│
    └────┬──────┘    └──────┬────────┘
         │                  │
    ┌────▼──────────────────▼──────┐
    │ Save to config/reports/      │
    │ - [command]-[date].md        │
    │ - [command]-[date].json      │
    │ - [command]-baseline.json    │
    └────┬───────────────────────┬─┘
         │                       │
    ┌────▼────┐         ┌───────▼──────┐
    │ Display  │         │ Optional:    │
    │ in CLI   │         │ Create issues│
    └──────────┘         └──────────────┘
```

### 3.4 GitHub Integration

All commands should support optional `--create-issues` flag:

```typescript
// scripts/core/qa-github-integration.ts

export async function createIssuesFromFindings(
  findings: QAFinding[],
  commandName: string
): Promise<GitHubIssueCreationResult[]>
```

---

## 4. Implementation Roadmap

### Phase 1: Foundation (Week 1 - 3)
**Goal**: Build shared infrastructure + CI/CD pipeline

**CI/CD Foundation Focus**:
- GitHub Actions workflow for automated QA checks
- Build gates for critical/high findings
- SARIF report generation for GitHub Security tab
- Automated trend tracking and baselines

- [ ] Create shared utility modules
- [ ] Create shared data models
- [ ] Create report generation pipeline
- [ ] Create baseline management system
- [ ] Create GitHub integration utilities
- [ ] **NEW: Create GitHub Actions workflow files**
- [ ] **NEW: Implement CI/CD report generation**
- [ ] **NEW: Configure build gates and checks**

**Deliverables**: 
- `scripts/utils/code-analyzer.ts`
- `scripts/utils/report-generator.ts`
- `scripts/core/qa-models.ts`
- `scripts/core/qa-github-integration.ts`
- **`scripts/core/ci-cd-report-generator.ts`** (NEW)
- **`.github/workflows/qa-checks.yml`** (NEW)
- **`.github/workflows/security-gate.yml`** (NEW)
- **`.github/workflows/performance-gate.yml`** (NEW)

---

## 2.7 CI/CD Integration Setup

**Type**: Infrastructure  
**Files**: GitHub Actions workflows + gate configuration  
**Input**: Automated on PR/commit events  
**Output**: Build pass/fail status, automated reports

### 2.7.1 GitHub Actions Workflow for QA Checks

**File**: `.github/workflows/qa-checks.yml`

**Purpose**: Run automated QA commands on every PR and commit to main

**Trigger Events**:
- Pull request creation/updates
- Push to main branch
- Nightly scheduled run (2 AM UTC)

**Workflow Steps**:

```yaml
name: Quality Assurance Checks

on:
  pull_request:
    branches: [main, 'release/**']
  push:
    branches: [main]
  schedule:
    - cron: '0 2 * * *'  # Nightly

jobs:
  qa-checks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Install dependencies
        run: npm ci
      
      - name: Build TypeScript
        run: npm run build
      
      - name: Run complexity audit
        run: npm run audit-complexity -- --max-complexity 10 --json
        continue-on-error: true
      
      - name: Run security audit
        run: npm run audit-security -- --severity high --json
        continue-on-error: true
      
      - name: Run performance audit
        run: npm run audit-performance -- --threshold 100 --json
        continue-on-error: true
      
      - name: Generate SARIF report
        run: npm run generate-sarif-report
        if: always()
      
      - name: Upload SARIF to GitHub Security
        uses: github/codeql-action/upload-sarif@v2
        if: always()
        with:
          sarif_file: config/reports/qa-checks.sarif
      
      - name: Comment PR with results
        if: github.event_name == 'pull_request'
        uses: actions/github-script@v6
        with:
          script: |
            // Read report and post comment
            const fs = require('fs');
            const report = JSON.parse(fs.readFileSync('config/reports/qa-checks.json', 'utf8'));
            const comment = generateCommentFromReport(report);
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: comment
            });
      
      - name: Archive reports
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: qa-reports
          path: config/reports/
          retention-days: 30
```

### 2.7.2 Security Gate Workflow

**File**: `.github/workflows/security-gate.yml`

**Purpose**: Fail build if critical/high security findings detected

**Critical Issues** (Block merge):
- 🔴 CRITICAL findings
- 🟠 HIGH findings > threshold (default: 0)

**Configuration**:
```yaml
name: Security Gate

on:
  pull_request:
    branches: [main]

jobs:
  security-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Run security audit
        run: npm run audit-security -- --severity critical --json --output security-results.json
      
      - name: Check for critical findings
        run: |
          CRITICAL=$(jq '.summary.critical' security-results.json)
          HIGH=$(jq '.summary.high' security-results.json)
          
          if [ "$CRITICAL" -gt 0 ]; then
            echo "❌ CRITICAL security issues found: $CRITICAL"
            exit 1
          fi
          
          if [ "$HIGH" -gt 5 ]; then
            echo "⚠️ Too many HIGH security issues: $HIGH (max: 5)"
            exit 1
          fi
          
          echo "✅ Security gate passed"
```

### 2.7.3 Performance Gate Workflow

**File**: `.github/workflows/performance-gate.yml`

**Purpose**: Detect performance regressions and prevent merge

**Performance Checks**:
- Function execution time regression >10%
- New O(n²) patterns
- Memory leak detection
- Bundle size increase >5%

**Configuration**:
```yaml
name: Performance Gate

on:
  pull_request:
    branches: [main]

jobs:
  performance-check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      
      - uses: actions/setup-node@v3
        with:
          node-version: '18'
      
      - name: Run performance audit
        run: npm run audit-performance -- --threshold 100 --json --output performance-current.json
      
      - name: Compare with baseline
        run: |
          # Compare current with baseline from main
          REGRESSION=$(node scripts/utils/compare-performance.js \
            --baseline config/reports/performance-baseline.json \
            --current performance-current.json \
            --threshold 10)
          
          if [ $? -ne 0 ]; then
            echo "❌ Performance regression detected"
            echo "$REGRESSION"
            exit 1
          fi
          
          echo "✅ Performance check passed"
```

### 2.7.4 Data Structures for CI/CD

```typescript
// scripts/core/ci-cd-report-generator.ts

interface CICheckResult {
  status: 'PASS' | 'FAIL' | 'WARNING';
  command: string;
  timestamp: Date;
  findings: QAFinding[];
  summary: {
    critical: number;
    high: number;
    medium: number;
    low: number;
  };
  metrics: {
    complexity: ComplexitySummary;
    security: SecuritySummary;
    performance: PerformanceSummary;
  };
  recommendations: string[];
}

interface SARIFReport {
  version: string;
  runs: SARIFRun[];
}

interface SARIFRun {
  tool: {
    driver: {
      name: string;
      version: string;
      rules: SARIFRule[];
    };
  };
  results: SARIFResult[];
}
```

### 2.7.5 Key Functions for CI/CD

**In `scripts/core/ci-cd-report-generator.ts`**:
- `generateCommentMarkdown(results: CICheckResult[])` - PR comment
- `generateSARIFReport(findings: QAFinding[])` - GitHub Security tab
- `shouldFailBuild(results: CICheckResult[])` - Gate decision logic
- `detectRegressions(baseline, current)` - Trend comparison
- `generateTrendChart(history)` - Performance history

**In `scripts/core/qa-github-integration.ts` (enhanced)**:
- `postPRComment(owner, repo, pr, comment)` - Comment on PR
- `uploadSARIF(owner, repo, sarif)` - Upload to GitHub Security
- `createCheckRun(owner, repo, results)` - GitHub Checks API
- `updateBuildStatus(owner, repo, status)` - Build success/fail

### 2.7.6 CI/CD Configuration Files

**`.github/.roadcrew-ci.yml`** (Gate thresholds):
```yaml
gates:
  security:
    failOn: [CRITICAL]
    maxHigh: 5
    maxMedium: 20
  
  complexity:
    maxCyclomaticComplexity: 10
    maxFunctionSize: 100
    maxNestingDepth: 5
  
  performance:
    maxFunctionDuration: 100  # ms
    maxRegressionPercentage: 10
    blockedPatterns: ['O(n²)', 'memory leak']
  
  coverage:
    minOverall: 80
    minCriticalPath: 95

notifications:
  slackChannel: '#qa-checks'
  emailOnCritical: true
```

**`config/reports/.gitkeep`** (ensure directory exists):
- Baseline files stored here for trend comparison
- Daily reports for tracking
- Historical data for quarterly reviews

---

## Updated Effort Estimates

### Phase 1: Foundation + CI/CD (Week 1-3)

| Component | Hours | Complexity |
|-----------|-------|-----------|
| Shared utilities | 8-10 | MEDIUM |
| Shared data models | 4-5 | LOW |
| Report generation | 6-8 | MEDIUM |
| **CI/CD workflows** | **10-12** | **MEDIUM** |
| **SARIF generation** | **4-6** | **LOW** |
| **Gate configuration** | **3-4** | **LOW** |
| **GitHub integration (CI)** | **6-8** | **MEDIUM** |
| **Phase 1 TOTAL** | **41-53 hours** | — |

### Phase 2: High-Priority Commands (Week 4-5)

| Command | Hours | Status |
|---------|-------|--------|
| audit-complexity | 15-20 | SAME |
| audit-security | 25-30 | SAME |
| review-code | 20-25 | SAME |
| **Phase 2 TOTAL** | **60-75 hours** | — |

### Phase 3: Supporting Commands (Week 6)

| Command | Hours | Status |
|---------|-------|--------|
| audit-performance | 20-25 | SAME |
| analyze-test-coverage | 18-22 | SAME |
| code-cleanup | 12-16 | SAME |
| **Phase 3 TOTAL** | **50-63 hours** | — |

### Phase 4: Testing & Integration (Week 7)

| Task | Hours | Status |
|------|-------|--------|
| Unit tests (all 6) | 8-10 | SAME |
| Integration tests | 10-12 | SAME |
| CI/CD testing | 6-8 | **NEW** |
| **Phase 4 TOTAL** | **24-30 hours** | — |

---

## Grand Total Effort

| Phase | Hours |
|-------|-------|
| Phase 1: Foundation + CI/CD | 41-53 |
| Phase 2: High-Priority Cmds | 60-75 |
| Phase 3: Supporting Cmds | 50-63 |
| Phase 4: Testing & CI/CD | 24-30 |
| **TOTAL** | **175-221 hours** |
| **Timeline** | **6-7 weeks** |

**Overhead**: 15-20% for review, refinement, and integration testing

---

## CI/CD Benefits

### Immediate (Week 2+)
- ✅ Automated security checks on every PR
- ✅ Complexity regressions caught early
- ✅ SARIF reports in GitHub Security tab
- ✅ Performance trends tracked automatically

### Ongoing
- ✅ Continuous baseline updates
- ✅ Zero-touch compliance reporting
- ✅ Early warning on security issues
- ✅ Data for quarterly tier validation

### Integration with Current Workflow
- ✅ Works with existing `/scope-release` process
- ✅ Feeds into release gates (v1.6.5 workflow)
- ✅ Supports multi-repo deployments (v1.7.0 roadmap)
- ✅ Enables autopilot decisions (v2.0.0 vision)

---

## Appendix A: Command Cheat Sheet

```bash
# Review code before PR
/review-code 123

# Audit for security vulnerabilities
/audit-security --severity high --create-issues

# Analyze performance bottlenecks
/audit-performance --threshold 500

# Check code complexity
/audit-complexity --max-complexity 10

# Analyze test coverage gaps
/analyze-test-coverage --min-coverage 80

# Clean up after new implementation works
/code-cleanup
```

---

## Appendix B: Report File Structure

```
config/reports/
├── review-code-2025-10-29.md
├── review-code-2025-10-29.json
├── audit-security-2025-10-29.md
├── audit-security-2025-10-29.json
├── audit-security-baseline.json
├── audit-performance-2025-10-29.md
├── audit-performance-2025-10-29.json
├── audit-complexity-2025-10-29.md
├── audit-complexity-2025-10-29.json
├── analyze-test-coverage-2025-10-29.md
├── analyze-test-coverage-2025-10-29.json
└── [command]-baseline.json (one per command)
```

---

**Document Version**: 1.0  
**Last Updated**: October 29, 2025  
**Status**: Ready for Implementation  
**Next Review**: Upon completion of Phase 1 foundation
