# Current Release: v1.6.7

**GitHub Issue**: #877 - CI/CD Foundation & Testing Infrastructure 🧪 PLANNED

**Goal:** Establish automated testing infrastructure, CI/CD pipelines, and structured logging with security hardening to create a stable foundation for development.

**Prerequisites:**
- v1.6.6 complete (QA commands operational)
- Jest configured and test scripts ready
- GitHub Actions infrastructure available
- GitHub CI workflow skeleton in place (.github/workflows/ci.yml)

**Estimated Timeline:** 2-3 weeks (21-33 hours)

**Focus Metrics:**
- CI/CD pipeline: Fully active on all PRs with 3 gates (lint, type-check, test)
- Security score: 7/10 (1,524 uncontrolled logs) → 8.5/10 (structured logging)
- Test coverage: 0% → 35-40% (10-12 files with baselines)
- Build gate effectiveness: 100% (all checks passing)
- Sensitive data redaction: 100% (zero tokens/emails in logs)

**Key Use Cases:**
- Every commit triggers automated lint, type-check, test, and build validation
- PR comments show coverage diff and gate status before merge
- Sensitive data (tokens, keys, emails) automatically redacted from logs
- Developers can't merge if tests fail, coverage drops, or lint/type-check fails
- All logs safe for audit/compliance review

**Scope:**

**Phase 1: CI/CD Infrastructure (Days 1-2, 4-6 hours)**
- Complete GitHub Actions workflow (`.github/workflows/ci.yml`)
- Configure Codecov integration for coverage tracking
- Set up branch protection rules for main/dev branches

**Phase 2: Security Hardening & Logging (Days 3-5, 8-12 hours)**
- Implement secure logger module (`scripts/core/logger.ts`)
- Redact sensitive data: GitHub tokens, API keys, emails, issue content
- Migrate top 10 critical files to structured logging
- Update CONTRIBUTING.md with logging guidelines

**Phase 3: Testing Foundation (Days 6-7, 6-10 hours)**
- Create tests for 6 foundation utilities (format-helpers, cost-calculator, mode-detector, etc.)
- Achieve ≥35% overall coverage (10-12 files with baseline)
- Set up coverage tracking and trending

**Success Criteria:**
- [ ] CI/CD pipeline active and passing on all PRs (lint, type-check, test, build)
- [ ] Codecov integration working with PR comments and coverage diff
- [ ] Branch protection preventing direct pushes to main/dev
- [ ] Structured logger module with redaction rules implemented and tested
- [ ] Top 10 critical files migrated to logger (0 console.log statements)
- [ ] Test coverage ≥35% overall (verified with npm run test:coverage)
- [ ] 6 foundation utilities fully tested (≥85% individual coverage)
- [ ] All error scenarios handled with proper logging
- [ ] No regressions in existing functionality
- [ ] All CI checks (lint, type-check, test, build) passing on main
- [ ] Documentation updated (CONTRIBUTING.md logging guidelines)
- [ ] Production ready with full test suite

**Epics:**
- **Epic 1: CI/CD Infrastructure** - GitHub Actions, Codecov integration, branch protection
- **Epic 2: Security Hardening** - Structured logging, sensitive data redaction, audit compliance
- **Epic 3: Testing Foundation** - 6 utility test files, 35%+ coverage, testing patterns

**Value:** Enables safe development practices with automated quality gates. Protects sensitive data in logs. Establishes testing baseline for future development. Makes codebase maintainable and audit-ready.


### EPIC 1: CI/CD Infrastructure & Deployment Automation

**GitHub Issue**: #878

**Goal:** Complete and verify automated quality validation on every commit with GitHub Actions, Codecov coverage tracking, and branch protection rules

**Description:** Verify and finalize GitHub Actions workflow with lint, type-check, test, and coverage steps. Configure Codecov integration for PR comments showing coverage diffs. Implement branch protection rules requiring all status checks to pass before merge.

**Related Spec**: [CI/CD Foundation & Testing Infrastructure](../requirements/specs/qa2-spec.md#1-executive-summary)

**Prerequisites:**
- Jest configured with test scripts (npm test, npm run test:coverage)
- GitHub repository with Actions enabled
- GitHub token available for API calls
- npm dependencies installed

**Estimated Timeline:** 2-3 days (4-6 hours)

**Issues:**

#### Issue 1.1: Complete GitHub Actions CI Workflow

**GitHub Issue**: #879

**Classification**: 5 (ai-led)

**Overview & User Story**: Finalize GitHub Actions workflow with parallel jobs for linting, type-checking, tests, and builds. Workflow already 70% complete in `.github/workflows/ci.yml`.

**Acceptance Criteria:**
- [ ] `.github/workflows/ci.yml` running lint, type-check, test, and coverage steps
- [ ] Workflow runs on push to main/dev/develop branches
- [ ] Workflow runs on all PRs targeting these branches
- [ ] All jobs complete in <10 minutes
- [ ] Coverage artifact uploaded to Codecov
- [ ] PR comments show status and coverage diff
- [ ] Failed jobs clearly report errors

**Technical Implementation:**
- Use existing `.github/workflows/ci.yml` as foundation
- Verify Node.js 18.x environment
- Confirm npm ci and coverage upload steps
- Test with sample PR to verify workflow execution

**Dependencies:** None (foundation already in place)

**Estimated Effort:** 2-3 hours


#### Issue 1.2: Configure Codecov Integration & Coverage Tracking

**GitHub Issue**: #880

**Classification**: 5 (ai-led)

**Overview & User Story**: Create codecov.yml configuration and authorize Codecov app on GitHub.

**Acceptance Criteria:**
- [ ] `codecov.yml` created with coverage thresholds
- [ ] Codecov app authorized on GitHub
- [ ] PR shows Codecov status check
- [ ] PR comment displays coverage diff (main vs branch)
- [ ] Coverage badge available for README
- [ ] Historical coverage tracked and visible

**Technical Implementation:**
- Create `codecov.yml` with precision: 2, project.default.target: 35%, patch.default.target: 50%
- Ignore patterns for tests, mocks, node_modules, coverage/, docs/
- Enable github_checks.annotations for inline comments
- Authorize Codecov GitHub app for the repository

**Dependencies:** Issue 1.1 (CI workflow uploads coverage)

**Estimated Effort:** 2-3 hours


#### Issue 1.3: Implement Branch Protection Rules

**GitHub Issue**: #881

**Classification**: 5 (ai-led)

**Overview & User Story**: Create and apply branch protection rules that prevent direct pushes to main/dev and require passing status checks.

**Acceptance Criteria:**
- [ ] main branch protected (no direct pushes)
- [ ] dev branch protected (no direct pushes)
- [ ] Required status checks: lint, type-check, test
- [ ] Require 1 approving review before merge
- [ ] Dismiss stale review approvals on push
- [ ] Enforce conversation resolution
- [ ] Prevent force pushes and deletions
- [ ] `setup-branch-protection.sh` script created

**Technical Implementation:**
- Create `setup-branch-protection.sh` bash script using GitHub CLI (gh)
- Script applies protection to main and dev branches
- Configures required status checks and review requirements
- Includes error handling and verification steps

**Script Template:**
```bash
#!/bin/bash
set -e

OWNER="tailwind-ai"
REPO="roadcrew-internal"

echo "🔒 Setting up branch protection for $REPO..."

# Protect main branch
gh api repos/$OWNER/$REPO/branches/main/protection \
  --input - << 'EOF'
{
  "required_status_checks": {
    "strict": true,
    "contexts": ["lint", "type-check", "test"]
  },
  "required_pull_request_reviews": {
    "dismiss_stale_reviews": true,
    "require_code_owner_reviews": false,
    "required_approving_review_count": 1
  },
  "enforce_admins": true,
  "allow_force_pushes": false,
  "allow_deletions": false
}
EOF

# Protect dev branch
gh api repos/$OWNER/$REPO/branches/dev/protection \
  --input - << 'EOF'
{
  "required_status_checks": {
    "strict": true,
    "contexts": ["lint", "type-check", "test"]
  },
  "required_pull_request_reviews": {
    "dismiss_stale_reviews": true,
    "require_code_owner_reviews": false,
    "required_approving_review_count": 1
  },
  "enforce_admins": true,
  "allow_force_pushes": false,
  "allow_deletions": false
}
EOF

echo "✅ Branch protection configured successfully"
```

**Dependencies:** Issue 1.1 (status checks from CI)

**Estimated Effort:** 2-3 hours


### EPIC 2: Security Hardening & Structured Logging

**Goal:** Implement structured logging with automatic sensitive data redaction to protect GitHub tokens, API keys, emails, and confidential information.

**Description:** Create a structured logger module with regex-based redaction patterns for sensitive data. Migrate top 10 critical files from console.log to the new logger. Implement error handling with graceful fallbacks to ensure logging failures don't crash the application.

**Related Spec**: [Security Hardening](../requirements/specs/qa2-spec.md#707-security-hardening--structured-logging-8-12-hours)

**Prerequisites:**
- Logger module design finalized
- Top 10 critical files identified
- Redaction rules defined

**Estimated Timeline:** 3-5 days (8-12 hours)

**Issues:**

#### Issue 2.1: Create Structured Logger Module with Redaction

**Classification**: 6 (ai-led)

**Overview & User Story**: Build reusable logger module with automatic redaction of sensitive data patterns (GitHub tokens, API keys, emails, environment variables, issue content).

**Acceptance Criteria:**
- [ ] `scripts/core/logger.ts` exports createLogger(moduleName) factory
- [ ] Logger supports 4 levels: debug, info, warn, error
- [ ] Redaction patterns implemented for:
  -  GitHub tokens (ghp_*, gho_*, ghu_*, ghs_*, ghr_*)
  - API keys and secrets
  - Email addresses (RFC 5322)
  - Environment variable values
  - Issue/PR content bodies
- [ ] All redacted values replaced with `[REDACTED_*]` tags
- [ ] Structured format: `[LEVEL] [MODULE] message`
- [ ] Environment-aware (verbose in dev, minimal in prod)
- [ ] 90%+ test coverage with redaction unit tests
- [ ] Error handling: graceful fallback if redaction fails

**Technical Implementation:**
- Export createLogger(moduleName) returning object with debug/info/warn/error methods
- redactSensitiveData() function with regex patterns:
  * GitHub token: `/gh[pousr]_[A-Za-z0-9_]{36,}/g` → `[REDACTED_TOKEN]`
  * Email: `/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g` → `[REDACTED_EMAIL]`
  * API key: `/api[_-]?key[_-]?[a-zA-Z0-9]{20,}/gi` → `[REDACTED_API_KEY]`
- Error handling: wrap redaction in try-catch, log failures to stderr
- Environment-aware: check `process.env.NODE_ENV === 'test'` → suppress, otherwise output

**Error Handling:**
```typescript
function redactSensitiveData(message: string): string {
  try {
    let redacted = message;
    redacted = redacted.replace(/gh[pousr]_[A-Za-z0-9_]{36,}/g, '[REDACTED_TOKEN]');
    redacted = redacted.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[REDACTED_EMAIL]');
    // ... other patterns
    return redacted;
  } catch (error) {
    console.error('[LOGGER ERROR] Redaction failed:', error instanceof Error ? error.message : String(error));
    return `[REDACTION_ERROR] ${message.substring(0, 50)}...`;
  }
}
```

**Dependencies:** None (foundational)

**Estimated Effort:** 6-8 hours


#### Issue 2.2: Migrate Critical Files to Structured Logging

**Classification**: 6 (ai-led)

**Overview & User Story**: Replace all `console.log()` statements in top 10 critical files with structured logger to ensure sensitive data never leaks.

**Acceptance Criteria:**
- [ ] `scripts/utils/github-auth.ts` - 0 console.log statements
- [ ] `scripts/utils/github-issue-creator.ts` - 0 console.log statements
- [ ] `scripts/utils/token-tracker.ts` - 0 console.log statements
- [ ] `scripts/utils/cost-calculator.ts` - 0 console.log statements
- [ ] `scripts/utils/expert-protection.ts` - 0 console.log statements
- [ ] `scripts/utils/github-projects.ts` - 0 console.log statements
- [ ] `scripts/utils/issue-classification.ts` - 0 console.log statements
- [ ] `scripts/utils/release-parser.ts` - 0 console.log statements
- [ ] `scripts/utils/validation.ts` - 0 console.log statements
- [ ] `scripts/utils/template-engine.ts` - 0 console.log statements
- [ ] All files import and use createLogger()
- [ ] No sensitive values logged (tokens, emails, API keys, issue bodies)
- [ ] Grep audit confirms: `grep -r "console\.(log|debug|error|warn)" scripts/utils/*.ts` returns 0 results
- [ ] Error handling: log failures gracefully without breaking execution

**Technical Implementation - Migration Pattern:**

**BEFORE:**
```typescript
// scripts/utils/github-auth.ts
console.log('Validating GitHub token...');
console.log('Token:', token); // ❌ LEAKS SENSITIVE DATA
console.log('API endpoint:', endpoint);
if (!response.ok) {
  console.error('Auth failed:', response.statusText);
}
```

**AFTER:**
```typescript
import { createLogger } from '../core/logger';
const logger = createLogger('github-auth');

logger.debug('Validating GitHub token');
logger.debug(`Token length: ${token.length} chars`); // ✅ Log metadata, not value
logger.debug(`Using endpoint: ${endpoint}`);
if (!response.ok) {
  logger.error(`Auth failed with status ${response.status}`);
}
```

**Key Rules:**
- Never log: token values, email addresses, API keys, issue/PR content bodies
- Always log: operation status, IDs, counts, errors (without sensitive context)
- Use appropriate levels: debug (dev-only), info (normal flow), warn (issues), error (failures)
- Wrap in try-catch: handle errors gracefully

**Error Handling for Migration:**
```typescript
// If logger fails during file migration, fall back safely
try {
  logger.info(`Processing file: ${fileName}`);
} catch (error) {
  // Logger error - don't crash the application
  console.error('[LOGGER_FALLBACK] Migration error:', error instanceof Error ? error.message : String(error));
  // Continue processing
}
```

**Dependencies:** Issue 2.1 (logger module must exist)

**Estimated Effort:** 2-4 hours


### EPIC 3: Testing Foundation & Coverage Baseline

**Goal:** Establish 35%+ test coverage by implementing comprehensive tests for 6 foundation utilities, creating testing patterns for future development.

**Description:** Create Jest test suites for 6 foundation utilities using Arrange-Act-Assert pattern. Target 85%+ individual coverage per file and 35%+ overall coverage. Implement happy path, edge case, and error scenario tests with proper mocking of external dependencies.

**Related Spec**: [Testing Foundation](../requirements/specs/qa2-spec.md#357-epic-3-testing-foundation--coverage-baseline-6-10-hours)

**Prerequisites:**
- Jest configuration complete
- CI/CD pipeline running
- 6 target utilities identified

**Estimated Timeline:** 3-4 days (6-10 hours)

**Issues:**

#### Issue 3.1: Create Test Suite for Foundation Utilities

**Classification**: 5 (ai-led)

**Overview & User Story**: Create comprehensive Jest tests for 6 foundation utility files to establish 35%+ coverage baseline and create reusable testing patterns.

**Acceptance Criteria:**
- [ ] `scripts/utils/__tests__/format-helpers.test.ts` created (100% coverage target)
- [ ] `scripts/utils/__tests__/cost-calculator.test.ts` created (100% coverage target)
- [ ] `scripts/utils/__tests__/mode-detector.test.ts` created (90%+ coverage)
- [ ] `scripts/utils/__tests__/check-submodule-name.test.ts` created (100% coverage)
- [ ] `scripts/utils/__tests__/classification-zones.test.ts` created (85%+ coverage)
- [ ] `scripts/utils/__tests__/path-validation.test.ts` created (90%+ coverage)
- [ ] Overall coverage ≥35% (verified with npm run test:coverage)
- [ ] All tests pass (npm test returns exit 0)
- [ ] Coverage report generated in coverage/lcov-report/

**Technical Implementation:**
- Test template: Arrange-Act-Assert pattern
- Test structure: describe() → describe(function) → it(scenario)
- Test naming: "should [expected behavior] when [condition]"
- Happy path: valid inputs returning expected output
- Edge cases: null, undefined, empty string, boundary values
- Error cases: invalid inputs throwing appropriate errors
- Each test file: 8-15 test cases for comprehensive coverage
- Mock external dependencies (filesystem, GitHub API, environment variables)

**Dependencies:** Issue 1.1 (CI workflow running tests)

**Estimated Effort:** 6-10 hours


## Effort Summary: v1.6.7 (Simplified)

|| Epic | Issues | Hours | Complexity |
||------|--------|-------|-----------|
|| Epic 1: CI/CD Infrastructure | 1.1, 1.2, 1.3 | 7-11 | LOW |
|| Epic 2: Security Hardening | 2.1, 2.2 | 8-12 | MEDIUM |
|| Epic 3: Testing Foundation | 3.1 | 6-10 | MEDIUM |
|| **TOTAL** | **6 issues** | **21-33 hours** | — |

**Timeline**: 2-3 weeks (can parallelize Epics 1 with 2 and 3)


## Success Criteria: v1.6.7

- [ ] GitHub Actions CI workflow fully active and passing on all PRs
- [ ] Codecov integration active with coverage tracking
- [ ] Branch protection preventing direct pushes to main/dev
- [ ] Structured logger module with redaction fully implemented and tested
- [ ] Top 10 critical files migrated to logger (0 console.log statements)
- [ ] Test coverage ≥35% overall (verified with npm run test:coverage)
- [ ] 6 foundation utility files fully tested (≥85% individual coverage)
- [ ] All error scenarios handled with proper logging and fallbacks
- [ ] No regressions in existing functionality
- [ ] All CI checks (lint, type-check, test, build) passing on main
- [ ] Documentation updated (CONTRIBUTING.md logging guidelines)
- [ ] Production ready with complete test suite


## Value Delivered

✅ **Automated Quality Validation**
- Every PR automatically validated (lint, type-check, test, build)
- No manual quality checks needed
- Regressions caught before merge

✅ **Security Hardened**
- Sensitive data protected (tokens, keys, emails never leak)
- Compliance audit score improved
- Logging practices standardized

✅ **Testable Codebase**
- Foundation established (35%+ coverage)
- Testing patterns replicated for future development
- Critical utilities now have test coverage

✅ **Foundation for Future**
- v1.6.8+: Can safely add features with automated validation
- v1.7.0: Automated infrastructure builds on this foundation
- Team: Can confidently maintain and extend codebase