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-1312]): cast representation & balance editorial check

Adam Eivy7c02273c602a
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index 0089148f02..a21f7097df 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -114,6 +114,6 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `proseTics.js` | Pure, dependency-free copy-edit prose-tic primitives for the #1306 line-edit group: `tokenizeWords` / `splitSentences` (shared tokenization), `findFilterWords` (`prose.filter-words`), `findCrutchWords` (`prose.crutch-words`), `findAdverbs` (`prose.adverbs` — `-ly` adverbs + dialogue-tag adverbs), `findPassiveVoice` (`prose.passive-voice` — be-verb + past-participle heuristic), `findGestures` (`prose.repeated-gestures` — gesture tally + body-part autonomy), plus the seed `FILTER_WORDS` / `CRUTCH_WORDS` / `GESTURE_WORDS` lists. The LLM sibling `prose.telling-emotion` handles the named-emotion judgment case. |
| `repetition.js` | Pure, dependency-free word-echo & rhythm primitives for #1306: `findWordEchoes` (`prose.word-echoes` — distinctive word repeated within a window), `findRepeatedOpeners` (runs of sentences sharing an opener, "He… He… He…"), and `measureSentenceRhythm` (`prose.sentence-rhythm` — sentence-length variation). Reuses `tokenizeWords` / `splitSentences` from `proseTics.js`. |
| `shotContinuity.js` | Pure, dependency-free storyboard shot-continuity primitives for the deterministic `visual.shot-continuity` check (#1315): `findAxisReversals` (180°-rule axis flips across a continuity-linked shot pair using `screenDirection`) and `findShotTypeMonotony` (a scene whose classified shots all share one `shotType`). Reads the shot-grammar fields from `server/lib/shotGrammar.js`. The judgment cases (eyeline match, appearance/prop continuity) are LLM-sibling follow-ups. |
-| `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. |
+| `dialogue.js` | Pure, dependency-free dialogue-tag primitives for the #1307 dialogue-craft group: `findSaidBookisms` (`dialogue.said-bookisms` — ornate speech tags like *expostulated*/*opined* and non-speech tags like "she smiled", matched only when adjacent to a double-quote span) and `findUnattributedDialogueRuns` (`dialogue.attribution-clarity` — runs of consecutive untagged/unbeated dialogue lines where the speaker can't be tracked), plus `attributeDialogueByOwner` (the coarse per-character dialogue-line tally behind `cast.representation-balance`'s dialogue-share signal, #1312 — credits each quoted paragraph to the first owner named in its beat) and the seed `SAID_BOOKISMS` / `NON_SPEECH_TAGS` lists. The LLM siblings `dialogue.on-the-nose` (subtext-free / "as you know, Bob" dialogue) and `dialogue.voice-distinctiveness` (per-character voice against canon `speechPattern`/`speechAccent`) handle the judgment cases. |
| `letteringDensity.js` | Pure, dependency-free comic lettering-density primitives for `comic.lettering-density` (#1313): `countWords`, `panelLetteringMetrics` (per-panel balloon/caption/SFX word + balloon tally over the `comicScriptParser` output), `analyzeComicLettering` (flags balloons/panels/pages over the configurable thresholds in `DEFAULT_LETTERING_THRESHOLDS`), `overflowSeverity` (severity scaled by how far over the limit), and `sanitizeLetteringThresholds`. Mirrored to `client/src/lib/letteringDensity.js` for the comic-script stage's inline warnings — keep the two in sync. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 1c4a3c2e95..ad6335fd4e 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -34,7 +34,7 @@ import {
} from './letteringDensity.js';
import { analyzeNamePair, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';
import { findCliches, findModifierStacking } from './cliches.js';
-import { findSaidBookisms, findUnattributedDialogueRuns } from './dialogue.js';
+import { findSaidBookisms, findUnattributedDialogueRuns, attributeDialogueByOwner } from './dialogue.js';
import { findItalicThoughts } from './italicThoughts.js';
import {
findFilterWords,
@@ -1020,6 +1020,82 @@ function buildRosterAppearances(ctx) {
return rows;
}
+// ---------------------------------------------------------------------------
+// Cast representation & balance (#1312) — three coarse, computable casting
+// signals over the canon + reverse-outline + stitched manuscript:
+// 1) Bechdel co-presence — does ANY scene put two+ non-male characters
+// together (the structural precondition for two women talking)? Computed
+// from the reverse-outline's per-scene charactersPresent against
+// pronoun-inferred gender. A coarse signal, not the full Bechdel test
+// (we can't read whether the conversation is about a man deterministically).
+// 2) Dialogue share — does one character dominate the spoken lines? Counts
+// attributed dialogue paragraphs per character (attributeDialogueByOwner)
+// and flags a lopsided distribution (top speaker over a configurable share).
+// 3) Screen-time balance — when gender is inferable, flag a strongly skewed
+// appearing cast (e.g. a near-all-male roster) as a representation nudge.
+//
+// All three are advisory (low/medium): representation is an authorial choice and
+// these are signals, not correctness errors. Gender is inferred ONLY from the
+// canon `pronouns` field — absent/ambiguous pronouns yield 'unknown', and the
+// gender-dependent signals stay silent rather than guess (absent ≠ a category).
+// ---------------------------------------------------------------------------
+
+// Infer a coarse gender bucket from a character's canon `pronouns` string. Only
+// the unambiguous subject/object pronoun sets map; anything else (neopronouns,
+// "any", blank, a sentence) is 'unknown' so a gender-dependent signal can opt
+// out rather than miscategorize. Returns 'female' | 'male' | 'nonbinary' | 'unknown'.
+function inferGender(pronouns) {
+ const p = typeof pronouns === 'string' ? pronouns.toLowerCase() : '';
+ if (!p) return 'unknown';
+ const has = (re) => re.test(p);
+ const she = has(/\bshe\b/) || has(/\bher\b/) || has(/\bhers\b/);
+ const he = has(/\bhe\b/) || has(/\bhim\b/) || has(/\bhis\b/);
+ const they = has(/\bthey\b/) || has(/\bthem\b/) || has(/\btheir\b/);
+ // A clean single set wins; a mixed string ("she/they") is ambiguous → unknown,
+ // except she+they / he+they which still read as a definite female/male identity
+ // with a secondary set. Both she AND he present is genuinely ambiguous.
+ if (she && he) return 'unknown';
+ if (she) return 'female';
+ if (he) return 'male';
+ if (they) return 'nonbinary';
+ return 'unknown';
+}
+
+// Normalized name → { char, gender, key } for every named canon character, plus
+// the per-owner whole-token matcher reused for dialogue attribution. Built once
+// per run so the dialogue scan and the co-presence scan share one identity map.
+function buildCastIdentities(ctx) {
+ const chars = Array.isArray(ctx.canon?.characters) ? ctx.canon.characters : [];
+ const identities = [];
+ for (const c of chars) {
+ if (!c || typeof c !== 'object') continue;
+ const name = typeof c.name === 'string' ? c.name.trim() : '';
+ if (!name) continue;
+ const key = normalizeName(name);
+ if (!key) continue;
+ const matcher = characterMatcher(characterNameTokens(c));
+ identities.push({ key, name, gender: inferGender(c.pronouns), matcher });
+ }
+ return identities;
+}
+
+// Resolve a scene's charactersPresent names to canon identity keys (so a scene
+// that lists "Bob" maps to canonical "Robert"). A present name that matches no
+// canon character is dropped — the co-presence signal is canon-relative.
+function sceneCastKeys(scene, identityByKey, identities) {
+ const present = Array.isArray(scene?.charactersPresent) ? scene.charactersPresent : [];
+ const keys = new Set();
+ for (const raw of present) {
+ if (typeof raw !== 'string' || !raw.trim()) continue;
+ const direct = identityByKey.get(normalizeName(raw));
+ if (direct) { keys.add(direct.key); continue; }
+ // Fall back to a token match (the present-name might be an alias surface form).
+ const hit = identities.find((id) => id.matcher && id.matcher.test(raw));
+ if (hit) keys.add(hit.key);
+ }
+ return keys;
+}
+
// ---------------------------------------------------------------------------
// Scene component balance (#1296) — reads the cached reverse-outline (#1286)
// scene segmentation, where each scene carries a `components` boolean signal
@@ -1738,6 +1814,188 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'cast.representation-balance',
+ sources: ['manuscript', 'canon', 'reverseOutline'],
+ label: 'Cast representation & balance (Bechdel signal, dialogue share, screen time)',
+ description:
+ 'Three coarse, computable casting signals: a Bechdel co-presence signal (does any scene put two or more non-male characters on the page together?), dialogue share (does one character dominate the spoken lines?), and screen-time balance (is the appearing named cast strongly skewed by inferred gender?). Gender is inferred only from the canon pronouns field — characters with absent or ambiguous pronouns are left out of the gender-dependent signals rather than guessed. Advisory: representation is an authorial choice, so these are nudges, not errors.',
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'casting',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript (per-issue sections) for the dialogue-share
+ // scan — so the runner only pays the section-collection I/O when enabled.
+ needsManuscript: true,
+ configSchema: z.object({
+ // Flag dialogue share when the top speaker holds more than this fraction of
+ // all attributed dialogue lines (and there are 2+ speakers). 1 disables it.
+ maxDialogueShare: z.number().min(0.1).max(1).default(0.6),
+ // Minimum attributed dialogue lines before the share check runs — a handful
+ // of lines isn't a meaningful distribution. 0 keeps the floor at 1.
+ minDialogueLines: z.number().int().min(0).max(500).default(12),
+ // Flag screen-time skew when one gender holds more than this fraction of the
+ // gender-known appearing cast (and 2+ are gender-known). 1 disables it.
+ maxGenderShare: z.number().min(0.1).max(1).default(0.8),
+ // Run the Bechdel co-presence signal (any scene with 2+ non-male characters).
+ bechdelSignal: z.boolean().default(true),
+ }),
+ configFields: [
+ {
+ key: 'maxDialogueShare',
+ label: 'Max dialogue share for one speaker',
+ type: 'number',
+ min: 0.1,
+ max: 1,
+ step: 0.05,
+ help: 'Flag when the top speaker holds more than this fraction of all attributed dialogue lines (with 2+ speakers). 1 disables the dialogue-share check.',
+ },
+ {
+ key: 'minDialogueLines',
+ label: 'Minimum attributed dialogue lines',
+ type: 'number',
+ min: 0,
+ max: 500,
+ step: 1,
+ help: 'Skip the dialogue-share check until at least this many dialogue lines can be attributed — a few lines is not a meaningful distribution.',
+ },
+ {
+ key: 'maxGenderShare',
+ label: 'Max screen-time share for one gender',
+ type: 'number',
+ min: 0.1,
+ max: 1,
+ step: 0.05,
+ help: 'Flag when one inferred gender holds more than this fraction of the gender-known appearing cast (with 2+ gender-known characters). 1 disables the screen-time check.',
+ },
+ {
+ key: 'bechdelSignal',
+ label: 'Bechdel co-presence signal',
+ type: 'boolean',
+ help: 'Flag when no scene puts two or more non-male characters on the page together — the structural precondition for the Bechdel test. Needs a reverse outline with charactersPresent.',
+ },
+ ],
+ // Need at least one named canon character to scan for; the per-signal gates
+ // (manuscript for dialogue, outline for Bechdel) are decided inside run().
+ gate: (ctx) => Array.isArray(ctx.canon?.characters)
+ && ctx.canon.characters.some((c) => typeof c?.name === 'string' && c.name.trim()),
+ run: (ctx) => {
+ const cfg = ctx.config || {};
+ const maxDialogueShare = cfg.maxDialogueShare ?? 0.6;
+ const minDialogueLines = Math.max(1, cfg.minDialogueLines ?? 12);
+ const maxGenderShare = cfg.maxGenderShare ?? 0.8;
+ const bechdelSignal = cfg.bechdelSignal !== false;
+
+ const identities = buildCastIdentities(ctx);
+ if (!identities.length) return [];
+ const identityByKey = new Map(identities.map((id) => [id.key, id]));
+ const nameByKey = new Map(identities.map((id) => [id.key, id.name]));
+ const genderByKey = new Map(identities.map((id) => [id.key, id.gender]));
+ const findings = [];
+ const flag = ({ severity, location, problem, suggestion, anchorQuote = '', issueNumber = null }) =>
+ findings.push({ severity, category: 'casting', location, problem, suggestion, anchorQuote, issueNumber });
+
+ // --- 1) Dialogue share ------------------------------------------------
+ // Longest-token-first owners so a beat naming two characters credits the
+ // more specific match first (mirrors characterMatcher's intent).
+ const sections = Array.isArray(ctx.sections) ? ctx.sections : [];
+ const manuscript = sections.map((s) => (typeof s?.content === 'string' ? s.content : '')).join('\n\n');
+ if (maxDialogueShare < 1 && manuscript.trim()) {
+ const owners = identities
+ .filter((id) => id.matcher)
+ .map((id) => ({ key: id.key, matcher: id.matcher }));
+ const { byOwner, attributed } = attributeDialogueByOwner(manuscript, owners);
+ if (attributed >= minDialogueLines && byOwner.size >= 2) {
+ let topKey = null;
+ let topCount = 0;
+ for (const [key, count] of byOwner) {
+ if (count > topCount) { topCount = count; topKey = key; }
+ }
+ const share = topCount / attributed;
+ if (topKey && share > maxDialogueShare) {
+ const pct = Math.round(share * 100);
+ // Escalate above the low floor when one voice utterly dominates (≥80%).
+ flag({
+ severity: escalateSeverity(ctx.severityDefault, share >= 0.8 ? 1 : 0),
+ location: 'Series dialogue',
+ problem: `"${nameByKey.get(topKey)}" speaks about ${pct}% of the attributed dialogue (${topCount} of ${attributed} lines across ${byOwner.size} speaking characters) — one voice dominating the page can flatten the rest of the cast.`,
+ suggestion: `Give other characters more of the conversation, or let scenes play out from a viewpoint where ${nameByKey.get(topKey)} isn't the one talking.`,
+ });
+ }
+ }
+ }
+
+ // --- 2) Bechdel co-presence signal -----------------------------------
+ // The structural precondition: at least one scene with two or more
+ // non-male (female / nonbinary) characters present. Coarse — we can't
+ // deterministically read whether they talk about something other than a
+ // man — so this is a "no scene even has the cast for it" nudge, and it
+ // only fires when gender is actually inferable for the cast.
+ if (bechdelSignal) {
+ const scenes = Array.isArray(ctx.reverseOutline) ? ctx.reverseOutline : [];
+ const scenesWithPresence = scenes.filter(
+ (s) => Array.isArray(s?.charactersPresent) && s.charactersPresent.length > 0
+ );
+ const haveNonMaleKnown = identities.some((id) => id.gender === 'female' || id.gender === 'nonbinary');
+ // Only meaningful when the outline records presence AND the cast has at
+ // least one known non-male character (otherwise "absent" is just unknown
+ // gender, not a representation gap).
+ if (scenesWithPresence.length > 0 && haveNonMaleKnown) {
+ const anyCopresent = scenesWithPresence.some((scene) => {
+ const keys = sceneCastKeys(scene, identityByKey, identities);
+ let nonMale = 0;
+ for (const k of keys) {
+ const g = genderByKey.get(k);
+ if (g === 'female' || g === 'nonbinary') nonMale += 1;
+ if (nonMale >= 2) return true;
+ }
+ return false;
+ });
+ if (!anyCopresent) {
+ flag({
+ severity: ctx.severityDefault,
+ location: 'Series cast',
+ problem: 'No scene puts two or more non-male characters on the page together (per the reverse-outline scene presence) — the structural precondition for the Bechdel test is never met. Two women (or non-male characters) are never in a scene to talk to each other.',
+ suggestion: 'Add at least one scene where two non-male characters share the page and a conversation that isn\'t about a man — or, if the story\'s premise genuinely calls for it, treat this as expected and disable the signal.',
+ });
+ }
+ }
+ }
+
+ // --- 3) Screen-time balance (gender skew) -----------------------------
+ // Over the APPEARING named cast (tied to prose appearances so canon-only
+ // bloat doesn't trip it), is one inferable gender strongly over-represented?
+ if (maxGenderShare < 1) {
+ const rows = buildRosterAppearances(ctx);
+ const appearingKeys = new Set(
+ rows.filter((r) => r.appearedInIssues.length > 0).map((r) => normalizeName(r.name))
+ );
+ const counts = { female: 0, male: 0, nonbinary: 0 };
+ for (const key of appearingKeys) {
+ const g = genderByKey.get(key);
+ if (g === 'female' || g === 'male' || g === 'nonbinary') counts[g] += 1;
+ }
+ const known = counts.female + counts.male + counts.nonbinary;
+ if (known >= 2) {
+ const entries = Object.entries(counts).filter(([, n]) => n > 0);
+ const [topGender, topN] = entries.reduce((a, b) => (b[1] > a[1] ? b : a));
+ const share = topN / known;
+ if (share > maxGenderShare) {
+ const pct = Math.round(share * 100);
+ flag({
+ severity: ctx.severityDefault,
+ location: 'Series cast',
+ problem: `Of the ${known} appearing named characters whose gender is inferable, ${pct}% are ${topGender} (${topN} of ${known}) — a strongly skewed cast. Representation is an authorial choice, but a near-monochrome roster is worth a deliberate look.`,
+ suggestion: 'Consider whether some named roles could be cast more diversely, or confirm the skew is intentional for the story and disable the screen-time signal.',
+ });
+ }
+ }
+ }
+
+ return findings;
+ },
+ },
{
id: 'scene.component-balance',
sources: ['reverseOutline'],
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 004357560e..b26d40071c 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -3071,3 +3071,136 @@ Panel 1
expect(getCheck(COMIC).run(ctx).length).toBeGreaterThan(0);
});
});
+
+describe('cast.representation-balance — deterministic check (#1312)', () => {
+ const REP = 'cast.representation-balance';
+ const sec = (number, content) => ({ number, content });
+ const runRep = (canon, { sections = [], reverseOutline = [], config = {} } = {}) =>
+ getCheck(REP).run({ canon, sections, reverseOutline, config, severityDefault: 'low' });
+ const dialogue = (findings) => findings.find((f) => f.location === 'Series dialogue');
+ const bechdel = (findings) => findings.find((f) => /Bechdel/.test(f.problem));
+ const screenTime = (findings) => findings.find((f) => /strongly skewed cast/.test(f.problem));
+ // Config that silences the two OTHER signals so a test can isolate one.
+ const only = (over) => ({ maxDialogueShare: 1, maxGenderShare: 1, bechdelSignal: false, ...over });
+
+ it('declares the expected scope / kind / sources', () => {
+ const c = getCheck(REP);
+ expect(c.kind).toBe('deterministic');
+ expect(c.scope).toBe('series');
+ expect(c.category).toBe('casting');
+ expect(c.needsManuscript).toBe(true);
+ expect(c.sources).toEqual(expect.arrayContaining(['manuscript', 'canon', 'reverseOutline']));
+ });
+
+ it('flags a dominating speaker by dialogue share', () => {
+ const canon = { characters: [{ name: 'Aria', pronouns: 'she/her' }, { name: 'Bram', pronouns: 'he/him' }] };
+ // 4 Aria lines, 1 Bram line → Aria = 80% of 5 attributed lines.
+ const content = [
+ '"One," said Aria.',
+ '"Two," said Aria.',
+ '"Three," said Aria.',
+ '"Four," said Aria.',
+ '"Five," said Bram.',
+ ].join('\n');
+ const findings = runRep(canon, {
+ sections: [sec(1, content)],
+ config: only({ maxDialogueShare: 0.6, minDialogueLines: 5 }),
+ });
+ const f = dialogue(findings);
+ expect(f).toBeTruthy();
+ expect(f.category).toBe('casting');
+ expect(f.severity).toBe('medium'); // 80% → escalated above the low floor
+ expect(f.problem).toMatch(/"Aria" speaks about 80%/);
+ });
+
+ it('skips the dialogue-share check below the minimum line floor', () => {
+ const canon = { characters: [{ name: 'Aria' }, { name: 'Bram' }] };
+ const content = '"Hi," said Aria.\n"Hey," said Bram.';
+ const findings = runRep(canon, {
+ sections: [sec(1, content)],
+ config: only({ maxDialogueShare: 0.4, minDialogueLines: 12 }),
+ });
+ expect(dialogue(findings)).toBeUndefined();
+ });
+
+ it('flags a missing Bechdel co-presence signal when no scene pairs non-male characters', () => {
+ const canon = {
+ characters: [
+ { name: 'Aria', pronouns: 'she/her' },
+ { name: 'Mara', pronouns: 'she/her' },
+ { name: 'Bram', pronouns: 'he/him' },
+ ],
+ };
+ // Aria only ever shares the page with Bram; Aria + Mara never co-present.
+ const reverseOutline = [
+ { heading: 'S1', charactersPresent: ['Aria', 'Bram'] },
+ { heading: 'S2', charactersPresent: ['Mara', 'Bram'] },
+ ];
+ const findings = runRep(canon, { reverseOutline, config: only({ bechdelSignal: true }) });
+ expect(bechdel(findings)).toBeTruthy();
+ });
+
+ it('passes the Bechdel signal when two non-male characters share a scene', () => {
+ const canon = {
+ characters: [
+ { name: 'Aria', pronouns: 'she/her' },
+ { name: 'Mara', pronouns: 'they/them' },
+ ],
+ };
+ const reverseOutline = [{ heading: 'S1', charactersPresent: ['Aria', 'Mara'] }];
+ const findings = runRep(canon, { reverseOutline, config: only({ bechdelSignal: true }) });
+ expect(bechdel(findings)).toBeUndefined();
+ });
+
+ it('stays silent on Bechdel when no scene presence is recorded', () => {
+ const canon = { characters: [{ name: 'Aria', pronouns: 'she/her' }, { name: 'Mara', pronouns: 'she/her' }] };
+ const findings = runRep(canon, { reverseOutline: [], config: only({ bechdelSignal: true }) });
+ expect(bechdel(findings)).toBeUndefined();
+ });
+
+ it('flags a strongly gender-skewed appearing cast', () => {
+ const canon = {
+ characters: [
+ { name: 'Al', pronouns: 'he/him' },
+ { name: 'Bo', pronouns: 'he/him' },
+ { name: 'Cy', pronouns: 'he/him' },
+ { name: 'Di', pronouns: 'he/him' },
+ { name: 'Eve', pronouns: 'she/her' },
+ ],
+ };
+ // All five appear; 4/5 = 80% male → over an 80%? No, must EXCEED. Use 0.7.
+ const content = 'Al, Bo, Cy, Di, and Eve all gathered at dawn.';
+ const findings = runRep(canon, {
+ sections: [sec(1, content)],
+ config: only({ maxGenderShare: 0.7 }),
+ });
+ const f = screenTime(findings);
+ expect(f).toBeTruthy();
+ expect(f.problem).toMatch(/80% are male/);
+ });
+
+ it('leaves unknown/ambiguous-pronoun characters out of the gender signals', () => {
+ const canon = {
+ characters: [
+ { name: 'Al', pronouns: 'he/him' },
+ { name: 'Bo' }, // no pronouns → unknown
+ { name: 'Cy', pronouns: 'she/he' }, // ambiguous → unknown
+ ],
+ };
+ const content = 'Al, Bo, and Cy gathered.';
+ // Only Al is gender-known → known < 2 → no screen-time finding.
+ const findings = runRep(canon, { sections: [sec(1, content)], config: only({ maxGenderShare: 0.5 }) });
+ expect(screenTime(findings)).toBeUndefined();
+ });
+
+ it('gate requires at least one named canon character', () => {
+ const c = getCheck(REP);
+ expect(c.gate({ canon: { characters: [] } })).toBeFalsy();
+ expect(c.gate({ canon: { characters: [{ name: 'Aria' }] } })).toBe(true);
+ });
+
+ it('tolerates empty canon / sections / outline without throwing', () => {
+ expect(() => runRep({ characters: [] })).not.toThrow();
+ expect(runRep({ characters: [{}, { name: '' }] }, { sections: [sec(1, 'x')] })).toEqual([]);
+ });
+});
diff --git a/server/lib/editorial/dialogue.js b/server/lib/editorial/dialogue.js
index c868430d83..655eaf32e8 100644
--- a/server/lib/editorial/dialogue.js
+++ b/server/lib/editorial/dialogue.js
@@ -302,3 +302,62 @@ export function findUnattributedDialogueRuns(text, opts = {}) {
flush();
return out;
}
+
+/**
+ * Attribute spoken dialogue paragraphs to the cast for a coarse dialogue-share
+ * signal (cast representation & balance, #1312). For each dialogue paragraph
+ * (one carrying a quoted span) the speaker is inferred from the NON-quoted beat
+ * around the quote — exactly the surface the attribution-clarity scan reads — so
+ * a name spoken INSIDE the dialogue ("I saw Bram") doesn't mis-attribute the
+ * line. A paragraph is credited to the FIRST owner whose token matches the beat;
+ * paragraphs whose speaker can't be resolved (no name/alias in the beat) are
+ * counted as `unattributed` rather than guessed, per the absent-vs-empty rule.
+ *
+ * Deliberately coarse: it measures *who is credited with speaking lines*, not a
+ * precise turn-by-turn transcript. That's the right grain for a balance ratio
+ * (does one character dominate the dialogue?), and it stays pure + dependency-
+ * free — the caller supplies the per-owner matchers it already builds for canon.
+ *
+ * @param {string} text
+ * @param {Array<{ key: string, matcher: RegExp }>} owners
+ * one entry per character; `matcher` is a non-global whole-token regex (e.g.
+ * the one checkRegistry's characterMatcher builds). Longest-token-first order
+ * is the caller's responsibility (it governs which owner wins a beat that
+ * names two characters — first match wins).
+ * @returns {{ byOwner: Map<string, number>, total: number, attributed: number, unattributed: number }}
+ * byOwner — dialogue-paragraph count per matched owner key (only owners with ≥1
+ * line appear); total — all dialogue paragraphs; attributed/unattributed split.
+ */
+export function attributeDialogueByOwner(text, owners) {
+ const byOwner = new Map();
+ const result = { byOwner, total: 0, attributed: 0, unattributed: 0 };
+ if (typeof text !== 'string' || !text) return result;
+ const list = (Array.isArray(owners) ? owners : []).filter(
+ (o) => o && typeof o.key === 'string' && o.matcher instanceof RegExp
+ );
+
+ const re = /[^\n]+/g;
+ let m;
+ while ((m = re.exec(text)) !== null) {
+ const para = m[0];
+ if (!para.trim() || !hasQuotedSpan(para)) continue;
+ result.total += 1;
+ // The beat is the narration around the quote — the only place a tag/name
+ // legitimately attributes the speaker (a name inside the quote is spoken text).
+ const beat = para.replace(QUOTED_SPAN_RE, ' ').replace(/\s+/g, ' ').trim();
+ let owner = null;
+ if (beat) {
+ for (const o of list) {
+ o.matcher.lastIndex = 0; // non-global, but reset defensively
+ if (o.matcher.test(beat)) { owner = o.key; break; }
+ }
+ }
+ if (owner) {
+ result.attributed += 1;
+ byOwner.set(owner, (byOwner.get(owner) || 0) + 1);
+ } else {
+ result.unattributed += 1;
+ }
+ }
+ return result;
+}
diff --git a/server/lib/editorial/dialogue.test.js b/server/lib/editorial/dialogue.test.js
index 91b5f9675e..81dfc1406b 100644
--- a/server/lib/editorial/dialogue.test.js
+++ b/server/lib/editorial/dialogue.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest';
import {
findSaidBookisms,
findUnattributedDialogueRuns,
+ attributeDialogueByOwner,
SAID_BOOKISMS,
NON_SPEECH_TAGS,
} from './dialogue.js';
@@ -195,3 +196,70 @@ describe('findUnattributedDialogueRuns', () => {
expect(findUnattributedDialogueRuns(curly)).toHaveLength(1);
});
});
+
+describe('attributeDialogueByOwner', () => {
+ // A whole-token matcher like the one checkRegistry builds (non-global).
+ const owner = (key, ...tokens) => ({
+ key,
+ matcher: new RegExp(`(?<!\\w)(?:${tokens.join('|')})(?!\\w)`, 'i'),
+ });
+
+ it('credits a dialogue line to the owner named in the beat, not inside the quote', () => {
+ const text = [
+ '"I saw Bram at the gate," said Aria.',
+ '"Then we move tonight," Bram replied.',
+ ].join('\n');
+ const { byOwner, total, attributed, unattributed } = attributeDialogueByOwner(text, [
+ owner('aria', 'Aria'),
+ owner('bram', 'Bram'),
+ ]);
+ expect(total).toBe(2);
+ expect(attributed).toBe(2);
+ expect(unattributed).toBe(0);
+ // Line 1 names "Bram" inside the quote but "Aria" in the beat → credited to Aria.
+ expect(byOwner.get('aria')).toBe(1);
+ expect(byOwner.get('bram')).toBe(1);
+ });
+
+ it('counts a dialogue line with no resolvable speaker as unattributed', () => {
+ const text = '"Who goes there?"\n"A friend," said Aria.';
+ const { byOwner, total, attributed, unattributed } = attributeDialogueByOwner(text, [
+ owner('aria', 'Aria'),
+ ]);
+ expect(total).toBe(2);
+ expect(attributed).toBe(1);
+ expect(unattributed).toBe(1);
+ expect(byOwner.get('aria')).toBe(1);
+ });
+
+ it('first-owner-wins when a beat names two characters', () => {
+ const text = '"Stop," Aria told Bram.';
+ const { byOwner } = attributeDialogueByOwner(text, [
+ owner('aria', 'Aria'),
+ owner('bram', 'Bram'),
+ ]);
+ expect(byOwner.get('aria')).toBe(1);
+ expect(byOwner.has('bram')).toBe(false);
+ });
+
+ it('ignores paragraphs with no quoted span (pure narration)', () => {
+ const text = 'Aria walked the long road home.\n"Finally," she said.';
+ const { total } = attributeDialogueByOwner(text, [owner('aria', 'Aria')]);
+ expect(total).toBe(1);
+ });
+
+ it('returns an empty result for non-strings and empty input', () => {
+ expect(attributeDialogueByOwner('', [owner('a', 'A')]).total).toBe(0);
+ expect(attributeDialogueByOwner(null, [owner('a', 'A')]).total).toBe(0);
+ const r = attributeDialogueByOwner('"Hi," said A.', []);
+ expect(r.total).toBe(1);
+ expect(r.unattributed).toBe(1);
+ });
+
+ it('tolerates malformed owner entries without throwing', () => {
+ const text = '"Hi," said Aria.';
+ expect(() => attributeDialogueByOwner(text, [null, { key: 'x' }, 'nope'])).not.toThrow();
+ const { unattributed } = attributeDialogueByOwner(text, [null, { key: 'x' }]);
+ expect(unattributed).toBe(1);
+ });
+});