# Automated Fix Flow: From PR Comment to Code Fix

## Current State

**What exists:**
- `auto-fix-lint.yml` - Automatically fixes lint errors when CI fails
- Pattern: `workflow_run` event → Check failure type → Run fix command → Commit & push

**What's missing:**
- Auto-fix for test failures, type errors, build errors
- Comment-based trigger mechanism
- Error-aware fix strategies

## Required Components for Full Automation

### 1. Comment Parsing & Trigger Detection

**What's needed:**
- Read PR comments created by failure notification workflow
- Detect when comment contains auto-fixable errors
- Extract error details from comment markdown

**Implementation:**
```typescript
// Read latest failure analysis comment
const comments = await octokit.rest.issues.listComments({
  owner,
  repo,
  issue_number: prNumber
});

const failureComment = comments.data.find(c => 
  c.user?.type === 'Bot' && 
  c.body?.includes('CI Failure Analysis')
);

if (failureComment) {
  const errors = parseErrorsFromComment(failureComment.body);
  const autoFixable = filterAutoFixable(errors);
  // Trigger auto-fix workflow
}
```

**Trigger options:**
- **Option A**: GitHub Actions `issue_comment` event (triggers on any comment)
- **Option B**: Same workflow that posts comment also attempts fixes
- **Option C**: Scheduled check that reads comments and triggers fixes

---

### 2. Error Type Classification & Fix Strategies

**What's needed:**
Different auto-fix strategies for each error type:

#### Lint Errors (Already implemented)
- **Fix**: `npm run lint:fix`
- **Safe**: ✅ Yes (formatting only)
- **Pattern**: Already working in `auto-fix-lint.yml`

#### Type Errors
- **Fix**: `npm run type-check` → Fix type issues → Re-run type-check
- **Safe**: ⚠️ Partial (can auto-fix some, not all)
- **Examples**:
  - Missing imports → Auto-add
  - Type mismatches → May need manual intervention
  - Missing type annotations → Auto-add from inference

#### Test Failures
- **Fix**: Varies by failure type
- **Safe**: ❌ Low (requires understanding test intent)
- **Examples**:
  - Assertion errors → Usually need manual fix
  - Missing mocks → Can auto-add from patterns
  - Import errors → Can auto-fix
  - Test data issues → May need manual fix

#### Build Errors
- **Fix**: Varies by error
- **Safe**: ⚠️ Partial
- **Examples**:
  - Missing dependencies → Can auto-install
  - Syntax errors → Usually need manual fix
  - Config errors → May need manual fix

**Implementation:**
```typescript
interface FixStrategy {
  errorType: 'lint-error' | 'type-error' | 'test-failure' | 'build-error';
  canAutoFix: (error: ParsedLogError) => boolean;
  fixCommand: (error: ParsedLogError) => string;
  maxAttempts: number;
  requiresApproval: boolean;
}

const strategies: FixStrategy[] = [
  {
    errorType: 'lint-error',
    canAutoFix: () => true,
    fixCommand: () => 'npm run lint:fix',
    maxAttempts: 2,
    requiresApproval: false
  },
  {
    errorType: 'type-error',
    canAutoFix: (e) => e.message.includes('Cannot find module') || 
                       e.message.includes('is not defined'),
    fixCommand: (e) => `npm run type-check && fix-imports ${e.file}`,
    maxAttempts: 1,
    requiresApproval: true // Require approval for type fixes
  },
  // ... more strategies
];
```

---

### 3. Enhanced Auto-Fix Workflow

**What's needed:**
Expand `auto-fix-lint.yml` to handle all error types, not just lint.

**Current flow:**
```
CI fails → Check lint job → Run lint:fix → Commit → Push
```

**Enhanced flow:**
```
CI fails → Download logs → Parse errors → Classify errors
  ↓
For each error type:
  ├─ Lint errors → npm run lint:fix (auto, max 2 attempts)
  ├─ Type errors → npm run type-check + auto-fix (auto, max 1 attempt, if safe)
  ├─ Test failures → Attempt targeted fixes (manual approval if complex)
  └─ Build errors → Attempt dependency/import fixes (auto, if safe)
  ↓
Commit fixes → Push → Re-run CI
```

**Implementation:**
```yaml
name: Auto-Fix CI Failures

on:
  workflow_run:
    workflows: ["CI"]
    types: [completed]

jobs:
  auto-fix:
    if: github.event.workflow_run.conclusion == 'failure'
    steps:
      - name: Download and parse logs
        run: |
          npm run download-logs -- --run-id ${{ github.run_id }} --parse-errors
          # Generates config/reports/logs/error-analysis.json
      
      - name: Classify errors
        id: classify
        run: |
          # Read parsed errors
          # Categorize: lint, type, test, build
          # Output: LINT_ERRORS=1 TYPE_ERRORS=2 TEST_ERRORS=0 BUILD_ERRORS=0
      
      - name: Auto-fix lint errors
        if: steps.classify.outputs.LINT_ERRORS > 0
        run: npm run lint:fix
      
      - name: Auto-fix type errors (safe only)
        if: steps.classify.outputs.TYPE_ERRORS > 0
        run: |
          # Only fix: missing imports, undefined variables
          # Skip: complex type mismatches
          npm run fix-types --safe-only
      
      - name: Auto-fix build errors (safe only)
        if: steps.classify.outputs.BUILD_ERRORS > 0
        run: |
          # Only fix: missing dependencies, import errors
          # Skip: config/syntax errors
          npm run fix-build --safe-only
      
      - name: Commit and push
        if: |
          steps.classify.outputs.LINT_ERRORS > 0 ||
          steps.classify.outputs.TYPE_ERRORS > 0 ||
          steps.classify.outputs.BUILD_ERRORS > 0
        run: |
          git add .
          git commit -m "chore: auto-fix CI errors [auto-fix attempt X/2]"
          git push
      
      - name: Request approval for test failures
        if: steps.classify.outputs.TEST_ERRORS > 0
        uses: actions/github-script@v7
        with:
          script: |
            // Post comment asking for approval to attempt test fixes
            // Link to /triage-pr command for manual review
```

---

### 4. Safe Auto-Fix Detection

**What's needed:**
Determine which errors can be safely auto-fixed without human review.

**Safe to auto-fix:**
- ✅ Lint/formatting issues
- ✅ Missing imports (can infer from usage)
- ✅ Undefined variables (typos, can suggest fixes)
- ✅ Missing dependencies (package.json updates)
- ✅ Simple type errors (string vs number, can coerce)

**Requires approval:**
- ⚠️ Test assertion failures (need to understand expected behavior)
- ⚠️ Complex type mismatches (may indicate design issue)
- ⚠️ Build configuration errors (may affect deployment)
- ⚠️ Logic errors (test failures that aren't simple fixes)

**Implementation:**
```typescript
function canAutoFixSafely(error: ParsedLogError): boolean {
  // Lint errors: always safe
  if (error.type === 'lint-error') return true;
  
  // Type errors: safe if simple
  if (error.type === 'type-error') {
    const safePatterns = [
      /Cannot find module/,
      /is not defined/,
      /Cannot find name/
    ];
    return safePatterns.some(p => p.test(error.message));
  }
  
  // Build errors: safe if dependency-related
  if (error.type === 'build-error') {
    return error.message.includes('Cannot find module') ||
           error.message.includes('npm ERR');
  }
  
  // Test failures: rarely safe
  if (error.type === 'test-failure') {
    return false; // Require manual review
  }
  
  return false;
}
```

---

### 5. Fix Implementation Scripts

**What's needed:**
Scripts that actually perform the fixes (beyond just `lint:fix`).

**Examples:**

```typescript
// scripts/fix-types.ts
export async function fixTypeErrors(errors: ParsedLogError[]): Promise<void> {
  for (const error of errors) {
    if (error.type === 'type-error' && error.file) {
      // Fix missing imports
      if (error.message.includes('Cannot find module')) {
        await addMissingImport(error.file, error.message);
      }
      
      // Fix undefined variables (typos)
      if (error.message.includes('is not defined')) {
        await suggestVariableFix(error.file, error.line, error.message);
      }
    }
  }
}

// scripts/fix-build.ts
export async function fixBuildErrors(errors: ParsedLogError[]): Promise<void> {
  for (const error of errors) {
    if (error.type === 'build-error') {
      // Install missing dependencies
      if (error.message.includes('Cannot find module')) {
        const module = extractModuleName(error.message);
        await exec(`npm install ${module}`);
      }
    }
  }
}
```

---

### 6. Approval Workflow for Complex Fixes

**What's needed:**
For errors that can't be auto-fixed safely, provide clear path to manual fix.

**Flow:**
```
Test failures detected → Can't auto-fix safely
  ↓
Post PR comment with:
  - Error summary
  - Suggested fixes (with file/line links)
  - Link to /triage-pr command
  - Option to approve auto-fix attempt
  ↓
Developer reviews → Approves via comment reaction or command
  ↓
If approved → Attempt fixes → Commit → Push
```

**Implementation:**
```yaml
- name: Request approval for complex fixes
  if: steps.classify.outputs.TEST_ERRORS > 0
  uses: actions/github-script@v7
  with:
    script: |
      await github.rest.issues.createComment({
        owner: context.repo.owner,
        repo: context.repo.repo,
        issue_number: prNumber,
        body: `
## ⚠️ Test Failures Require Review

**Test Failures:** ${testErrorCount}

These failures require manual review as they may indicate logic issues.

### Options:

1. **Manual Review**: Run \`/triage-pr ${prNumber}\` for detailed analysis
2. **Approve Auto-Fix Attempt**: React with 👍 to this comment to attempt automatic fixes
3. **Review Errors**: See details below

### Error Summary:
${testErrors.map(e => `- ${e.file}:${e.line} - ${e.message}`).join('\n')}
        `
      });
```

---

## Complete Automation Flow

### Scenario 1: Fully Auto-Fixable (Lint Errors)
```
CI fails → workflow_run triggers
  ↓
Download logs → Parse errors → Classify as lint
  ↓
Run npm run lint:fix
  ↓
Changes detected?
  ↓
YES → Commit & push → CI re-runs → Success ✅
```

### Scenario 2: Partially Auto-Fixable (Type Errors)
```
CI fails → workflow_run triggers
  ↓
Download logs → Parse errors → Classify as type errors
  ↓
Filter to safe fixes only
  ↓
Run auto-fix-types script
  ↓
Changes detected?
  ↓
YES → Commit & push → CI re-runs
  ↓
Still failing? → Post comment with remaining errors
```

### Scenario 3: Requires Approval (Test Failures)
```
CI fails → workflow_run triggers
  ↓
Download logs → Parse errors → Classify as test failures
  ↓
Cannot auto-fix safely
  ↓
Post PR comment with:
  - Error summary
  - Suggested fixes
  - Approval request
  ↓
Developer reviews → Approves via reaction
  ↓
Approval detected → Attempt fixes → Commit → Push
```

---

## Implementation Requirements Summary

### Phase 1: Enhanced Auto-Fix (Immediate)
1. ✅ **Expand auto-fix-lint.yml** to download logs first
2. ✅ **Add error classification** (lint vs type vs test vs build)
3. ✅ **Add type error auto-fix** (safe cases only)
4. ✅ **Add build error auto-fix** (dependency fixes)

### Phase 2: Comment-Based Triggers (Future)
5. **Comment parsing** - Read failure analysis comments
6. **Approval mechanism** - React-based or command-based approval
7. **Complex fix strategies** - Handle test failures with approval

### Phase 3: Full Automation (Future)
8. **AI-powered fixes** - Use Cursor AI to generate fixes from errors
9. **Fix validation** - Test fixes before committing
10. **Rollback mechanism** - Revert if fixes make things worse

---

## Key Decision: Comment-Based vs Direct Fix

**Option A: Comments trigger fixes** (separate workflow)
- Pros: Clear separation, can approve/reject
- Cons: Extra step, comment parsing complexity

**Option B: Same workflow fixes immediately** (current pattern)
- Pros: Faster, simpler
- Cons: Less control, can't approve/reject

**Recommendation:** Start with Option B (enhance existing auto-fix workflow), add Option A later for complex cases requiring approval.

---

## Safety Mechanisms

1. **Max attempts** - Limit to 2-3 auto-fix attempts per PR
2. **Error type limits** - Only auto-fix safe error types
3. **Change detection** - Only commit if fixes actually change code
4. **Test before commit** - Run fix commands, verify they work
5. **Rollback on regression** - If fixes make things worse, revert

---

This provides a complete picture of what's needed for comments to automatically trigger fixes.

