All files / src/fix customFixEngine.ts

61.9% Statements 117/189
61.11% Branches 22/36
100% Functions 4/4
61.9% Lines 117/189

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 1902x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 6x 6x 6x 6x 6x 6x 6x 7x 7x 7x 7x 7x 7x 5x 7x     6x 6x 6x 6x 1x 1x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                               5x 5x                                     5x 5x 6x 6x 6x 1x 1x 1x 5x 5x 6x 1x 1x 1x 4x 4x 4x 6x       4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 6x 2x 2x 2x 6x 3x 5x 1x 1x 1x     1x 1x 1x                             2x 5x     2x 2x 2x 2x                              
import * as vscode from 'vscode';
import type { AIProvider, ChatOptions } from '../ai/providers/base';
import { chatWithRetry, parseJsonResponse } from '../ai/engine';
import { buildFixSystemPrompt, buildFixUserPrompt, buildFixContext, buildVerifySystemPrompt, buildVerifyUserPrompt, type ReviewIssueInput } from './fixPrompt';
import type { AppliedFix, FixResult } from './fixEngine';
 
interface AiCodeFix {
  originalText: string;
  newText: string;
}
 
interface AiVerifyResult {
  fixed: boolean;
  reason?: string;
}
 
async function requestFix(
  provider: AIProvider,
  options: ChatOptions,
  diag: ReviewIssueInput,
  context: string
): Promise<AiCodeFix | null> {
  const attempt = async (): Promise<AiCodeFix | null> => {
    try {
      const response = await chatWithRetry(provider, buildFixSystemPrompt(), buildFixUserPrompt(diag, context), options);
      const parsed = parseJsonResponse(response) as Partial<AiCodeFix>;
      const originalText = typeof parsed.originalText === 'string' ? parsed.originalText : '';
      const newText = typeof parsed.newText === 'string' ? parsed.newText : '';
      if (originalText.trim() === '') { return null; }
      return { originalText, newText };
    } catch {
      return null;
    }
  };
 
  const first = await attempt();
  if (first) { return first; }
  return attempt();
}
 
async function verifyFixed(
  provider: AIProvider,
  options: ChatOptions,
  diag: ReviewIssueInput,
  code: string
): Promise<AiVerifyResult> {
  try {
    const response = await chatWithRetry(provider, buildVerifySystemPrompt(), buildVerifyUserPrompt(diag, code), options);
    const parsed = parseJsonResponse(response) as Partial<AiVerifyResult> & { fixed?: unknown };
    const f = parsed.fixed;
    const fixedValue = typeof f === 'string' ? f : String(f);
    return { fixed: f === true || fixedValue === 'true', reason: parsed.reason };
  } catch {
    return { fixed: false };
  }
}
 
export async function aiFixReviewIssue(
  document: vscode.TextDocument,
  diag: ReviewIssueInput,
  maxIterations: number,
  provider: AIProvider,
  options: ChatOptions,
  dryRun?: boolean
): Promise<FixResult> {
  const originalText = document.getText();
  let currentText = originalText;
  const appliedFixes: AppliedFix[] = [];
  let converged = false;
 
  const pre = diag.fix;
  if (pre?.originalText && pre?.newText) {
    const startIndex = currentText.indexOf(pre.originalText);
    if (startIndex !== -1) {
      const endIndex = startIndex + pre.originalText.length;
      const nextText = currentText.slice(0, startIndex) + pre.newText + currentText.slice(endIndex);
      if (nextText !== currentText) {
        appliedFixes.push({
          originalText: pre.originalText,
          newText: pre.newText,
          line: diag.line,
        });
        currentText = nextText;
        converged = true;
      }
    }
  }
 
  if (converged) {
    if (currentText === originalText) {
      return { success: true, attempts: 0, appliedFixes };
    }
    if (dryRun) {
      return { success: true, attempts: 0, appliedFixes, newText: currentText };
    }
    const edit = new vscode.WorkspaceEdit();
    const fullRange = new vscode.Range(
      document.positionAt(0),
      document.positionAt(originalText.length)
    );
    edit.replace(document.uri, fullRange, currentText);
    const applied = await vscode.workspace.applyEdit(edit);
    if (!applied) {
      return { success: false, attempts: 0, message: 'apply-failed', appliedFixes };
    }
    return { success: true, attempts: 0, appliedFixes };
  }
 
  for (let round = 1; round <= maxIterations; round++) {
    const context = buildFixContext(currentText, diag.line);
    const fix = await requestFix(provider, options, diag, context);
    if (!fix || fix.originalText.trim() === '') {
      console.log('[code-reviewer] review-fix', diag.ruleId, 'round', round, 'ai-no-fix');
      return { success: false, attempts: round, message: 'ai-no-fix', appliedFixes };
    }
 
    const startIndex = currentText.indexOf(fix.originalText);
    if (startIndex === -1) {
      console.log('[code-reviewer] review-fix', diag.ruleId, 'round', round, 'ai-match-failed');
      return { success: false, attempts: round, message: 'ai-match-failed', appliedFixes };
    }
 
    const endIndex = startIndex + fix.originalText.length;
    const nextText = currentText.slice(0, startIndex) + fix.newText + currentText.slice(endIndex);
    if (nextText === currentText) {
      console.log('[code-reviewer] review-fix', diag.ruleId, 'round', round, 'no-change');
      return { success: false, attempts: round, message: 'no-change', appliedFixes };
    }
 
    appliedFixes.push({
      originalText: fix.originalText,
      newText: fix.newText,
      line: diag.line,
    });
    currentText = nextText;
 
    const verify = await verifyFixed(provider, options, diag, currentText);
    console.log('[code-reviewer] review-fix', diag.ruleId, 'round', round, 'applied', fix.newText.slice(0, 60), 'verify', verify.fixed, verify.reason ?? '');
    if (verify.fixed) {
      converged = true;
      break;
    }
  }
 
  if (!converged) {
    if (appliedFixes.length > 0) {
      console.log('[code-reviewer] review-fix', diag.ruleId, 'accept-last-fix', appliedFixes.length);
      if (currentText === originalText) {
        return { success: true, attempts: 0, appliedFixes };
      }
      if (dryRun) {
        return { success: true, attempts: maxIterations, appliedFixes, newText: currentText };
      }
      const edit = new vscode.WorkspaceEdit();
      const fullRange = new vscode.Range(
        document.positionAt(0),
        document.positionAt(originalText.length)
      );
      edit.replace(document.uri, fullRange, currentText);
      const applied = await vscode.workspace.applyEdit(edit);
      if (!applied) {
        return { success: false, attempts: maxIterations, message: 'apply-failed', appliedFixes };
      }
      return { success: true, attempts: maxIterations, appliedFixes };
    }
    return { success: false, attempts: maxIterations, message: 'max-iterations', appliedFixes };
  }
 
  if (currentText === originalText) {
    return { success: true, attempts: 0, appliedFixes };
  }
 
  if (dryRun) {
    return { success: true, attempts: maxIterations, appliedFixes, newText: currentText };
  }

  const edit = new vscode.WorkspaceEdit();
  const fullRange = new vscode.Range(
    document.positionAt(0),
    document.positionAt(originalText.length)
  );
  edit.replace(document.uri, fullRange, currentText);
  const applied = await vscode.workspace.applyEdit(edit);
  if (!applied) {
    return { success: false, attempts: maxIterations, message: 'apply-failed', appliedFixes };
  }

  return { success: true, attempts: maxIterations, appliedFixes };
}