All files / src/fix aiFixEngine.ts

72.88% Statements 129/177
69.23% Branches 27/39
100% Functions 4/4
72.88% Lines 129/177

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 1782x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 6x 6x 6x 6x 6x 6x 4x 6x     5x 5x 5x 5x 1x 1x 2x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 2x 2x 2x 2x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x                               4x 4x                                     4x 4x 5x 5x 5x 1x 1x 4x 4x 5x 1x 1x 3x 3x 3x 5x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 2x 2x 2x 5x       5x 2x 4x     2x 4x     2x 4x     2x 2x 2x 2x 2x 2x 2x 2x 4x     2x 2x 2x  
import * as vscode from 'vscode';
import type { AIProvider, ChatOptions } from '../ai/providers/base';
import { chatWithRetry, parseJsonResponse } from '../ai/engine';
import type { LinterAdapter, LinterDiagnostic } from '../types';
import { mockDocument } from '../utils/mockDocument';
import { buildFixSystemPrompt, buildFixUserPrompt, buildFixContext, type ReviewIssueInput } from './fixPrompt';
import type { AppliedFix, FixResult } from './fixEngine';
 
interface AiCodeFix {
  originalText: string;
  newText: string;
}
 
async function requestFix(
  provider: AIProvider,
  options: ChatOptions,
  diag: LinterDiagnostic,
  context: string
): Promise<AiCodeFix | null> {
  const issueInput: ReviewIssueInput = {
    ruleId: diag.ruleId,
    line: diag.range.start.line,
    message: diag.message,
    suggestion: diag.suggestion,
  };
  const attempt = async (): Promise<AiCodeFix | null> => {
    try {
      const response = await chatWithRetry(provider, buildFixSystemPrompt(), buildFixUserPrompt(issueInput, 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();
}
 
function sameRuleAtRegion(
  diagnostics: LinterDiagnostic[],
  ruleId: string,
  start: number,
  end: number,
  mock: vscode.TextDocument
): boolean {
  for (const d of diagnostics) {
    if (d.ruleId !== ruleId) { continue; }
    const dStart = mock.offsetAt(d.range.start);
    const dEnd = mock.offsetAt(d.range.end);
    if (dStart < end && dEnd > start) { return true; }
  }
  return false;
}
 
export async function aiFixDiagnostic(
  document: vscode.TextDocument,
  workingDir: string,
  adapter: LinterAdapter,
  diag: LinterDiagnostic,
  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.aiFix;
  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.range.start.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.range.start.line);
    const fix = await requestFix(provider, options, diag, context);
    if (!fix || fix.originalText.trim() === '') {
      return { success: false, attempts: round, message: 'ai-no-fix', appliedFixes };
    }
 
    const startIndex = currentText.indexOf(fix.originalText);
    if (startIndex === -1) {
      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) {
      return { success: false, attempts: round, message: 'no-change', appliedFixes };
    }
 
    appliedFixes.push({
      originalText: fix.originalText,
      newText: fix.newText,
      line: diag.range.start.line,
    });
    currentText = nextText;
 
    try {
      const mock = mockDocument(currentText, document.languageId, document.fileName);
      const verify = await adapter.check(mock, workingDir);
      const fixedStart = startIndex;
      const fixedEnd = startIndex + fix.newText.length;
      if (!sameRuleAtRegion(verify.diagnostics, diag.ruleId, fixedStart, fixedEnd, mock)) {
        converged = true;
        break;
      }
    } catch {
      converged = false;
      break;
    }
  }
 
  if (!converged) {
    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 };
}