All files / src/sdk fix-quality.ts

90.72% Statements 88/97
84.5% Branches 60/71
100% Functions 8/8
95.55% Lines 86/90

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 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253                                                                        18x     5x 5x 5x       25x 25x 25x           7x 7x 7x   7x 7x   7x       6x 6x 6x 6x 6x 6x   6x     6x 6x 6x                 8x   8x 8x 8x   7x 7x   7x 7x 1x   6x     6x       6x   5x 5x 5x 5x 8x     5x 5x         5x 5x 5x   1x       18x                     4x 4x 1x   3x 3x   3x                                 4x                       3x 1x     2x             15x           15x 15x   15x 11x 3x 3x     8x   8x 8x 4x 4x 4x             4x 4x     4x           4x 3x     4x 1x 1x 1x             1x 1x     3x 2x     3x     15x 15x    
import { readFileSync } from 'node:fs';
import { join, resolve, sep } from 'node:path';
import { z } from 'zod';
import { parsePatch } from '../diff/parser.js';
import { applyDiffToContent } from '../diff/apply.js';
import type { Finding, UsageStats } from '../types/index.js';
import { getRuntime } from './runtimes/index.js';
import type { RuntimeName } from './runtimes/index.js';
import { aggregateUsage } from './usage.js';
import { canUseRuntimeAuth } from './extract.js';
import { buildJsonOutputSection, buildTaggedSection, joinPromptSections } from './prompt-sections.js';
import type { FindingProcessingEvent } from './types.js';
 
export interface FixQualityStats {
  checked: number;
  strippedDeterministic: number;
  strippedSemantic: number;
  semanticUnavailable: number;
}
 
export interface SanitizeSuggestedFixesResult {
  findings: Finding[];
  stats: FixQualityStats;
  usage?: UsageStats;
}
 
interface SanitizeSuggestedFixesOptions {
  repoPath: string;
  apiKey?: string;
  runtime?: RuntimeName;
  model?: string;
  maxRetries?: number;
  agentName?: string;
  onFindingProcessing?: (event: FindingProcessingEvent) => void;
}
 
const SEMANTIC_PROMPT_MAX_CHARS = 4000;
 
function stripSuggestedFix(finding: Finding): Finding {
  const { suggestedFix, ...rest } = finding;
  void suggestedFix;
  return rest;
}
 
function normalizeDiffPath(rawPath: string): string {
  const trimmed = rawPath.trim();
  Eif (trimmed.startsWith('a/') || trimmed.startsWith('b/')) {
    return trimmed.slice(2);
  }
  return trimmed;
}
 
function extractDiffPaths(diff: string): { oldPath?: string; newPath?: string; headerCount: number } {
  const oldHeaders = diff.match(/^---\s+([^\n]+)$/gm) ?? [];
  const newHeaders = diff.match(/^\+\+\+\s+([^\n]+)$/gm) ?? [];
  const headerCount = Math.max(oldHeaders.length, newHeaders.length);
 
  const oldPath = oldHeaders[0]?.replace(/^---\s+/, '');
  const newPath = newHeaders[0]?.replace(/^\+\+\+\s+/, '');
 
  return { oldPath, newPath, headerCount };
}
 
function overlapsAnchor(diff: string, finding: Finding): boolean {
  const location = finding.location;
  const anchorStart = location?.startLine;
  Iif (!anchorStart || !location) return false;
  const anchorEnd = location.endLine ?? anchorStart;
  const hunks = parsePatch(diff);
  Iif (hunks.length === 0) return false;
 
  return hunks.some((h) => {
    // Finding locations are in pre-fix file coordinates, so compare against
    // the old-side hunk range to avoid false mismatches when line counts shift.
    const start = h.oldStart;
    const end = h.oldStart + Math.max(h.oldCount, 1) - 1;
    return start <= anchorEnd && end >= anchorStart;
  });
}
 
type DeterministicResult =
  | { pass: true; fileContent: string; patchedContent: string }
  | { pass: false };
 
function runDeterministicGate(finding: Finding, repoPath: string): DeterministicResult {
  Iif (!finding.location?.path || !finding.suggestedFix?.diff) return { pass: false };
 
  const diff = finding.suggestedFix.diff;
  const hunks = parsePatch(diff);
  if (hunks.length === 0) return { pass: false };
 
  const { oldPath, newPath, headerCount } = extractDiffPaths(diff);
  Iif (headerCount > 1) return { pass: false };
 
  const findingPath = finding.location.path;
  if (oldPath && oldPath !== '/dev/null' && normalizeDiffPath(oldPath) !== findingPath) {
    return { pass: false };
  }
  Iif (newPath && newPath !== '/dev/null' && normalizeDiffPath(newPath) !== findingPath) {
    return { pass: false };
  }
  Iif (oldPath && newPath && oldPath !== '/dev/null' && newPath !== '/dev/null' && normalizeDiffPath(oldPath) !== normalizeDiffPath(newPath)) {
    return { pass: false };
  }
 
  if (!overlapsAnchor(diff, finding)) return { pass: false };
 
  const fullPath = join(repoPath, findingPath);
  const resolvedFull = resolve(fullPath);
  const resolvedRepo = resolve(repoPath);
  const inRepo = resolvedFull === resolvedRepo || resolvedFull.startsWith(resolvedRepo + sep);
  Iif (!inRepo) return { pass: false };
 
  let fileContent: string;
  try {
    fileContent = readFileSync(fullPath, 'utf-8');
  } catch {
    return { pass: false };
  }
 
  try {
    const patchedContent = applyDiffToContent(fileContent, diff);
    return { pass: true, fileContent, patchedContent };
  } catch {
    return { pass: false };
  }
}
 
const SemanticFixVerdictSchema = z.object({
  verdict: z.enum(['pass', 'fail']),
  reason: z.string().min(1),
});
 
async function runSemanticGate(
  finding: Finding,
  fileContent: string,
  patchedContent: string,
  options: SanitizeSuggestedFixesOptions
): Promise<{ verdict: 'pass' | 'fail' | 'unavailable'; usage?: UsageStats }> {
  const { apiKey, runtime, model, maxRetries } = options;
  if (!canUseRuntimeAuth(options)) {
    return { verdict: 'unavailable' };
  }
  const originalForPrompt = fileContent.slice(0, SEMANTIC_PROMPT_MAX_CHARS);
  const patchedForPrompt = patchedContent.slice(0, SEMANTIC_PROMPT_MAX_CHARS);
 
  const prompt = joinPromptSections([
    `<task>
Judge whether this suggested code fix is valid.
</task>`,
    `<fix_quality_rule>
Pass only if the diff clearly addresses the stated issue without obvious regressions in the shown code.
</fix_quality_rule>`,
    buildTaggedSection('issue', [
      `<title>${finding.title}</title>`,
      `<description>${finding.description}</description>`,
    ]),
    buildTaggedSection('original_file', originalForPrompt),
    buildTaggedSection('patched_file', patchedForPrompt),
    buildTaggedSection('suggested_diff', finding.suggestedFix?.diff ?? ''),
    buildJsonOutputSection('{"verdict":"pass|fail","reason":"..."}'),
  ]);
 
  const result = await getRuntime(runtime ?? 'claude').runAuxiliary({
    task: 'fix_quality',
    agentName: options.agentName,
    apiKey,
    prompt,
    schema: SemanticFixVerdictSchema,
    model,
    maxTokens: 220,
    timeout: 8000,
    maxRetries: maxRetries ?? 1,
  });
 
  if (!result.success) {
    return { verdict: 'unavailable', usage: result.usage };
  }
 
  return { verdict: result.data.verdict, usage: result.usage };
}
 
export async function sanitizeFindingsSuggestedFixes(
  findings: Finding[],
  options: SanitizeSuggestedFixesOptions
): Promise<SanitizeSuggestedFixesResult> {
  const stats: FixQualityStats = {
    checked: 0,
    strippedDeterministic: 0,
    strippedSemantic: 0,
    semanticUnavailable: 0,
  };
  const semanticUsage: UsageStats[] = [];
  const sanitized: Finding[] = [];
 
  for (const finding of findings) {
    if (!finding.suggestedFix) {
      sanitized.push(finding);
      continue;
    }
 
    stats.checked++;
 
    const deterministic = runDeterministicGate(finding, options.repoPath);
    if (!deterministic.pass) {
      stats.strippedDeterministic++;
      const stripped = stripSuggestedFix(finding);
      options.onFindingProcessing?.({
        stage: 'fix_gate',
        action: 'stripped_fix',
        finding,
        replacement: stripped,
        reason: 'suggested fix failed deterministic validation',
      });
      sanitized.push(stripped);
      continue;
    }
 
    const semantic = await runSemanticGate(
      finding,
      deterministic.fileContent,
      deterministic.patchedContent,
      options
    );
    if (semantic.usage) {
      semanticUsage.push(semantic.usage);
    }
 
    if (semantic.verdict === 'fail') {
      stats.strippedSemantic++;
      const stripped = stripSuggestedFix(finding);
      options.onFindingProcessing?.({
        stage: 'fix_gate',
        action: 'stripped_fix',
        finding,
        replacement: stripped,
        reason: 'suggested fix failed semantic validation',
      });
      sanitized.push(stripped);
      continue;
    }
 
    if (semantic.verdict === 'unavailable') {
      stats.semanticUnavailable++;
    }
 
    sanitized.push(finding);
  }
 
  const usage = semanticUsage.length > 0 ? aggregateUsage(semanticUsage) : undefined;
  return { findings: sanitized, stats, usage };
}