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-1303]): per-series style guide + conformance editorial checks

[._.]/ Adam Eivy196b0448777f
diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsx
index 01d7fa4fad..7520f803b2 100644
--- a/client/src/pages/PipelineSeries.jsx
+++ b/client/src/pages/PipelineSeries.jsx
@@ -49,7 +49,7 @@ const STYLE_OVERRIDE_MODE_TABS = [
// empty-value defaults the server expects for the optional ones. Module-level
// constants so the `useArcCanvasSync` callbacks keep a stable identity.
const ARC_FLUSH_FIELDS = [
- 'name', 'logline', 'premise', 'styleNotes', 'titleLogo', 'author', 'authorId',
+ 'name', 'logline', 'premise', 'styleNotes', 'styleGuide', 'titleLogo', 'author', 'authorId',
'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId',
];
const ARC_PAYLOAD_DEFAULTS = {
@@ -58,8 +58,27 @@ const ARC_PAYLOAD_DEFAULTS = {
authorId: null,
stylePromptOverride: '',
stylePromptOverrideMode: STYLE_OVERRIDE_MODE_DEFAULT,
+ // Structured house style — null means "no style guide", which the server
+ // sanitizer also produces from an all-empty guide.
+ styleGuide: null,
};
+// Style-guide option lists — mirror the enums in server/lib/styleGuide.js. Each
+// select carries a blank ("—") option so a field can be left unset (null).
+const STYLE_GUIDE_FIELDS = [
+ { key: 'tense', label: 'Tense', options: [['past', 'Past'], ['present', 'Present']] },
+ { key: 'povPerson', label: 'POV person', options: [['first', 'First person'], ['third-limited', 'Third — limited'], ['third-omniscient', 'Third — omniscient'], ['second', 'Second person']] },
+ { key: 'targetAudience', label: 'Target audience', options: [['children', 'Children'], ['middle-grade', 'Middle-grade'], ['YA', 'YA'], ['adult', 'Adult']] },
+ { key: 'contentRating', label: 'Content rating', options: [['G', 'G'], ['PG', 'PG'], ['PG-13', 'PG-13'], ['R', 'R'], ['custom', 'Custom']] },
+ { key: 'profanity', label: 'Profanity', options: [['none', 'None'], ['mild', 'Mild'], ['moderate', 'Moderate'], ['strong', 'Strong']] },
+];
+// Tri-state boolean conventions rendered as —/Yes/No selects so "unset" stays
+// distinct from "No" (matches the server's tri-state sanitizer).
+const STYLE_GUIDE_TRISTATE = [
+ { key: 'oxfordComma', label: 'Oxford comma' },
+ { key: 'italicizeThoughts', label: 'Italicize thoughts' },
+];
+
export default function PipelineSeries() {
const { seriesId } = useParams();
const navigate = useNavigate();
@@ -355,6 +374,8 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP
/>
</Field>
+ <StyleGuideSection series={series} patchSeries={patchSeries} />
+
<div className="block">
<div className="flex items-center justify-between mb-1">
<label
@@ -462,6 +483,126 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP
);
}
+// Per-series house style (#1303). Structured tense/POV/audience/rating/reading-
+// level/tone/conventions, edited into local series state via patchSeries and
+// persisted on Save (styleGuide is in ARC_FLUSH_FIELDS). Picking the blank
+// option clears a field to null; the server collapses an all-empty guide to
+// null. Each control is htmlFor/id paired for screen readers + click-to-focus.
+function StyleGuideSection({ series, patchSeries }) {
+ const sg = series.styleGuide || {};
+ const conv = sg.conventions || {};
+ const setSG = (patch) => patchSeries({ styleGuide: pruneEmpty({ ...sg, ...patch }) });
+ const setConv = (patch) => setSG({ conventions: pruneEmpty({ ...conv, ...patch }) });
+
+ return (
+ <div className="block">
+ <h3 className="text-xs uppercase tracking-wider text-gray-500 mb-2">Style guide (house style)</h3>
+ <p className="text-[11px] text-gray-500 mb-3 -mt-1">
+ Structured tense / POV / audience / rating fed into generation and checked by the editorial conformance checks.
+ </p>
+ <div className="grid grid-cols-2 gap-2">
+ {STYLE_GUIDE_FIELDS.map(({ key, label, options }) => (
+ <SgSelect
+ key={key}
+ id={`sg-${key}`}
+ label={label}
+ value={sg[key] || ''}
+ options={options}
+ onChange={(e) => setSG({ [key]: e.target.value || null })}
+ />
+ ))}
+ <div className="block">
+ <label htmlFor="sg-readingLevel" className="block text-[11px] text-gray-500 mb-1">Reading level (grade)</label>
+ <input
+ id="sg-readingLevel"
+ type="number"
+ min={1}
+ max={18}
+ value={Number.isFinite(sg.readingLevel) ? sg.readingLevel : ''}
+ onChange={(e) => {
+ const n = parseInt(e.target.value, 10);
+ setSG({ readingLevel: Number.isFinite(n) ? n : null });
+ }}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ />
+ </div>
+ </div>
+
+ <div className="mt-2">
+ <label htmlFor="sg-tone" className="block text-[11px] text-gray-500 mb-1">Tone (comma-separated)</label>
+ <input
+ id="sg-tone"
+ value={Array.isArray(sg.tone) ? sg.tone.join(', ') : ''}
+ onChange={(e) => {
+ const tone = e.target.value.split(',').map((t) => t.trim()).filter(Boolean);
+ setSG({ tone: tone.length ? tone : null });
+ }}
+ placeholder="noir, hopeful, wry"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ />
+ </div>
+
+ <div className="grid grid-cols-3 gap-2 mt-2">
+ <SgSelect
+ id="sg-spelling"
+ label="Spelling"
+ value={conv.spelling || ''}
+ options={[['US', 'US'], ['UK', 'UK']]}
+ onChange={(e) => setConv({ spelling: e.target.value || null })}
+ />
+ {STYLE_GUIDE_TRISTATE.map(({ key, label }) => (
+ <SgSelect
+ key={key}
+ id={`sg-${key}`}
+ label={label}
+ value={triValue(conv[key])}
+ options={TRISTATE_OPTIONS}
+ onChange={(e) => setConv({ [key]: triParse(e.target.value) })}
+ />
+ ))}
+ </div>
+ </div>
+ );
+}
+
+// Merge helper: drop keys cleared to null/undefined/empty-array, then collapse
+// an all-empty object to null so the style guide round-trips to null (matching
+// the server's empty-collapse) instead of an object full of nulls.
+function pruneEmpty(obj) {
+ const out = { ...obj };
+ for (const k of Object.keys(out)) {
+ const v = out[k];
+ if (v == null || (Array.isArray(v) && v.length === 0)) delete out[k];
+ }
+ return Object.keys(out).length ? out : null;
+}
+
+// Tri-state boolean <-> select-value mapping for the convention toggles, so
+// "unset" stays distinct from "No".
+const TRISTATE_OPTIONS = [['yes', 'Yes'], ['no', 'No']];
+const triValue = (v) => (v === true ? 'yes' : v === false ? 'no' : '');
+const triParse = (v) => (v === 'yes' ? true : v === 'no' ? false : null);
+
+// A blank-first labeled <select> — the single render path for every style-guide
+// dropdown (enums, spelling, tri-state) so the markup + Tailwind classes live
+// once.
+function SgSelect({ id, label, value, options, onChange }) {
+ return (
+ <div className="block">
+ <label htmlFor={id} className="block text-[11px] text-gray-500 mb-1">{label}</label>
+ <select
+ id={id}
+ value={value}
+ onChange={onChange}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm"
+ >
+ <option value="">—</option>
+ {options.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
+ </select>
+ </div>
+ );
+}
+
function Field({ label, children }) {
return (
<label className="block">
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 7243e2e4eb..5ab5ad449b 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -491,6 +491,13 @@
"model": "default",
"returnsJson": true,
"variables": []
+ },
+ "pipeline-editorial-style-conformance": {
+ "name": "Pipeline — Editorial Check: Style-guide conformance",
+ "description": "Editorial check (#1303): flags prose that drifts from the series style guide — wrong narrative tense, point-of-view person drift, or content/profanity beyond the configured rating ceiling. Reads the stitched manuscript plus the declared style-guide expectations. Returns issue-anchored findings.",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
}
}
}
diff --git a/data.reference/prompts/stages/pipeline-editorial-style-conformance.md b/data.reference/prompts/stages/pipeline-editorial-style-conformance.md
new file mode 100644
index 0000000000..1beaf5dd33
--- /dev/null
+++ b/data.reference/prompts/stages/pipeline-editorial-style-conformance.md
@@ -0,0 +1,67 @@
+# Pipeline — Editorial Check: Style-guide conformance
+
+You are a developmental editor doing a single focused pass: checking whether the
+drafted manuscript conforms to the series' **style guide** (house style). Flag
+only genuine, on-the-page **drift** from the declared expectations.
+
+## Style guide (the expectations to enforce)
+
+```
+{{styleGuide}}
+```
+
+What each expectation means:
+
+- **Tense** — the prose should stay in the declared narrative tense (past or
+ present). Flag passages that slip into the other tense (excluding dialogue,
+ which naturally uses any tense).
+- **Point-of-view person** — the narration should hold the declared person
+ (first / second / third-limited / third-omniscient). Flag drift (e.g. a
+ first-person book slipping into omniscient narration, or a limited POV
+ head-hopping into another character's interiority).
+- **Content rating ceiling** — flag profanity, violence, or sexual content that
+ exceeds the declared rating for the target audience.
+- **Profanity allowed** — flag profanity stronger than the declared level.
+
+Only enforce the expectations that are actually listed above. If an expectation
+isn't listed, don't invent it.
+
+## Manuscript
+
+The manuscript is stitched from the drafted issues. Each section begins with a
+header like `# Issue 3 — Title (prose)`; use the issue number in that header to
+attribute each finding to its `issueNumber`.
+
+```
+{{manuscript}}
+```
+
+## Task
+
+Identify the clearest conformance violations. For each, quote a short verbatim
+anchor from the text (≤ 200 characters) so the editor can jump to it, name the
+issue number it appears in, explain which style-guide expectation it breaks, and
+suggest a concrete fix.
+
+Be specific and cite the text. If the manuscript conforms to the style guide,
+return an empty `findings` array — do not invent violations.
+
+## Output contract
+
+Return ONLY valid JSON matching this shape — no prose, no markdown fence, no
+commentary:
+
+```json
+{
+ "findings": [
+ {
+ "severity": "high|medium|low",
+ "issueNumber": 3,
+ "location": "string — where in the issue (scene/paragraph)",
+ "problem": "1–3 sentences naming which style-guide expectation is broken and how",
+ "suggestion": "1–3 sentences on how to bring the passage into conformance",
+ "anchorQuote": "short verbatim quote from the manuscript (≤ 200 chars)"
+ }
+ ]
+}
+```
diff --git a/scripts/migrations/095-editorial-style-conformance-stage.js b/scripts/migrations/095-editorial-style-conformance-stage.js
new file mode 100644
index 0000000000..affaf2a6d5
--- /dev/null
+++ b/scripts/migrations/095-editorial-style-conformance-stage.js
@@ -0,0 +1,75 @@
+/**
+ * Seed the `pipeline-editorial-style-conformance` stage into existing installs (#1303).
+ *
+ * Mirrors `092-editorial-info-dumping-stage.js`: copies the `.md` template from
+ * `data.reference/prompts/stages/` and merges the stage-config entry into
+ * `data/prompts/stage-config.json`. Boot runs migrations (server/index.js) but
+ * NOT `setup-data.js`, so an upgrade that pulls + `pm2 restart`s (rather than
+ * running `update.sh`) would otherwise leave the new style-conformance stage
+ * unseeded and the `style.conformance` editorial check would throw
+ * "Stage not found" the first time it runs.
+ */
+
+import { access, copyFile, mkdir, readFile, writeFile, constants } from 'fs/promises';
+import { dirname, join } from 'path';
+
+const FILENAME = 'pipeline-editorial-style-conformance.md';
+const STAGE_KEY = 'pipeline-editorial-style-conformance';
+
+export default {
+ async up({ rootDir }) {
+ const stagesDir = join(rootDir, 'data', 'prompts', 'stages');
+ await mkdir(stagesDir, { recursive: true });
+
+ const dataPath = join(stagesDir, FILENAME);
+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);
+
+ const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);
+ if (exists) {
+ console.log(`📝 pipeline-editorial-style-conformance prompt: already present`);
+ } else {
+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);
+ if (!sampleExists) {
+ console.warn(`⚠️ pipeline-editorial-style-conformance: sample missing for ${FILENAME} — skipping copy`);
+ } else {
+ try {
+ await copyFile(samplePath, dataPath);
+ console.log(`✅ seeded ${FILENAME}`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-style-conformance: copy failed for ${FILENAME}: ${err.message}`);
+ }
+ }
+ }
+
+ const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');
+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');
+ const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);
+ if (!sampleConfigExists) {
+ console.warn('⚠️ pipeline-editorial-style-conformance: data.reference stage-config.json missing — cannot resolve entry; skipping config write');
+ return;
+ }
+ try {
+ const sample = JSON.parse(await readFile(sampleConfigPath, 'utf8'));
+ const installedExists = await access(installedConfigPath, constants.F_OK).then(() => true, () => false);
+ const installed = installedExists
+ ? JSON.parse(await readFile(installedConfigPath, 'utf8'))
+ : { stages: {} };
+ installed.stages = installed.stages || {};
+ if (installed.stages[STAGE_KEY]) {
+ console.log(`📝 pipeline-editorial-style-conformance stage-config: already present`);
+ return;
+ }
+ if (!sample?.stages?.[STAGE_KEY]) {
+ console.warn(`⚠️ pipeline-editorial-style-conformance: sample stage-config missing ${STAGE_KEY} — skipping`);
+ return;
+ }
+ installed.stages[STAGE_KEY] = sample.stages[STAGE_KEY];
+ await mkdir(dirname(installedConfigPath), { recursive: true });
+ await writeFile(installedConfigPath, JSON.stringify(installed, null, 2) + '\n', 'utf8');
+ const action = installedExists ? 'merged' : 'created';
+ console.log(`📝 pipeline-editorial-style-conformance stage-config (${action}): 1 added`);
+ } catch (err) {
+ console.warn(`⚠️ pipeline-editorial-style-conformance: stage-config merge failed: ${err.message}`);
+ }
+ },
+};
diff --git a/server/lib/README.md b/server/lib/README.md
index b620d9588e..90a71d3f9e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -47,6 +47,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `editorial/` | Extensible editorial-check registry (#1284) — `EDITORIAL_CHECKS` + fail-fast guards + lookup/state helpers. See `editorial/README.md`. The runner that executes checks lives at `server/services/pipeline/editorial/checkRunner.js`. |
| `storyBible.js` | Canonical Character / Place / Object shapes + `BIBLE_LIMITS`. |
| `storyArc.js` | Canonical Arc + Season + Reader-Map shapes for pipeline arc planning. |
+| `styleGuide.js` | Per-series house style (tense/POV/audience/rating/reading-level/tone/conventions): `sanitizeStyleGuide` + `renderStyleGuide` generation block + enums. |
| `storyBuilderSteps.js` | Unified Story Builder ordered step definitions + helpers (`STEPS`, `STEP_IDS`, `STEP_STATUSES`, `isValidStepId`, `stepIndex`). |
| `storyBuilderIntegrity.js` | Pure staleness hashing for the Story Builder (`hashUpstream`, `computeStaleSteps`, `computeSyncDrift`). |
| `canonPrompt.js` | Per-kind field-precedence rules; SHORT/RICH/PREVIEW spec tables; `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` / `descriptorForCanonEntry`. |
diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.js
index 38303f7fa7..9f915031a9 100644
--- a/server/lib/editorial/checkRegistry.js
+++ b/server/lib/editorial/checkRegistry.js
@@ -51,6 +51,12 @@ export const INFO_DUMPING_STAGE = 'pipeline-editorial-info-dumping';
export const OBJECT_MOTIVATION_STAGE = 'pipeline-editorial-object-motivation';
export const OBJECT_BACKSTORY_STAGE = 'pipeline-editorial-object-backstory';
+// Stage name for the style-guide conformance LLM check (#1303). Ships in
+// data.reference/prompts/stages/ + stage-config.json (fresh installs via
+// setup-data.js) and migrates to existing installs via migration 095 (boot runs
+// migrations but NOT setup-data, so the migration is required).
+export const STYLE_CONFORMANCE_STAGE = 'pipeline-editorial-style-conformance';
+
// ---------------------------------------------------------------------------
// Deterministic helpers for the character-name dissimilarity check.
// ---------------------------------------------------------------------------
@@ -206,6 +212,60 @@ function mapLlmFindings(raw, { severityDefault, category, max, withIssueNumber }
})).filter((f) => f.problem);
}
+// ---------------------------------------------------------------------------
+// Deterministic helpers for the style-guide reading-level check (#1303). A
+// self-contained Flesch–Kincaid grade-level estimate so the registry stays pure
+// (no import out to the styleGuide lib). The heuristic is approximate — it only
+// needs to catch "the prose reads several grades off the configured target".
+// ---------------------------------------------------------------------------
+
+// Hoisted out of countSyllables so the per-word loop over a full manuscript
+// doesn't recompile them on every call.
+const NON_ALPHA_RE = /[^a-z]/g;
+const VOWEL_GROUP_RE = /[aeiouy]+/g;
+const SENTENCE_END_RE = /[.!?]+/g;
+const WORD_RE = /\b[a-zA-Z]+\b/g;
+
+function countSyllables(word) {
+ const w = String(word).toLowerCase().replace(NON_ALPHA_RE, '');
+ if (!w) return 0;
+ if (w.length <= 3) return 1;
+ // Drop a trailing silent 'e', then count vowel groups (each run of vowels is
+ // ~one syllable). Floor at 1 — every real word has at least one.
+ const groups = w.replace(/e$/, '').match(VOWEL_GROUP_RE);
+ return Math.max(1, groups ? groups.length : 1);
+}
+
+// Flesch–Kincaid grade level for a manuscript corpus. Returns null when there
+// are no words to measure (caller skips rather than flagging a phantom grade).
+function readingGradeLevel(text) {
+ const clean = String(text || '');
+ const sentences = (clean.match(SENTENCE_END_RE) || []).length || 1;
+ const words = clean.match(WORD_RE) || [];
+ if (words.length === 0) return null;
+ const syllables = words.reduce((sum, w) => sum + countSyllables(w), 0);
+ return 0.39 * (words.length / sentences) + 11.8 * (syllables / words.length) - 15.59;
+}
+
+// Compact bullet list of the conformance-relevant style-guide expectations, fed
+// to the conformance LLM so it knows exactly what to measure the prose against.
+// Inlined (not imported from styleGuide.js) to keep this registry pure. Returns
+// '' when no conformance-relevant field is set (the check's gate also tests this).
+function styleGuideExpectations(sg) {
+ if (!sg || typeof sg !== 'object') return '';
+ const lines = [];
+ if (sg.tense) lines.push(`- Tense: ${sg.tense}`);
+ if (sg.povPerson) lines.push(`- Point-of-view person: ${sg.povPerson}`);
+ if (sg.targetAudience) lines.push(`- Target audience: ${sg.targetAudience}`);
+ if (sg.contentRating && sg.contentRating !== 'custom') lines.push(`- Content rating ceiling: ${sg.contentRating}`);
+ if (sg.profanity) lines.push(`- Profanity allowed: ${sg.profanity}`);
+ return lines.join('\n');
+}
+
+// True when the style guide carries at least one field the conformance LLM can
+// measure prose against. Shared by the check's gate and run so they agree.
+const hasConformanceFields = (sg) => styleGuideExpectations(sg).length > 0;
+
// ---------------------------------------------------------------------------
// Registry entries.
// ---------------------------------------------------------------------------
@@ -662,6 +722,120 @@ export const EDITORIAL_CHECKS = [
});
},
},
+ {
+ id: 'style.reading-level',
+ label: 'Reading-level conformance',
+ description:
+ "Measures the drafted manuscript's reading grade level (Flesch–Kincaid) and flags it when it drifts beyond a tolerance from the series style guide's target reading level.",
+ scope: 'series',
+ kind: 'deterministic',
+ category: 'style',
+ severityDefault: 'low',
+ defaultEnabled: true,
+ // Reads the stitched manuscript to measure the actual grade level.
+ needsManuscript: true,
+ configSchema: z.object({
+ // How many grade levels the measured reading level may drift from the
+ // target before it's flagged.
+ tolerance: z.number().int().min(0).max(6).default(2),
+ }),
+ configFields: [
+ {
+ key: 'tolerance',
+ label: 'Reading-level tolerance (grades)',
+ type: 'number',
+ min: 0,
+ max: 6,
+ step: 1,
+ help: 'How many grade levels the measured reading level may differ from the style-guide target before it is flagged.',
+ },
+ ],
+ // Only run when the style guide sets a target AND there's prose to measure.
+ gate: (ctx) => Number.isFinite(ctx.series?.styleGuide?.readingLevel)
+ && (ctx.manuscript || '').trim().length > 0,
+ run: (ctx) => {
+ const target = ctx.series?.styleGuide?.readingLevel;
+ if (!Number.isFinite(target)) return [];
+ const grade = readingGradeLevel(ctx.manuscript);
+ if (grade == null) return [];
+ const tolerance = ctx.config?.tolerance ?? 2;
+ const rounded = Math.round(grade * 10) / 10;
+ const delta = rounded - target;
+ if (Math.abs(delta) <= tolerance) return [];
+ const tooHard = delta > 0;
+ const off = Math.round(Math.abs(delta) * 10) / 10;
+ return [{
+ severity: ctx.severityDefault,
+ category: 'style',
+ location: 'Series manuscript (whole-corpus reading level)',
+ problem: `The drafted manuscript reads at about a grade-${rounded} level, ${tooHard ? 'above' : 'below'} the style-guide target of grade ${target} (off by ${off} grade${off === 1 ? '' : 's'}).`,
+ suggestion: tooHard
+ ? 'Shorten sentences and prefer plainer words to bring the reading level down toward the target.'
+ : 'Vary sentence length and vocabulary to raise the reading level toward the target.',
+ anchorQuote: '',
+ issueNumber: null,
+ }];
+ },
+ },
+ {
+ id: 'style.conformance',
+ label: 'Style-guide conformance (tense / POV / rating)',
+ description:
+ "LLM scan — flags passages where the prose drifts from the series style guide's tense, point-of-view person, or content rating (profanity/violence/sexual content beyond the configured ceiling).",
+ scope: 'issue',
+ kind: 'llm',
+ category: 'style',
+ severityDefault: 'medium',
+ defaultEnabled: true,
+ needsManuscript: true,
+ configSchema: z.object({
+ // Cap findings per run so a long manuscript can't flood the review.
+ maxFindings: z.number().int().min(1).max(50).default(12),
+ // Bound the prompt so a long series can't overflow a small/local
+ // provider's context window. Single-call safeguard — mirrors info-dumping.
+ maxManuscriptChars: z.number().int().min(2000).max(200_000).default(48_000),
+ }),
+ configFields: [
+ {
+ key: 'maxFindings',
+ label: 'Max findings per run',
+ type: 'number',
+ min: 1,
+ max: 50,
+ step: 1,
+ help: 'Cap findings so a long manuscript can not flood the review.',
+ },
+ {
+ key: 'maxManuscriptChars',
+ label: 'Max manuscript characters analyzed',
+ type: 'number',
+ min: 2000,
+ max: 200_000,
+ step: 1000,
+ help: 'Bounds the prompt so a long series can not overflow a small provider context window.',
+ },
+ ],
+ // Skip unless there's prose AND the style guide declares at least one
+ // conformance-relevant field (tense / POV / rating / profanity / audience).
+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0
+ && hasConformanceFields(ctx.series?.styleGuide),
+ run: async (ctx) => {
+ const expectations = styleGuideExpectations(ctx.series?.styleGuide);
+ if (!expectations) return [];
+ const manuscript = capManuscript(ctx.manuscript, ctx.config?.maxManuscriptChars ?? 48_000);
+ const { content } = await ctx.callStagedLLM(
+ STYLE_CONFORMANCE_STAGE,
+ { manuscript, styleGuide: expectations },
+ { returnsJson: true, source: STYLE_CONFORMANCE_STAGE },
+ );
+ return mapLlmFindings(content?.findings, {
+ severityDefault: ctx.severityDefault,
+ category: 'style',
+ max: ctx.config?.maxFindings ?? 12,
+ withIssueNumber: true,
+ });
+ },
+ },
];
// ---------------------------------------------------------------------------
diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.js
index 33420c2eaf..765982d108 100644
--- a/server/lib/editorial/checkRegistry.test.js
+++ b/server/lib/editorial/checkRegistry.test.js
@@ -534,3 +534,91 @@ describe('objects.backstory-consistency — LLM check (#1288)', () => {
expect(called).toBe(false);
});
});
+
+describe('style.reading-level — deterministic check (#1303)', () => {
+ const check = getCheck('style.reading-level');
+ const run = (styleGuide, manuscript, config = {}) =>
+ check.run({ series: { styleGuide }, manuscript, config, severityDefault: 'low' });
+ const gate = (styleGuide, manuscript) => check.gate({ series: { styleGuide }, manuscript });
+
+ // Simple grade-3-ish prose (short words, short sentences) vs. dense academic
+ // prose (long words, long sentences) — far enough apart that the FK estimate
+ // lands on opposite sides of a mid-range target with a tight tolerance.
+ const SIMPLE = 'The cat sat. The dog ran. We had fun. It was a good day. '.repeat(8);
+ const DENSE = ('The aforementioned epistemological ramifications necessitated unprecedented '
+ + 'interdisciplinary collaboration amongst numerous distinguished academic institutions '
+ + 'throughout the consequential deliberations. ').repeat(6);
+ // Ordinary narrative prose — grade lands in a middle band, so a mid target
+ // with the max tolerance is comfortably within range regardless of the exact
+ // FK estimate.
+ const MEDIUM = ('The surveyor walked along the quiet harbor and counted the empty boats. '
+ + 'She wondered where the fishermen had gone. The morning felt strange and still. ').repeat(5);
+
+ it('gate requires both a target reading level and a non-empty manuscript', () => {
+ expect(gate({ readingLevel: 8 }, '')).toBe(false);
+ expect(gate(null, SIMPLE)).toBe(false);
+ expect(gate({ readingLevel: 8 }, SIMPLE)).toBe(true);
+ });
+
+ it('returns nothing when the measured grade is within tolerance', () => {
+ // Ordinary prose targeted at a mid grade with the max tolerance → within.
+ expect(run({ readingLevel: 6 }, MEDIUM, { tolerance: 6 })).toEqual([]);
+ });
+
+ it('flags prose that reads ABOVE the target', () => {
+ const findings = run({ readingLevel: 3 }, DENSE, { tolerance: 2 });
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('style');
+ expect(findings[0].problem).toMatch(/above/i);
+ expect(findings[0].issueNumber).toBeNull();
+ });
+
+ it('flags prose that reads BELOW the target', () => {
+ const findings = run({ readingLevel: 12 }, SIMPLE, { tolerance: 2 });
+ expect(findings).toHaveLength(1);
+ expect(findings[0].problem).toMatch(/below/i);
+ });
+
+ it('is enabled by default', () => {
+ expect(check.defaultEnabled).toBe(true);
+ });
+});
+
+describe('style.conformance — LLM check (#1303)', () => {
+ const check = getCheck('style.conformance');
+ const gate = (styleGuide, manuscript = 'Some prose.') => check.gate({ series: { styleGuide }, manuscript });
+
+ it('gate requires prose AND a conformance-relevant style-guide field', () => {
+ expect(gate({ tense: 'past' }, '')).toBe(false); // no prose
+ expect(gate({ tone: ['noir'] })).toBe(false); // tone alone isn't conformance-relevant
+ expect(gate(null)).toBe(false);
+ expect(gate({ tense: 'past' })).toBe(true);
+ expect(gate({ contentRating: 'PG-13' })).toBe(true);
+ });
+
+ it('passes the declared expectations + manuscript to the model and maps findings', async () => {
+ let sentVars = null;
+ const findings = await check.run({
+ series: { styleGuide: { tense: 'past', povPerson: 'first', contentRating: 'PG' } },
+ manuscript: '# Issue 2 — Drift (prose)\n\nI walk to the door.',
+ config: { maxFindings: 5 },
+ severityDefault: 'medium',
+ callStagedLLM: async (_stage, vars) => {
+ sentVars = vars;
+ return { content: { findings: [{ severity: 'high', issueNumber: 2, problem: 'present-tense slip', anchorQuote: 'I walk' }] } };
+ },
+ });
+ expect(sentVars.styleGuide).toMatch(/Tense: past/);
+ expect(sentVars.styleGuide).toMatch(/Point-of-view person: first/);
+ expect(sentVars.styleGuide).toMatch(/Content rating ceiling: PG/);
+ expect(sentVars.manuscript).toContain('I walk to the door');
+ expect(findings).toHaveLength(1);
+ expect(findings[0].category).toBe('style');
+ expect(findings[0].issueNumber).toBe(2);
+ expect(findings[0].severity).toBe('high');
+ });
+
+ it('is enabled by default', () => {
+ expect(check.defaultEnabled).toBe(true);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 8e71e96936..de7fd77137 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -53,6 +53,7 @@ export * from './scenePrompt.js';
export * from './seasonStructure.js';
export * from './seriesLlmOverride.js';
export * from './storyArc.js';
+export * from './styleGuide.js';
export * from './storyBuilderIntegrity.js';
export * from './storyBuilderSteps.js';
// `storyBible.js` re-exports `normalizeSlugline` from `scenePrompt.js` for
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 7af55783b2..50db125120 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -83,7 +83,14 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// would silently strip the countdown and last-writer-wins the loss back onto
// the newer peer. Bump makes the older peer reject the ahead-version series
// transfer instead. Per-category gate → only series sync pauses with old peers.
- pipelineSeries: 3,
+ // v4 = `series.styleGuide` added (#1303) — a top-level series house-style
+ // field (tense/POV/audience/rating/reading-level/tone/conventions). Same
+ // silent-strip-then-LWW corruption as readerMap/tickingClock, just one level
+ // up: a ≤v3 peer re-sanitizes a series through its styleGuide-unaware
+ // `sanitizeSeries`, drops the guide, and last-writer-wins the loss back onto
+ // the newer peer. Bump makes the older peer reject the ahead-version series
+ // transfer instead. Per-category gate → only series sync pauses with old peers.
+ pipelineSeries: 4,
// NOT bumped for the manuscript-review sibling doc now bundled on series
// pushes/exports (`data/pipeline-series/{id}/manuscript-review.json`).
// Unlike `readerMap` (v2), the review is NOT a field inside the series
diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.js
index 680300bc76..2797ce8acc 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -27,8 +27,8 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {
it('declares pipeline collection layout versions', () => {
// pipelineIssues bumped to 2 when stages.audio.audioMode + cues[] were added.
expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(2);
- // pipelineSeries bumped to 3 when series.arc.tickingClock was added (v2 = readerMap).
- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(3);
+ // pipelineSeries bumped to 4 when series.styleGuide was added (v2 = readerMap, v3 = tickingClock).
+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(4);
});
it('declares mediaCollections layout version', () => {
@@ -42,7 +42,7 @@ describe('buildPortosMeta', () => {
expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);
expect(meta.schemaVersions.universes).toBe(7);
expect(meta.schemaVersions.pipelineIssues).toBe(2);
- expect(meta.schemaVersions.pipelineSeries).toBe(3);
+ expect(meta.schemaVersions.pipelineSeries).toBe(4);
});
it('overrides merge into schemaVersions', async () => {
diff --git a/server/lib/styleGuide.js b/server/lib/styleGuide.js
new file mode 100644
index 0000000000..797659309b
--- /dev/null
+++ b/server/lib/styleGuide.js
@@ -0,0 +1,177 @@
+/**
+ * Per-series style guide (house style) — #1303.
+ *
+ * A structured companion to the free-text `series.styleNotes`. Where styleNotes
+ * is tonal/visual prose, the style guide captures the *mechanical* house style —
+ * tense, POV person, target audience, content rating, reading level, tone words,
+ * and copy-edit conventions — so generation and editorial conformance checks
+ * share one source of truth instead of re-deriving intent from free text.
+ *
+ * Lives at `series.styleGuide` (a top-level series field, sibling to
+ * `styleNotes`). Sanitized on every series load/save by `sanitizeSeries`
+ * (services/pipeline/series.js); rendered into generation contexts by
+ * `renderStyleGuide` (folded into the already-rendered `styleNotes`, so no
+ * stage-prompt template variable — and thus no migration — is needed); and
+ * audited by the `style.*` editorial checks (lib/editorial/checkRegistry.js).
+ *
+ * This module is PURE — no side-effecting imports. Mirrors the sanitizer
+ * conventions in storyArc.js: absent/invalid → null/absent so a partial payload
+ * from an LLM or an older series.json never crashes a downstream reader, and an
+ * all-empty guide collapses to `null` ("no style guide yet").
+ */
+
+import { isStr, trimTo } from './storyBible.js';
+
+export const STYLE_GUIDE_LIMITS = Object.freeze({
+ TONE_MAX: 60,
+ TONES_MAX: 20,
+ READING_LEVEL_MIN: 1,
+ READING_LEVEL_MAX: 18,
+});
+
+export const STYLE_GUIDE_TENSES = Object.freeze(['past', 'present']);
+export const STYLE_GUIDE_POV_PERSONS = Object.freeze(['first', 'third-limited', 'third-omniscient', 'second']);
+export const STYLE_GUIDE_AUDIENCES = Object.freeze(['children', 'middle-grade', 'YA', 'adult']);
+export const STYLE_GUIDE_RATINGS = Object.freeze(['G', 'PG', 'PG-13', 'R', 'custom']);
+export const STYLE_GUIDE_PROFANITY = Object.freeze(['none', 'mild', 'moderate', 'strong']);
+export const STYLE_GUIDE_SPELLING = Object.freeze(['US', 'UK']);
+
+// Human-readable labels for the prompt/render block + the editorial-check
+// finding text, so generation and checks describe a value identically.
+const POV_PERSON_LABELS = Object.freeze({
+ first: 'first person',
+ 'third-limited': 'third-person limited',
+ 'third-omniscient': 'third-person omniscient',
+ second: 'second person',
+});
+const AUDIENCE_LABELS = Object.freeze({
+ children: 'children',
+ 'middle-grade': 'middle-grade',
+ YA: 'young-adult (YA)',
+ adult: 'adult',
+});
+
+const enumOrNull = (raw, allowed) => (allowed.includes(raw) ? raw : null);
+
+// Tri-state boolean: only `true`/`false` count as a set value — anything else is
+// "unspecified" (absent), so an LLM that omits a convention can't silently flip
+// it off (matches the absent-vs-empty rule in CLAUDE.md).
+const optBool = (raw) => (typeof raw === 'boolean' ? raw : null);
+
+// Target grade level. Finite → clamped to [1,18]; otherwise null (unspecified)
+// so "no target" stays distinguishable from "grade 0".
+const optReadingLevel = (raw) => (Number.isFinite(raw)
+ ? Math.max(STYLE_GUIDE_LIMITS.READING_LEVEL_MIN, Math.min(STYLE_GUIDE_LIMITS.READING_LEVEL_MAX, Math.round(raw)))
+ : null);
+
+function cleanTone(raw) {
+ if (!Array.isArray(raw)) return [];
+ const out = [];
+ const seen = new Set();
+ for (const v of raw) {
+ const s = trimTo(v, STYLE_GUIDE_LIMITS.TONE_MAX);
+ const key = s.toLowerCase();
+ if (!s || seen.has(key)) continue;
+ seen.add(key);
+ out.push(s);
+ if (out.length >= STYLE_GUIDE_LIMITS.TONES_MAX) break;
+ }
+ return out;
+}
+
+// Sanitize the copy-edit conventions sub-object. Returns null when nothing is
+// set so a guide that declares only tense/POV doesn't carry an empty husk.
+function sanitizeConventions(raw) {
+ if (raw == null || typeof raw !== 'object') return null;
+ const oxfordComma = optBool(raw.oxfordComma);
+ const spelling = enumOrNull(raw.spelling, STYLE_GUIDE_SPELLING);
+ const italicizeThoughts = optBool(raw.italicizeThoughts);
+ if (oxfordComma == null && spelling == null && italicizeThoughts == null) return null;
+ return { oxfordComma, spelling, italicizeThoughts };
+}
+
+/**
+ * Sanitize the optional `series.styleGuide` field. Returns `null` when the
+ * guide carries no identifying content (every field absent/invalid) so callers
+ * store `null` to mean "no style guide yet" — mirroring `sanitizeArc` /
+ * `sanitizeReaderMap`. Legacy-tolerant: a series.json predating this field has
+ * `styleGuide` absent → `sanitizeStyleGuide(undefined)` → null.
+ */
+export function sanitizeStyleGuide(raw) {
+ if (raw == null || typeof raw !== 'object') return null;
+ const tense = enumOrNull(raw.tense, STYLE_GUIDE_TENSES);
+ const povPerson = enumOrNull(raw.povPerson, STYLE_GUIDE_POV_PERSONS);
+ const targetAudience = enumOrNull(raw.targetAudience, STYLE_GUIDE_AUDIENCES);
+ const contentRating = enumOrNull(raw.contentRating, STYLE_GUIDE_RATINGS);
+ const profanity = enumOrNull(raw.profanity, STYLE_GUIDE_PROFANITY);
+ const readingLevel = optReadingLevel(raw.readingLevel);
+ const tone = cleanTone(raw.tone);
+ const conventions = sanitizeConventions(raw.conventions);
+ if (
+ tense == null && povPerson == null && targetAudience == null && contentRating == null
+ && profanity == null && readingLevel == null && tone.length === 0 && conventions == null
+ ) {
+ return null;
+ }
+ return { tense, povPerson, targetAudience, contentRating, profanity, readingLevel, tone, conventions };
+}
+
+/**
+ * Render the style guide as a directive block for generation prompts. Returns a
+ * single string (folded into the already-rendered `styleNotes` by the context
+ * builders, so no stage-prompt template variable is added — and no migration is
+ * needed) or `null` when the guide is empty/absent. Mirrors `renderTickingClock`
+ * in storyArc.js.
+ */
+export function renderStyleGuide(styleGuide) {
+ if (!styleGuide || typeof styleGuide !== 'object') return null;
+ const directives = [];
+ if (styleGuide.tense) directives.push(`Write in **${styleGuide.tense} tense**.`);
+ if (styleGuide.povPerson) {
+ directives.push(`Narrate in **${POV_PERSON_LABELS[styleGuide.povPerson] || styleGuide.povPerson}** point of view.`);
+ }
+ if (styleGuide.targetAudience) {
+ directives.push(`Target audience: **${AUDIENCE_LABELS[styleGuide.targetAudience] || styleGuide.targetAudience}** — pitch vocabulary, sentence complexity, and subject matter accordingly.`);
+ }
+ if (styleGuide.contentRating && styleGuide.contentRating !== 'custom') {
+ directives.push(`Keep content within a **${styleGuide.contentRating}** rating.`);
+ }
+ if (styleGuide.profanity) {
+ directives.push(styleGuide.profanity === 'none'
+ ? 'Use **no profanity**.'
+ : `Profanity may be **${styleGuide.profanity}**, no stronger.`);
+ }
+ if (styleGuide.readingLevel != null) {
+ directives.push(`Aim for roughly a **grade-${styleGuide.readingLevel} reading level**.`);
+ }
+ if (Array.isArray(styleGuide.tone) && styleGuide.tone.length) {
+ directives.push(`Tone: ${styleGuide.tone.join(', ')}.`);
+ }
+ const conv = styleGuide.conventions;
+ if (conv) {
+ if (conv.spelling) directives.push(`Use **${conv.spelling} spelling**.`);
+ if (conv.oxfordComma === true) directives.push('Use the Oxford (serial) comma.');
+ else if (conv.oxfordComma === false) directives.push('Do not use the Oxford (serial) comma.');
+ if (conv.italicizeThoughts === true) directives.push('Render internal thoughts in italics.');
+ else if (conv.italicizeThoughts === false) directives.push('Do not italicize internal thoughts.');
+ }
+ if (directives.length === 0) return null;
+ return `Series style guide (house style — follow exactly):\n${directives.map((d) => `- ${d}`).join('\n')}`;
+}
+
+/**
+ * Compose a series' free-text `styleNotes` with the rendered structured style
+ * guide into the single `styleNotes` string the stage templates already render
+ * (`{{series.styleNotes}}`). Folding the guide in here means generation honors
+ * tense/POV/rating/reading-level with NO new stage-prompt template variable —
+ * and therefore no prompt migration — exactly as `appendTickingClock` folds the
+ * countdown into the arc-level `shapeGuidance` block.
+ *
+ * The structured guide leads (deterministic house style first), the author's
+ * free-text notes trail. Returns `''` when neither is present.
+ */
+export function composeStyleNotes(series) {
+ const guide = renderStyleGuide(series?.styleGuide);
+ const notes = isStr(series?.styleNotes) ? series.styleNotes.trim() : '';
+ return [guide, notes].filter(Boolean).join('\n\n');
+}
diff --git a/server/lib/styleGuide.test.js b/server/lib/styleGuide.test.js
new file mode 100644
index 0000000000..27b44e180b
--- /dev/null
+++ b/server/lib/styleGuide.test.js
@@ -0,0 +1,102 @@
+import { describe, it, expect } from 'vitest';
+import {
+ sanitizeStyleGuide,
+ renderStyleGuide,
+ STYLE_GUIDE_LIMITS,
+} from './styleGuide.js';
+
+describe('sanitizeStyleGuide', () => {
+ it('returns null for absent / non-object / empty input (legacy-tolerant)', () => {
+ expect(sanitizeStyleGuide(undefined)).toBeNull();
+ expect(sanitizeStyleGuide(null)).toBeNull();
+ expect(sanitizeStyleGuide('past')).toBeNull();
+ expect(sanitizeStyleGuide({})).toBeNull();
+ // Every field invalid → no identifying content → null.
+ expect(sanitizeStyleGuide({
+ tense: 'future', povPerson: 'fourth', targetAudience: 'aliens',
+ contentRating: 'NC-17', profanity: 'extreme', readingLevel: 'x', tone: 'noir',
+ })).toBeNull();
+ });
+
+ it('keeps valid enum fields and drops invalid ones', () => {
+ const sg = sanitizeStyleGuide({
+ tense: 'present',
+ povPerson: 'third-limited',
+ targetAudience: 'YA',
+ contentRating: 'PG-13',
+ profanity: 'mild',
+ });
+ expect(sg).toMatchObject({
+ tense: 'present',
+ povPerson: 'third-limited',
+ targetAudience: 'YA',
+ contentRating: 'PG-13',
+ profanity: 'mild',
+ });
+ });
+
+ it('clamps readingLevel to [1,18] and rounds; non-finite → null', () => {
+ expect(sanitizeStyleGuide({ readingLevel: 7.4 }).readingLevel).toBe(7);
+ expect(sanitizeStyleGuide({ readingLevel: 99 }).readingLevel).toBe(STYLE_GUIDE_LIMITS.READING_LEVEL_MAX);
+ expect(sanitizeStyleGuide({ readingLevel: 0 }).readingLevel).toBe(STYLE_GUIDE_LIMITS.READING_LEVEL_MIN);
+ expect(sanitizeStyleGuide({ tense: 'past', readingLevel: 'nope' }).readingLevel).toBeNull();
+ });
+
+ it('cleans tone: trims, dedupes case-insensitively, caps', () => {
+ const sg = sanitizeStyleGuide({ tone: ['Noir', ' noir ', 'hopeful', '', 42] });
+ expect(sg.tone).toEqual(['Noir', 'hopeful']);
+ const many = sanitizeStyleGuide({ tone: Array.from({ length: 50 }, (_, i) => `t${i}`) });
+ expect(many.tone).toHaveLength(STYLE_GUIDE_LIMITS.TONES_MAX);
+ });
+
+ it('sanitizes conventions tri-state; all-unset → null conventions', () => {
+ expect(sanitizeStyleGuide({ tense: 'past', conventions: {} }).conventions).toBeNull();
+ const sg = sanitizeStyleGuide({
+ conventions: { oxfordComma: true, spelling: 'UK', italicizeThoughts: false, junk: 1 },
+ });
+ expect(sg.conventions).toEqual({ oxfordComma: true, spelling: 'UK', italicizeThoughts: false });
+ // A non-boolean oxfordComma is "unspecified", not false.
+ const sg2 = sanitizeStyleGuide({ conventions: { oxfordComma: 'yes', spelling: 'US' } });
+ expect(sg2.conventions).toEqual({ oxfordComma: null, spelling: 'US', italicizeThoughts: null });
+ });
+
+ it('survives when only one field is set', () => {
+ expect(sanitizeStyleGuide({ tense: 'past' })).toMatchObject({ tense: 'past', povPerson: null });
+ });
+});
+
+describe('renderStyleGuide', () => {
+ it('returns null for empty/absent guide', () => {
+ expect(renderStyleGuide(null)).toBeNull();
+ expect(renderStyleGuide(sanitizeStyleGuide({}))).toBeNull();
+ });
+
+ it('renders directives for the set fields', () => {
+ const block = renderStyleGuide(sanitizeStyleGuide({
+ tense: 'present',
+ povPerson: 'first',
+ targetAudience: 'YA',
+ contentRating: 'PG',
+ profanity: 'none',
+ readingLevel: 8,
+ tone: ['noir', 'hopeful'],
+ conventions: { oxfordComma: true, spelling: 'UK', italicizeThoughts: true },
+ }));
+ expect(block).toContain('present tense');
+ expect(block).toContain('first person');
+ expect(block).toContain('young-adult');
+ expect(block).toContain('PG');
+ expect(block).toContain('no profanity');
+ expect(block).toContain('grade-8');
+ expect(block).toContain('noir, hopeful');
+ expect(block).toContain('UK spelling');
+ expect(block).toContain('Oxford');
+ expect(block).toContain('italics');
+ });
+
+ it('omits the content-rating directive when rating is "custom"', () => {
+ const block = renderStyleGuide(sanitizeStyleGuide({ contentRating: 'custom', tense: 'past' }));
+ expect(block).not.toContain('rating');
+ expect(block).toContain('past tense');
+ });
+});
diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.js
index c03701c2d2..6b212cde15 100644
--- a/server/routes/pipeline/series.js
+++ b/server/routes/pipeline/series.js
@@ -21,6 +21,10 @@ import {
CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,
} from '../../lib/issueLength.js';
import { ARC_LIMITS, ARC_STATUSES, ARC_SHAPE_IDS, SEASON_STATUSES } from '../../lib/storyArc.js';
+import {
+ STYLE_GUIDE_LIMITS, STYLE_GUIDE_TENSES, STYLE_GUIDE_POV_PERSONS, STYLE_GUIDE_AUDIENCES,
+ STYLE_GUIDE_RATINGS, STYLE_GUIDE_PROFANITY, STYLE_GUIDE_SPELLING,
+} from '../../lib/styleGuide.js';
import { mapServiceError } from './shared.js';
// Inline until better/code-quality lands and exports this from validation.js
@@ -62,6 +66,29 @@ const arcSchema = z.object({
status: z.enum(ARC_STATUSES).optional(),
});
+// Per-series style guide (house style) — #1303. Structured Zod parity for the
+// `series.styleGuide` field; every field optional + nullable so a partial
+// update or an intentional clear (null) both round-trip, and the service-side
+// `sanitizeStyleGuide` stays the authority (collapses an all-empty guide to
+// null). `tone` and `conventions` mirror the sanitizer's shape.
+const styleGuideSchema = z.object({
+ tense: z.enum(STYLE_GUIDE_TENSES).nullable().optional(),
+ povPerson: z.enum(STYLE_GUIDE_POV_PERSONS).nullable().optional(),
+ targetAudience: z.enum(STYLE_GUIDE_AUDIENCES).nullable().optional(),
+ contentRating: z.enum(STYLE_GUIDE_RATINGS).nullable().optional(),
+ profanity: z.enum(STYLE_GUIDE_PROFANITY).nullable().optional(),
+ readingLevel: z.number()
+ .min(STYLE_GUIDE_LIMITS.READING_LEVEL_MIN).max(STYLE_GUIDE_LIMITS.READING_LEVEL_MAX)
+ .nullable().optional(),
+ tone: z.array(z.string().trim().min(1).max(STYLE_GUIDE_LIMITS.TONE_MAX))
+ .max(STYLE_GUIDE_LIMITS.TONES_MAX).optional(),
+ conventions: z.object({
+ oxfordComma: z.boolean().nullable().optional(),
+ spelling: z.enum(STYLE_GUIDE_SPELLING).nullable().optional(),
+ italicizeThoughts: z.boolean().nullable().optional(),
+ }).nullable().optional(),
+}).strict();
+
// Volume-cover / back-cover sub-schema — accepts the script text plus the
// pre-split legacy fields. Render-slot details (`proofImage`, `finalImage`)
// arrive only from the render route's PATCH path, which builds them
@@ -121,6 +148,7 @@ const seriesCreateSchema = z.object({
seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),
locked: seriesLockedSchema.optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),
+ styleGuide: styleGuideSchema.nullable().optional(),
titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional().default(''),
author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional().default(''),
authorId: z.string().trim().max(seriesSvc.AUTHOR_ID_MAX).nullable().optional(),
@@ -144,6 +172,7 @@ const seriesPatchSchema = z.object({
seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),
locked: seriesLockedSchema.optional(),
styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),
+ styleGuide: styleGuideSchema.nullable().optional(),
titleLogo: z.string().trim().max(seriesSvc.TITLE_LOGO_MAX).optional(),
author: z.string().trim().max(seriesSvc.AUTHOR_MAX).optional(),
authorId: z.string().trim().max(seriesSvc.AUTHOR_ID_MAX).nullable().optional(),
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 59f572de30..cd839d63e2 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1053,12 +1053,12 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
const result = await dataSync.applyRemote('pipeline', {
series: [{ id: 'ser-1', name: 'Foundry', updatedAt: '2026-05-17T11:00:00Z' }],
issues: [],
- }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 4, pipelineIssues: 1, mediaCollections: 1 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 5, pipelineIssues: 1, mediaCollections: 1 } } });
expect(result.applied).toBe(false);
expect(result.blockedBySchema).toBeDefined();
// The reported gap is scoped to the relevant category — NOT mis-attributed.
expect(result.blockedBySchema.ahead).toEqual([
- { category: 'pipelineSeries', senderV: 4, receiverV: 3 },
+ { category: 'pipelineSeries', senderV: 5, receiverV: 4 },
]);
expect(readSeriesState()).toEqual([]); // nothing written
});
diff --git a/server/services/pipeline/arcPlanner/context.js b/server/services/pipeline/arcPlanner/context.js
index 7d2671b8b4..2fc3c5d0ae 100644
--- a/server/services/pipeline/arcPlanner/context.js
+++ b/server/services/pipeline/arcPlanner/context.js
@@ -10,6 +10,7 @@
import { MANUSCRIPT_TYPES } from '../series.js';
import { listIssues } from '../issues.js';
import { ARC_ROLES as ARC_ROLE_LIST, ARC_SHAPE_IDS, READER_MAP_BEAT_KINDS, buildSeason, renderArcShapeGuidance, renderTickingClock, sanitizeSeasonList } from '../../../lib/storyArc.js';
+import { composeStyleNotes } from '../../../lib/styleGuide.js';
import { describeStructure, recommendStructure } from '../../../lib/seasonStructure.js';
import { DEFAULT_LENGTH_PROFILE, LENGTH_PROFILE_NAMES } from '../../../lib/issueLength.js';
import { getUniverse } from '../../universeBuilder.js';
@@ -332,7 +333,10 @@ export async function buildArcOverviewContext(series, preloadedWorld) {
name: series.name,
logline: series.logline,
premise: series.premise,
- styleNotes: series.styleNotes,
+ // Structured style guide folded into the free-text notes (see
+ // composeStyleNotes) so arc generation respects house style without a
+ // new template variable / migration.
+ styleNotes: composeStyleNotes(series),
issueCountTarget: series.issueCountTarget,
},
...world,
diff --git a/server/services/pipeline/arcPlanner/episodeSeedPass.js b/server/services/pipeline/arcPlanner/episodeSeedPass.js
index 0e9165c503..6e1f8a6702 100644
--- a/server/services/pipeline/arcPlanner/episodeSeedPass.js
+++ b/server/services/pipeline/arcPlanner/episodeSeedPass.js
@@ -7,6 +7,7 @@ import { runStagedLLM } from '../../../lib/stageRunner.js';
import { getSeries } from '../series.js';
import { createIssue, listIssues } from '../issues.js';
import { renderArcShapeGuidance, renderArcShapePositionSummary } from '../../../lib/storyArc.js';
+import { composeStyleNotes } from '../../../lib/styleGuide.js';
import { extractCanonFromProse } from '../../universeCanon.js';
import { resolveSeriesLlmOverride } from '../../../lib/seriesLlmOverride.js';
import { getSeriesCanon } from '../seriesCanon.js';
@@ -36,7 +37,10 @@ export async function buildSeasonEpisodesContext(series, season, priorSeasons, p
name: series.name,
logline: series.logline,
premise: series.premise,
- styleNotes: series.styleNotes,
+ // Fold the structured style guide into styleNotes so episode-beat
+ // generation honors house style (see composeStyleNotes) — same as the
+ // arc-overview and per-issue text contexts.
+ styleNotes: composeStyleNotes(series),
},
...world,
arc: {
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 9cc334a54c..ed33b8252c 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -15,6 +15,7 @@ import { randomUUID } from 'crypto';
import { getSeriesStore } from './seriesStore/store.js';
import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
+import { sanitizeStyleGuide } from '../../lib/styleGuide.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import {
@@ -181,6 +182,11 @@ const sanitizeSeries = (raw) => {
seasons: sanitizeSeasonList(raw.seasons),
locked: sanitizeSeriesLocked(raw.locked),
styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),
+ // Per-series house style (tense/POV/audience/rating/reading-level/tone/
+ // conventions). Structured companion to the free-text styleNotes above;
+ // sanitizeStyleGuide returns null when empty so existing series.json files
+ // (which predate this field) migrate forward without a writer pass.
+ styleGuide: sanitizeStyleGuide(raw.styleGuide),
titleLogo: trimTo(raw.titleLogo, TITLE_LOGO_MAX),
author: trimTo(raw.author, AUTHOR_MAX),
authorId: trimTo(raw.authorId, AUTHOR_ID_MAX) || null,
@@ -256,6 +262,7 @@ export async function createSeries(input = {}) {
seasons: input.seasons || [],
locked: input.locked || {},
styleNotes: input.styleNotes || '',
+ styleGuide: input.styleGuide || null,
titleLogo: input.titleLogo || '',
author: input.author || '',
authorId: input.authorId || null,
@@ -414,6 +421,9 @@ export async function updateSeries(id, patch = {}) {
// Wholesale replace — `locked: {}` clears every lock; omission preserves.
...('locked' in patch ? { locked: patch.locked } : {}),
...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),
+ // Wholesale replace — sanitizeStyleGuide normalizes an empty object back
+ // to null (clear); omission preserves. Mirrors the arc/readerMap pattern.
+ ...('styleGuide' in patch ? { styleGuide: patch.styleGuide } : {}),
...('titleLogo' in patch ? { titleLogo: patch.titleLogo } : {}),
...('author' in patch ? { author: patch.author } : {}),
...('authorId' in patch ? { authorId: patch.authorId } : {}),
diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.js
index 90404c14f4..f3676b5c9b 100644
--- a/server/services/pipeline/textStages.js
+++ b/server/services/pipeline/textStages.js
@@ -23,6 +23,7 @@ import { getUniverse } from '../universeBuilder.js';
import { compareIssuesByPosition, NO_LINKED_UNIVERSE_PLACEHOLDER } from './arcPlanner.js';
import { computeIssueTargets } from '../../lib/issueLength.js';
import { renderEntitiesSummary } from '../../lib/universePromptRenderers.js';
+import { composeStyleNotes } from '../../lib/styleGuide.js';
const STAGE_TO_TEMPLATE = Object.freeze({
idea: 'pipeline-idea-expansion',
@@ -216,7 +217,11 @@ function buildStageContext({ series, canon, world, issue, stageId, seedInput, so
name: series.name,
logline: series.logline,
premise: series.premise,
- styleNotes: series.styleNotes,
+ // Fold the structured style guide (tense/POV/rating/reading-level/tone/
+ // conventions) into the free-text styleNotes the template already renders,
+ // so prose/script generation honors house style with no new template
+ // variable (and thus no stage-prompt migration). See composeStyleNotes.
+ styleNotes: composeStyleNotes(series),
universeId: series.universeId || '',
characters: canon?.characters || [],
},
diff --git a/server/services/pipeline/textStages.test.js b/server/services/pipeline/textStages.test.js
index f75b42bbc9..d871d7b967 100644
--- a/server/services/pipeline/textStages.test.js
+++ b/server/services/pipeline/textStages.test.js
@@ -101,6 +101,25 @@ describe('pipeline text stage generator', () => {
expect(llmCalls[0].prompt).toContain('RENDERED:pipeline-idea-expansion');
});
+ it('folds the structured style guide into series.styleNotes in the prompt context', async () => {
+ const series = await seriesSvc.createSeries({
+ name: 'Salt Run',
+ logline: 'A foundry city goes silent.',
+ premise: 'Salt-mining city.',
+ styleNotes: 'moebius linework',
+ styleGuide: { tense: 'present', povPerson: 'first', contentRating: 'PG-13' },
+ });
+ const issue = await issuesSvc.createIssue({ seriesId: series.id, title: 'The Hush' });
+ await textStages.generateStage(issue.id, 'prose', { seedInput: 'beats' });
+ const ctx = ctxFromCall(llmCalls[0]);
+ // The free-text notes are preserved AND the structured guide directives are
+ // prepended, so generation honors house style with no new template variable.
+ expect(ctx.series.styleNotes).toContain('moebius linework');
+ expect(ctx.series.styleNotes).toContain('present tense');
+ expect(ctx.series.styleNotes).toContain('first person');
+ expect(ctx.series.styleNotes).toContain('PG-13');
+ });
+
it('stage prompt context includes only PRIOR stages', async () => {
const { issue } = await seed();
// Fill idea + prose, then run comicScript. Context should include both
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 4951a95022..c83ab20c58 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2223,7 +2223,7 @@ describe('sharing round-trip', () => {
const result = await importer.processManifest(bucket.id, exp.filename);
expect(result.skipped).toBe(true);
expect(result.reason).toBe('portos-schema-ahead');
- expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 3 }]);
+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 4 }]);
expect(result.producedByVersion).toBe('99.0.0');
// Series stayed tombstoned (or absent) — apply was refused.
await expect(series.getSeries(s.id)).rejects.toThrow();