/** * Approximate string matching for anchor re-binding. The anchor resolver falls * back to these when exact and marker-normalized quote lookups both miss - the * quoted text is still present but was lightly edited (a word changed, a typo * fixed, punctuation adjusted). Everything here is pure and offset-exact so it * can be tested in isolation from the resolver. */ /** A window of the haystack that best matches the needle. */ export interface FuzzyMatch { start: number; end: number; similarity: number; } /** * Levenshtein edit distance: the fewest single-character insertions, deletions, * or substitutions that turn `left` into `right`. Uses two rolling rows, so it * costs O(left.length * right.length) time and O(right.length) space. */ export function levenshteinDistance(left: string, right: string): number { if (left === right) return 0; if (left.length === 0) return right.length; if (right.length === 0) return left.length; let previousRow: number[] = Array.from({ length: right.length + 1 }, (_unused, column) => column); let currentRow: number[] = Array.from({ length: right.length + 1 }, () => 0); for (let leftIndex = 1; leftIndex <= left.length; leftIndex++) { currentRow[0] = leftIndex; for (let rightIndex = 1; rightIndex <= right.length; rightIndex++) { const substitutionCost = left[leftIndex - 1] === right[rightIndex - 1] ? 0 : 1; currentRow[rightIndex] = Math.min( currentRow[rightIndex - 1]! + 1, // insertion previousRow[rightIndex]! + 1, // deletion previousRow[rightIndex - 1]! + substitutionCost, // substitution ); } const swap = previousRow; previousRow = currentRow; currentRow = swap; } return previousRow[right.length]!; } /** * Similarity of two strings in [0, 1]: 1 is identical, 0 shares nothing. Derived * from the edit distance normalized by the longer string. Two empty strings are * defined as identical (1). */ export function similarityRatio(left: string, right: string): number { const longestLength = Math.max(left.length, right.length); if (longestLength === 0) return 1; return 1 - levenshteinDistance(left, right) / longestLength; } /** * Character comparisons a fuzzy search may spend before it gives up and returns * the best window found so far (or null). The scan is O(haystack * needle^3) - a * long quote fuzzed over a long document (a stale multi-block anchor whose text * is gone) would otherwise pin the CPU for a minute; a passage that is truly gone * is better left orphaned than fuzzed. Small everyday quotes never approach it. */ const FUZZY_WORK_BUDGET = 150_000_000; /** * A mutable work allowance shared across a group of fuzzy searches. Resolving one * anchor scans every block, so a per-call cap would still let a stale multi-block * anchor spend budget x blocks; sharing one budget across those scans bounds the * whole anchor to a single budget, not one per block. */ export interface FuzzyBudget { remaining: number; } /** A fresh work allowance for one anchor's fuzzy search across its blocks. */ export function newFuzzyBudget(): FuzzyBudget { return { remaining: FUZZY_WORK_BUDGET }; } /** * Find the haystack window most similar to the needle, or null when nothing * clears `minimumSimilarity`. Windows range around the needle length so the * match tolerates a few inserted or deleted characters, not only substitutions. * Ties keep the earliest window. Offsets index the haystack directly. The scan * spends from `budget` (its own single-budget allowance by default) and stops * once the budget is exhausted, returning the best window so far - so a caller * scanning many blocks can pass one budget to bound them together. */ export function fuzzyFindBestMatch( needle: string, haystack: string, minimumSimilarity: number, budget: FuzzyBudget = newFuzzyBudget(), ): FuzzyMatch | null { if (needle === "" || haystack === "") return null; const lengthTolerance = Math.max(2, Math.round(needle.length * 0.25)); const minimumWindowLength = Math.max(1, needle.length - lengthTolerance); const maximumWindowLength = needle.length + lengthTolerance; let bestMatch: FuzzyMatch | null = null; for (let start = 0; start < haystack.length; start++) { for ( let windowLength = minimumWindowLength; windowLength <= maximumWindowLength && start + windowLength <= haystack.length; windowLength++ ) { // each window costs a needle x window edit-distance pass; spend that from the shared budget budget.remaining -= needle.length * windowLength; if (budget.remaining <= 0) return bestMatch; const window = haystack.slice(start, start + windowLength); const similarity = similarityRatio(needle, window); if (similarity < minimumSimilarity) continue; if (bestMatch === null || similarity > bestMatch.similarity) { bestMatch = { start, end: start + windowLength, similarity }; } } } return bestMatch; }