All files / src/llm-orchestration/action-handlers/matchers normalized.matcher.ts

98.52% Statements 67/68
93.75% Branches 15/16
100% Functions 14/14
100% Lines 59/59

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            9x 47x           47x         22x 22x     22x 2x                 20x             20x 4x                 16x 21x     16x 3x     3x           13x 8x 8x 8x   8x                   5x       10x                         44x   76x 76x                         20x 20x 20x 20x     20x 50x 50x   50x     50x 21x   21x       21x       21x                       20x               50x 32x 32x   31x 31x 31x             31x   31x 341x   31x 357x     31x 310x 3432x 3432x               31x                   8x 8x                   8x 8x      
import { ContentMatcher, MatchResult, MatchCandidate } from './base.matcher';
 
/**
 * Normalized matcher that handles whitespace variations.
 * Normalizes tabs, trailing spaces, and multiple spaces before comparing.
 */
export class NormalizedMatcher implements ContentMatcher {
  readonly name = 'NormalizedMatcher';
 
  /**
   * Confidence threshold for accepting a normalized match.
   * Can be configured via environment variable.
   */
  private readonly confidenceThreshold: number = parseFloat(
    process.env.NORMALIZED_MATCH_THRESHOLD || '0.95',
  );
 
  match(searchBlock: string, content: string): MatchResult {
    const normalizedSearch = this.normalizeForComparison(searchBlock);
    const normalizedContent = this.normalizeForComparison(content);
 
    // If normalized search is empty, fail
    if (!normalizedSearch.trim()) {
      return {
        found: false,
        unique: false,
        confidence: 0,
        candidates: [],
      };
    }
 
    // Find all candidates with similarity scores
    const candidates = this.findSimilarCandidates(
      normalizedSearch,
      normalizedContent,
      content,
    );
 
    // No candidates found
    if (candidates.length === 0) {
      return {
        found: false,
        unique: false,
        confidence: 0,
        candidates: [],
      };
    }
 
    // Filter by confidence threshold
    const highConfidenceCandidates = candidates.filter(
      (c) => c.confidence >= this.confidenceThreshold,
    );
 
    if (highConfidenceCandidates.length === 0) {
      return {
        found: true,
        unique: false,
        confidence: Math.max(...candidates.map((c) => c.confidence)),
        candidates,
      };
    }
 
    // Check uniqueness
    if (highConfidenceCandidates.length === 1) {
      const candidate = highConfidenceCandidates[0];
      const before = this.extractOriginalBefore(candidate, content);
      const after = this.extractOriginalAfter(candidate, content);
 
      return {
        found: true,
        unique: true,
        confidence: candidate.confidence,
        before,
        after,
      };
    }
 
    // Multiple high-confidence matches
    return {
      found: true,
      unique: false,
      confidence: Math.max(
        ...highConfidenceCandidates.map((c) => c.confidence),
      ),
      candidates: highConfidenceCandidates,
    };
  }
 
  /**
   * Normalize text for comparison by:
   * - Removing leading and trailing whitespace per line
   * - Converting tabs to spaces (2 spaces per tab)
   * Note: We preserve internal spacing to match string literals and aligned code
   */
  private normalizeForComparison(text: string): string {
    return text
      .split('\n')
      .map((line) => line.trim()) // Remove both leading and trailing whitespace
      .map((line) => line.replace(/\t/g, '  ')) // Tabs → spaces
      .join('\n')
      .trim();
  }
 
  /**
   * Find all candidates similar to the normalized search block.
   */
  private findSimilarCandidates(
    normalizedSearch: string,
    normalizedContent: string,
    originalContent: string,
  ): MatchCandidate[] {
    const candidates: MatchCandidate[] = [];
    const normalizedLines = normalizedContent.split('\n');
    const searchLines = normalizedSearch.split('\n');
    const originalLines = originalContent.split('\n');
 
    // Sliding window to find similar blocks
    for (let i = 0; i <= normalizedLines.length - searchLines.length; i++) {
      const windowLines = normalizedLines.slice(i, i + searchLines.length);
      const windowText = windowLines.join('\n');
 
      const similarity = this.calculateSimilarity(normalizedSearch, windowText);
 
      // Only consider candidates with > 50% similarity
      if (similarity > 0.5) {
        const beforeAnchor = i > 0 ? originalLines[i - 1] : undefined;
        const afterAnchor =
          i + searchLines.length < originalLines.length
            ? originalLines[i + searchLines.length]
            : undefined;
 
        const originalBlock = originalLines
          .slice(i, i + searchLines.length)
          .join('\n');
 
        candidates.push({
          block: originalBlock,
          startLine: i,
          endLine: i + searchLines.length - 1,
          confidence: similarity,
          beforeAnchor,
          afterAnchor,
        });
      }
    }
 
    // Sort by confidence descending
    return candidates.sort((a, b) => b.confidence - a.confidence);
  }
 
  /**
   * Calculate similarity using Levenshtein distance.
   * Returns a value between 0.0 (no match) and 1.0 (perfect match).
   */
  private calculateSimilarity(a: string, b: string): number {
    if (a === b) return 1.0;
    Iif (a.length === 0) return 0.0;
    if (b.length === 0) return 0.0;
 
    const distance = this.levenshteinDistance(a, b);
    const maxLen = Math.max(a.length, b.length);
    return 1.0 - distance / maxLen;
  }
 
  /**
   * Calculate Levenshtein distance between two strings.
   */
  private levenshteinDistance(a: string, b: string): number {
    const matrix: number[][] = [];
 
    for (let i = 0; i <= b.length; i++) {
      matrix[i] = [i];
    }
    for (let j = 0; j <= a.length; j++) {
      matrix[0][j] = j;
    }
 
    for (let i = 1; i <= b.length; i++) {
      for (let j = 1; j <= a.length; j++) {
        const cost = b[i - 1] === a[j - 1] ? 0 : 1;
        matrix[i][j] = Math.min(
          matrix[i - 1][j] + 1, // deletion
          matrix[i][j - 1] + 1, // insertion
          matrix[i - 1][j - 1] + cost, // substitution
        );
      }
    }
 
    return matrix[b.length][a.length];
  }
 
  /**
   * Extract the original content before the match.
   */
  private extractOriginalBefore(
    candidate: MatchCandidate,
    content: string,
  ): string {
    const lines = content.split('\n');
    return lines.slice(0, candidate.startLine).join('\n');
  }
 
  /**
   * Extract the original content after the match.
   */
  private extractOriginalAfter(
    candidate: MatchCandidate,
    content: string,
  ): string {
    const lines = content.split('\n');
    return lines.slice(candidate.endLine + 1).join('\n');
  }
}