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

93.8% Statements 106/113
89.18% Branches 33/37
93.33% Functions 14/15
93.75% Lines 90/96

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 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324            9x 51x         51x             51x                 27x 27x     27x 2x       25x     25x 3x 1x       22x 22x     22x     22x             22x 4x                 18x 43x     18x                   18x 5x 5x 5x   5x                     20x 13x 13x       13x                           13x       33x                                 22x   22x 85x 85x   85x           85x 42x       43x                     43x   43x           43x   43x       43x                     39x                         43x     43x 43x     43x       43x     43x   43x 33x 147x 147x 35x       10x       43x   43x 34x 150x 150x 40x       9x         43x   43x     43x             297x 297x 399x   75x             85x 58x 57x   56x 56x 56x             56x   56x 1027x   56x 1003x     56x 971x 25066x 25066x               56x             5x             5x      
import { ContentMatcher, MatchResult, MatchCandidate } from './base.matcher';
 
/**
 * Context-aware matcher that uses surrounding lines as "anchors"
 * to disambiguate between identical or similar blocks.
 */
export class ContextAwareMatcher implements ContentMatcher {
  readonly name = 'ContextAwareMatcher';
 
  /**
   * Confidence threshold for accepting a context-aware match.
   */
  private readonly confidenceThreshold: number = parseFloat(
    process.env.CONTEXT_AWARE_MATCH_THRESHOLD || '0.85',
  );
 
  /**
   * Number of lines to consider as context on each side.
   */
  private readonly anchorWindow: number = parseInt(
    process.env.CONTEXT_ANCHOR_WINDOW || '3',
  );
 
  /**
   * Calculate optimal anchor window based on file characteristics.
   * Dense files need more context to find unique anchors.
   */
  private getAdaptiveAnchorWindow(contentLines: string[]): number {
    const totalLines = contentLines.length;
    const totalChars = contentLines.join('\n').length;
 
    // Handle edge cases
    if (totalLines === 0 || totalChars === 0) {
      return 3; // Default window for empty/tiny files
    }
 
    // Calculate density (lines per 1000 characters)
    const density = (totalLines / totalChars) * 1000;
 
    // Dense files (many short lines) need more lines for uniqueness
    if (density > 50) return 5; // Very dense (minified, JSON)
    if (density > 25) return 4; // Dense (short lines)
    return 3; // Normal/sparse (typical code)
  }
 
  match(searchBlock: string, content: string): MatchResult {
    const searchLines = searchBlock.split('\n');
    const contentLines = content.split('\n');
 
    // Use adaptive window based on file density
    const adaptiveWindow = this.getAdaptiveAnchorWindow(contentLines);
 
    // Find all candidates with similarity scoring
    const candidates = this.findCandidatesWithScoring(
      searchBlock,
      searchLines,
      contentLines,
      adaptiveWindow,
    );
 
    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,
    );
 
    Iif (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.extractBefore(candidate, contentLines);
      const after = this.extractAfter(candidate, contentLines);
 
      return {
        found: true,
        unique: true,
        confidence: candidate.confidence,
        before,
        after,
      };
    }
 
    // Multiple high-confidence matches - check if one is significantly better
    // This handles disambiguation when one block has unique context
    highConfidenceCandidates.sort((a, b) => b.confidence - a.confidence);
    const best = highConfidenceCandidates[0];
    const secondBest = highConfidenceCandidates[1];
 
    // Only consider it unique if the gap is very large (>= 25%)
    // This prevents treating similar contexts as unique
    Iif (best.confidence - secondBest.confidence >= 0.25) {
      const before = this.extractBefore(best, contentLines);
      const after = this.extractAfter(best, contentLines);
 
      return {
        found: true,
        unique: true,
        confidence: best.confidence,
        before,
        after,
      };
    }
 
    // Multiple high-confidence matches
    return {
      found: true,
      unique: false,
      confidence: Math.max(
        ...highConfidenceCandidates.map((c) => c.confidence),
      ),
      candidates: highConfidenceCandidates,
    };
  }
 
  /**
   * Find candidates and score them based on:
   * 1. Similarity of the block itself
   * 2. Uniqueness of surrounding context (anchors)
   */
  private findCandidatesWithScoring(
    searchBlock: string,
    searchLines: string[],
    contentLines: string[],
    windowSize: number,
  ): MatchCandidate[] {
    const candidates: MatchCandidate[] = [];
 
    for (let i = 0; i <= contentLines.length - searchLines.length; i++) {
      const windowLines = contentLines.slice(i, i + searchLines.length);
      const windowBlock = windowLines.join('\n');
 
      const blockSimilarity = this.calculateSimilarity(
        searchBlock,
        windowBlock,
      );
 
      // Only consider blocks with reasonable similarity
      if (blockSimilarity < 0.5) {
        continue;
      }
 
      // Calculate anchor uniqueness scores
      const contextScore = this.calculateContextUniqueness(
        i,
        searchLines.length,
        contentLines,
        windowSize,
      );
 
      // Combine block similarity with context uniqueness
      // If anchors are unique (score > 0.5), give them higher weight
      // This helps disambiguate identical blocks with unique context
      let combinedConfidence: number;
      if (contextScore > 0.5) {
        // Unique context - boost confidence significantly
        combinedConfidence = blockSimilarity * 0.4 + contextScore * 0.6;
      } else E{
        // Common context - rely more on block similarity
        combinedConfidence = blockSimilarity * 0.9 + contextScore * 0.1;
      }
 
      const beforeAnchor = i > 0 ? contentLines[i - 1] : undefined;
      const afterAnchor =
        i + searchLines.length < contentLines.length
          ? contentLines[i + searchLines.length]
          : undefined;
 
      candidates.push({
        block: windowBlock,
        startLine: i,
        endLine: i + searchLines.length - 1,
        confidence: combinedConfidence,
        beforeAnchor,
        afterAnchor,
      });
    }
 
    // Sort by combined confidence descending
    return candidates.sort((a, b) => b.confidence - a.confidence);
  }
 
  /**
   * Calculate how unique the context around a position is.
   * Higher score means the context is more distinctive (appears fewer times in the file).
   */
  private calculateContextUniqueness(
    startIndex: number,
    blockLength: number,
    contentLines: string[],
    windowSize: number,
  ): number {
    const totalLines = contentLines.length;
 
    // Extract before-anchor context (window of lines before the block)
    const beforeStart = Math.max(0, startIndex - windowSize);
    const beforeLines = contentLines.slice(beforeStart, startIndex);
 
    // Extract after-anchor context (window of lines after the block)
    const afterEnd = Math.min(
      totalLines,
      startIndex + blockLength + windowSize,
    );
    const afterLines = contentLines.slice(startIndex + blockLength, afterEnd);
 
    // Count occurrences of before context
    let beforeOccurrences = 0;
    // Empty before context means start of file - treat as unique
    if (beforeLines.length > 0) {
      for (let i = 0; i <= totalLines - beforeLines.length; i++) {
        const window = contentLines.slice(i, i + beforeLines.length);
        if (this.arraysEqual(window, beforeLines)) {
          beforeOccurrences++;
        }
      }
    } else {
      beforeOccurrences = 0; // Start of file is unique
    }
 
    // Count occurrences of after context
    let afterOccurrences = 0;
    // Empty after context means end of file - treat as unique
    if (afterLines.length > 0) {
      for (let i = 0; i <= totalLines - afterLines.length; i++) {
        const window = contentLines.slice(i, i + afterLines.length);
        if (this.arraysEqual(window, afterLines)) {
          afterOccurrences++;
        }
      }
    } else {
      afterOccurrences = 0; // End of file is unique
    }
 
    // Calculate uniqueness score (1.0 = completely unique)
    const beforeUniqueness =
      beforeOccurrences === 0 ? 1.0 : 1.0 / beforeOccurrences;
    const afterUniqueness =
      afterOccurrences === 0 ? 1.0 : 1.0 / afterOccurrences;
 
    // Average the two
    return (beforeUniqueness + afterUniqueness) / 2;
  }
 
  /**
   * Helper to compare string arrays for equality.
   */
  private arraysEqual(a: string[], b: string[]): boolean {
    Iif (a.length !== b.length) return false;
    for (let i = 0; i < a.length; i++) {
      if (a[i] !== b[i]) return false;
    }
    return true;
  }
 
  /**
   * Calculate similarity using Levenshtein distance.
   */
  private calculateSimilarity(a: string, b: string): number {
    if (a === b) return 1.0;
    if (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.
   */
  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,
          matrix[i][j - 1] + 1,
          matrix[i - 1][j - 1] + cost,
        );
      }
    }
 
    return matrix[b.length][a.length];
  }
 
  private extractBefore(
    candidate: MatchCandidate,
    contentLines: string[],
  ): string {
    return contentLines.slice(0, candidate.startLine).join('\n');
  }
 
  private extractAfter(
    candidate: MatchCandidate,
    contentLines: string[],
  ): string {
    return contentLines.slice(candidate.endLine + 1).join('\n');
  }
}