From 4d8d3a2ca88cc94f77778fb80cae1593b35c7adb Mon Sep 17 00:00:00 2001 From: Peter Bowyer Date: Fri, 24 Apr 2026 04:32:30 +0100 Subject: [PATCH] feat(ui): quieter plan diffs on prose edits (#603) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(ui): atomize balanced emphasis pairs in plan diff Before word-diffing, replace each balanced `**…**`, `__…__`, `~~…~~`, `*…*`, `_…_` (and triples `***…***` / `___…___`) with a unique word-char sentinel — same pattern as the existing code-span / link atomization passes. Identical phrases pair as unchanged; different phrases produce a single remove+add. Fixes the "preliminary analysis" → "final analysis" demo case (⑯), which previously orphaned the closing `**` into the unchanged tail and rendered as literal asterisks. Now renders as one clean bold-struck → bold-green swap. Pair matching uses CommonMark-ish flanking rules so stray `2**3` or intraword `my__var` / `snake_case` stay literal. Longest-first ordering prevents single delimiters from eating the inside of a double-delim pair. * feat(ui): coalesce adjacent diff sites separated by thin tokens After `diffWordsWithSpace` and sentinel restoration, merge dirty runs of ≥2 change sites separated only by thin unchanged tokens (whitespace, commas, periods, semicolons, colons, dashes, quotes) into a single phrase-level swap. Parens and brackets are excluded so inline links and bracketed content stay as hard boundaries. Turns alternating red/green word-noise (e.g. paragraph reworks with multiple adjacent word swaps) into a readable before/after. Also rescues the atomization edge case where wrapping a previously-plain phrase in emphasis (`foo bar baz` → `foo **bar baz**`) would otherwise surface as fragmented literal delimiters inside colored tags. Single-site dirty runs pass through unchanged so isolated word swaps keep word-level highlighting. * feat(ui): atomize hyphenated compounds in plan diff Hyphens between word chars (`ninety-five`, `64-byte`, `state-of-the-art`) are semantic compound words, not two tokens. `diffWordsWithSpace` splits on word boundaries, so without this pass `ninety-five` → `ninety-nine` fragments into an unchanged `ninety-` prefix and a swapped `five`/`nine` suffix — a visually noisy partial-word diff. Added a sentinel pass that replaces infix hyphens with a word-char marker before diffing and restores them afterwards. Runs after the code/link/emphasis passes so hyphens inside those constructs stay hidden. Unlike the other sentinels this one uses a fixed marker — all hyphens restore to the same character, so uniqueness isn't needed. Leading/trailing dashes and em-dash-like separators (dash with space on one side) are not substituted; only true compound infixes. --- apps/hook/dev-mock-api.ts | 4 +- packages/editor/demoPlanDiffDemo.ts | 4 +- packages/ui/utils/planDiffEngine.test.ts | 379 ++++++++++++++++++++++- packages/ui/utils/planDiffEngine.ts | 231 +++++++++++++- 4 files changed, 606 insertions(+), 12 deletions(-) diff --git a/apps/hook/dev-mock-api.ts b/apps/hook/dev-mock-api.ts index 05984ed..40adac4 100644 --- a/apps/hook/dev-mock-api.ts +++ b/apps/hook/dev-mock-api.ts @@ -483,9 +483,9 @@ module.exports = { authenticate }; --- -## ⑯ Known Limitation — Word Swap Inside a Multi-Word Bold Phrase +## ⑯ Fixed — Word Swap Inside a Multi-Word Bold Phrase -> **What to watch for (this is a known glitch):** When a single word inside a multi-word bold phrase changes — like **preliminary analysis** becoming **final analysis** — the engine splits the bold markers across the change boundary. You will likely see raw \`**\` asterisks rendered as literal text and the word "analysis" lose its bold styling. This is a boundary case we haven't fixed yet; it was surfaced by an adversarial audit of the engine. +> **What to watch for:** When a single word inside a multi-word bold phrase changes — like **preliminary analysis** becoming **final analysis** — the diff engine atomizes the whole balanced \`**…**\` pair so it renders as a clean old-bold-struck + new-bold-green swap. Previously the closing \`**\` orphaned into unchanged-tail text and rendered as a literal asterisk; that limitation is resolved. Before the leadership steering committee signs off on the external rollout phase, the team must complete a full pass over the **preliminary analysis** of load testing results, confirm that the error budget still permits the planned migration window, and escalate any unresolved dependencies to the program lead. Any open question at this stage must be either resolved or formally deferred to the post-launch review with named owners and dates. diff --git a/packages/editor/demoPlanDiffDemo.ts b/packages/editor/demoPlanDiffDemo.ts index ad0dca1..bfd20a9 100644 --- a/packages/editor/demoPlanDiffDemo.ts +++ b/packages/editor/demoPlanDiffDemo.ts @@ -239,9 +239,9 @@ export async function authenticate(request: Request): Promise **What to watch for (this is a known glitch):** When a single word inside a multi-word bold phrase changes — like **preliminary analysis** becoming **final analysis** — the engine splits the bold markers across the change boundary. You will likely see raw \`**\` asterisks rendered as literal text and the word "analysis" lose its bold styling. This is a boundary case we haven't fixed yet; it was surfaced by an adversarial audit of the engine. +> **What to watch for:** When a single word inside a multi-word bold phrase changes — like **preliminary analysis** becoming **final analysis** — the diff engine atomizes the whole balanced \`**…**\` pair so it renders as a clean old-bold-struck + new-bold-green swap. Previously the closing \`**\` orphaned into unchanged-tail text and rendered as a literal asterisk; that limitation is resolved. Before the leadership steering committee signs off on the external rollout phase, the team must complete a full pass over the **final analysis** of load testing results, confirm that the error budget still permits the planned migration window, and escalate any unresolved dependencies to the program lead. Any open question at this stage must be either resolved or formally deferred to the post-launch review with named owners and dates. diff --git a/packages/ui/utils/planDiffEngine.test.ts b/packages/ui/utils/planDiffEngine.test.ts index e36667e..bbab629 100644 --- a/packages/ui/utils/planDiffEngine.test.ts +++ b/packages/ui/utils/planDiffEngine.test.ts @@ -134,6 +134,12 @@ describe("computeInlineDiff — token content", () => { }); test("unified string round-trip preserves delimiter pair around diff tags", () => { + // After pair-based emphasis atomization, the whole `**phrase**` + // becomes one atomic token on each side — so the unified string + // starts with `**important**` rather than + // `**important...**`. Visual render is equivalent because + // `` recurses into `InlineMarkdown` and the inner `**…**` parses + // as bold. const result = computeInlineDiff( "**important** text\n", "**critical** text\n" @@ -146,10 +152,375 @@ describe("computeInlineDiff — token content", () => { return t.value; }) .join(""); - expect(unified.startsWith("**")).toBe(true); - expect(unified.includes("** text")).toBe(true); - expect(unified).toContain("critical"); - expect(unified).toContain("important"); + expect(unified).toContain("**important**"); + expect(unified).toContain("**critical**"); + expect(unified).toContain(" text"); + }); +}); + +// Helper to build a unified /-wrapped string from a computeInlineDiff +// result for readable assertions in tests below. +function unify(result: { tokens: import("./planDiffEngine").InlineDiffToken[] }) { + return result.tokens + .map((t) => { + if (t.type === "added") return `${t.value}`; + if (t.type === "removed") return `${t.value}`; + return t.value; + }) + .join(""); +} + +describe("computeInlineDiff — emphasis pair atomization (A3)", () => { + test("single-word bold swap atomizes as one phrase per side", () => { + const r = computeInlineDiff("**old** end", "**new** end"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("**old****new** end"); + }); + + test("multi-word bold with one-word change renders as balanced bold swap", () => { + // The demo case: `**preliminary analysis**` → `**final analysis**`. + // Before this fix, the closing `**` orphaned into unchanged-tail, + // leaving raw literal asterisks in the rendered view. + const r = computeInlineDiff( + "Review the **preliminary analysis** today.", + "Review the **final analysis** today." + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("**preliminary analysis**"); + expect(u).toContain("**final analysis**"); + // No literal unbalanced `**` outside diff tags. + expect(u).not.toMatch(/\*\*[^*]*\*\*/g.test( + u.replace(/<(?:ins|del)>[\s\S]*?<\/(?:ins|del)>/g, "") + ) ? /.*/ : /never/); + }); + + test("multi-word bold, both words change, renders as phrase swap", () => { + const r = computeInlineDiff("**foo bar**", "**baz qux**"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("**foo bar****baz qux**"); + }); + + test("italic `*…*` swap atomizes per pair", () => { + const r = computeInlineDiff("*italic* stuff", "*bold* stuff"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("*italic**bold* stuff"); + }); + + test("strikethrough `~~…~~` swap atomizes per pair", () => { + const r = computeInlineDiff("~~strike~~", "~~gone~~"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("~~strike~~~~gone~~"); + }); + + test("bold-alt `__…__` swap atomizes per pair", () => { + const r = computeInlineDiff("__alt bold__", "__new stuff__"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("__alt bold____new stuff__"); + }); + + test("italic-alt `_…_` swap atomizes per pair", () => { + const r = computeInlineDiff("_alt italic_", "_new_"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("_alt italic__new_"); + }); + + test("word-boundary guard: `my__var__name` → `my__var__names` leaves intraword `__` alone", () => { + // Markdown doesn't treat intraword `__` as bold delimiters, so the pair + // regex must not consume them. Verify the diff treats both sides as + // single identifiers rather than mis-sentinelizing them. + const r = computeInlineDiff("my__var__name", "my__var__names"); + expect(r).not.toBeNull(); + const u = unify(r!); + // The exact diff shape can vary, but no token should contain an + // unmatched sentinel fragment and the full identifiers must survive + // the round-trip. + expect(u).toContain("my__var__name"); + expect(u).toContain("my__var__names"); + expect(u).not.toMatch(/PLDIFFEMPH/); + }); + + test("word-boundary guard: single-underscore intraword preserved (`snake_case`)", () => { + const r = computeInlineDiff("snake_case", "snake_casey"); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("snake_case"); + expect(u).toContain("snake_casey"); + expect(u).not.toMatch(/PLDIFFEMPH/); + }); + + test("nested triple `***foo***` atomizes as one token", () => { + const r = computeInlineDiff("***foo***", "***bar***"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe("***foo******bar***"); + }); + + test("nested triple with multi-word inside", () => { + const r = computeInlineDiff("***foo bar***", "***baz qux***"); + expect(r).not.toBeNull(); + expect(unify(r!)).toBe( + "***foo bar******baz qux***" + ); + }); + + test("stray unbalanced `**` in arithmetic context is preserved as literal", () => { + // `2**3` (exponent in prose) must not be mis-matched. Only the real + // balanced `**bold**` should atomize. + const r = computeInlineDiff( + "2**3 and **bold** text", + "2**4 and **bold** text" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + // `**bold**` unchanged + expect(u).toContain("**bold**"); + // The stray `**` preserved literally; the 3→4 swap shows normally + expect(u).toContain("3"); + expect(u).toContain("4"); + }); + + test("existing code-span sentinel format is not corrupted", () => { + // Two paragraphs both containing inline code spans — the diff should + // still round-trip the code spans correctly with the pair atomization + // layered on top. + const r = computeInlineDiff( + "Call `foo()` inside **bold text** here.", + "Call `bar()` inside **bold text** here." + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("`foo()`"); + expect(u).toContain("`bar()`"); + expect(u).toContain("**bold text**"); + expect(u).not.toMatch(/PLDIFF(?:CODE|LINK|EMPH)/); + }); +}); + +describe("computeInlineDiff — hyphenated compound atomization", () => { + test("letter-letter compound swaps whole token (ninety-five → ninety-nine)", () => { + const r = computeInlineDiff( + "at least ninety-five percent", + "at least ninety-nine percent" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("ninety-five"); + expect(u).toContain("ninety-nine"); + // No partial-word fragmentation. + expect(u).not.toContain("five"); + expect(u).not.toContain("nine"); + expect(u).not.toMatch(/PLDIFFHY/); + }); + + test("digit-letter compound swaps whole token (64-byte → 2048-bit)", () => { + const r = computeInlineDiff( + "a 64-byte value", + "a 2048-bit value" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("64-byte"); + expect(u).toContain("2048-bit"); + expect(u).not.toMatch(/PLDIFFHY/); + }); + + test("multi-hyphen compound atomizes fully (state-of-the-art → state-of-the-craft)", () => { + const r = computeInlineDiff( + "the state-of-the-art approach", + "the state-of-the-craft approach" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("state-of-the-art"); + expect(u).toContain("state-of-the-craft"); + expect(u).not.toMatch(/PLDIFFHY/); + }); + + test("hyphenated compound unchanged between versions stays unchanged", () => { + const r = computeInlineDiff( + "the cookie-based flow runs nightly", + "the cookie-based flow runs daily" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + // Compound must be intact in unchanged context — no PLDIFFHY leak. + expect(u).toContain("cookie-based"); + expect(u).toContain("nightly"); + expect(u).toContain("daily"); + expect(u).not.toMatch(/PLDIFFHY/); + }); + + test("leading/trailing dash is not substituted (em-dash-like prose)", () => { + // A dash with no word char on one side is a separator, not a compound. + const r = computeInlineDiff("foo - bar end", "foo - baz end"); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("bar"); + expect(u).toContain("baz"); + expect(u).not.toMatch(/PLDIFFHY/); + }); + + test("hyphens inside bold phrase stay atomic via emphasis pass, not corrupted", () => { + const r = computeInlineDiff("**cookie-based** flow", "**token-based** flow"); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("**cookie-based**"); + expect(u).toContain("**token-based**"); + expect(u).not.toMatch(/PLDIFFHY/); + }); +}); + +describe("computeInlineDiff — coalescing pass (Commit 2)", () => { + test("two adjacent swaps separated by a single space coalesce into one swap", () => { + const r = computeInlineDiff("foo bar baz", "qux quux baz"); + expect(r).not.toBeNull(); + const u = unify(r!); + // Both word swaps merge into a single phrase swap ending at the + // unchanged tail ` baz`. + expect(u).toContain("foo barqux quux"); + expect(u).toContain(" baz"); + }); + + test("three adjacent swaps (the motivating paragraph example) coalesce", () => { + // Parens act as hard boundaries because they aren't in the thin set. + const r = computeInlineDiff( + "(and the originating case)", + "(and a small set of admins who opted in)" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toBe( + "(and the originating casea small set of admins who opted in)" + ); + }); + + test("single isolated swap stays word-level (no coalescing)", () => { + const r = computeInlineDiff("the quick brown fox", "the slow brown fox"); + expect(r).not.toBeNull(); + const u = unify(r!); + // Only the `quick` → `slow` change should be diffed; `brown fox` must + // stay as unchanged text. + expect(u).toContain("quick"); + expect(u).toContain("slow"); + expect(u).toContain(" brown fox"); + // No accidental absorption of `brown fox` into a combined swap. + expect(u).not.toContain("quick brown fox"); + expect(u).not.toContain("slow brown fox"); + }); + + test("asymmetric coalesce: two removes + one add in dirty run", () => { + const r = computeInlineDiff("foo bar baz end", "foo newword end"); + expect(r).not.toBeNull(); + const u = unify(r!); + // `bar` and `baz` both removed, `newword` added — coalesce absorbs the + // intervening space into the combined swap. The trailing space to the + // unchanged `end` gets pulled into the ins/del because jsdiff pairs + // `baz ` with `newword ` as a single token-level swap. + expect(u).toContain("bar baz"); + expect(u).toContain("newword"); + expect(u).toContain("end"); + }); + + test("swap + swap separated by a comma coalesces (thin punctuation)", () => { + const r = computeInlineDiff("alpha, beta end", "gamma, delta end"); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("alpha, betagamma, delta"); + }); + + test("swap + swap separated by unchanged word does NOT coalesce", () => { + const r = computeInlineDiff("foo bar baz qux end", "zap bar zip end"); + expect(r).not.toBeNull(); + const u = unify(r!); + // `bar` unchanged word between the two swaps must block coalescing. + expect(u).toContain("foo"); + expect(u).toContain("zap"); + expect(u).toContain(" bar "); + expect(u).toContain("baz qux"); + expect(u).toContain("zip"); + // Sanity: not a single combined swap across `bar`. + expect(u).not.toContain("foo bar baz qux"); + }); + + test("swap + swap separated by an unchanged inline link does NOT coalesce", () => { + // The link is an atomic unchanged token whose value is the whole + // `[text](url)` string — that contains non-thin chars (`[`, `]`, `(`, + // `)`), so it blocks coalescing. + const r = computeInlineDiff( + "see foo [docs](https://example.com) bar end", + "see zop [docs](https://example.com) zip end" + ); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("foo"); + expect(u).toContain("zop"); + expect(u).toContain("[docs](https://example.com)"); + expect(u).toContain("bar"); + expect(u).toContain("zip"); + // Not coalesced across the link. + expect(u).not.toContain("foo [docs]"); + }); + + test("multi-word bold phrase swap via coalescing-rescue (Case 2 wrap)", () => { + // `foo bar baz` → `foo **bar baz**`: without coalescing, atomization + // leaves `bar` and `baz` as two word tokens on the old side but + // `**bar baz**` as one atomic pair on the new side, producing + // alternating removes/adds that coalescing folds back into a single + // clean phrase swap. + const r = computeInlineDiff("foo bar baz end", "foo **bar baz** end"); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toContain("bar baz"); + expect(u).toContain("**bar baz**"); + }); +}); + +describe("computeInlineDiff — broader integration", () => { + test("code-span swap adjacent to unchanged text still renders cleanly", () => { + const r = computeInlineDiff("Call `foo()` now.", "Call `bar()` now."); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toBe("Call `foo()``bar()` now."); + }); + + test("link URL swap atomizes the whole link", () => { + const r = computeInlineDiff("See [docs](old)", "See [docs](new)"); + expect(r).not.toBeNull(); + const u = unify(r!); + expect(u).toBe("See [docs](old)[docs](new)"); + }); + + test("heading modification populates inlineTokens with heading wrap", () => { + const r = computeInlineDiff("## **Plan** v1\n", "## **Plan** v2\n"); + expect(r).not.toBeNull(); + expect(r!.wrap.type).toBe("heading"); + expect(r!.wrap.level).toBe(2); + const u = unify(r!); + expect(u).toContain("v"); + expect(u).toContain(""); + expect(u).toContain(""); + }); + + test("computePlanDiff end-to-end with bold-phrase change produces one modified block with balanced inline tokens", () => { + const old = + "Review the **preliminary analysis** of load testing results today.\n"; + const neu = "Review the **final analysis** of load testing results today.\n"; + const { blocks } = computePlanDiff(old, neu); + const mod = blocks.find((b) => b.type === "modified"); + expect(mod).toBeDefined(); + expect(mod!.inlineTokens).toBeDefined(); + const u = mod!.inlineTokens! + .map((t) => + t.type === "added" + ? `${t.value}` + : t.type === "removed" + ? `${t.value}` + : t.value + ) + .join(""); + // Balanced bold pair on each side of the diff — no orphan delimiters. + expect(u).toContain("**preliminary analysis**"); + expect(u).toContain("**final analysis**"); }); }); diff --git a/packages/ui/utils/planDiffEngine.ts b/packages/ui/utils/planDiffEngine.ts index c1da225..f213d7b 100644 --- a/packages/ui/utils/planDiffEngine.ts +++ b/packages/ui/utils/planDiffEngine.ts @@ -221,6 +221,199 @@ function restoreFencedBlocks( return value.replace(FENCE_SENTINEL_PATTERN, (m) => fenceMap.get(m) ?? m); } +// Inline-emphasis sentinels. Each balanced markdown emphasis pair +// (`**...**`, `__...__`, `~~...~~`, `*...*`, `_..._`) gets a unique +// word-char sentinel before `diffWordsWithSpace` runs so that: +// +// - The whole phrase diffs as a single atomic token (sentinels contain +// no whitespace, and `diffWordsWithSpace` splits on whitespace). +// - Identical phrases on both sides pair as unchanged via sentinel +// identity; different phrases pair as a single remove + add. +// +// This is the "pair" form of atomization discussed in the bold-phrase +// design doc: it reliably handles both single-word (`**important**`) and +// multi-word (`**preliminary analysis**`) emphasis without fragmenting +// the closing delimiter into unchanged-tail tokens, which the earlier +// single-delimiter substitution couldn't achieve. +// +// Pair matching uses CommonMark-ish flanking rules: opening delimiter +// must not be preceded by a word char and must be followed by a non-space +// char; closing delimiter must be preceded by a non-space char and not +// followed by a word char. Content is matched lazily. Stray unbalanced +// delimiters (e.g., `2**3` arithmetic) don't match and are left verbatim, +// preserving existing behaviour. +// +// Longest-first ordering (`**`/`__`/`~~` before `*`/`_`) prevents single +// delimiters from eating the inside of a double-delim pair. +const PAIR_SENTINEL_PREFIX = "PLDIFFEMPH"; +const PAIR_SENTINEL_PATTERN = /PLDIFFEMPH\d+ZZ/g; + +const PAIR_PATTERNS: Array<{ delim: string; regex: RegExp }> = [ + // Triples first so `***foo***` (bold+italic) atomizes as one token + // instead of being split into `**` pair plus a leftover `*`. + { delim: "***", regex: /(?, + pairToId: Map +): string { + for (const { regex } of PAIR_PATTERNS) { + text = text.replace(regex, (match) => { + let id = pairToId.get(match); + if (id === undefined) { + id = pairToId.size; + pairMap.set(pairSentinelFor(id), match); + pairToId.set(match, id); + } + return pairSentinelFor(id); + }); + } + return text; +} + +function restoreEmphasisPairs( + value: string, + pairMap: Map +): string { + if (pairMap.size === 0) return value; + return value.replace(PAIR_SENTINEL_PATTERN, (m) => pairMap.get(m) ?? m); +} + +// Hyphen sentinel. Hyphens between word chars (e.g. `ninety-five`, +// `64-byte`, `state-of-the-art`) are semantic compound words, not two +// tokens. `diffWordsWithSpace` splits on word boundaries, so without +// this pass `ninety-five` → `ninety-nine` fragments into an unchanged +// `ninety-` prefix and a swapped `five`/`nine` suffix, producing +// visually noisy partial-word diffs that confuse readers. +// +// Replace each infix hyphen with a word-char marker before diffing and +// restore afterwards. The sentinel is a fixed string (no per-instance +// id) because all hyphens restore to the same character — uniqueness +// isn't needed, only opacity to the word-boundary tokenizer. +// +// Runs AFTER the code/link/emphasis sentinel passes so hyphens inside +// those constructs (e.g. `**state-of-the-art**`, `[link-text](url)`) +// are already hidden and not re-processed here. +const HYPHEN_SENTINEL = "PLDIFFHYZZ"; +const HYPHEN_SENTINEL_PATTERN = /PLDIFFHYZZ/g; +const HYPHEN_INFIX_PATTERN = /(?<=\w)-(?=\w)/g; + +function substituteHyphens(text: string): string { + return text.replace(HYPHEN_INFIX_PATTERN, HYPHEN_SENTINEL); +} + +function restoreHyphens(value: string): string { + return value.replace(HYPHEN_SENTINEL_PATTERN, "-"); +} + +// Coalescing pass (Commit 2). After `diffWordsWithSpace` and sentinel +// restoration, adjacent word-level changes separated by only "thin" +// unchanged tokens (whitespace + closed punctuation) get merged into a +// single phrase-level swap. This turns alternating red/green word-noise +// into a readable before/after, and rescues the A3 regression where +// mashed sentinel-plus-word tokens would otherwise render as fragmented +// literal delimiters inside colored tags. +// +// Definitions (from the design doc): +// - change site: contiguous non-unchanged run +// - thin unchanged: value consists only of whitespace + { , . ; : — – " ' } +// (parens/brackets EXCLUDED so inline links stay as hard boundaries) +// - dirty run: maximal sequence of change sites joined by thin-unchanged +// Coalesce when a dirty run has ≥2 change sites (asymmetric counts allowed). +// Single-site dirty runs pass through so isolated swaps keep word-level +// highlighting. +const THIN_UNCHANGED_RE = + /^[\s,.;:—–"'‘’“”]+$/; + +function isChangeToken(t: InlineDiffToken): boolean { + return t.type !== "unchanged"; +} + +function isThinUnchangedToken(t: InlineDiffToken): boolean { + return t.type === "unchanged" && THIN_UNCHANGED_RE.test(t.value); +} + +function coalesceChangeTokens(tokens: InlineDiffToken[]): InlineDiffToken[] { + const out: InlineDiffToken[] = []; + let i = 0; + while (i < tokens.length) { + if (!isChangeToken(tokens[i])) { + out.push(tokens[i]); + i++; + continue; + } + // Scan first change site. + let lastChangeEnd = i; + while ( + lastChangeEnd + 1 < tokens.length && + isChangeToken(tokens[lastChangeEnd + 1]) + ) { + lastChangeEnd++; + } + let siteCount = 1; + while (true) { + let scan = lastChangeEnd + 1; + while (scan < tokens.length && isThinUnchangedToken(tokens[scan])) scan++; + if (scan < tokens.length && isChangeToken(tokens[scan])) { + let newEnd = scan; + while ( + newEnd + 1 < tokens.length && + isChangeToken(tokens[newEnd + 1]) + ) { + newEnd++; + } + lastChangeEnd = newEnd; + siteCount++; + } else { + break; + } + } + if (siteCount >= 2) { + let removedText = ""; + let addedText = ""; + for (let j = i; j <= lastChangeEnd; j++) { + const t = tokens[j]; + if (t.type === "removed") removedText += t.value; + else if (t.type === "added") addedText += t.value; + else { + removedText += t.value; + addedText += t.value; + } + } + if (removedText.length > 0) + out.push({ type: "removed", value: removedText }); + if (addedText.length > 0) out.push({ type: "added", value: addedText }); + } else { + for (let j = i; j <= lastChangeEnd; j++) out.push(tokens[j]); + } + i = lastChangeEnd + 1; + } + return out; +} + function wrapFromBlock(block: Block): InlineDiffWrap { if (block.type === "heading") { return { type: "heading", level: block.level }; @@ -258,31 +451,61 @@ export function computeInlineDiff( if (!INLINE_DIFFABLE_TYPES.has(a.type)) return null; if (!structuralFieldsMatch(a, b)) return null; - // Atomic passes before word-diffing: + // Atomic passes before word-diffing (longest-lived sentinels first): // 1. Inline code spans — protect backtick-wrapped content so diff markers // never land between backticks (see SENTINEL_PREFIX comment). // 2. Markdown links [text](url) — protect the whole link so diff markers // never land inside the link's bracketed text or parenthesized href. + // 3. Balanced emphasis pairs (**…**, __…__, ~~…~~, *…*, _…_) — replace + // each whole pair with a unique word-char sentinel so the phrase + // diffs atomically, avoiding the fragmented/unbalanced-delimiter + // output that whitespace-splitting `diffWordsWithSpace` produces + // for multi-word emphasis changes. + // 4. Infix hyphens — replace `-` between word chars with a word-char + // marker so hyphenated compounds (`ninety-five`, `64-byte`, + // `state-of-the-art`) diff as single atomic tokens instead of + // fragmenting into an unchanged prefix + swapped suffix. // // Code spans are substituted first so that a backticked literal like // `[fake](link)` is treated as code and not accidentally captured by the - // link regex. Restorations run in reverse order afterwards. + // link regex; similarly, code and link sentinels are opaque to the + // emphasis-pair regex. Hyphens run last so that hyphens inside those + // constructs are already hidden. Restorations run in reverse order. const codeMap = new Map(); const codeToId = new Map(); const linkMap = new Map(); const linkToId = new Map(); + const pairMap = new Map(); + const pairToId = new Map(); let substA = substituteCodeSpans(a.content, codeMap, codeToId); let substB = substituteCodeSpans(b.content, codeMap, codeToId); substA = substituteLinks(substA, linkMap, linkToId); substB = substituteLinks(substB, linkMap, linkToId); + substA = substituteEmphasisPairs(substA, pairMap, pairToId); + substB = substituteEmphasisPairs(substB, pairMap, pairToId); + substA = substituteHyphens(substA); + substB = substituteHyphens(substB); const changes = diffWordsWithSpace(substA, substB); - const tokens: InlineDiffToken[] = changes.map((c) => ({ + const rawTokens: InlineDiffToken[] = changes.map((c) => ({ type: c.added ? "added" : c.removed ? "removed" : "unchanged", - value: restoreCodeSpans(restoreLinks(c.value, linkMap), codeMap), + value: restoreCodeSpans( + restoreLinks( + restoreEmphasisPairs(restoreHyphens(c.value), pairMap), + linkMap + ), + codeMap + ), })); + // Coalesce adjacent change sites separated by thin unchanged context into + // single phrase-level swaps. Turns alternating red/green word-noise into + // a readable before/after, and rescues the Case-2 regression where + // wrapping a previously-plain phrase in emphasis would otherwise surface + // as fragmented literal delimiters inside colored tags. + const tokens = coalesceChangeTokens(rawTokens); + // Build the render wrapper from the NEW block so ordered-list items that // renumbered (e.g., 3. → 4. because a step was inserted above) display the // current plan's numeral rather than the previous version's. -- knotmirror 0.0.1