Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-1291]): enrich name-dissimilarity check with edit-distance, phonetic, aliases, locked + crowding

[._.]/ Adam Eivy317688c51d48
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 78a94c209f..efefbacdad 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -81,4 +81,5 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| Module | Purpose |
|---|---|
| `checkRegistry.js` | `EDITORIAL_CHECKS` array + `EDITORIAL_SOURCES` (the per-check `sources` vocabulary the staleness runner fingerprints, #1387) + fail-fast guards + lookup/state helpers (`getCheck`, `getCheckById`, `getAllChecks`, `listChecks`, `resolveCheckState`, `getEnabledChecks`, `resolveCheckConfig`). User-defined-check helpers (`buildCustomCheck`, `buildCustomCheckPrompt`, `readCustomCheckDefs`, `isCustomCheckId`, `isValidCustomCheckDef`). Ships two reference checks: `naming.dissimilar-names` (deterministic) and `prose.info-dumping` (LLM). |
+| `nameSimilarity.js` | Pure, dependency-free name-confusability primitives for `naming.dissimilar-names` (#1291): `normalizeName`, `vowelSkeleton`, `soundex` (phonetic key), `levenshtein` (edit distance), `nameSimilaritySignals` (the per-pair signal list, with option toggles), and `firstLetterHistogram` / `findFirstLetterClusters` (cast first-letter crowding). |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 3f0978a1ee..37dab18465 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -26,6 +26,12 @@
import { z } from 'zod';
import { estimateTokens } from '../contextBudget.js';
+import {
+ nameSimilaritySignals,
+ levenshtein,
+ soundex,
+ findFirstLetterClusters,
+} from './nameSimilarity.js';
export const CHECK_SCOPES = Object.freeze(['series', 'issue', 'scene', 'noun']);
export const CHECK_KINDS = Object.freeze(['deterministic', 'llm']);
@@ -87,26 +93,53 @@ export const OBJECT_BACKSTORY_STAGE = 'pipeline-editorial-object-backstory';
export const STYLE_CONFORMANCE_STAGE = 'pipeline-editorial-style-conformance';
// ---------------------------------------------------------------------------
-// Deterministic helpers for the character-name dissimilarity check.
+// Character-name dissimilarity (#1291) reads cast names + aliases and respects
+// locked entries. The pure similarity primitives live in ./nameSimilarity.js;
+// the helpers below turn the canon into the flat name list the check walks.
// ---------------------------------------------------------------------------
-const letters = (s) => String(s || '').toLowerCase().replace(/[^a-z]/g, '');
-const vowelSkeleton = (s) => letters(s).replace(/[^aeiou]/g, '');
-
-// The similarity signals two character names can share. Two names that trip
-// enough of these are easy for a reader to confuse on the page.
-function nameSimilaritySignals(a, b) {
- const la = letters(a);
- const lb = letters(b);
- if (!la || !lb) return [];
- const signals = [];
- if (la[0] === lb[0]) signals.push('same first letter');
- if (la.length === lb.length) signals.push('same length');
- const vsa = vowelSkeleton(a);
- if (vsa && vsa === vowelSkeleton(b)) signals.push('same vowel pattern');
- if (la.length >= 3 && lb.length >= 3 && la.slice(0, 3) === lb.slice(0, 3)) signals.push('same opening');
- if (la.endsWith(lb.slice(-2)) && la.slice(-2) === lb.slice(-2)) signals.push('same ending');
- return signals;
+// SEVERITIES is ordered high→…→low (index 0 = most severe). Escalate `base` up
+// by `steps` ranks, clamped at the top — a strong collision (near-identical
+// spelling, dense first-letter cluster) outranks the check's low floor.
+function escalateSeverity(base, steps) {
+ const i = SEVERITIES.indexOf(base);
+ const idx = i === -1 ? SEVERITIES.length - 1 : i;
+ return SEVERITIES[Math.max(0, idx - Math.max(0, steps))];
+}
+
+// The flat list of confusable name tokens for a cast: each character's `name`
+// plus every alias, tagged with the owning character (id-or-index), whether that
+// character is locked, and whether the token is an alias. Two tokens owned by the
+// same character never pair (a name vs. its own alias isn't a reader collision).
+function castNameTokens(ctx) {
+ const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];
+ const tokens = [];
+ chars.forEach((c, idx) => {
+ if (!c || typeof c !== 'object') return;
+ const owner = c.id || `idx-${idx}`;
+ const locked = c.locked === true;
+ const primary = typeof c.name === 'string' ? c.name.trim() : '';
+ if (primary) tokens.push({ token: primary, owner, ownerName: primary, locked, isAlias: false });
+ const aliases = Array.isArray(c.aliases) ? c.aliases : [];
+ for (const a of aliases) {
+ const alias = typeof a === 'string' ? a.trim() : '';
+ if (alias) tokens.push({ token: alias, owner, ownerName: primary || alias, locked, isAlias: true });
+ }
+ });
+ return tokens;
+}
+
+// How to phrase the rename suggestion given which of the two characters are
+// locked — always steer the author toward renaming an UNLOCKED one (#1291).
+function renameSuggestion(a, b) {
+ const aLabel = a.isAlias ? `${a.token} (alias of ${a.ownerName})` : a.token;
+ const bLabel = b.isAlias ? `${b.token} (alias of ${b.ownerName})` : b.token;
+ if (a.locked && b.locked) {
+ return `Both ${a.ownerName} and ${b.ownerName} are locked — unlock one to rename it so readers can tell them apart.`;
+ }
+ if (a.locked) return `Rename ${b.ownerName} (${a.ownerName} is locked) so it reads less like "${aLabel}".`;
+ if (b.locked) return `Rename ${a.ownerName} (${b.ownerName} is locked) so it reads less like "${bLabel}".`;
+ return `Rename one of ${a.ownerName} / ${b.ownerName} so readers can tell them apart at a glance.`;
}
// ---------------------------------------------------------------------------
@@ -622,15 +655,26 @@ export const EDITORIAL_CHECKS = [
sources: ['canon'],
label: 'Character name dissimilarity',
description:
- 'Flags pairs of character names a reader could confuse — sharing a first letter, length, vowel pattern, opening, or ending.',
+ 'Flags character names a reader could confuse — sharing a first letter, length, vowel pattern, opening, ending, near-identical spelling (edit distance) or phonetic key — plus first-letter crowding across the cast. Reads aliases and respects locked characters.',
scope: 'series',
kind: 'deterministic',
category: 'naming',
severityDefault: 'low',
defaultEnabled: true,
configSchema: z.object({
- // How many similarity signals two names must share before they're flagged.
- minSharedSignals: z.number().int().min(1).max(5).default(2),
+ // How many similarity signals two names must share before they're flagged
+ // (near-identical spelling and a phonetic match also flag on their own).
+ minSharedSignals: z.number().int().min(1).max(7).default(2),
+ // Flag name pairs within this Levenshtein edit distance regardless of the
+ // shared-signal count. 0 disables the edit-distance signal entirely.
+ minEditDistance: z.number().int().min(0).max(3).default(1),
+ // Toggle the individual signals that tend to be noisy on large casts.
+ flagSameLength: z.boolean().default(true),
+ vowelSkeletonCollision: z.boolean().default(true),
+ usePhonetic: z.boolean().default(true),
+ // Flag first-letter crowding when a single starting letter is shared by at
+ // least 3 names AND at least this fraction of the cast (0 disables).
+ maxShareFirstLetterRatio: z.number().min(0).max(1).default(0.4),
}),
configFields: [
{
@@ -638,33 +682,111 @@ export const EDITORIAL_CHECKS = [
label: 'Minimum shared signals to flag',
type: 'number',
min: 1,
- max: 5,
+ max: 7,
+ step: 1,
+ help: 'How many similarity signals (first letter, length, vowel pattern, opening, ending, near-identical spelling, phonetic key) two names must share before they are flagged.',
+ },
+ {
+ key: 'minEditDistance',
+ label: 'Flag within edit distance',
+ type: 'number',
+ min: 0,
+ max: 3,
step: 1,
- help: 'How many similarity signals (first letter, length, vowel pattern, opening, ending) two names must share before they are flagged.',
+ help: 'Always flag name pairs within this many single-character edits (e.g. Alina / Alana = 1). 0 turns the edit-distance signal off.',
+ },
+ {
+ key: 'flagSameLength',
+ label: 'Treat equal length as a signal',
+ type: 'boolean',
+ help: 'Count two names of the same length as one similarity signal (noisy on large casts — turn off to ignore).',
+ },
+ {
+ key: 'vowelSkeletonCollision',
+ label: 'Treat shared vowel pattern as a signal',
+ type: 'boolean',
+ help: 'Count names with the same ordered vowels (Blake / Jane → a-e) as one similarity signal.',
+ },
+ {
+ key: 'usePhonetic',
+ label: 'Treat phonetic match as a signal',
+ type: 'boolean',
+ help: 'Count names that sound alike (same Soundex key, e.g. Smith / Smyth) as a similarity signal.',
+ },
+ {
+ key: 'maxShareFirstLetterRatio',
+ label: 'First-letter crowding ratio',
+ type: 'number',
+ min: 0,
+ max: 1,
+ step: 0.05,
+ help: 'Flag a starting letter shared by ≥3 names when they make up at least this fraction of the cast. 0 disables the crowding check.',
},
],
run: (ctx) => {
- const min = ctx.config?.minSharedSignals ?? 2;
- const names = (ctx.canon?.characters || [])
- .map((c) => (typeof c?.name === 'string' ? c.name.trim() : ''))
- .filter(Boolean);
+ const cfg = ctx.config || {};
+ const min = cfg.minSharedSignals ?? 2;
+ const signalOpts = {
+ minEditDistance: cfg.minEditDistance ?? 1,
+ flagSameLength: cfg.flagSameLength !== false,
+ vowelSkeletonCollision: cfg.vowelSkeletonCollision !== false,
+ usePhonetic: cfg.usePhonetic !== false,
+ };
+ const tokens = castNameTokens(ctx);
const findings = [];
- for (let i = 0; i < names.length; i += 1) {
- for (let j = i + 1; j < names.length; j += 1) {
- if (names[i].toLowerCase() === names[j].toLowerCase()) continue;
- const signals = nameSimilaritySignals(names[i], names[j]);
+
+ // Pairwise confusability over name + alias tokens (skip same-owner pairs).
+ for (let i = 0; i < tokens.length; i += 1) {
+ for (let j = i + 1; j < tokens.length; j += 1) {
+ const a = tokens[i];
+ const b = tokens[j];
+ if (a.owner === b.owner) continue;
+ const signals = nameSimilaritySignals(a.token, b.token, signalOpts);
+ // The user-controlled shared-signal count is the single gate (edit
+ // distance and phonetic match are already among the counted signals).
if (signals.length < min) continue;
+ const dist = signalOpts.minEditDistance > 0 ? levenshtein(a.token, b.token) : Infinity;
+ const phonetic = signalOpts.usePhonetic && soundex(a.token) !== '' && soundex(a.token) === soundex(b.token);
+ // Severity scales with how confusable the pair really is, above the
+ // check's low floor: edit distance ≤1 is a near-typo (escalate 2), a
+ // phonetic match or 4+ signals is strong (escalate 1).
+ const steps = dist <= 1 ? 2 : (phonetic || signals.length >= 4 ? 1 : 0);
findings.push({
- severity: ctx.severityDefault,
+ severity: escalateSeverity(ctx.severityDefault, steps),
category: 'naming',
- location: `Characters: ${names[i]} / ${names[j]}`,
- problem: `Character names "${names[i]}" and "${names[j]}" are easy to confuse (${signals.join(', ')}).`,
- suggestion: 'Rename one of these characters so readers can tell them apart at a glance.',
- anchorQuote: names[i],
+ location: `Characters: ${a.ownerName} / ${b.ownerName}`,
+ problem: `Character names "${a.token}"${a.isAlias ? ` (alias of ${a.ownerName})` : ''} and "${b.token}"${b.isAlias ? ` (alias of ${b.ownerName})` : ''} are easy to confuse (${signals.join(', ')}).`,
+ suggestion: renameSuggestion(a, b),
+ anchorQuote: a.token,
issueNumber: null,
});
}
}
+
+ // First-letter crowding across the cast — severity scaled by how much of the
+ // cast clusters on one starting letter (#1291's "2 of 30 is fine, 4 of 6 is not").
+ const ratio = cfg.maxShareFirstLetterRatio ?? 0.4;
+ if (ratio > 0) {
+ const primaries = tokens.filter((t) => !t.isAlias);
+ const byOwner = new Map(primaries.map((t) => [t.token, t]));
+ const clusters = findFirstLetterClusters(primaries.map((t) => t.token), { minCount: 3, maxRatio: ratio });
+ for (const cluster of clusters) {
+ const unlocked = cluster.names.filter((n) => !byOwner.get(n)?.locked);
+ const renameHint = unlocked.length
+ ? `Consider renaming some of the unlocked ones (${unlocked.join(', ')}) so the cast doesn't blur together.`
+ : 'All of these are locked — unlock one to rename it so the cast doesn\'t blur together.';
+ findings.push({
+ severity: escalateSeverity(ctx.severityDefault, cluster.ratio >= 0.5 ? 2 : 1),
+ category: 'naming',
+ location: `Characters starting with "${cluster.letter.toUpperCase()}"`,
+ problem: `${cluster.names.length} of ${primaries.length} character names start with "${cluster.letter.toUpperCase()}" (${cluster.names.join(', ')}) — readers can confuse names that all open the same way.`,
+ suggestion: renameHint,
+ anchorQuote: cluster.names[0],
+ issueNumber: null,
+ });
+ }
+ }
+
return findings;
},
},
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index a1cba32cf4..222904e4f7 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -174,7 +174,7 @@ describe('editorial check registry — config + state resolution', () => {
const naming = rows.find((r) => r.id === NAMING);
expect(Array.isArray(naming.configFields)).toBe(true);
const field = naming.configFields.find((f) => f.key === 'minSharedSignals');
- expect(field).toMatchObject({ type: 'number', min: 1, max: 5 });
+ expect(field).toMatchObject({ type: 'number', min: 1, max: 7 });
expect(field.label).toBeTruthy();
// Every declared config field is renderable (key + label + known type).
for (const row of rows) {
@@ -301,6 +301,71 @@ describe('naming.dissimilar-names — deterministic check', () => {
expect(run([])).toEqual([]);
expect(run([{}, { name: '' }])).toEqual([]);
});
+
+ it('compares aliases against other characters\' names', () => {
+ const findings = run([
+ { id: 'a', name: 'Alina', aliases: ['Lina'] },
+ { id: 'b', name: 'Tina' },
+ ]);
+ // "Lina" (alias of Alina) vs "Tina" — same length, vowel pattern, ending, edit distance 1.
+ const aliasFinding = findings.find((f) => f.problem.includes('Lina') && f.problem.includes('Tina'));
+ expect(aliasFinding).toBeTruthy();
+ expect(aliasFinding.problem).toMatch(/alias of Alina/);
+ });
+
+ it('does not pair a character\'s own name with its own alias', () => {
+ const findings = run([{ id: 'a', name: 'Robert', aliases: ['Rupert'] }]);
+ // Robert/Rupert share a phonetic key + signals, but they are the SAME character.
+ expect(findings).toEqual([]);
+ });
+
+ it('steers the rename suggestion toward the unlocked character', () => {
+ const findings = run([
+ { id: 'a', name: 'Alina', locked: true },
+ { id: 'b', name: 'Alana', locked: false },
+ ]);
+ expect(findings.length).toBeGreaterThan(0);
+ expect(findings[0].suggestion).toMatch(/Rename Alana/);
+ expect(findings[0].suggestion).toMatch(/Alina is locked/);
+ });
+
+ it('notes when both confusable characters are locked', () => {
+ const findings = run([
+ { id: 'a', name: 'Alina', locked: true },
+ { id: 'b', name: 'Alana', locked: true },
+ ]);
+ expect(findings[0].suggestion).toMatch(/both .*locked/i);
+ });
+
+ it('escalates severity for near-identical (edit-distance-1) names above the low floor', () => {
+ const findings = run([{ name: 'Alina' }, { name: 'Alana' }]);
+ expect(findings[0].severity).toBe('high'); // edit distance 1 → escalate 2 ranks from low
+ });
+
+ it('flags first-letter crowding scaled by cast size (4 of 6), not a sparse 2 of 30', () => {
+ const crowded = run([
+ { name: 'Sam' }, { name: 'Sid' }, { name: 'Sky' }, { name: 'Sue' },
+ { name: 'Bree' }, { name: 'Tom' },
+ ]);
+ const cluster = crowded.find((f) => f.location.startsWith('Characters starting with'));
+ expect(cluster).toBeTruthy();
+ expect(cluster.problem).toMatch(/start with "S"/);
+ expect(cluster.severity).toBe('high'); // 4/6 ≥ 0.5
+
+ const sparse = run([
+ { name: 'Mike' }, { name: 'Mark' },
+ ...Array.from({ length: 28 }, (_, i) => ({ name: `${'abcdefghijklnopqrstuvwxyz'[i % 25]}ame${i}` })),
+ ]);
+ expect(sparse.find((f) => f.location.startsWith('Characters starting with'))).toBeFalsy();
+ });
+
+ it('disables first-letter crowding when the ratio is set to 0', () => {
+ const findings = run(
+ [{ name: 'Sam' }, { name: 'Sid' }, { name: 'Sky' }],
+ { minSharedSignals: 2, maxShareFirstLetterRatio: 0 },
+ );
+ expect(findings.find((f) => f.location.startsWith('Characters starting with'))).toBeFalsy();
+ });
});
describe('relationships.reciprocity — deterministic check', () => {
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index cc454619ef..d5a303cc44 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -1,3 +1,4 @@
// Barrel for server/lib/editorial/ — the extensible editorial-check registry
// (#1284). See README.md for the catalog. Re-export every public module here.
export * from './checkRegistry.js';
+export * from './nameSimilarity.js';
diff --git a/server/lib/editorial/nameSimilarity.js b/server/lib/editorial/nameSimilarity.js
new file mode 100644
index 0000000000..947510869e
--- /dev/null
+++ b/server/lib/editorial/nameSimilarity.js
@@ -0,0 +1,143 @@
+// Pure, dependency-free helpers for the `naming.dissimilar-names` editorial
+// check (#1291). Everything here operates on plain strings so it can be unit
+// tested in isolation and reused by any check that needs to reason about how
+// confusable two character names are. No imports — keeps the registry pure.
+
+// Lowercased letters only ("O'Brien" → "obrien"), the canonical form every
+// similarity signal compares against.
+export const normalizeName = (s) => String(s || '').toLowerCase().replace(/[^a-z]/g, '');
+
+// The ordered vowel skeleton ("Rachel" → "ae"). Two names sharing this read as
+// rhythmically similar even when the consonants differ (Blake / Jane → "ae").
+export const vowelSkeleton = (s) => normalizeName(s).replace(/[^aeiou]/g, '');
+
+// Classic Soundex phonetic key (e.g. "Smith"/"Smyth" → "S530"). A cheap stand-in
+// for full double-metaphone that needs no dependency: two names with the same key
+// sound alike enough to be confused when read aloud. Returns '' for input with no
+// letters so a nameless entry never collides with another.
+const SOUNDEX_CODES = {
+ b: '1', f: '1', p: '1', v: '1',
+ c: '2', g: '2', j: '2', k: '2', q: '2', s: '2', x: '2', z: '2',
+ d: '3', t: '3',
+ l: '4',
+ m: '5', n: '5',
+ r: '6',
+};
+
+export function soundex(s) {
+ const letters = normalizeName(s);
+ if (!letters) return '';
+ const first = letters[0];
+ // Code every letter; vowels and h/w/y are separators (undefined → no digit).
+ const codes = [...letters].map((ch) => SOUNDEX_CODES[ch]);
+ let out = '';
+ // Walk from the second letter, collapsing runs of the same digit. A separator
+ // (vowel / h / w / y) breaks a run so two same-coded consonants split by a vowel
+ // are kept (per the standard algorithm). The first letter's own code is dropped
+ // but still seeds the "previous code" so an immediately-following same-coded
+ // consonant collapses into it.
+ let prev = codes[0];
+ for (let i = 1; i < letters.length && out.length < 3; i += 1) {
+ const code = codes[i];
+ if (code && code !== prev) out += code;
+ // Vowels/h/w/y (undefined code) reset the run so a later same digit can re-emit;
+ // a same-coded consonant run collapses (prev stays set).
+ prev = code === undefined ? undefined : code;
+ }
+ return (first + out).padEnd(4, '0').toUpperCase();
+}
+
+// Levenshtein edit distance — the minimum single-character insert/delete/substitute
+// edits to turn `a` into `b`. Operates on the normalized forms so casing and
+// punctuation don't inflate the distance. O(min(a,b)) space.
+export function levenshtein(a, b) {
+ const s = normalizeName(a);
+ const t = normalizeName(b);
+ if (s === t) return 0;
+ if (!s.length) return t.length;
+ if (!t.length) return s.length;
+ let prev = Array.from({ length: t.length + 1 }, (_, i) => i);
+ let curr = new Array(t.length + 1);
+ for (let i = 1; i <= s.length; i += 1) {
+ curr[0] = i;
+ for (let j = 1; j <= t.length; j += 1) {
+ const cost = s[i - 1] === t[j - 1] ? 0 : 1;
+ curr[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
+ }
+ [prev, curr] = [curr, prev];
+ }
+ return prev[t.length];
+}
+
+// Default thresholds for `nameSimilaritySignals` — mirrored by the registry
+// check's configSchema defaults so the helper is usable standalone with sensible
+// behavior and the UI knobs map 1:1 onto these option keys.
+export const DEFAULT_SIGNAL_OPTS = Object.freeze({
+ minEditDistance: 1, // flag pairs within this Levenshtein distance (0 disables)
+ flagSameLength: true,
+ vowelSkeletonCollision: true,
+ usePhonetic: true,
+});
+
+// The confusability signals two names share. Each present signal is one reason a
+// reader could blur the two on the page; the registry check counts them (plus the
+// strong standalone signals — near-identical spelling and phonetic match — which
+// also drive severity). Returns [] when either name has no letters.
+export function nameSimilaritySignals(a, b, opts = {}) {
+ const { minEditDistance, flagSameLength, vowelSkeletonCollision, usePhonetic } = {
+ ...DEFAULT_SIGNAL_OPTS,
+ ...opts,
+ };
+ const la = normalizeName(a);
+ const lb = normalizeName(b);
+ if (!la || !lb || la === lb) return [];
+ const signals = [];
+ if (la[0] === lb[0]) signals.push('same first letter');
+ if (flagSameLength && la.length === lb.length) signals.push('same length');
+ if (vowelSkeletonCollision) {
+ const vsa = vowelSkeleton(a);
+ if (vsa && vsa === vowelSkeleton(b)) signals.push('same vowel pattern');
+ }
+ if (la.length >= 3 && lb.length >= 3 && la.slice(0, 3) === lb.slice(0, 3)) signals.push('same opening');
+ if (la.length >= 2 && la.slice(-2) === lb.slice(-2)) signals.push('same ending');
+ if (minEditDistance > 0) {
+ const dist = levenshtein(la, lb);
+ if (dist <= minEditDistance) signals.push(`near-identical spelling (edit distance ${dist})`);
+ }
+ if (usePhonetic) {
+ const ka = soundex(a);
+ if (ka && ka === soundex(b)) signals.push('same phonetic key');
+ }
+ return signals;
+}
+
+// A first-letter histogram over a list of names: Map<letter, name[]> keyed by the
+// lowercased first letter (entries with no letters are skipped). The check uses
+// this to spot first-letter crowding — a cast where many names start the same way.
+export function firstLetterHistogram(names) {
+ const hist = new Map();
+ for (const name of names) {
+ const norm = normalizeName(name);
+ if (!norm) continue;
+ const letter = norm[0];
+ if (!hist.has(letter)) hist.set(letter, []);
+ hist.get(letter).push(name);
+ }
+ return hist;
+}
+
+// First-letter clusters worth flagging: letters shared by at least `minCount`
+// names AND by at least `maxRatio` of the cast. Returns [{ letter, names, ratio }]
+// sorted densest-first so the worst crowding surfaces as the first finding.
+export function findFirstLetterClusters(names, { minCount = 3, maxRatio = 0.4 } = {}) {
+ const total = names.filter((n) => normalizeName(n)).length;
+ if (!total) return [];
+ const clusters = [];
+ for (const [letter, group] of firstLetterHistogram(names)) {
+ const ratio = group.length / total;
+ if (group.length >= minCount && ratio >= maxRatio) {
+ clusters.push({ letter, names: group, ratio });
+ }
+ }
+ return clusters.sort((x, y) => y.ratio - x.ratio || y.names.length - x.names.length);
+}
diff --git a/server/lib/editorial/nameSimilarity.test.js b/server/lib/editorial/nameSimilarity.test.js
new file mode 100644
index 0000000000..07e7be3034
--- /dev/null
+++ b/server/lib/editorial/nameSimilarity.test.js
@@ -0,0 +1,145 @@
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeName,
+ vowelSkeleton,
+ soundex,
+ levenshtein,
+ nameSimilaritySignals,
+ firstLetterHistogram,
+ findFirstLetterClusters,
+} from './nameSimilarity.js';
+
+describe('normalizeName', () => {
+ it('lowercases and strips non-letters', () => {
+ expect(normalizeName("O'Brien")).toBe('obrien');
+ expect(normalizeName('Anne-Marie')).toBe('annemarie');
+ expect(normalizeName(' Zoë 3 ')).toBe('zo'); // diacritics + digits dropped
+ });
+ it('tolerates empty / nullish input', () => {
+ expect(normalizeName('')).toBe('');
+ expect(normalizeName(null)).toBe('');
+ expect(normalizeName(undefined)).toBe('');
+ });
+});
+
+describe('vowelSkeleton', () => {
+ it('keeps only the ordered vowels', () => {
+ expect(vowelSkeleton('Rachel')).toBe('ae');
+ expect(vowelSkeleton('Blake')).toBe('ae');
+ expect(vowelSkeleton('Jane')).toBe('ae');
+ expect(vowelSkeleton('Zog')).toBe('o');
+ });
+ it('returns empty when there are no vowels', () => {
+ expect(vowelSkeleton('Bryn')).toBe('');
+ });
+});
+
+describe('soundex', () => {
+ it('matches known classic Soundex codes', () => {
+ expect(soundex('Robert')).toBe('R163');
+ expect(soundex('Rupert')).toBe('R163');
+ expect(soundex('Smith')).toBe('S530');
+ expect(soundex('Smyth')).toBe('S530');
+ expect(soundex('Tymczak')).toBe('T522');
+ expect(soundex('Pfister')).toBe('P236'); // adjacent same-code (p/f) collapses
+ });
+ it('pads short names to four chars', () => {
+ expect(soundex('Sam')).toBe('S500');
+ expect(soundex('Sun')).toBe('S500'); // Sam and Sun share a phonetic key
+ expect(soundex('Lee')).toBe('L000');
+ });
+ it('returns empty for letterless input so it never collides', () => {
+ expect(soundex('')).toBe('');
+ expect(soundex('123')).toBe('');
+ });
+});
+
+describe('levenshtein', () => {
+ it('counts single-character edits on the normalized form', () => {
+ expect(levenshtein('Alina', 'Alana')).toBe(1); // one substitution
+ expect(levenshtein('John', 'Jon')).toBe(1); // one deletion
+ expect(levenshtein('Sam', 'Sun')).toBe(2); // two substitutions
+ expect(levenshtein('kitten', 'sitting')).toBe(3);
+ });
+ it('is zero for equal (normalized) names and handles empties', () => {
+ expect(levenshtein('Bo', 'bo')).toBe(0);
+ expect(levenshtein('', 'abc')).toBe(3);
+ expect(levenshtein('abc', '')).toBe(3);
+ });
+});
+
+describe('nameSimilaritySignals', () => {
+ it('detects each signal type', () => {
+ expect(nameSimilaritySignals('Sam', 'Sid')).toContain('same first letter');
+ expect(nameSimilaritySignals('Sam', 'Tom', { vowelSkeletonCollision: false })).toContain('same length');
+ expect(nameSimilaritySignals('Blake', 'Jane')).toContain('same vowel pattern');
+ expect(nameSimilaritySignals('Marcus', 'Marvin')).toContain('same opening'); // "mar"
+ expect(nameSimilaritySignals('Brian', 'Ian')).toContain('same ending'); // "an"
+ expect(nameSimilaritySignals('Alina', 'Alana')).toContain('near-identical spelling (edit distance 1)');
+ expect(nameSimilaritySignals('Smith', 'Smyth')).toContain('same phonetic key');
+ });
+
+ it('returns no signals for clearly distinct names', () => {
+ expect(nameSimilaritySignals('Zog', 'Bree')).toEqual([]);
+ });
+
+ it('returns no signals when a name has no letters or names are equal', () => {
+ expect(nameSimilaritySignals('', 'Sam')).toEqual([]);
+ expect(nameSimilaritySignals('Sam', 'sam')).toEqual([]);
+ });
+
+ it('honors the option toggles', () => {
+ // flagSameLength off removes the length signal (Sam/Tim are both length 3)
+ expect(nameSimilaritySignals('Sam', 'Tim')).toContain('same length');
+ expect(nameSimilaritySignals('Sam', 'Tim', { flagSameLength: false })).not.toContain('same length');
+ // vowelSkeletonCollision off removes the vowel signal
+ expect(nameSimilaritySignals('Blake', 'Jane', { vowelSkeletonCollision: false })).not.toContain('same vowel pattern');
+ // usePhonetic off removes the phonetic signal
+ expect(nameSimilaritySignals('Smith', 'Smyth', { usePhonetic: false })).not.toContain('same phonetic key');
+ // minEditDistance 0 disables the edit-distance signal
+ expect(nameSimilaritySignals('Alina', 'Alana', { minEditDistance: 0 }))
+ .not.toContain('near-identical spelling (edit distance 1)');
+ });
+});
+
+describe('firstLetterHistogram', () => {
+ it('buckets names by their first normalized letter', () => {
+ const hist = firstLetterHistogram(['Mike', 'Mark', 'Matt', 'Zog', "'Aaron"]);
+ expect(hist.get('m')).toEqual(['Mike', 'Mark', 'Matt']);
+ expect(hist.get('z')).toEqual(['Zog']);
+ expect(hist.get('a')).toEqual(["'Aaron"]); // leading punctuation stripped
+ });
+ it('skips letterless names', () => {
+ const hist = firstLetterHistogram(['123', '', 'Bo']);
+ expect([...hist.keys()]).toEqual(['b']);
+ });
+});
+
+describe('findFirstLetterClusters', () => {
+ it('flags a letter shared by enough of the cast', () => {
+ const cast = ['Mike', 'Mark', 'Matt', 'Zog', 'Bree', 'Tom'];
+ const clusters = findFirstLetterClusters(cast, { minCount: 3, maxRatio: 0.4 });
+ expect(clusters).toHaveLength(1);
+ expect(clusters[0].letter).toBe('m');
+ expect(clusters[0].names).toEqual(['Mike', 'Mark', 'Matt']);
+ expect(clusters[0].ratio).toBeCloseTo(0.5);
+ });
+ it('does not flag a sparse first-letter share in a large cast (2 of 30)', () => {
+ // 2 names start with M; the other 28 spread across 25 non-M letters (3 letters
+ // doubled), so no letter is both shared by ≥3 names and ≥40% of the cast.
+ const letters = 'abcdefghijklnopqrstuvwxyz'.split(''); // 25 letters, no 'm'
+ const others = Array.from({ length: 28 }, (_, i) => `${letters[i % letters.length]}ame${i}`);
+ const cast = ['Mike', 'Mark', ...others];
+ expect(cast).toHaveLength(30);
+ expect(findFirstLetterClusters(cast, { minCount: 3, maxRatio: 0.4 })).toEqual([]);
+ });
+ it('flags dense crowding (4 of 6) and sorts densest first', () => {
+ const cast = ['Sam', 'Sid', 'Sue', 'Sky', 'Bree', 'Tom'];
+ const clusters = findFirstLetterClusters(cast, { minCount: 3, maxRatio: 0.4 });
+ expect(clusters[0].letter).toBe('s');
+ expect(clusters[0].names).toHaveLength(4);
+ });
+ it('returns nothing for an empty cast', () => {
+ expect(findFirstLetterClusters([])).toEqual([]);
+ });
+});