# TypeScript Migration - Risk Management Matrix

## Risk Assessment Overview

**Project Risk Level:** MEDIUM
**Risk Mitigation Strategy:** Incremental migration with checkpoints
**Rollback Capability:** High (module-level, phase-level, complete)

---

## Risk Register

| ID | Risk | Prob | Impact | Severity | Owner | Mitigation | Status |
|----|------|------|--------|----------|-------|------------|--------|
| R1 | Type errors break code | M | H | **HIGH** | Lead Dev | Incremental + tests | Monitor |
| R2 | Tests fail post-migration | M | H | **HIGH** | QA Lead | Parallel test migration | Monitor |
| R3 | Breaking API changes | L | H | **MEDIUM** | Architect | Maintain compatibility | Watch |
| R4 | Scope creep (refactoring) | H | M | **HIGH** | PM | Strict no-refactor rule | Active |
| R5 | DOM type issues (jsdom) | M | M | **MEDIUM** | Dev Team | Proper @types packages | Monitor |
| R6 | Generic type complexity | M | L | **LOW** | Senior Dev | Start simple | Watch |
| R7 | Build pipeline issues | L | M | **LOW** | DevOps | Test early in Phase 0 | Monitor |
| R8 | Developer learning curve | M | M | **MEDIUM** | Tech Lead | Training + pairing | Active |
| R9 | IDE performance issues | L | L | **LOW** | Dev Team | Configure tsconfig | Watch |
| R10 | Third-party type defs | L | M | **LOW** | Dev Team | Verify all @types exist | Watch |
| R11 | Merge conflicts | M | M | **MEDIUM** | Team | Feature freeze during migration | Active |
| R12 | Performance degradation | L | H | **MEDIUM** | Tech Lead | Benchmark early | Monitor |
| R13 | Incomplete rollback | L | H | **MEDIUM** | Lead Dev | Document rollback steps | Prevent |
| R14 | Timeline overrun | M | M | **MEDIUM** | PM | 50% contingency buffer | Active |
| R15 | Team burnout | M | M | **MEDIUM** | PM | Balanced timeline | Active |

**Legend:**
- Probability: L=Low, M=Medium, H=High
- Impact: L=Low, M=Medium, H=High
- Severity: LOW (P×I <4), MEDIUM (P×I 4-6), HIGH (P×I >6)

---

## High-Priority Risks (Detailed Plans)

### R1: Type Errors Break Existing Code

**Probability:** Medium (40%)
**Impact:** High (Critical functionality breaks)
**Severity:** HIGH

#### Symptoms
- Compilation errors after type addition
- Runtime errors in previously working code
- Type assertions failing unexpectedly
- Null/undefined errors appearing

#### Root Causes
- Loose JavaScript patterns exposed by strict types
- Hidden null/undefined values
- Incorrect type assumptions
- Missing null checks

#### Prevention Strategy
```typescript
// 1. Add types incrementally
class Board {
    // Start with basic types
    grid: any[][]; // Temporarily use any

    // Then refine
    grid: (Piece | null)[][]; // Add proper types

    // Finally validate
    getPiece(row: number, col: number): Piece | null {
        // Add runtime checks
        if (!this.isInBounds(row, col)) {
            return null;
        }
        return this.grid[row][col];
    }
}

// 2. Use type guards
function isPiece(obj: any): obj is Piece {
    return obj && typeof obj.type === 'string';
}

// 3. Add null safety
const piece = board.getPiece(row, col);
if (piece) {
    piece.getValidMoves(board); // Safe
}
```

#### Detection
- Continuous type checking: `npx tsc --noEmit`
- Run tests after each module
- Manual smoke testing
- Monitor console for runtime errors

#### Mitigation
1. **Keep .js files temporarily**
   ```bash
   # Don't delete .js until .ts validated
   cp Board.js Board.ts
   # Work on Board.ts
   # Test thoroughly
   rm Board.js # Only after validation
   ```

2. **Use temporary workarounds**
   ```typescript
   // @ts-expect-error - TODO: Fix in Phase 6
   const piece = board.grid[row][col];
   ```

3. **Add null checks**
   ```typescript
   // Before
   return this.grid[row][col].getValidMoves();

   // After
   const piece = this.grid[row][col];
   if (!piece) return [];
   return piece.getValidMoves();
   ```

#### Rollback Plan
```bash
# 1. Revert to .js version
git checkout HEAD -- js/game/Board.js
rm js/game/Board.ts

# 2. Update imports in dependent files
# Change: import { Board } from './Board.ts'
# To:     import { Board } from './Board.js'

# 3. Verify tests pass
npm test

# 4. Document issue for retry
echo "Board.ts rollback: type issue with grid" >> migration-log.md
```

#### Success Criteria
- Zero new runtime errors
- All tests passing
- Type inference working correctly
- No `any` types in final code

---

### R2: Tests Fail After Migration

**Probability:** Medium (40%)
**Impact:** High (Cannot validate correctness)
**Severity:** HIGH

#### Symptoms
- Jest failures after module migration
- Type errors in test files
- Mocking issues with TypeScript
- Import errors in tests

#### Root Causes
- Test expectations don't match new types
- Mock objects lack type definitions
- Import paths need updating
- jsdom type issues

#### Prevention Strategy
```typescript
// 1. Migrate tests alongside source
// When migrating Board.js → Board.ts
// Also migrate Board.test.js → Board.test.ts

// 2. Add proper type imports
import { Board } from '../../src/game/Board';
import type { Position } from '../../src/types/chess';

// 3. Type test fixtures
const mockPosition: Position = { row: 0, col: 0 };
const mockBoard: Board = new Board();

// 4. Use type-safe assertions
expect(result).toEqual<Position>({ row: 1, col: 1 });
```

#### Detection
- Run tests after each module: `npm test -- <module>.test.ts`
- Full test suite before checkpoint
- Coverage report: `npm run test:coverage`
- CI/CD integration (if available)

#### Mitigation
1. **Fix test imports**
   ```typescript
   // Before
   import { Board } from '../../js/game/Board.js';

   // After
   import { Board } from '../../src/game/Board';
   ```

2. **Update test expectations**
   ```typescript
   // Before
   expect(moves.length).toBe(8);

   // After (with types)
   const moves: Position[] = piece.getValidMoves(board);
   expect(moves).toHaveLength(8);
   expect(moves).toEqual(
       expect.arrayContaining([
           expect.objectContaining({ row: expect.any(Number) })
       ])
   );
   ```

3. **Mock with types**
   ```typescript
   const mockPiece: Piece = {
       color: 'white',
       position: { row: 0, col: 0 },
       type: 'pawn',
       hasMoved: false,
       getValidMoves: jest.fn().mockReturnValue([]),
   } as Piece;
   ```

#### Rollback Plan
```bash
# 1. Keep test file as .js temporarily
mv Board.test.ts Board.test.js

# 2. Continue with source migration
# Tests can stay .js until Phase 5

# 3. Or rollback entire module
git checkout HEAD -- js/game/Board.{js,ts}
git checkout HEAD -- tests/unit/game/Board.test.{js,ts}
```

#### Success Criteria
- 124/124 tests passing
- No test file type errors
- Coverage maintained (>80%)
- All assertions type-safe

---

### R4: Scope Creep (Refactoring During Migration)

**Probability:** High (60%)
**Impact:** Medium (Timeline delay)
**Severity:** HIGH

#### Symptoms
- "While we're here, let's improve..."
- Logic changes during type addition
- New features added during migration
- Timeline slipping without clear cause

#### Root Causes
- Temptation to fix old code
- Discovery of improvement opportunities
- Lack of clear boundaries
- No accountability for changes

#### Prevention Strategy
```markdown
# GOLDEN RULE: Migration ONLY, Zero Refactoring

## Allowed ✅
- Adding type annotations
- Adding null checks for type safety
- Fixing type-related bugs exposed
- Updating imports for .ts files

## FORBIDDEN ❌
- Changing algorithms
- Renaming variables/functions
- Restructuring code
- Adding new features
- Performance optimizations
- Code style improvements

## Gray Area → Defer to Phase 6
- Converting loops to .map()
- Adding helper functions
- Extracting constants
- Simplifying conditionals
```

#### Detection
```bash
# Review each commit for logic changes
git diff HEAD~1 --stat

# Red flags in commit:
# - More than 50% lines changed
# - New files created
# - Function signatures changed (beyond types)

# Use code review checklist
- [ ] Only type annotations added?
- [ ] Logic unchanged?
- [ ] No new functions?
- [ ] No performance changes?
```

#### Mitigation
1. **Strict code review**
   ```markdown
   Code Review Checklist:
   - [ ] Only types added (no logic changes)
   - [ ] Tests still pass
   - [ ] No new files (except .ts versions)
   - [ ] Commit message says "feat: migrate" not "refactor:"
   ```

2. **Document improvements for later**
   ```typescript
   // TODO Phase 6: Refactor this to use .map()
   // Current loop works but could be cleaner
   for (const piece of pieces) {
       // ...
   }
   ```

3. **Time-box exploration**
   ```markdown
   If improvement seems necessary:
   1. Time-box investigation: 15 minutes
   2. If simple fix (<10 lines): Consider it
   3. If complex: Create issue for Phase 6
   4. Always defer if uncertain
   ```

#### Rollback Plan
```bash
# If refactoring snuck in:
# 1. Identify pure type changes
git diff HEAD~1 -- js/game/Board.ts > types-only.patch

# 2. Revert commit
git revert HEAD

# 3. Reapply only type changes
git apply types-only.patch
```

#### Success Criteria
- Each commit modifies only types
- No logic changes in diff
- Tests have same behavior
- Timeline on track

---

## Medium-Priority Risks

### R3: Breaking API Changes

**Risk:** External code depends on current API
**Mitigation:**
- Keep public API signatures identical
- Add new typed methods alongside old ones
- Use adapter pattern if needed
- Document breaking changes

**Rollback:** Restore old API, add deprecation warnings

---

### R5: DOM Type Issues (jsdom)

**Risk:** TypeScript DOM types incompatible with jsdom
**Mitigation:**
```typescript
// Install proper types
npm install --save-dev @types/jsdom

// Configure jest
module.exports = {
    testEnvironment: 'jsdom',
};

// Use proper DOM types
const element: HTMLElement | null = document.getElementById('board');
if (!element) throw new Error('Board element not found');

// Add custom types if needed
declare global {
    interface Window {
        chessGame: GameController;
    }
}
```

**Rollback:** Remove jsdom types, use `any` temporarily

---

### R8: Developer Learning Curve

**Risk:** Team unfamiliar with TypeScript
**Mitigation:**
- Provide TypeScript training (2-4 hours)
- Pair programming sessions
- Code review with explanations
- Share TypeScript resources
- Start with simple types, progress to advanced

**Training Plan:**
```markdown
Week 0: TypeScript Basics (4 hours)
- Session 1: Types, Interfaces, Classes (2h)
- Session 2: Generics, Unions, Type Guards (2h)

During Migration:
- Pair programming on complex modules
- Code review as learning opportunity
- Share patterns and best practices
```

**Rollback:** Extend timeline, add more training

---

### R11: Merge Conflicts

**Risk:** Other development during migration causes conflicts
**Mitigation:**
- Feature freeze during migration (recommended)
- Small, frequent commits
- Clear branch strategy
- Communicate migration schedule

**Branch Strategy:**
```bash
# Option 1: Feature branch
git checkout -b typescript-migration
# Merge to main at checkpoints

# Option 2: Main branch
# Small commits directly to main
# Easier to track, but riskier

# Recommended: Feature branch with checkpoints
Week 1: Merge Phase 0-1
Week 2: Merge Phase 2
# etc.
```

**Rollback:** Use conflict resolution tools, or rollback to pre-merge

---

### R12: Performance Degradation

**Risk:** TypeScript compilation or runtime overhead
**Mitigation:**
```bash
# Benchmark before migration
npm test -- --coverage
# Note baseline metrics

# Monitor during migration
# Build time
time npm run build

# Test execution time
time npm test

# Runtime performance
# Use browser DevTools Performance tab
```

**Acceptable Thresholds:**
- Build time: +50% max
- Test time: +20% max
- Runtime: +5% max (should be 0%)

**Rollback:** Investigate, optimize config, or revert

---

### R14: Timeline Overrun

**Risk:** Migration takes longer than estimated
**Mitigation:**
- 50% contingency buffer built in
- Weekly velocity tracking
- Time-box each module
- Escalate blockers quickly

**Velocity Tracking:**
```markdown
Week 1: Planned 10h, Actual 12h → 20% over
Week 2: Planned 10h, Actual 11h → 10% over
Cumulative: 23h vs 20h planned → 15% over

Action: If >25% over by Week 3, extend timeline
```

**Rollback:** Re-estimate, extend timeline, or reduce scope

---

## Risk Response Decision Tree

```
Issue Detected
    ↓
Small issue? (<30min fix)
    ├─ Yes → Fix immediately
    └─ No → Assess severity
                ↓
        Severity Level?
            ├─ Low → Document, continue
            ├─ Medium → Time-box fix (2h)
            │            ├─ Fixed? → Continue
            │            └─ Not fixed? → Escalate
            └─ High → STOP
                        ↓
                  Affects module only?
                      ├─ Yes → Module rollback
                      └─ No → Phase rollback?
                                  ├─ Yes → Phase rollback
                                  └─ No → Complete rollback
```

---

## Rollback Procedures

### Level 1: Module Rollback (< 1 hour)

**When:** Single module has issues
**Impact:** Low - other modules unaffected

**Procedure:**
```bash
# 1. Revert module to .js
git checkout HEAD -- js/path/to/Module.js
rm js/path/to/Module.ts

# 2. Update imports in dependent modules
# Find files importing this module
grep -r "from './Module.ts'" js/

# 3. Change imports back to .js
sed -i '' "s/Module.ts/Module.js/g" js/**/*.ts

# 4. Verify tests
npm test -- Module.test

# 5. Document issue
echo "Module rollback: [reason]" >> rollback-log.md

# 6. Continue with other modules
# Retry problem module later
```

---

### Level 2: Phase Rollback (2-4 hours)

**When:** Entire phase is problematic
**Impact:** Medium - lose phase progress

**Procedure:**
```bash
# 1. Identify checkpoint tag
git tag --list

# 2. Revert to last checkpoint
git reset --hard checkpoint-phase-N

# 3. Create rollback branch
git checkout -b rollback-phase-N

# 4. Assess what went wrong
# Review commits since checkpoint
git log checkpoint-phase-N..HEAD

# 5. Create new approach
# Update plan based on learnings

# 6. Re-start phase with new strategy
```

---

### Level 3: Complete Rollback (1 day)

**When:** Fundamental issues, multiple phases failing
**Impact:** High - lose all migration progress

**Procedure:**
```bash
# 1. Revert to pre-migration state
git reset --hard pre-migration-baseline

# 2. Verify game works
npm test
npm run dev
# Manual testing

# 3. Keep TypeScript config for future
# Don't delete tsconfig.json, package.json changes

# 4. Post-mortem analysis
# Document what went wrong
# What would we do differently?

# 5. Re-evaluate project readiness
# Is the codebase ready for TypeScript?
# Does the team need more training?
# Should we adjust the approach?

# 6. Create new migration plan
# Based on lessons learned
# Maybe phased differently
# Maybe with more training first
```

---

## Early Warning System

### Weekly Health Check

```markdown
## Week X Health Check

### Green Flags ✅ (All is well)
- [ ] On schedule (within 10% of estimate)
- [ ] All tests passing
- [ ] No rollbacks this week
- [ ] Team confident
- [ ] Zero critical blockers

### Yellow Flags ⚠️ (Caution)
- [ ] 10-25% over schedule
- [ ] 1-2 module rollbacks
- [ ] Minor blockers (resolved)
- [ ] Team has questions
- [ ] Some test failures (fixed)

### Red Flags 🚨 (Action required)
- [ ] >25% over schedule
- [ ] >3 module rollbacks
- [ ] Unresolved critical blockers
- [ ] Team morale low
- [ ] Multiple phase rollbacks
- [ ] Test pass rate <90%

### Action Required
If ANY red flag:
1. Pause migration
2. Team meeting
3. Assess root cause
4. Decide: Continue, adjust, or rollback
```

---

## Risk Mitigation Checklist

### Phase 0: Foundation
- [ ] TypeScript version compatible (5.3+)
- [ ] All @types packages installed
- [ ] tsconfig.json validated
- [ ] Jest configured correctly
- [ ] Baseline benchmarks recorded

### Phase 1: Core Types
- [ ] No `any` types used
- [ ] Strict mode enabled
- [ ] All util tests passing
- [ ] Type inference working
- [ ] Team comfortable with types

### Phase 2: Models
- [ ] Board class compiles
- [ ] Piece hierarchy correct
- [ ] All piece tests passing
- [ ] No runtime errors
- [ ] Performance unchanged

### Phase 3: Engine
- [ ] Game logic typed
- [ ] Move validation works
- [ ] Special moves correct
- [ ] Check/checkmate functional
- [ ] Tests 100% passing

### Phase 4: UI
- [ ] DOM types working
- [ ] Event handlers typed
- [ ] Full game playable
- [ ] No console errors
- [ ] Manual testing passed

### Phase 5: Integration
- [ ] All source files .ts
- [ ] All test files .ts
- [ ] 124/124 tests passing
- [ ] Build successful
- [ ] Ready for production

---

## Post-Incident Review Template

**If any rollback occurs:**

```markdown
## Rollback Post-Mortem: [Module/Phase]

**Date:** YYYY-MM-DD
**Level:** Module / Phase / Complete
**Duration:** Xh to resolve

### What Happened
[Description of the issue]

### Root Cause
[Why did this happen?]

### Timeline
- HH:MM: Issue detected
- HH:MM: Investigation started
- HH:MM: Decision to rollback
- HH:MM: Rollback completed
- HH:MM: Resolution

### Impact
- Tests affected: X
- Time lost: Xh
- Modules affected: X

### What Went Well
- [Things that helped]

### What Went Wrong
- [Things that hindered]

### Action Items
- [ ] Prevent recurrence: [action]
- [ ] Update documentation: [what]
- [ ] Team training: [topic]
- [ ] Plan adjustment: [change]

### Lessons Learned
1. [Lesson 1]
2. [Lesson 2]

**Prepared by:** [Name]
**Reviewed by:** [Team]
```

---

## Risk Communication Plan

### Daily
- Update progress tracking
- Document blockers
- Share quick wins

### Weekly
- Checkpoint meeting
- Health check review
- Velocity assessment
- Adjust plan if needed

### On Issue
- Immediate notification
- Assessment within 1 hour
- Decision within 4 hours
- Communication to stakeholders

### Stakeholder Communication
```markdown
Subject: TypeScript Migration - Week X Update

Status: On Track / At Risk / Delayed

Progress:
- Phase: X
- Files: X/18 (X%)
- Tests: X/124 (X%)

Highlights:
- [Achievement 1]
- [Achievement 2]

Challenges:
- [Challenge 1] - Mitigation: [action]

Next Week:
- [Plan]

Confidence: High / Medium / Low
```

---

**Keep this document accessible throughout the migration!**

Version 1.0 | Last Updated: 2025-11-23
