// A finding's quote against what was heard (release 38 lane C, stage 7's audio check): the quote's words aligned with // a transcript's (a window transcribed through the editor, or another caption track) by longest common subsequence. // Pure and client-safe: the case page draws the diff, the MCP's case_verify can say the same numbers. import { wordsOf } from "../report/quoteWords"; export type WordOp = { op: "same" | "missing" | "extra"; word: string }; export type WordDiff = { /** The quote's words found in order in the transcript. */ matched: number; /** The quote's words. */ words: number; /** * The alignment over the stretch of the transcript the quote matched: `missing` is a quote word the transcript does * not have there, `extra` a transcript word the quote does not have. Transcript words before the first match and * after the last are left out (the window is wider than the quote). */ ops: WordOp[]; }; const split = (s: string) => wordsOf(s).split(" ").filter(Boolean); /** How much of `quote` the `heard` text holds, in order, and where they differ. */ export function quoteWordDiff(quote: string, heard: string): WordDiff { const q = split(quote); const h = split(heard); const n = q.length; const m = h.length; if (n === 0) return { matched: 0, words: 0, ops: [] }; if (m === 0) return { matched: 0, words: n, ops: q.map((word) => ({ op: "missing", word })) }; // lcs[i][j]: the LCS of q[i..] and h[j..]. const lcs: number[][] = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0)); for (let i = n - 1; i >= 0; i--) { for (let j = m - 1; j >= 0; j--) { lcs[i][j] = q[i] === h[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); } } const ops: WordOp[] = []; let i = 0; let j = 0; while (i < n && j < m) { if (q[i] === h[j]) { ops.push({ op: "same", word: q[i] }); i++; j++; } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { ops.push({ op: "missing", word: q[i++] }); } else { ops.push({ op: "extra", word: h[j++] }); } } while (i < n) ops.push({ op: "missing", word: q[i++] }); // Trim the transcript's words outside the matched stretch. const firstSame = ops.findIndex((o) => o.op === "same"); if (firstSame < 0) return { matched: 0, words: n, ops: q.map((word) => ({ op: "missing", word })) }; let lastSame = ops.length - 1; while (lastSame > 0 && ops[lastSame].op !== "same") lastSame--; const trimmed = ops.filter((o, k) => o.op !== "extra" || (k > firstSame && k < lastSame)); return { matched: lcs[0][0], words: n, ops: trimmed }; } /** The share of the quote heard, 0–1. */ export const heardShare = (d: Pick): number => (d.words ? d.matched / d.words : 0);