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

editorial: add comic.balloon-attribution check for unshown/unmarked speakers

[._.]/ Adam Eivy12ba4335c1ca
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index f0582b2c1a..659dcc2f3a 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -151,4 +151,5 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `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`). Also `summarizeStoryboardShots` (#1466) — renders the collected `{ issueNumber, scene }` storyboard list into a compact per-scene shot block shared by the LLM siblings `visual.eyeline-match` (gaze reciprocity / eyeline-vs-screen-direction) and `visual.appearance-continuity` (#1467 — diffs the same entity's wardrobe/prop/setting descriptions across shots for contradictions). Reads the shot-grammar fields from `server/lib/shotGrammar.js`. |
| `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. |
+| `balloonAttribution.js` | Pure, dependency-free comic speech-balloon attribution primitives for `comic.balloon-attribution`: `analyzeBalloonAttribution` (flags a dialogue line whose speaker isn't shown in the panel description and carries no off-panel/broadcast cue — the case the image model mis-attributes to a visible character), `splitSpeaker`, `nameInText`, and `OFFPANEL_OK_MODIFIER` (the broadcast/off-panel/V.O./transmission modifier vocabulary — mirrors `visualStages.js` `BALLOON_STYLE_HINTS`, keep in sync). Severity scales `medium`/`low` by whether another canon character is visibly named in the panel. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/balloonAttribution.js b/server/lib/editorial/balloonAttribution.js
new file mode 100644
index 0000000000..3d1169f102
--- /dev/null
+++ b/server/lib/editorial/balloonAttribution.js
@@ -0,0 +1,148 @@
+/**
+ * Comic speech-balloon attribution check — pure analysis over the parsed comic
+ * pages `comicScriptParser` emits.
+ *
+ * Problem this catches: a dialogue line whose SPEAKER is not visible in the
+ * panel and is not marked as speaking from off-panel/over a device/broadcast.
+ * When that happens the image model letters a normal balloon and tails it to
+ * whoever IS drawn — mis-attributing the line (the real bug: JUNO, the station
+ * AI, "speaking" a line that got a tail pointing at a visible newlywed). The
+ * render side translates an off-panel/broadcast modifier into a disembodied
+ * balloon (see visualStages.js BALLOON_STYLE_HINTS); this check is the authoring
+ * guard that flags the cases where that modifier is MISSING, so the script can
+ * be fixed (show the speaker, or mark the line off-panel/broadcast) before art.
+ *
+ * Deterministic + side-effect-free (pure), so it's unit-testable and the same
+ * helper can back both the server `comic.balloon-attribution` editorial check
+ * and any future inline comic-script-stage warning.
+ *
+ * Conservative by design — it prefers a miss to a false alarm:
+ * - A speaker carrying ANY "voice from elsewhere" modifier (PA, off-panel,
+ * V.O., radio/earpiece/transmission, …) is treated as intentionally absent
+ * and never flagged — the author already declared the attribution.
+ * - Presence is checked PAGE-WIDE, not per-panel: a character shown in one
+ * panel persists through the scene, so a speaker named in ANY panel
+ * description on the page counts as present (kills the "shown in panel 1,
+ * speaks in panel 3" false positive that per-panel matching produces).
+ * - "Present" matches the speaker's full name OR any distinctive (≥4-char)
+ * token of it, so an incidental speaker the prose refers to loosely ("the
+ * newlyweds" vs "NEWLYWED TWO") reads as present rather than flagged.
+ * - Findings are deduped to ONE per (page, speaker): a narrator who speaks
+ * unshown across a whole page yields a single finding (with a panel count),
+ * not one per balloon — so the check stays advisory, not a flood.
+ * - Severity scales with risk: `medium` when another canon character IS named
+ * in the same panel (a concrete wrong target the balloon can tail to),
+ * `low` when no one is clearly visible (an orphaned/unclear balloon).
+ */
+
+// Speaker modifiers that mean "this speaker need not be drawn in the panel" —
+// broadcast/PA, off-panel/off-screen, voice-over/narration, and transmission
+// devices (the remote party isn't in frame). Mirrors the disembodied + device
+// vocabulary in visualStages.js BALLOON_STYLE_HINTS — keep the two in sync.
+// NOT included: whisper / shout / thought / sing — those imply the speaker IS
+// present, so a missing on-panel speaker for them is still a real gap.
+export const OFFPANEL_OK_MODIFIER =
+ /\b(SPEAKERS?|P\.?A\.?|BROADCAST|ANNOUNCE(?:D|S|MENT)?|ANNOUNCER|LOUDSPEAKER|OVERHEAD|INTERCOM|TANNOY|PAGING|STATIONWIDE|SHIPWIDE|OFF[\s-]?PANEL|OFF[\s-]?SCREEN|O\.?\s?S\.?|O\.?\s?P\.?|V\.?\s?O\.?|VOICE[\s-]?OVER|NARRATION|NARRATOR|EARPIECE|RADIO|COMMS?|TRANSMISSION|PHONE|HOLO|HOLOGRAM|TV|MONITOR|VIDEO|COMLINK|CHANNEL|PHONE|COMM[\s-]?LINK)\b/i;
+
+// The severity ranks a violation can take (most-severe first). Local copy so the
+// module stays self-contained.
+const ATTRIBUTION_SEVERITIES = ['high', 'medium', 'low'];
+
+const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+
+// Split a `NAME (MODIFIER)` speaker token into { speaker, modifier }. Tolerates
+// stacked parentheticals by treating the whole inner-paren blob as the modifier.
+// Mirrors formatBalloon's split in visualStages.js.
+export function splitSpeaker(character) {
+ const raw = (typeof character === 'string' ? character : '').trim();
+ const m = raw.match(/^([^(]+?)\s*\(([^)]*)\)\s*$/);
+ return {
+ speaker: (m ? m[1] : raw).trim(),
+ modifier: m ? m[2].trim() : '',
+ };
+}
+
+// Is `name` referenced in `text`? True on a word-boundary match of the full name
+// OR any distinctive (≥4-char) token of it — case-insensitive. The token pass
+// keeps loosely-named incidental speakers from false-flagging (see header).
+export function nameInText(name, text) {
+ const n = (typeof name === 'string' ? name : '').trim().toLowerCase();
+ const t = (typeof text === 'string' ? text : '').toLowerCase();
+ if (!n || !t) return false;
+ if (new RegExp(`\\b${escapeRe(n)}\\b`).test(t)) return true;
+ const tokens = n.split(/[^a-z0-9]+/).filter((tok) => tok.length >= 4);
+ return tokens.some((tok) => new RegExp(`\\b${escapeRe(tok)}\\b`).test(t));
+}
+
+/**
+ * Analyze the parsed pages of ONE comic script for balloon-attribution risks.
+ *
+ * @param {Array<{ panels: Array<object> }>} pages parseComicScript(...).pages
+ * @param {object} [opts]
+ * @param {string[]} [opts.characterNames] canon character display names (+ aliases)
+ * used to detect a concrete mis-attribution target in the panel description.
+ * @returns {Array<object>} violations, one per (page, speaker), each:
+ * { pageNumber, panelNumber, speaker, line, severity, visibleOthers, panelCount, anchorQuote }
+ * `panelNumber`/`line`/`anchorQuote` point at the FIRST offending panel;
+ * `panelCount` is how many panels on the page have this unshown speaker.
+ */
+export function analyzeBalloonAttribution(pages, { characterNames = [] } = {}) {
+ const list = Array.isArray(pages) ? pages : [];
+ const names = (Array.isArray(characterNames) ? characterNames : [])
+ .filter((n) => typeof n === 'string' && n.trim());
+ const violations = [];
+ list.forEach((page, pageIdx) => {
+ const pageNumber = pageIdx + 1;
+ const panels = Array.isArray(page?.panels) ? page.panels : [];
+ // Page-wide description: a character shown anywhere on the page persists
+ // through the scene, so presence is judged against the whole page, not the
+ // single panel the line sits in.
+ const pageText = panels
+ .map((p) => (typeof p?.description === 'string' ? p.description : ''))
+ .join('\n');
+ // Accumulate per speaker so a narrator speaking unshown across the page is
+ // ONE finding, not one per balloon.
+ const bySpeaker = new Map();
+ panels.forEach((panel, panelIdx) => {
+ const panelNumber = panelIdx + 1;
+ const description = typeof panel?.description === 'string' ? panel.description : '';
+ const dialogue = Array.isArray(panel?.dialogue) ? panel.dialogue : [];
+ if (!dialogue.length) return;
+ const visibleCanon = names.filter((n) => nameInText(n, description));
+ dialogue.forEach((d) => {
+ const { speaker, modifier } = splitSpeaker(d?.character);
+ if (!speaker) return;
+ // Author marked it as a voice-from-elsewhere — intentional, not a gap.
+ if (OFFPANEL_OK_MODIFIER.test(modifier)) return;
+ // Speaker is shown somewhere on the page — a tailed balloon is fine.
+ if (nameInText(speaker, pageText)) return;
+ const visibleOthers = visibleCanon.filter((n) => n.toLowerCase() !== speaker.toLowerCase());
+ const key = speaker.toLowerCase();
+ const prior = bySpeaker.get(key);
+ if (prior) {
+ prior.panelCount += 1;
+ // Escalate to medium if ANY panel has a concrete mis-attribution target.
+ if (visibleOthers.length) {
+ prior.severity = 'medium';
+ for (const o of visibleOthers) if (!prior.visibleOthers.includes(o)) prior.visibleOthers.push(o);
+ }
+ return;
+ }
+ bySpeaker.set(key, {
+ pageNumber,
+ panelNumber,
+ speaker,
+ line: typeof d?.line === 'string' ? d.line : '',
+ severity: visibleOthers.length ? 'medium' : 'low',
+ visibleOthers: [...visibleOthers],
+ panelCount: 1,
+ anchorQuote: typeof d?.line === 'string' ? d.line.trim() : '',
+ });
+ });
+ });
+ violations.push(...bySpeaker.values());
+ });
+ return violations;
+}
+
+export { ATTRIBUTION_SEVERITIES };
diff --git a/server/lib/editorial/balloonAttribution.test.js b/server/lib/editorial/balloonAttribution.test.js
new file mode 100644
index 0000000000..44fcaf985f
--- /dev/null
+++ b/server/lib/editorial/balloonAttribution.test.js
@@ -0,0 +1,116 @@
+import { describe, it, expect } from 'vitest';
+import {
+ analyzeBalloonAttribution,
+ splitSpeaker,
+ nameInText,
+ OFFPANEL_OK_MODIFIER,
+} from './balloonAttribution.js';
+
+const page = (panels) => ({ panels });
+const panel = (description, dialogue) => ({ description, dialogue });
+
+describe('splitSpeaker', () => {
+ it('splits NAME (MODIFIER)', () => {
+ expect(splitSpeaker('JUNO (SPEAKERS)')).toEqual({ speaker: 'JUNO', modifier: 'SPEAKERS' });
+ expect(splitSpeaker('Maggie')).toEqual({ speaker: 'Maggie', modifier: '' });
+ expect(splitSpeaker('LINA (EARPIECE, WHISPERED)')).toEqual({ speaker: 'LINA', modifier: 'EARPIECE, WHISPERED' });
+ });
+});
+
+describe('nameInText', () => {
+ it('matches full name and distinctive tokens case-insensitively', () => {
+ expect(nameInText('Maggie', 'Maggie ducks behind a crate.')).toBe(true);
+ expect(nameInText('Dr. Thomas Russo', 'A dark figure — RUSSO — steps out.')).toBe(true); // token match
+ expect(nameInText('Kai', 'Two newlyweds laugh.')).toBe(false);
+ });
+ it('does not match a short token substring', () => {
+ expect(nameInText('JUNO', 'The junior clerk frowns.')).toBe(false); // no \bjuno\b
+ });
+});
+
+describe('OFFPANEL_OK_MODIFIER', () => {
+ it('recognizes broadcast/off-panel/V.O./transmission, not whisper/thought', () => {
+ for (const m of ['SPEAKERS', 'PA', 'BROADCAST', 'OVERHEAD', 'OFF-PANEL', 'O.S.', 'V.O.', 'RADIO', 'EARPIECE', 'INTERCOM']) {
+ expect(OFFPANEL_OK_MODIFIER.test(m)).toBe(true);
+ }
+ for (const m of ['WHISPERED', 'THOUGHT', 'SHOUTING', 'SINGING', '']) {
+ expect(OFFPANEL_OK_MODIFIER.test(m)).toBe(false);
+ }
+ });
+});
+
+describe('analyzeBalloonAttribution', () => {
+ it('flags an unshown speaker with no off-panel cue, medium when another canon character is visible', () => {
+ const pages = [page([
+ panel('Maggie crouches at the containment rail, alone with the readout.', [
+ { character: 'KAI', line: 'You absolute menace.' },
+ ]),
+ ])];
+ const v = analyzeBalloonAttribution(pages, { characterNames: ['Maggie', 'Kai'] });
+ expect(v).toHaveLength(1);
+ expect(v[0]).toMatchObject({ pageNumber: 1, panelNumber: 1, speaker: 'KAI', severity: 'medium' });
+ expect(v[0].visibleOthers).toContain('Maggie');
+ });
+
+ it('flags low when the speaker is unshown and no other character is visible', () => {
+ const pages = [page([
+ panel('An empty corridor, lights flickering.', [
+ { character: 'KAI', line: 'Anyone there?' },
+ ]),
+ ])];
+ const v = analyzeBalloonAttribution(pages, { characterNames: ['Maggie', 'Kai'] });
+ expect(v).toHaveLength(1);
+ expect(v[0].severity).toBe('low');
+ });
+
+ it('does NOT flag a speaker marked off-panel / broadcast / transmission', () => {
+ const pages = [page([
+ panel('Two newlyweds duck under exploding light-orbs.', [
+ { character: 'JUNO (SPEAKERS)', line: 'Beverages are permitted.' },
+ { character: 'MAGGIE (V.O.)', line: 'Not for long.' },
+ { character: 'TOM (RADIO)', line: 'On my way.' },
+ ]),
+ ])];
+ const v = analyzeBalloonAttribution(pages, { characterNames: ['Maggie', 'Tom', 'Juno'] });
+ expect(v).toHaveLength(0);
+ });
+
+ it('does NOT flag a speaker who is shown in the panel description', () => {
+ const pages = [page([
+ panel('Maggie leans over the rail as Kai works the console.', [
+ { character: 'KAI', line: 'Almost in.' },
+ { character: 'MAGGIE', line: 'Hurry.' },
+ ]),
+ ])];
+ const v = analyzeBalloonAttribution(pages, { characterNames: ['Maggie', 'Kai'] });
+ expect(v).toHaveLength(0);
+ });
+
+ it('does NOT flag a speaker shown in an earlier panel on the same page (scene persistence)', () => {
+ // Kai is described in panel 1, speaks in panel 3 without being re-described —
+ // page-wide presence must treat him as present, not flag him.
+ const pages = [page([
+ panel('Kai lounges against a coral-lit pillar, slate under one arm.', []),
+ panel('Close on the security console, glyphs scrolling.', []),
+ panel('The console blooms green.', [{ character: 'KAI', line: 'Almost in.' }]),
+ ])];
+ const v = analyzeBalloonAttribution(pages, { characterNames: ['Kai'] });
+ expect(v).toHaveLength(0);
+ });
+
+ it('dedups to one finding per (page, speaker) with a panel count', () => {
+ const pages = [page([
+ panel('An empty maintenance ring hums.', [{ character: 'KAI', line: 'Line one.' }]),
+ panel('Sparks drift past dead consoles.', [{ character: 'KAI', line: 'Line two.' }]),
+ ])];
+ const v = analyzeBalloonAttribution(pages, { characterNames: ['Kai'] });
+ expect(v).toHaveLength(1);
+ expect(v[0]).toMatchObject({ speaker: 'KAI', panelCount: 2, panelNumber: 1 });
+ });
+
+ it('tolerates missing/empty input', () => {
+ expect(analyzeBalloonAttribution(null)).toEqual([]);
+ expect(analyzeBalloonAttribution([page([panel('x', [])])])).toEqual([]);
+ expect(analyzeBalloonAttribution([page([panel('x', [{ character: '', line: 'hi' }])])])).toEqual([]);
+ });
+});
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index c712e7aa55..1a7e2e6f5c 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -32,6 +32,7 @@ import {
analyzeComicLettering,
DEFAULT_LETTERING_THRESHOLDS,
} from './letteringDensity.js';
+import { analyzeBalloonAttribution } from './balloonAttribution.js';
import { analyzeNamePair, comparisonName, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';
import { findCliches, findModifierStacking } from './cliches.js';
import { findSaidBookisms, findUnattributedDialogueRuns, attributeDialogueByOwner } from './dialogue.js';
@@ -1579,6 +1580,26 @@ function comicLetteringFinding(v, number) {
};
}
+// Map a balloon-attribution violation to a manuscriptReview finding for issue
+// `number`. The wording is PortOS-facing copy (kept here, not in the pure
+// helper). Severity rides the violation's risk-scaled value.
+function balloonAttributionFinding(v, number) {
+ const where = `Page ${v.pageNumber} · Panel ${v.panelNumber}`;
+ const more = v.panelCount > 1 ? ` (and ${v.panelCount - 1} more panel${v.panelCount - 1 === 1 ? '' : 's'} on this page)` : '';
+ const target = Array.isArray(v.visibleOthers) && v.visibleOthers.length
+ ? ` Another character (${v.visibleOthers.slice(0, 3).join(', ')}) IS shown on the page, so the balloon will likely be tailed to the wrong character.`
+ : ' No one is clearly shown speaking it, so the balloon reads as orphaned.';
+ return {
+ severity: v.severity,
+ category: 'continuity',
+ location: number != null ? `Issue ${number} · ${where}` : where,
+ problem: `${v.speaker} speaks here${more} but is not shown anywhere on the page and the line carries no off-panel/broadcast cue.${target}`,
+ suggestion: `Either show ${v.speaker} in a panel on this page, or mark the line as spoken from elsewhere — e.g. ${v.speaker} (OFF-PANEL), (V.O.), (RADIO), or (SPEAKERS)/(PA) for a broadcast — so it renders as a disembodied balloon instead of being attributed to a visible character.`,
+ anchorQuote: typeof v.anchorQuote === 'string' ? v.anchorQuote : '',
+ issueNumber: number,
+ };
+}
+
export const EDITORIAL_CHECKS = [
{
id: 'naming.dissimilar-names',
@@ -2077,6 +2098,36 @@ export const EDITORIAL_CHECKS = [
return findings;
},
},
+ {
+ id: 'comic.balloon-attribution',
+ sources: ['comicScript'],
+ label: 'Comic speech-balloon attribution',
+ description:
+ 'Flags a comic dialogue line whose speaker is not shown in the panel and carries no off-panel/broadcast cue — the image model then letters a normal balloon and tails it to whoever IS drawn, mis-attributing the line (e.g. a station-AI PA line pointed at a visible bystander). Parses each issue\'s comic script and checks every panel\'s dialogue speakers against the panel description and the canon cast.',
+ scope: 'issue',
+ kind: 'deterministic',
+ category: 'continuity',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ configSchema: z.object({}),
+ configFields: [],
+ // Same cheap presence gate as the lettering check — needs at least one issue
+ // with comic content; canon is read from ctx for the visible-cast match.
+ gate: (ctx) => hasComicContent(ctx.issues),
+ run: (ctx) => {
+ const characterNames = (ctx.canon?.characters || [])
+ .filter((c) => c && typeof c === 'object')
+ .flatMap((c) => [c.name, ...(Array.isArray(c.aliases) ? c.aliases : [])])
+ .filter((n) => typeof n === 'string' && n.trim());
+ const findings = [];
+ for (const { number, pages } of comicLetteringIssues(ctx.issues)) {
+ for (const v of analyzeBalloonAttribution(pages, { characterNames })) {
+ findings.push(balloonAttributionFinding(v, number));
+ }
+ }
+ return findings;
+ },
+ },
{
id: 'cast.representation-balance',
sources: ['manuscript', 'canon', 'reverseOutline'],
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index 245c1b8b61..c369ac40a4 100644
--- a/server/lib/editorial/index.js
+++ b/server/lib/editorial/index.js
@@ -1,6 +1,7 @@
// 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 './balloonAttribution.js';
export * from './cliches.js';
export * from './comicPacing.js';
export * from './dialogue.js';