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

make editorial severity weights + autopilot blocking sets tunable per series (#1616)

[._.]/ Adam Eivya6ee6c974ed7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index e650e5a07f..0865a2ec6f 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -58,6 +58,7 @@
## Editorial checks
+- **[issue-1616] The editorial health-score severity weights and the autopilot blocking-severity sets are now tunable per series.** The health score deducted a fixed penalty per open finding (High 12 / Medium 5 / Low 1) and each Series Autopilot gate blocked on a fixed severity set — arc verification and beat continuity on High+Medium, the editorial review on High — with no way to say "for this series, Medium findings shouldn't pause the run" or "weight Low nits more heavily." Each series can now override both from the Editorial Checks page: a **Severity tuning** panel sets per-severity health-score weights (blank = the default) and, per autopilot gate (arc / beat continuity / editorial review), which severities count as blocking (checking none = nothing blocks that gate). The score shown in the panel, the health gate, and the persisted revision-trend snapshots all reflect the override, and the resolved blocking sets drive every autopilot gate read. Both default to "unset → frozen defaults," so existing series are unchanged; the overrides ride peer sync wire-gated at `pipelineSeries` schema v9 (a behind peer rejects the ahead-version transfer rather than stripping the override). Follow-up to the per-check severity override (#1596). (`server/lib/editorial/severityConfig.js`, `server/services/pipeline/editorialScore.js`, `server/services/pipeline/seriesAutopilot.js`, `server/services/pipeline/series.js`, `server/lib/schemaVersions.js`, `server/routes/pipeline/series.js`, `server/routes/pipeline/editorial.js`, `client/src/components/pipeline/editorial/SeriesSeverityConfig.jsx`)
- **[issue-1626] On-the-nose dialogue findings now say *why* a line is flat, not just that it is.** `dialogue.on-the-nose` flagged subtext-free dialogue but labeled every finding the same way — too broad to act on. Each finding is now sub-classified into one of three subtypes so the fix is obvious: **exposition** (info-dump / "maid-and-butler" lines that state facts to inform the reader), **emotion-tell** (a character naming their own feeling outright instead of letting it surface through behavior), and **relationship-report** (a line describing a bond instead of dramatizing it). The stage prompt classifies and emits the subtype, the runner validates it against an allow-list (a stray label falls back to none), and it renders as a small badge on the finding in both the manuscript comment card and the editorial triage list. Additive and backward-compatible — older findings and synced peers carry no subtype and render unchanged; existing installs pick up the new prompt via boot migration 144. (`server/lib/editorial/checkRegistry.js`, `data.reference/prompts/stages/pipeline-editorial-on-the-nose.md`, `server/services/pipeline/manuscriptReview.js`, `client/src/components/pipeline/manuscript/ManuscriptCommentCard.jsx`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `scripts/migrations/144-editorial-on-the-nose-subtype.js`)
- **[issue-1631] Findings that name canon entities now link straight to the universe's canon section.** A continuity or character finding ("Aria's eye colour drifts between issues") named a canon entity in plain prose with no way to jump to that entity's record — you'd manually cross-reference. When the selected series has a linked universe, each finding now carries a **Canon** chip row: every character, place, or object whose name appears in the finding's problem/location text becomes a one-click link into the universe's canon section, with the entity's descriptor shown as a hovercard (and a per-kind icon). Matching is whole-word and case-insensitive, prefers the longest name so "Jon Snow" wins over "Jon", and collapses repeated mentions to one chip. The chips render outside the finding's manuscript deep-link (no nested links) and appear on resolved findings too, so a continuity review can cross-reference in place. A series with no linked universe, or a finding that names no canon entity, shows no chips — existing behavior is unchanged. (`client/src/lib/editorialChecks.js`, `client/src/components/pipeline/editorial/EditorialFindingsTriage.jsx`, `client/src/pages/PipelineEditorialChecks.jsx`)
- **[issue-1630] Click a point on the editorial health-trend sparkline to drill into that revision — what was open then, and what changed since the prior run.** The score sparkline in the Editorial Health panel was read-only: you could watch the line dip after an edit pass but not see *why*. Every recorded revision is now a clickable point. Selecting one opens a drill-down showing that snapshot's score (with its delta vs the previous revision) and its open-finding breakdown by severity and category, plus a per-dimension diff against the prior revision — which severities, categories, and checks rose (regressed, in red) or fell (improved, in green), biggest change first. The first recorded revision says there's nothing to compare yet; a revision recorded before per-check tracking shipped omits the per-check diff rather than inventing an all-new baseline. (`client/src/components/pipeline/editorial/EditorialHealthPanel.jsx`, `client/src/lib/editorialHealth.js`, `server/services/pipeline/editorialScore.js`)
diff --git a/client/src/components/pipeline/editorial/SeriesSeverityConfig.jsx b/client/src/components/pipeline/editorial/SeriesSeverityConfig.jsx
new file mode 100644
index 0000000000..82da257e30
--- /dev/null
+++ b/client/src/components/pipeline/editorial/SeriesSeverityConfig.jsx
@@ -0,0 +1,186 @@
+/**
+ * Per-series severity config panel (#1616) for the Editorial Checks page.
+ *
+ * Two per-series overrides, both saved through the parent's serialized silent
+ * save tail (`onSaveField(field, value)`):
+ *
+ * - SEVERITY WEIGHTS — the health-score penalty weights (high/medium/low). The
+ * defaults are high:12 / medium:5 / low:1; an unset series shows the defaults.
+ * A weight input round-trips a single key; an empty input clears that key back
+ * to the default (an absent key in the stored override → default applies).
+ * - BLOCKING SEVERITIES — which severities count as blocking for each autopilot
+ * gate (arc, beatContinuity, editorial). Checkboxes over high/medium/low; an
+ * unset gate shows the gate's default set. Unchecking ALL boxes for a gate
+ * persists an explicit empty array = "nothing blocks this gate" (distinct from
+ * "unset → defaults"), so the gate is honored as-is on the next run.
+ *
+ * Display always shows the EFFECTIVE (override-merged-with-default) values, and
+ * saves merge the touched key onto the series' STORED override (not the merged
+ * effective values) so an untouched key/gate stays absent and keeps tracking the
+ * default. Mirrors the server's mergeSeverityWeights / resolveBlockingSet
+ * semantics so the UI never lies about what the autopilot will do.
+ */
+import { useEffect, useState } from 'react';
+
+export const DEFAULT_SEVERITY_WEIGHTS = { high: 12, medium: 5, low: 1 };
+export const DEFAULT_BLOCKING_SEVERITIES = {
+ arc: ['high', 'medium'],
+ beatContinuity: ['high', 'medium'],
+ editorial: ['high'],
+};
+const SEVERITIES = ['high', 'medium', 'low'];
+const SEVERITY_LABELS = { high: 'High', medium: 'Medium', low: 'Low' };
+const GATES = [
+ { id: 'arc', label: 'Arc verification' },
+ { id: 'beatContinuity', label: 'Beat continuity' },
+ { id: 'editorial', label: 'Editorial review' },
+];
+
+const isNonNegNumber = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
+
+// Effective weight for a severity: the stored override when it's a valid
+// non-negative number, else the frozen default. Mirrors mergeSeverityWeights.
+function effectiveWeight(override, sev) {
+ const raw = override && typeof override === 'object' ? override[sev] : undefined;
+ return isNonNegNumber(raw) ? raw : DEFAULT_SEVERITY_WEIGHTS[sev];
+}
+
+// Effective blocking set for a gate: the stored array when present (even empty),
+// else the gate's default. Mirrors resolveBlockingSet (Array.isArray first).
+function effectiveBlocking(override, gate) {
+ const raw = override && typeof override === 'object' ? override[gate] : undefined;
+ if (Array.isArray(raw)) return raw.filter((s) => SEVERITIES.includes(s));
+ return DEFAULT_BLOCKING_SEVERITIES[gate];
+}
+
+export default function SeriesSeverityConfig({ series, onSaveField, saving = false }) {
+ const weightsOverride = series && typeof series.severityWeights === 'object' && series.severityWeights
+ ? series.severityWeights : {};
+ const blockingOverride = series && typeof series.blockingSeverities === 'object' && series.blockingSeverities
+ ? series.blockingSeverities : {};
+
+ // Draft state for the number inputs so typing doesn't fight the controlled
+ // value. Re-seeded from the persisted effective values whenever the series id
+ // or its stored weights change (covers a failed-save revert too — the parent
+ // leaves the series record untouched on failure, so the effective values are
+ // still the persisted ones).
+ const seriesId = series?.id || '';
+ const [draft, setDraft] = useState({});
+ useEffect(() => {
+ setDraft({
+ high: String(effectiveWeight(weightsOverride, 'high')),
+ medium: String(effectiveWeight(weightsOverride, 'medium')),
+ low: String(effectiveWeight(weightsOverride, 'low')),
+ });
+ }, [seriesId, JSON.stringify(weightsOverride)]);
+
+ if (!series) return null;
+
+ // Persist a single weight key. An empty/invalid input CLEARS the key (absent →
+ // default); a valid number sets it. Built onto the STORED override so untouched
+ // keys stay absent.
+ const commitWeight = (sev, rawText) => {
+ const next = { ...weightsOverride };
+ const trimmed = (rawText ?? '').trim();
+ if (trimmed === '') {
+ delete next[sev];
+ } else {
+ const num = Number(trimmed);
+ if (!Number.isFinite(num) || num < 0) {
+ // Invalid → revert the draft to the persisted effective value, no save.
+ setDraft((d) => ({ ...d, [sev]: String(effectiveWeight(weightsOverride, sev)) }));
+ return;
+ }
+ next[sev] = num;
+ }
+ // No-op guard: if nothing actually changed vs the stored override, skip.
+ if (JSON.stringify(next) === JSON.stringify(weightsOverride)) return;
+ onSaveField('severityWeights', next);
+ };
+
+ // Toggle one severity for one gate. Built onto the STORED override so an
+ // untouched gate stays absent (tracks the default). An explicit empty array is
+ // preserved (= nothing blocks this gate).
+ const toggleBlocking = (gate, sev) => {
+ const current = effectiveBlocking(blockingOverride, gate);
+ const nextSet = current.includes(sev)
+ ? current.filter((s) => s !== sev)
+ : [...current, sev];
+ // Order canonically (high → low) for a stable persisted shape.
+ const ordered = SEVERITIES.filter((s) => nextSet.includes(s));
+ const next = { ...blockingOverride, [gate]: ordered };
+ onSaveField('blockingSeverities', next);
+ };
+
+ return (
+ <section className="space-y-3 rounded border border-port-border bg-port-card/40 p-3">
+ <div className="flex items-center justify-between gap-2">
+ <h3 className="text-sm font-semibold text-gray-200">Severity tuning (this series)</h3>
+ {saving ? <span className="text-xs text-gray-500">Saving…</span> : null}
+ </div>
+
+ {/* Severity weights */}
+ <div className="space-y-1.5">
+ <p className="text-xs text-gray-400">
+ Health-score weights — points deducted per open finding. Blank = default.
+ </p>
+ <div className="flex flex-wrap gap-3">
+ {SEVERITIES.map((sev) => {
+ const id = `sev-weight-${sev}`;
+ return (
+ <div key={sev} className="flex items-center gap-1.5">
+ <label htmlFor={id} className="text-xs text-gray-300">{SEVERITY_LABELS[sev]}</label>
+ <input
+ id={id}
+ type="number"
+ min="0"
+ step="1"
+ inputMode="numeric"
+ value={draft[sev] ?? ''}
+ placeholder={String(DEFAULT_SEVERITY_WEIGHTS[sev])}
+ onChange={(e) => setDraft((d) => ({ ...d, [sev]: e.target.value }))}
+ onBlur={(e) => commitWeight(sev, e.target.value)}
+ className="w-16 rounded border border-port-border bg-port-bg px-2 py-1 text-sm text-gray-100 focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ );
+ })}
+ </div>
+ </div>
+
+ {/* Blocking severities per gate */}
+ <div className="space-y-1.5">
+ <p className="text-xs text-gray-400">
+ Blocking severities — which findings pause each autopilot gate. None checked = nothing blocks.
+ </p>
+ <div className="grid gap-2 sm:grid-cols-3">
+ {GATES.map((gate) => {
+ const blocking = effectiveBlocking(blockingOverride, gate.id);
+ return (
+ <fieldset key={gate.id} className="rounded border border-port-border/60 p-2">
+ <legend className="px-1 text-xs font-medium text-gray-300">{gate.label}</legend>
+ <div className="flex flex-col gap-1">
+ {SEVERITIES.map((sev) => {
+ const id = `block-${gate.id}-${sev}`;
+ return (
+ <label key={sev} htmlFor={id} className="flex items-center gap-1.5 text-xs text-gray-300">
+ <input
+ id={id}
+ type="checkbox"
+ checked={blocking.includes(sev)}
+ onChange={() => toggleBlocking(gate.id, sev)}
+ className="h-3.5 w-3.5 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"
+ />
+ {SEVERITY_LABELS[sev]}
+ </label>
+ );
+ })}
+ </div>
+ </fieldset>
+ );
+ })}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/client/src/components/pipeline/editorial/SeriesSeverityConfig.test.jsx b/client/src/components/pipeline/editorial/SeriesSeverityConfig.test.jsx
new file mode 100644
index 0000000000..fbd01ff685
--- /dev/null
+++ b/client/src/components/pipeline/editorial/SeriesSeverityConfig.test.jsx
@@ -0,0 +1,75 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import SeriesSeverityConfig from './SeriesSeverityConfig';
+
+const series = (over = {}) => ({ id: 'ser-1', name: 'S', ...over });
+const weightInput = (sev) => document.getElementById(`sev-weight-${sev}`);
+
+describe('SeriesSeverityConfig (#1616)', () => {
+ let onSaveField;
+ beforeEach(() => { onSaveField = vi.fn(); });
+
+ it('shows the frozen defaults for an unset series', () => {
+ render(<SeriesSeverityConfig series={series()} onSaveField={onSaveField} />);
+ expect(weightInput('high')).toHaveValue(12);
+ expect(weightInput('medium')).toHaveValue(5);
+ expect(weightInput('low')).toHaveValue(1);
+ // arc default = high + medium checked, low unchecked.
+ expect(screen.getByText('Arc verification')).toBeTruthy();
+ expect(document.getElementById('block-arc-high').checked).toBe(true);
+ expect(document.getElementById('block-arc-medium').checked).toBe(true);
+ expect(document.getElementById('block-arc-low').checked).toBe(false);
+ // editorial default = high only.
+ expect(document.getElementById('block-editorial-high').checked).toBe(true);
+ expect(document.getElementById('block-editorial-medium').checked).toBe(false);
+ });
+
+ it('reflects a stored override (effective values)', () => {
+ render(<SeriesSeverityConfig
+ series={series({ severityWeights: { high: 30 }, blockingSeverities: { arc: ['high'], editorial: [] } })}
+ onSaveField={onSaveField}
+ />);
+ // overridden high, default medium/low.
+ expect(weightInput('high')).toHaveValue(30);
+ expect(weightInput('medium')).toHaveValue(5);
+ // arc override = high only (medium now unchecked).
+ expect(document.getElementById('block-arc-medium').checked).toBe(false);
+ // editorial explicit [] → nothing checked.
+ expect(document.getElementById('block-editorial-high').checked).toBe(false);
+ });
+
+ it('saves a single weight key onto the stored override on blur', () => {
+ render(<SeriesSeverityConfig series={series({ severityWeights: { low: 2 } })} onSaveField={onSaveField} />);
+ const high = weightInput('high');
+ fireEvent.change(high, { target: { value: '20' } });
+ fireEvent.blur(high);
+ // merges onto the stored override (keeps low:2), doesn't send the merged defaults.
+ expect(onSaveField).toHaveBeenCalledWith('severityWeights', { low: 2, high: 20 });
+ });
+
+ it('clears a weight key when the input is emptied', () => {
+ render(<SeriesSeverityConfig series={series({ severityWeights: { high: 20, low: 2 } })} onSaveField={onSaveField} />);
+ const high = weightInput('high');
+ fireEvent.change(high, { target: { value: '' } });
+ fireEvent.blur(high);
+ expect(onSaveField).toHaveBeenCalledWith('severityWeights', { low: 2 });
+ });
+
+ it('toggles a blocking severity, persisting an ordered array onto the stored override', () => {
+ render(<SeriesSeverityConfig series={series()} onSaveField={onSaveField} />);
+ // uncheck arc medium → arc becomes [high].
+ fireEvent.click(document.getElementById('block-arc-medium'));
+ expect(onSaveField).toHaveBeenCalledWith('blockingSeverities', { arc: ['high'] });
+ });
+
+ it('unchecking the last box persists an explicit empty array (nothing blocks)', () => {
+ render(<SeriesSeverityConfig series={series({ blockingSeverities: { editorial: ['high'] } })} onSaveField={onSaveField} />);
+ fireEvent.click(document.getElementById('block-editorial-high'));
+ expect(onSaveField).toHaveBeenCalledWith('blockingSeverities', { editorial: [] });
+ });
+
+ it('renders nothing without a series', () => {
+ const { container } = render(<SeriesSeverityConfig series={null} onSaveField={onSaveField} />);
+ expect(container.firstChild).toBeNull();
+ });
+});
diff --git a/client/src/pages/PipelineEditorialChecks.jsx b/client/src/pages/PipelineEditorialChecks.jsx
index bb0f8a9e88..f4e8c462af 100644
--- a/client/src/pages/PipelineEditorialChecks.jsx
+++ b/client/src/pages/PipelineEditorialChecks.jsx
@@ -19,6 +19,7 @@ import EditorialCheckCard from '../components/pipeline/editorial/EditorialCheckC
import EditorialCustomCheckForm from '../components/pipeline/editorial/EditorialCustomCheckForm';
import EditorialFindingsTriage from '../components/pipeline/editorial/EditorialFindingsTriage';
import EditorialHealthPanel from '../components/pipeline/editorial/EditorialHealthPanel';
+import SeriesSeverityConfig from '../components/pipeline/editorial/SeriesSeverityConfig';
import ProviderModelSelector from '../components/ProviderModelSelector';
import TabPills from '../components/ui/TabPills';
import { groupChecksByScope, groupFindingsByCheck, normCategory, canonEntitiesFromUniverse } from '../lib/editorialChecks';
@@ -433,6 +434,30 @@ export default function PipelineEditorialChecks() {
.finally(() => setSavingSeriesIds((s) => { const n = new Set(s); n.delete(checkId); return n; }));
}, []);
+ // Per-series severity config (#1616): the health-score weights + per-gate
+ // blocking-severity sets live as top-level series fields (`severityWeights` /
+ // `blockingSeverities`). Saved through the SAME serialized silent tail as the
+ // per-check override so two quick edits can't reorder/clobber, NON-optimistic
+ // (the panel reverts to the persisted value on failure since the series record
+ // is left untouched). Keyed in savingSeriesIds so the run buttons gate on the
+ // save landing (the autopilot reads the persisted series record).
+ const handleSeriesFieldSave = useCallback((field, value) => {
+ const sid = activeSeriesRef.current;
+ if (!sid) return;
+ setSavingSeriesIds((s) => new Set(s).add(field));
+ seriesSaveTailRef.current = seriesSaveTailRef.current
+ .then(async () => {
+ const saved = await updatePipelineSeries(sid, { [field]: value }, { silent: true })
+ .catch((err) => { toast.error(err.message || 'Failed to save severity config'); return null; });
+ // On success sync THIS series' record by id (keyed, never clobbers
+ // another series); on failure leave it untouched so the panel keeps
+ // showing — and reverts to — the persisted values.
+ if (saved) setSeries((rows) => rows.map((r) => (r.id === saved.id ? saved : r)));
+ })
+ .finally(() => setSavingSeriesIds((s) => { const n = new Set(s); n.delete(field); return n; }));
+ }, []);
+ const severitySaving = savingSeriesIds.has('severityWeights') || savingSeriesIds.has('blockingSeverities');
+
// ---- Custom-check authoring (#1346). The form is URL-driven (?custom=new |
// ?custom=<checkId>) so it's deep-linkable, not a stateful modal. ----
const customParam = searchParams.get('custom') || '';
@@ -633,6 +658,14 @@ export default function PipelineEditorialChecks() {
) : null}
</div>
+ {selectedSeries ? (
+ <SeriesSeverityConfig
+ series={selectedSeries}
+ onSaveField={handleSeriesFieldSave}
+ saving={severitySaving}
+ />
+ ) : null}
+
{loadingCatalog ? (
<p className="flex items-center gap-2 text-sm text-gray-400"><Loader2 size={16} className="animate-spin" /> Loading checks…</p>
) : (
diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.md
index f593b8e1e2..636b1f2e6e 100644
--- a/server/lib/editorial/README.md
+++ b/server/lib/editorial/README.md
@@ -204,4 +204,5 @@ runner-injected `ctx.callInlineLLM` (an inline-prompt sibling of
| `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. Also `inventoryDialogueTags` + `splitScenes` + `findDialogueTagVariety` (`dialogue.tag-variety`, #1587 — per-scene tag inventory flagging within-scene **monotony** (one verb dominates) and **over-variation** (a fresh verb on nearly every line); collapses inflections onto a base lemma via `PLAIN_SPEECH_TAG_GROUPS`). 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. |
+| `severityConfig.js` | Pure per-series severity-config helpers (#1616): the frozen `DEFAULT_SEVERITY_WEIGHTS` (high:12/medium:5/low:1) + `DEFAULT_BLOCKING_SEVERITIES` per autopilot gate (`BLOCKING_GATES` = arc/beatContinuity/editorial), `mergeSeverityWeights` (merge a per-series weight override over the defaults — absent/invalid keys keep the default), `resolveBlockingSet` (the per-gate blocking `Set` — `Array.isArray` first so an explicit empty `[]` "nothing blocks" is distinct from an absent gate's default), and the wire bounders `sanitizeSeverityWeights` / `sanitizeBlockingSeverities` (persisted on the series record, gated at `pipelineSeries` v9). Reuses `CHECK_SEVERITIES` from `checkRegistry.js` as the canonical enum so the wire gate can't drift. |
| `index.js` | Barrel re-export of the above. |
diff --git a/server/lib/editorial/index.js b/server/lib/editorial/index.js
index c369ac40a4..9b2a3c6661 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 './severityConfig.js';
export * from './balloonAttribution.js';
export * from './cliches.js';
export * from './comicPacing.js';
diff --git a/server/lib/editorial/severityConfig.js b/server/lib/editorial/severityConfig.js
new file mode 100644
index 0000000000..423615872f
--- /dev/null
+++ b/server/lib/editorial/severityConfig.js
@@ -0,0 +1,131 @@
+/**
+ * Editorial severity configuration (#1616) — the frozen DEFAULT severity
+ * weights + per-gate blocking-severity sets, plus pure merge/resolve/sanitize
+ * helpers that let a SERIES override either one without ever clobbering the
+ * defaults when no override is set.
+ *
+ * This module is PURE (no side-effecting imports). The canonical severity enum
+ * is `CHECK_SEVERITIES` (`['high','medium','low']`) re-used from
+ * `./checkRegistry.js` so the wire gate, the score weights, and the blocking
+ * sets can never drift apart.
+ *
+ * ABSENT vs INTENTIONALLY-EMPTY is the load-bearing distinction here (mirrors
+ * the PortOS LLM-merge rule):
+ *
+ * - severity weights: an ABSENT key (override omits high/medium/low, or the
+ * value isn't a finite non-negative number) keeps the frozen default. An
+ * empty `{}` override is "nothing overridden" → all defaults. There is no
+ * "intentionally cleared weight" — a weight is always a number.
+ * - blocking sets: an ABSENT gate (override omits the gate, or its value isn't
+ * an array) falls back to the gate's DEFAULT blocking set. An explicit EMPTY
+ * array (`[]`) is a legitimate, distinct choice — "nothing blocks this gate"
+ * — and is honored as-is (NOT treated as absent). So `Array.isArray` MUST be
+ * checked first, before any emptiness check.
+ */
+
+import { CHECK_SEVERITIES } from './checkRegistry.js';
+
+// Transparent severity penalty weights (mirrors editorialScore.SEVERITY_WEIGHTS,
+// which now re-exports this). A draft starts at 100 and loses points per OPEN
+// finding: a `high` costs as much as a dozen `low` nits.
+export const DEFAULT_SEVERITY_WEIGHTS = Object.freeze({ high: 12, medium: 5, low: 1 });
+
+// The autopilot gates that consume a blocking-severity set, and their defaults.
+// arc + beatContinuity are structural-continuity gates (block on high + medium);
+// editorial is the manuscript-review gate (blocks on high only).
+export const BLOCKING_GATES = Object.freeze(['arc', 'beatContinuity', 'editorial']);
+export const DEFAULT_BLOCKING_SEVERITIES = Object.freeze({
+ arc: Object.freeze(['high', 'medium']),
+ beatContinuity: Object.freeze(['high', 'medium']),
+ editorial: Object.freeze(['high']),
+});
+
+const isFiniteNonNegative = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
+
+/**
+ * Merge a per-series severity-weight override over the frozen defaults. Each of
+ * high/medium/low is replaced ONLY when `override[key]` is a finite,
+ * non-negative number; an absent or invalid key keeps its default. A non-object
+ * override (or `{}`) returns the defaults unchanged — absent must NOT clobber.
+ *
+ * Returns a fresh PLAIN object (never the frozen default) so callers may read it
+ * without mutating the shared constant.
+ *
+ * @param {object} [override] — partial `{ high?, medium?, low? }`
+ * @returns {{ high: number, medium: number, low: number }}
+ */
+export function mergeSeverityWeights(override) {
+ const out = { ...DEFAULT_SEVERITY_WEIGHTS };
+ if (!override || typeof override !== 'object' || Array.isArray(override)) return out;
+ for (const sev of CHECK_SEVERITIES) {
+ if (isFiniteNonNegative(override[sev])) out[sev] = override[sev];
+ }
+ return out;
+}
+
+/**
+ * Resolve the blocking-severity Set for one autopilot gate from a per-series
+ * override. `Array.isArray(override[gate])` is checked FIRST so an explicit
+ * empty array (`[]` → "nothing blocks", a legitimate choice) is distinguished
+ * from an absent gate (falls back to the gate's default set). When present, the
+ * array is filtered to the CHECK_SEVERITIES subset (junk dropped) and deduped —
+ * even if that resolves to an empty Set.
+ *
+ * @param {object} [override] — per-series `{ arc?, beatContinuity?, editorial? }`
+ * @param {string} gate — one of BLOCKING_GATES
+ * @returns {Set<string>} the severities that block this gate
+ */
+export function resolveBlockingSet(override, gate) {
+ const raw = override && typeof override === 'object' && !Array.isArray(override)
+ ? override[gate]
+ : undefined;
+ if (Array.isArray(raw)) {
+ // Explicit (possibly empty) override — filter to known severities + dedupe.
+ return new Set(raw.filter((s) => CHECK_SEVERITIES.includes(s)));
+ }
+ // Absent / not-an-array → the gate's frozen default set.
+ return new Set(DEFAULT_BLOCKING_SEVERITIES[gate] || []);
+}
+
+/**
+ * Wire-shape bounder for a per-series severity-weight override (persisted on the
+ * series record). Returns a plain object containing ONLY the high/medium/low
+ * keys whose value is a finite non-negative number (everything else dropped);
+ * returns `{}` when nothing is valid. An empty override therefore persists as
+ * `{}` and `mergeSeverityWeights` falls back to the defaults — so "tunes
+ * nothing" round-trips as the frozen defaults rather than a frozen snapshot.
+ *
+ * @param {*} raw
+ * @returns {object} bounded `{ high?, medium?, low? }`
+ */
+export function sanitizeSeverityWeights(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ const out = {};
+ for (const sev of CHECK_SEVERITIES) {
+ if (isFiniteNonNegative(raw[sev])) out[sev] = raw[sev];
+ }
+ return out;
+}
+
+/**
+ * Wire-shape bounder for a per-series blocking-severity override (persisted on
+ * the series record). Returns a plain object containing ONLY the keys in
+ * BLOCKING_GATES whose value is an Array, each filtered to the CHECK_SEVERITIES
+ * subset and deduped. An explicit empty array is PRESERVED as `[]` (the distinct
+ * "nothing blocks" choice); a non-array gate value is dropped. Returns `{}` when
+ * nothing is valid.
+ *
+ * @param {*} raw
+ * @returns {object} bounded `{ arc?, beatContinuity?, editorial? }`
+ */
+export function sanitizeBlockingSeverities(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ const out = {};
+ for (const gate of BLOCKING_GATES) {
+ if (Array.isArray(raw[gate])) {
+ // Dedupe + drop junk, preserving an explicit empty array as [].
+ out[gate] = [...new Set(raw[gate].filter((s) => CHECK_SEVERITIES.includes(s)))];
+ }
+ }
+ return out;
+}
diff --git a/server/lib/editorial/severityConfig.test.js b/server/lib/editorial/severityConfig.test.js
new file mode 100644
index 0000000000..16ba191593
--- /dev/null
+++ b/server/lib/editorial/severityConfig.test.js
@@ -0,0 +1,118 @@
+import { describe, it, expect } from 'vitest';
+import {
+ DEFAULT_SEVERITY_WEIGHTS,
+ DEFAULT_BLOCKING_SEVERITIES,
+ BLOCKING_GATES,
+ mergeSeverityWeights,
+ resolveBlockingSet,
+ sanitizeSeverityWeights,
+ sanitizeBlockingSeverities,
+} from './severityConfig.js';
+
+describe('severityConfig defaults (#1616)', () => {
+ it('exposes the frozen default weights', () => {
+ expect(DEFAULT_SEVERITY_WEIGHTS).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(Object.isFrozen(DEFAULT_SEVERITY_WEIGHTS)).toBe(true);
+ });
+
+ it('exposes the frozen default blocking sets + gate list', () => {
+ expect(BLOCKING_GATES).toEqual(['arc', 'beatContinuity', 'editorial']);
+ expect(DEFAULT_BLOCKING_SEVERITIES.arc).toEqual(['high', 'medium']);
+ expect(DEFAULT_BLOCKING_SEVERITIES.beatContinuity).toEqual(['high', 'medium']);
+ expect(DEFAULT_BLOCKING_SEVERITIES.editorial).toEqual(['high']);
+ expect(Object.isFrozen(DEFAULT_BLOCKING_SEVERITIES)).toBe(true);
+ });
+});
+
+describe('mergeSeverityWeights (#1616)', () => {
+ it('empty / non-object override keeps the defaults (absent must not clobber)', () => {
+ expect(mergeSeverityWeights({})).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(mergeSeverityWeights(undefined)).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(mergeSeverityWeights(null)).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(mergeSeverityWeights([1, 2, 3])).toEqual({ high: 12, medium: 5, low: 1 });
+ });
+
+ it('applies a partial override, keeping defaults for absent keys', () => {
+ expect(mergeSeverityWeights({ high: 20 })).toEqual({ high: 20, medium: 5, low: 1 });
+ expect(mergeSeverityWeights({ medium: 8, low: 2 })).toEqual({ high: 12, medium: 8, low: 2 });
+ });
+
+ it('accepts 0 as a valid weight (non-negative)', () => {
+ expect(mergeSeverityWeights({ low: 0 })).toEqual({ high: 12, medium: 5, low: 0 });
+ });
+
+ it('rejects negative / NaN / string / non-finite per-key (keeps the default)', () => {
+ expect(mergeSeverityWeights({ high: -1 })).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(mergeSeverityWeights({ high: NaN })).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(mergeSeverityWeights({ high: '20' })).toEqual({ high: 12, medium: 5, low: 1 });
+ expect(mergeSeverityWeights({ high: Infinity })).toEqual({ high: 12, medium: 5, low: 1 });
+ });
+
+ it('returns a fresh object, never the frozen default', () => {
+ const out = mergeSeverityWeights({});
+ expect(out).not.toBe(DEFAULT_SEVERITY_WEIGHTS);
+ expect(Object.isFrozen(out)).toBe(false);
+ });
+});
+
+describe('resolveBlockingSet (#1616)', () => {
+ it('absent gate → the gate default set', () => {
+ expect([...resolveBlockingSet({}, 'arc')].sort()).toEqual(['high', 'medium']);
+ expect([...resolveBlockingSet(undefined, 'editorial')]).toEqual(['high']);
+ // gate present but not an array → default
+ expect([...resolveBlockingSet({ arc: 'high' }, 'arc')].sort()).toEqual(['high', 'medium']);
+ });
+
+ it('explicit empty array → empty Set (nothing blocks, distinct from absent)', () => {
+ const set = resolveBlockingSet({ arc: [] }, 'arc');
+ expect(set.size).toBe(0);
+ });
+
+ it('filters junk severities and dedupes', () => {
+ const set = resolveBlockingSet({ arc: ['high', 'bogus', 'high', 'low'] }, 'arc');
+ expect([...set].sort()).toEqual(['high', 'low']);
+ });
+
+ it('a single-severity override is honored', () => {
+ expect([...resolveBlockingSet({ arc: ['high'] }, 'arc')]).toEqual(['high']);
+ });
+});
+
+describe('sanitizeSeverityWeights (#1616)', () => {
+ it('keeps only valid non-negative numeric keys, drops the rest', () => {
+ expect(sanitizeSeverityWeights({ high: 20, medium: -1, low: '2', bogus: 9 }))
+ .toEqual({ high: 20 });
+ expect(sanitizeSeverityWeights({ low: 0 })).toEqual({ low: 0 });
+ });
+
+ it('returns {} for empty / invalid input (round-trips as defaults via merge)', () => {
+ expect(sanitizeSeverityWeights({})).toEqual({});
+ expect(sanitizeSeverityWeights(null)).toEqual({});
+ expect(sanitizeSeverityWeights('x')).toEqual({});
+ expect(sanitizeSeverityWeights([1])).toEqual({});
+ // an all-invalid override persists as {} and merge falls back to defaults
+ expect(mergeSeverityWeights(sanitizeSeverityWeights({ high: 'no' })))
+ .toEqual({ high: 12, medium: 5, low: 1 });
+ });
+});
+
+describe('sanitizeBlockingSeverities (#1616)', () => {
+ it('keeps only gate keys whose value is an array, filtered + deduped', () => {
+ expect(sanitizeBlockingSeverities({
+ arc: ['high', 'bogus', 'high'],
+ beatContinuity: 'high', // non-array → dropped
+ editorial: ['medium', 'low'],
+ bogusGate: ['high'], // unknown gate → dropped
+ })).toEqual({ arc: ['high'], editorial: ['medium', 'low'] });
+ });
+
+ it('preserves an explicit empty array (nothing blocks)', () => {
+ expect(sanitizeBlockingSeverities({ arc: [] })).toEqual({ arc: [] });
+ });
+
+ it('returns {} for empty / invalid input', () => {
+ expect(sanitizeBlockingSeverities({})).toEqual({});
+ expect(sanitizeBlockingSeverities(null)).toEqual({});
+ expect(sanitizeBlockingSeverities([])).toEqual({});
+ });
+});
diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.js
index 33cfa5a406..128e9197d0 100644
--- a/server/lib/schemaVersions.js
+++ b/server/lib/schemaVersions.js
@@ -124,7 +124,17 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({
// 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: 8,
+ // v9 = `series.severityWeights` + `series.blockingSeverities` added (#1616) —
+ // per-series overrides of the editorial health-score severity weights (default
+ // high:12/medium:5/low:1) and of which severities count as blocking for each
+ // autopilot gate (arc/beatContinuity/editorial). Both default to `{}` (no
+ // override → frozen defaults apply). Same silent-strip-then-LWW corruption as
+ // editorialCheckConfig: a ≤v8 peer that re-sanitizes a series through its
+ // severityWeights/blockingSeverities-unaware `sanitizeSeries` would drop the
+ // overrides 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: 9,
// 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 e2b8976a01..c7666d229f 100644
--- a/server/lib/schemaVersions.test.js
+++ b/server/lib/schemaVersions.test.js
@@ -27,10 +27,11 @@ 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 8 when series.editorialCheckConfig was added (#1591)
- // (v2 = readerMap, v3 = tickingClock, v4 = styleGuide, v5 = coverImage,
- // v6 = characterArcs, v7 = factCritical + factReference).
- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(8);
+ // pipelineSeries bumped to 9 when series.severityWeights + blockingSeverities
+ // were added (#1616) (v2 = readerMap, v3 = tickingClock, v4 = styleGuide,
+ // v5 = coverImage, v6 = characterArcs, v7 = factCritical + factReference,
+ // v8 = editorialCheckConfig).
+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(9);
});
it('declares mediaCollections layout version', () => {
@@ -44,7 +45,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(8);
+ expect(meta.schemaVersions.pipelineSeries).toBe(9);
});
it('overrides merge into schemaVersions', async () => {
diff --git a/server/routes/pipeline.test.js b/server/routes/pipeline.test.js
index f6381f125e..2f14f9bc35 100644
--- a/server/routes/pipeline.test.js
+++ b/server/routes/pipeline.test.js
@@ -2077,6 +2077,32 @@ describe('pipeline routes', () => {
});
});
+ it('PATCH /series/:id accepts + persists severityWeights/blockingSeverities (#1616)', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const r = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
+ severityWeights: { high: 20, low: 2 },
+ blockingSeverities: { arc: ['high'], editorial: [] },
+ });
+ expect(r.status).toBe(200);
+ expect(r.body.severityWeights).toEqual({ high: 20, low: 2 });
+ // Explicit empty array preserved (= nothing blocks the editorial gate).
+ expect(r.body.blockingSeverities).toEqual({ arc: ['high'], editorial: [] });
+ });
+
+ it('PATCH /series/:id 400s on an invalid severity weight / blocking enum (#1616)', async () => {
+ const app = makeApp();
+ const ser = await request(app).post('/api/pipeline/series').send({ name: 'S', universeId: 'u-test' });
+ const neg = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
+ severityWeights: { high: -1 },
+ });
+ expect(neg.status).toBe(400);
+ const badEnum = await request(app).patch(`/api/pipeline/series/${ser.body.id}`).send({
+ blockingSeverities: { arc: ['critical'] },
+ });
+ expect(badEnum.status).toBe(400);
+ });
+
it('PATCH /series/:id/arc-fields/:field/lock merges a single arc field lock', async () => {
const app = makeApp();
const ser = await request(app).post('/api/pipeline/series').send({
diff --git a/server/routes/pipeline/editorial.js b/server/routes/pipeline/editorial.js
index 201cbee548..b71ae8628f 100644
--- a/server/routes/pipeline/editorial.js
+++ b/server/routes/pipeline/editorial.js
@@ -23,6 +23,7 @@ import {
readCustomCheckDefs,
isCustomCheckId,
CUSTOM_CHECK_ID_PREFIX,
+ mergeSeverityWeights,
} from '../../lib/editorial/index.js';
import * as seriesSvc from '../../services/pipeline/series.js';
import * as issuesSvc from '../../services/pipeline/issues.js';
@@ -109,10 +110,13 @@ router.get('/editorial/checks', asyncHandler(async (req, res) => {
// series + per issue), the readiness signal, and the revision trend +
// regressions. Reads the same manuscript-review findings the triage view shows.
router.get('/series/:id/editorial/health', asyncHandler(async (req, res) => {
- await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
const settings = await getSettings();
const gate = readReadinessGate(settings) || DEFAULT_READINESS_GATE;
- res.json(await getSeriesHealth(req.params.id, { gate }));
+ // Per-series severity-weight override (#1616) so the returned score + `weights`
+ // echo reflect the override the autopilot health gate also uses.
+ const weights = mergeSeverityWeights(series?.severityWeights);
+ res.json(await getSeriesHealth(req.params.id, { gate, weights }));
}));
// Set the editorial-health readiness gate (the convergence signal the autopilot
diff --git a/server/routes/pipeline/editorial.test.js b/server/routes/pipeline/editorial.test.js
index 0a40adb099..3cffc73ff2 100644
--- a/server/routes/pipeline/editorial.test.js
+++ b/server/routes/pipeline/editorial.test.js
@@ -288,13 +288,15 @@ describe('editorial health (#1316)', () => {
expect(res.body.seriesId).toBe('s1');
expect(res.body.score).toBe(100);
// No gate configured → service called with the default.
- expect(getSeriesHealth).toHaveBeenCalledWith('s1', { gate: 'noOpenHigh' });
+ // #1616: the route also threads the series' merged severity weights (the mock
+ // series carries no override → the frozen defaults).
+ expect(getSeriesHealth).toHaveBeenCalledWith('s1', { gate: 'noOpenHigh', weights: { high: 12, medium: 5, low: 1 } });
});
it('GET .../editorial/health resolves the configured gate from settings', async () => {
await request(app).patch('/api/pipeline/editorial/readiness-gate').send({ readinessGate: 'noOpenHighOrMedium' });
await request(app).get('/api/pipeline/series/s1/editorial/health');
- expect(getSeriesHealth).toHaveBeenLastCalledWith('s1', { gate: 'noOpenHighOrMedium' });
+ expect(getSeriesHealth).toHaveBeenLastCalledWith('s1', { gate: 'noOpenHighOrMedium', weights: { high: 12, medium: 5, low: 1 } });
});
it('GET .../editorial/health 404s a missing series', async () => {
diff --git a/server/routes/pipeline/manuscript.js b/server/routes/pipeline/manuscript.js
index 3fc5c9d23a..29e8f7fb4d 100644
--- a/server/routes/pipeline/manuscript.js
+++ b/server/routes/pipeline/manuscript.js
@@ -19,7 +19,7 @@ import * as manuscriptFix from '../../services/pipeline/manuscriptFix.js';
import * as completenessRunner from '../../services/pipeline/manuscriptCompletenessRunner.js';
import { getReviewWithStaleness } from '../../services/pipeline/editorial/checkRunner.js';
import { recordTrendSnapshot } from '../../services/pipeline/editorialScore.js';
-import { readReadinessGate } from '../../lib/editorial/index.js';
+import { readReadinessGate, mergeSeverityWeights } from '../../lib/editorial/index.js';
import { getSettings } from '../../services/settings.js';
import { mapServiceError, providerOverrideShape } from './shared.js';
@@ -89,7 +89,7 @@ const manuscriptReformatSchema = z.object({
// Manuscript-completeness editor pass — categorized "finish the draft"
// suggestions read from the actual drafted script (not synopses). Advisory.
router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res) => {
- await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
+ const series = await seriesSvc.getSeries(req.params.id).catch((err) => { throw mapServiceError(err); });
const body = validateRequest(manuscriptCompletenessSchema, req.body ?? {});
const result = await arcPlanner.analyzeManuscriptCompleteness(req.params.id, body)
.catch((err) => { throw mapServiceError(err); });
@@ -101,7 +101,10 @@ router.post('/series/:id/manuscript/completeness', asyncHandler(async (req, res)
// Revision-trend snapshot (#1316): this completeness pass is a revision
// boundary. Best-effort — never fail the request on a ledger-write error.
const gate = readReadinessGate(await getSettings().catch(() => null)) || undefined;
- await recordTrendSnapshot(req.params.id, { runId: result.runId, gate, comments: review.comments })
+ // Series severity-weight override (#1616) so a persisted trend score matches
+ // the live computeHealth score the UI shows.
+ const weights = mergeSeverityWeights(series?.severityWeights);
+ await recordTrendSnapshot(req.params.id, { runId: result.runId, gate, weights, comments: review.comments })
.catch((err) => { console.error(`⚠️ editorial trend snapshot failed — series=${String(req.params.id).slice(0, 12)} ${err.message}`); });
res.json({ ...result, review });
}));
diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.js
index ce24807817..157d209794 100644
--- a/server/routes/pipeline/series.js
+++ b/server/routes/pipeline/series.js
@@ -164,6 +164,26 @@ const seriesLockedSchema = z.object({
arcFields: z.object(optionalBooleanMap(seriesSvc.ARC_LOCKABLE_FIELDS)).optional(),
}).passthrough();
+// Per-series autopilot severity config (#1616). `severityWeights` overrides the
+// health-score weights (high/medium/low → nonnegative number, all optional);
+// `blockingSeverities` overrides which severities block each autopilot gate
+// (arc/beatContinuity/editorial → array of high|medium|low, all optional, an
+// explicit `[]` = "nothing blocks this gate"). Both are re-bounded by the
+// sanitizers (sanitizeSeverityWeights / sanitizeBlockingSeverities) on persist;
+// `null`/`{}` clears the override (frozen defaults apply). Shared between create
+// + patch so the two can't drift.
+const severityWeightsSchema = z.object({
+ high: z.number().nonnegative().optional(),
+ medium: z.number().nonnegative().optional(),
+ low: z.number().nonnegative().optional(),
+}).strict();
+const blockingSeverityEnum = z.enum(['high', 'medium', 'low']);
+const blockingSeveritiesSchema = z.object({
+ arc: z.array(blockingSeverityEnum).optional(),
+ beatContinuity: z.array(blockingSeverityEnum).optional(),
+ editorial: z.array(blockingSeverityEnum).optional(),
+}).strict();
+
const seriesCreateSchema = z.object({
name: z.string().trim().min(1).max(seriesSvc.NAME_MAX),
logline: z.string().trim().max(seriesSvc.LOGLINE_MAX).optional().default(''),
@@ -185,6 +205,9 @@ const seriesCreateSchema = z.object({
// per check at run time, bounded by sanitizeEditorialCheckConfig); forwarded so an
// importer / share-bucket create that seeds tuned thresholds keeps them.
editorialCheckConfig: z.record(z.record(z.unknown())).nullable().optional(),
+ // Per-series autopilot severity config (#1616). null/{} clears.
+ severityWeights: severityWeightsSchema.nullable().optional(),
+ blockingSeverities: blockingSeveritiesSchema.nullable().optional(),
// Fact-checking opt-in + author fact reference (#1588).
factCritical: z.boolean().optional().default(false),
factReference: z.string().trim().max(seriesSvc.FACT_REFERENCE_MAX).optional().default(''),
@@ -233,6 +256,12 @@ const seriesPatchSchema = z.object({
// sanitizeEditorialCheckConfig on persist; this gate just keeps the wire shape sane.
// `null`/`{}` clears all overrides.
editorialCheckConfig: z.record(z.record(z.unknown())).nullable().optional(),
+ // Per-series autopilot severity config (#1616): { high?, medium?, low? } weights
+ // and { arc?, beatContinuity?, editorial? } blocking-severity arrays. Re-bounded
+ // by the sanitizers on persist; `null`/`{}` clears (frozen defaults apply). An
+ // explicit empty array on a gate = "nothing blocks this gate".
+ severityWeights: severityWeightsSchema.nullable().optional(),
+ blockingSeverities: blockingSeveritiesSchema.nullable().optional(),
}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });
const arcFieldLockSchema = z.object({ locked: z.boolean() });
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 1b5d8c3ada..ca5d71563a 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: 9, pipelineIssues: 1, mediaCollections: 1 } } });
+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 10, 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: 9, receiverV: 8 },
+ { category: 'pipelineSeries', senderV: 10, receiverV: 9 },
]);
expect(readSeriesState()).toEqual([]); // nothing written
});
diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.js
index 05c2c1cb90..6addf0cfa3 100644
--- a/server/services/pipeline/editorial/checkRunner.js
+++ b/server/services/pipeline/editorial/checkRunner.js
@@ -30,7 +30,7 @@ import { getFactsLedger } from '../continuityBible.js';
import { getSeriesEditorial } from '../editorialAnalysis.js';
import { seedReviewFromFindings, getReview } from '../manuscriptReview.js';
import { recordTrendSnapshot } from '../editorialScore.js';
-import { readReadinessGate } from '../../../lib/editorial/index.js';
+import { readReadinessGate, mergeSeverityWeights } from '../../../lib/editorial/index.js';
import { canonicalStringify } from '../../../lib/objects.js';
// Per-check severity breakdown for telemetry (#1578). Bucket a check's findings
@@ -768,7 +768,10 @@ export async function runEditorialChecks(seriesId, options = {}) {
// recordTrendSnapshot reads the current review itself. Best-effort — a ledger
// write must never fail the check run (it's telemetry).
const gate = readReadinessGate(settings) || undefined;
- await recordTrendSnapshot(seriesId, { runId, gate, comments: lastReview?.comments }).catch((err) => {
+ // Series severity-weight override (#1616) so the persisted trend score
+ // matches the live computeHealth score the UI shows.
+ const weights = mergeSeverityWeights(series?.severityWeights);
+ await recordTrendSnapshot(seriesId, { runId, gate, weights, comments: lastReview?.comments }).catch((err) => {
console.error(`⚠️ editorial trend snapshot failed — series=${String(seriesId).slice(0, 12)} ${err.message}`);
});
}
diff --git a/server/services/pipeline/editorialScore.js b/server/services/pipeline/editorialScore.js
index d25d980625..58a902999b 100644
--- a/server/services/pipeline/editorialScore.js
+++ b/server/services/pipeline/editorialScore.js
@@ -24,6 +24,7 @@ import { join } from 'path';
import { PATHS, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { createFileWriteQueue } from '../../lib/fileWriteQueue.js';
import { getReview } from './manuscriptReview.js';
+import { DEFAULT_SEVERITY_WEIGHTS } from '../../lib/editorial/severityConfig.js';
// Storage-layout version for the trend ledger. Bump + migrate if the snapshot
// shape changes in a way older peers can't read. (Trend snapshots are local
@@ -36,7 +37,11 @@ const SEVERITIES = Object.freeze(['high', 'medium', 'low']);
// per OPEN finding: a `high` finding costs as much as a dozen `low` nits. These
// are the published formula — surfaced in the API + UI so the score is never a
// black box. Accepted (fixed) and dismissed (waived) findings cost nothing.
-export const SEVERITY_WEIGHTS = Object.freeze({ high: 12, medium: 5, low: 1 });
+// The canonical default lives in `server/lib/editorial/severityConfig.js`
+// (#1616); re-exported here so existing consumers keep working. A SERIES may
+// override these weights — `computeHealth`/`getSeriesHealth` accept a resolved
+// `weights` opt (via `mergeSeverityWeights`) and fall back to this default.
+export const SEVERITY_WEIGHTS = DEFAULT_SEVERITY_WEIGHTS;
// Readiness gates — the convergence signal the autopilot + UI read as "clean".
// `noOpenHigh` (default) is the manuscript-not-clean threshold; the stricter
@@ -90,10 +95,18 @@ export function isReadyUnderGate(openBySeverity, gate) {
}
// The weighted health score for a list of OPEN findings: 100 minus the summed
-// severity penalty, clamped to 0..100. Pure + deterministic.
-export function scoreFromOpen(openBySeverity) {
+// severity penalty, clamped to 0..100. Pure + deterministic. `weights` defaults
+// to SEVERITY_WEIGHTS; a SERIES override (resolved via mergeSeverityWeights)
+// re-weights the penalty so the same finding mix can score differently per
+// series. A missing per-severity weight falls back to the default (defensive
+// against a partial weights object).
+export function scoreFromOpen(openBySeverity, weights = SEVERITY_WEIGHTS) {
const counts = openBySeverity || emptySeverityCounts();
- const penalty = SEVERITIES.reduce((sum, sev) => sum + (counts[sev] || 0) * SEVERITY_WEIGHTS[sev], 0);
+ const w = weights || SEVERITY_WEIGHTS;
+ const penalty = SEVERITIES.reduce(
+ (sum, sev) => sum + (counts[sev] || 0) * (Number.isFinite(w[sev]) ? w[sev] : SEVERITY_WEIGHTS[sev]),
+ 0,
+ );
return Math.max(0, Math.min(100, 100 - penalty));
}
@@ -203,9 +216,11 @@ const newAcc = () => ({
});
// Finalize an accumulator into a scored metric block (adds score + ready).
-function finalize(acc, gate) {
+// `weights` threads the (possibly series-overridden) severity weights into the
+// score; the readiness gate is independent of weights.
+function finalize(acc, gate, weights = SEVERITY_WEIGHTS) {
return {
- score: scoreFromOpen(acc.openBySeverity),
+ score: scoreFromOpen(acc.openBySeverity, weights),
ready: isReadyUnderGate(acc.openBySeverity, gate),
total: acc.total,
open: acc.open,
@@ -224,10 +239,15 @@ function finalize(acc, gate) {
*
* @param {Array} comments — manuscriptReview comment records
* @param {string} [gate] — readiness gate (default DEFAULT_READINESS_GATE)
+ * @param {object} [opts]
+ * @param {object} [opts.weights] — resolved severity weights (a series override,
+ * via mergeSeverityWeights); defaults to SEVERITY_WEIGHTS. Echoed back as the
+ * result's `weights` so the API/UI reflect the override that scored it.
* @returns {{ score, ready, ...series-rollup, gate, weights, perIssue: [] }}
*/
-export function computeHealth(comments, gate = DEFAULT_READINESS_GATE) {
+export function computeHealth(comments, gate = DEFAULT_READINESS_GATE, { weights = SEVERITY_WEIGHTS } = {}) {
const resolvedGate = resolveReadinessGate(gate);
+ const resolvedWeights = weights || SEVERITY_WEIGHTS;
const list = Array.isArray(comments) ? comments : [];
const seriesAcc = newAcc();
const byIssue = new Map();
@@ -241,13 +261,13 @@ export function computeHealth(comments, gate = DEFAULT_READINESS_GATE) {
tally(byIssue.get(key), c);
}
const perIssue = [...byIssue.entries()]
- .map(([issueNumber, acc]) => ({ issueNumber, ...finalize(acc, resolvedGate) }))
+ .map(([issueNumber, acc]) => ({ issueNumber, ...finalize(acc, resolvedGate, resolvedWeights) }))
// Stable order: real issue numbers ascending, the null (series-scoped) bucket last.
.sort((a, b) => (a.issueNumber ?? Infinity) - (b.issueNumber ?? Infinity));
return {
- ...finalize(seriesAcc, resolvedGate),
+ ...finalize(seriesAcc, resolvedGate, resolvedWeights),
gate: resolvedGate,
- weights: SEVERITY_WEIGHTS,
+ weights: resolvedWeights,
perIssue,
};
}
@@ -349,13 +369,15 @@ export async function getTrendLedger(seriesId) {
* @param {object} [opts]
* - runId: the run that produced this revision (snapshot identity)
* - gate: readiness gate to stamp the snapshot's `ready` flag
+ * - weights: resolved (possibly series-overridden) severity weights so a
+ * persisted trend score matches the live computeHealth score (#1616)
* - comments: pre-loaded review comments (skips the getReview round-trip)
* @returns {Promise<object>} the appended snapshot
*/
-export async function recordTrendSnapshot(seriesId, { runId = null, gate = DEFAULT_READINESS_GATE, comments } = {}) {
+export async function recordTrendSnapshot(seriesId, { runId = null, gate = DEFAULT_READINESS_GATE, weights = SEVERITY_WEIGHTS, comments } = {}) {
assertValidSeriesId(seriesId);
const list = Array.isArray(comments) ? comments : (await getReview(seriesId)).comments;
- const health = computeHealth(list, gate);
+ const health = computeHealth(list, gate, { weights });
const snapshot = {
runId: typeof runId === 'string' ? runId : null,
at: nowIso(),
@@ -447,10 +469,10 @@ export function computeTrend(snapshots) {
* readiness signal, and the revision trend + regressions. The single read the
* route + UI consume.
*/
-export async function getSeriesHealth(seriesId, { gate = DEFAULT_READINESS_GATE } = {}) {
+export async function getSeriesHealth(seriesId, { gate = DEFAULT_READINESS_GATE, weights = SEVERITY_WEIGHTS } = {}) {
assertValidSeriesId(seriesId);
const [review, ledger] = await Promise.all([getReview(seriesId), readLedger(seriesId)]);
- const health = computeHealth(review.comments, gate);
+ const health = computeHealth(review.comments, gate, { weights });
const trend = computeTrend(ledger.snapshots);
return { seriesId, ...health, trend, generatedAt: nowIso() };
}
diff --git a/server/services/pipeline/editorialScore.test.js b/server/services/pipeline/editorialScore.test.js
index ce9343f0e0..2360964f57 100644
--- a/server/services/pipeline/editorialScore.test.js
+++ b/server/services/pipeline/editorialScore.test.js
@@ -149,6 +149,29 @@ describe('computeHealth', () => {
expect(health.open).toBe(0);
expect(health.ready).toBe(true);
});
+
+ // Per-series severity-weight override (#1616).
+ it('scores identically to the default when no weights are passed', () => {
+ const comments = [open('high', { issueNumber: 1 }), open('low', { issueNumber: 1 })];
+ expect(computeHealth(comments).score).toBe(100 - SEVERITY_WEIGHTS.high - SEVERITY_WEIGHTS.low);
+ expect(computeHealth(comments).weights).toEqual(SEVERITY_WEIGHTS);
+ });
+
+ it('scoreFromOpen honors a custom weights argument', () => {
+ expect(scoreFromOpen({ high: 1, medium: 0, low: 0 }, { high: 30, medium: 5, low: 1 })).toBe(70);
+ // A missing per-severity weight falls back to the default.
+ expect(scoreFromOpen({ medium: 1 }, { high: 30 })).toBe(100 - SEVERITY_WEIGHTS.medium);
+ });
+
+ it('computeHealth applies a series weight override to the score + echoes it in `weights`', () => {
+ const comments = [open('medium', { issueNumber: 1 }), open('medium', { issueNumber: 2 })];
+ const weights = { high: 12, medium: 20, low: 1 };
+ const health = computeHealth(comments, 'noOpenHigh', { weights });
+ expect(health.score).toBe(100 - 2 * 20);
+ expect(health.weights).toEqual(weights);
+ // The per-issue breakdown is weighted with the same override.
+ expect(health.perIssue.find((p) => p.issueNumber === 1).score).toBe(80);
+ });
});
describe('computeTrend', () => {
diff --git a/server/services/pipeline/manuscriptCompletenessRunner.js b/server/services/pipeline/manuscriptCompletenessRunner.js
index cc95e9b93b..9b7496275f 100644
--- a/server/services/pipeline/manuscriptCompletenessRunner.js
+++ b/server/services/pipeline/manuscriptCompletenessRunner.js
@@ -21,8 +21,9 @@ import { createSseRunner } from '../../lib/sseUtils.js';
import { analyzeManuscriptCompleteness } from './arcPlanner.js';
import { seedReviewFromFindings } from './manuscriptReview.js';
import { recordTrendSnapshot } from './editorialScore.js';
-import { readReadinessGate } from '../../lib/editorial/index.js';
+import { readReadinessGate, mergeSeverityWeights } from '../../lib/editorial/index.js';
import { getSettings } from '../settings.js';
+import { getSeries } from './series.js';
const runner = createSseRunner({ logLabel: 'completeness review' });
@@ -78,7 +79,11 @@ export function startCompletenessReview(seriesId, options = {}) {
// Revision-trend snapshot (#1316): this completeness run is a revision
// boundary. Best-effort telemetry — never fail the run on a ledger write.
const gate = readReadinessGate(await getSettings().catch(() => null)) || undefined;
- await recordTrendSnapshot(seriesId, { runId: result.runId, gate, comments: review.comments }).catch((err) => {
+ // Series severity-weight override (#1616) so the persisted trend score
+ // matches the live computeHealth score the UI shows.
+ const series = await getSeries(seriesId).catch(() => null);
+ const weights = mergeSeverityWeights(series?.severityWeights);
+ await recordTrendSnapshot(seriesId, { runId: result.runId, gate, weights, comments: review.comments }).catch((err) => {
console.error(`⚠️ editorial trend snapshot failed — series=${String(seriesId).slice(0, 12)} ${err.message}`);
});
broadcast({
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 3cc9e42e7a..9b57d7990d 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -17,6 +17,7 @@ import { isStr, trimTo } from '../../lib/storyBible.js';
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';
import { sanitizeStyleGuide } from '../../lib/styleGuide.js';
+import { sanitizeSeverityWeights, sanitizeBlockingSeverities } from '../../lib/editorial/severityConfig.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';
import {
@@ -280,6 +281,12 @@ const sanitizeSeries = (raw) => {
const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;
const autopilot = sanitizeAutopilot(raw.autopilot);
const editorialCheckConfig = sanitizeEditorialCheckConfig(raw.editorialCheckConfig);
+ // Per-series autopilot severity config (#1616). Both default to `{}` (tunes
+ // nothing → frozen defaults apply via mergeSeverityWeights/resolveBlockingSet),
+ // mirroring editorialCheckConfig — so a clear propagates between v9 peers and a
+ // behind-sender's omission is preserved (see ADDITIVE_SERIES_FIELDS).
+ const severityWeights = sanitizeSeverityWeights(raw.severityWeights);
+ const blockingSeverities = sanitizeBlockingSeverities(raw.blockingSeverities);
return {
id: raw.id,
name,
@@ -372,6 +379,12 @@ const sanitizeSeries = (raw) => {
// ADDITIVE_SERIES_FIELDS). Wire-gated at pipelineSeries v8 so a ≤v7 peer can't
// strip-then-LWW the overrides back onto a newer peer.
editorialCheckConfig,
+ // Per-series autopilot severity config (#1616) — the health-score severity
+ // weights + per-gate blocking-severity sets. Both always present (empty `{}`
+ // when nothing is tuned), like editorialCheckConfig. Wire-gated at
+ // pipelineSeries v9 so a ≤v8 peer can't strip-then-LWW them back.
+ severityWeights,
+ blockingSeverities,
};
};
@@ -424,6 +437,11 @@ export async function createSeries(input = {}) {
// importer / promote flow that seeds a series with tuned thresholds keeps
// them; sanitizeSeries normalizes an empty/malformed map to `{}`.
editorialCheckConfig: input.editorialCheckConfig,
+ // Per-series autopilot severity config (#1616) — forwarded so an importer /
+ // promote flow that seeds tuned weights/blocking sets keeps them;
+ // sanitizeSeries normalizes empty/malformed values to `{}`.
+ severityWeights: input.severityWeights,
+ blockingSeverities: input.blockingSeverities,
});
await store().saveOne(created.id, created);
// Skip auto-subscribe for ephemeral series — wire-side push would short-
@@ -603,6 +621,11 @@ export async function updateSeries(id, patch = {}) {
// `{}`/`null` clears every override; omission preserves. The sanitizer drops
// empty/malformed entries and normalizes to `{}` (always present).
...('editorialCheckConfig' in patch ? { editorialCheckConfig: patch.editorialCheckConfig } : {}),
+ // Per-series autopilot severity config (#1616). Wholesale replace —
+ // `{}`/`null` clears the override (defaults apply); omission preserves. The
+ // sanitizer drops malformed values and normalizes to `{}` (always present).
+ ...('severityWeights' in patch ? { severityWeights: patch.severityWeights } : {}),
+ ...('blockingSeverities' in patch ? { blockingSeverities: patch.blockingSeverities } : {}),
llm: mergedLlm,
updatedAt: new Date().toISOString(),
});
@@ -811,7 +834,7 @@ async function cascadeDeleteSideEffects(id) {
// consult the RAW remote payload to tell the two apart: key absent → preserve
// local; key present (even null/empty) → honor the intentional clear. Mirrors
// the `universeId` hierarchy guard. See issue #1361.
-const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical', 'editorialCheckConfig'];
+const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs', 'factReference', 'factCritical', 'editorialCheckConfig', 'severityWeights', 'blockingSeverities'];
// Additive sub-fields nested inside `arc`. A peer that predates these (readerMap
// shipped at schema v2, tickingClock at #1289/v3) still sends an `arc` object —
// just without these keys — so the erasure for them happens one level down.
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index 8324dc494f..606a7cb226 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -166,6 +166,47 @@ describe('pipeline series service', () => {
expect(cleared.editorialCheckConfig).toEqual({});
});
+ it('defaults severityWeights/blockingSeverities to {} and round-trips overrides (#1616)', async () => {
+ const plain = await svc.createSeries({ name: 'PlainSev' });
+ expect(plain.severityWeights).toEqual({});
+ expect(plain.blockingSeverities).toEqual({});
+
+ const tuned = await svc.createSeries({
+ name: 'TunedSev',
+ severityWeights: { high: 20, low: 2 },
+ blockingSeverities: { arc: ['high'], editorial: [] },
+ });
+ expect(tuned.severityWeights).toEqual({ high: 20, low: 2 });
+ // Explicit empty array preserved (= nothing blocks the editorial gate).
+ expect(tuned.blockingSeverities).toEqual({ arc: ['high'], editorial: [] });
+ });
+
+ it('sanitizes severityWeights/blockingSeverities: drops junk, keeps valid (#1616)', async () => {
+ const s = await svc.createSeries({
+ name: 'MessySev',
+ severityWeights: { high: 20, medium: -1, low: '2', bogus: 9 },
+ blockingSeverities: { arc: ['high', 'nope', 'high'], beatContinuity: 'high', bogusGate: ['high'] },
+ });
+ expect(s.severityWeights).toEqual({ high: 20 });
+ expect(s.blockingSeverities).toEqual({ arc: ['high'] });
+ });
+
+ it('updateSeries replaces severity overrides wholesale and clears with {} (#1616)', async () => {
+ const s = await svc.createSeries({
+ name: 'TunableSev',
+ severityWeights: { high: 20 },
+ blockingSeverities: { arc: ['high'] },
+ });
+ // Omission preserves.
+ const kept = await svc.updateSeries(s.id, { logline: 'L2' });
+ expect(kept.severityWeights).toEqual({ high: 20 });
+ expect(kept.blockingSeverities).toEqual({ arc: ['high'] });
+ // Wholesale replace + clear.
+ const replaced = await svc.updateSeries(s.id, { severityWeights: { low: 3 }, blockingSeverities: {} });
+ expect(replaced.severityWeights).toEqual({ low: 3 });
+ expect(replaced.blockingSeverities).toEqual({});
+ });
+
it('updateSeries throws ERR_NOT_FOUND for unknown id', async () => {
await expect(svc.updateSeries('ser-nope', { name: 'x' })).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
@@ -668,6 +709,27 @@ describe('pipeline series service', () => {
expect(cleared.editorialCheckConfig).toEqual({});
});
+ it('preserves severityWeights/blockingSeverities when a behind-sender omits them, applies an explicit clear (#1616)', async () => {
+ const s = await svc.createSeries({
+ name: 'SevKeep',
+ severityWeights: { high: 20 },
+ blockingSeverities: { arc: ['high'] },
+ });
+ // Behind-sender (older peer) omits both keys → local overrides preserved.
+ const behind = { id: s.id, name: 'SevKeep (peer edit)', updatedAt: NEWER };
+ await svc.mergeSeriesFromSync([behind]);
+ const kept = await svc.getSeries(s.id);
+ expect(kept.name).toBe('SevKeep (peer edit)');
+ expect(kept.severityWeights).toEqual({ high: 20 });
+ expect(kept.blockingSeverities).toEqual({ arc: ['high'] });
+ // Up-to-date peer present-but-empty maps → the clear applies (present key wins).
+ const clear = { id: s.id, name: 'SevKeep', severityWeights: {}, blockingSeverities: {}, updatedAt: '2999-06-01T00:00:00.000Z' };
+ await svc.mergeSeriesFromSync([clear]);
+ const cleared = await svc.getSeries(s.id);
+ expect(cleared.severityWeights).toEqual({});
+ expect(cleared.blockingSeverities).toEqual({});
+ });
+
it('preserves arc (incl. readerMap + tickingClock) when the remote omits arc', async () => {
const s = await svc.createSeries({
name: 'ArcKeep',
diff --git a/server/services/pipeline/seriesAutopilot.js b/server/services/pipeline/seriesAutopilot.js
index 3a7b0736a0..da702c0213 100644
--- a/server/services/pipeline/seriesAutopilot.js
+++ b/server/services/pipeline/seriesAutopilot.js
@@ -96,7 +96,7 @@ import { runEditorialChecks, buildEditorialCheckPlan, enabledChecksConsumeRevers
import { generateReverseOutline, getReverseOutline } from './reverseOutline.js';
import { computeHealth, openBlockers, READINESS_GATES, resolveReadinessGate, summarizeEditorialBlockers, formatBlockerSummary } from './editorialScore.js';
import { getSettings } from '../settings.js';
-import { readReadinessGate } from '../../lib/editorial/index.js';
+import { readReadinessGate, mergeSeverityWeights, resolveBlockingSet } from '../../lib/editorial/index.js';
import { generateManuscriptFix, acceptManuscriptFix } from './manuscriptFix.js';
import { verifyComicScript } from './scriptVerify.js';
import { checkSeriesCanonReadiness } from './canonReadiness.js';
@@ -287,13 +287,12 @@ function summarizePlanCost(plan) {
// editorial terminal into draft cover/page rendering (see runVisualDraft).
export const VISUAL_DRAFT_ENABLED = true;
-// Severities that block a verify/review gate (low is informational).
-const ARC_BLOCKING = new Set(['high', 'medium']);
-// Beat continuity is the same class of structural continuity gate as arc verify
-// (a cross-issue continuity break, not a craft note), so it blocks at the same
-// altitude — high + medium.
-const BEAT_CONTINUITY_BLOCKING = ARC_BLOCKING;
-const EDITORIAL_BLOCKING = new Set(['high']);
+// Which severities block each verify/review gate (low is informational) is now
+// PER-SERIES configurable (#1616): the defaults (arc/beatContinuity → high+medium,
+// editorial → high) live in `lib/editorial/severityConfig.js` and a series may
+// override any gate. `startSeriesAutopilot` resolves each gate's blocking Set
+// once via `resolveBlockingSet(series.blockingSeverities, gate)` and stamps it on
+// `record.options.blockingSets` so every read site uses the same resolved set.
// Poll cadence while awaiting a delegated child runner (volume beats / auto-run).
const CHILD_POLL_MS = 750;
@@ -737,7 +736,7 @@ async function runArcVerify(seriesId, record) {
if (beforeVerify) return beforeVerify;
const { issues } = await verifyArc(seriesId, providerOverrideOpts(record));
await recordDomainUsage('cos', { actions: 1 });
- const blocking = issues.filter((i) => ARC_BLOCKING.has(i.severity));
+ const blocking = issues.filter((i) => record.options.blockingSets.arc.has(i.severity));
broadcast(seriesId, {
type: 'verify:round', scope: 'arc', round, findings: issues.length, blocking: blocking.length,
});
@@ -792,7 +791,7 @@ async function runBeatContinuity(seriesId, record) {
if (beforeVerify) return beforeVerify;
const { issues } = await analyzeBeatContinuity(seriesId, providerOverrideOpts(record));
await recordDomainUsage('cos', { actions: 1 });
- const blocking = issues.filter((i) => BEAT_CONTINUITY_BLOCKING.has(i.severity));
+ const blocking = issues.filter((i) => record.options.blockingSets.beatContinuity.has(i.severity));
broadcast(seriesId, {
type: 'verify:round', scope: 'beatContinuity', round, findings: issues.length, blocking: blocking.length,
});
@@ -1022,7 +1021,7 @@ async function runEditorial(sId, record) {
...providerOverrideOpts(record),
});
await recordDomainUsage('cos', { actions: 1 });
- const blocking = (issues || []).filter((i) => EDITORIAL_BLOCKING.has(i.severity));
+ const blocking = (issues || []).filter((i) => record.options.blockingSets.editorial.has(i.severity));
broadcast(sId, {
type: 'verify:round', scope: 'editorial', round, findings: (issues || []).length, blocking: blocking.length,
});
@@ -1047,7 +1046,7 @@ async function runEditorial(sId, record) {
// the loop re-analyzes. Each fix is wrapped so one bad anchor doesn't abort
// the pass (boundary use of try/catch — these call into LLM/file paths).
const review = await getReview(sId).catch(() => ({ comments: [] }));
- const open = (review.comments || []).filter((c) => c.status === 'open' && EDITORIAL_BLOCKING.has(c.severity));
+ const open = (review.comments || []).filter((c) => c.status === 'open' && record.options.blockingSets.editorial.has(c.severity));
for (const comment of open) {
if (record.cancelRequested) return { canceled: true };
// Each generated fix is its own LLM call — gate AND bill per comment so a
@@ -1281,7 +1280,9 @@ async function runEditorialHealthGate(sId, record) {
// top-level catch, which records a clean `error` terminal state.
const review = await getReview(sId);
const comments = review.comments || [];
- const health = computeHealth(comments, gate);
+ // Per-series severity-weight override (#1616) resolved + stamped at start, so
+ // the health score the gate reads matches the live + persisted scores.
+ const health = computeHealth(comments, gate, { weights: record.options.severityWeights });
broadcast(sId, {
type: 'verify:round', scope: 'editorialHealth', round: 1,
findings: health.open, blocking: health.ready ? 0 : health.open, score: health.score,
@@ -1675,12 +1676,25 @@ export async function startSeriesAutopilot(sId, options = {}) {
// effective values. A resume reuses this same path, so a raised persisted
// setting takes effect on the next Resume without re-specifying it.
const settings = await getSettings().catch(() => null);
+ // Per-series severity config (#1616): resolve the (possibly overridden) health
+ // severity weights + the per-gate blocking-severity Sets ONCE at start and
+ // stamp them onto run options, mirroring the round bounds / readiness gate —
+ // so every gate read site + the health gate use the same resolved values, and
+ // a resume re-reads them fresh. Loading the series here is cheap; a missing
+ // series (deleted mid-run) falls through to the frozen defaults.
+ const seriesRecord = await getSeries(sId).catch(() => null);
const runOptions = {
...options,
...resolveAutopilotRounds(options, settings),
readinessGate: resolveAutopilotReadinessGate(options, settings),
checkFindingsPauseThreshold: resolveAutopilotCheckPauseThreshold(options, settings),
notifyOnPause: resolveAutopilotNotifyOnPause(options, settings),
+ severityWeights: mergeSeverityWeights(seriesRecord?.severityWeights),
+ blockingSets: {
+ arc: resolveBlockingSet(seriesRecord?.blockingSeverities, 'arc'),
+ beatContinuity: resolveBlockingSet(seriesRecord?.blockingSeverities, 'beatContinuity'),
+ editorial: resolveBlockingSet(seriesRecord?.blockingSeverities, 'editorial'),
+ },
};
if (existing) {
diff --git a/server/services/pipeline/seriesAutopilot.test.js b/server/services/pipeline/seriesAutopilot.test.js
index 11077ee1c4..1210469ebd 100644
--- a/server/services/pipeline/seriesAutopilot.test.js
+++ b/server/services/pipeline/seriesAutopilot.test.js
@@ -1016,6 +1016,64 @@ describe('autopilot conductor', () => {
expect(series.autopilot?.residualFindings?.[0]?.problem).toBe('plot hole');
});
+ // Per-series blocking-severity sets (#1616).
+ it('arc gate: default blocks a medium finding (pauses)', async () => {
+ verifyFindings = [{ severity: 'medium', problem: 'soft beat', location: 'V1' }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('verifyArc');
+ });
+
+ it('arc gate: a per-series arc:[high] override lets a medium finding pass', async () => {
+ verifyFindings = [{ severity: 'medium', problem: 'soft beat', location: 'V1' }];
+ const { seriesId } = await seedComplete();
+ await seriesSvc.updateSeries(seriesId, { blockingSeverities: { arc: ['high'] } });
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ // medium no longer blocks arc → the run proceeds past arc to completion.
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('arc gate: an empty arc:[] override never blocks, even on a high finding', async () => {
+ verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
+ const { seriesId } = await seedComplete();
+ await seriesSvc.updateSeries(seriesId, { blockingSeverities: { arc: [] } });
+ await autopilot.startSeriesAutopilot(seriesId, { maxArcVerifyRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('beatContinuity gate: a per-series beatContinuity:[high] override lets a medium finding pass', async () => {
+ beatContinuityFindings = [{ severity: 'medium', problem: 'beat drift', location: 'I1' }];
+ const { seriesId } = await seedComplete();
+ await seriesSvc.updateSeries(seriesId, { blockingSeverities: { beatContinuity: ['high'] } });
+ await autopilot.startSeriesAutopilot(seriesId, { maxBeatContinuityRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('editorial gate: an empty editorial:[] override never blocks, even on a high finding', async () => {
+ editorialFindings = [{ severity: 'high', problem: 'missing scene', issueNumber: 1 }];
+ const { seriesId } = await seedComplete();
+ await seriesSvc.updateSeries(seriesId, { blockingSeverities: { editorial: [] } });
+ await autopilot.startSeriesAutopilot(seriesId, { maxEditorialRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ expect(autopilot.__testing.runs.get(seriesId)?.lastPayload?.type).toBe('complete');
+ });
+
+ it('editorial gate: default blocks a high finding (pauses)', async () => {
+ editorialFindings = [{ severity: 'high', problem: 'missing scene', issueNumber: 1 }];
+ const { seriesId } = await seedComplete();
+ await autopilot.startSeriesAutopilot(seriesId, { maxEditorialRounds: 1 });
+ await waitFor(runFinished(seriesId));
+ const last = autopilot.__testing.runs.get(seriesId)?.lastPayload;
+ expect(last?.type).toBe('paused');
+ expect(last?.scope).toBe('editorialReview');
+ });
+
it('posts an in-app notification when a run pauses, with a resume link (#1615)', async () => {
verifyFindings = [{ severity: 'high', problem: 'plot hole', location: 'V1' }];
const { seriesId } = await seedComplete();
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index 519100ba1f..1ab58f043c 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -2333,7 +2333,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: 8 }]);
+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 9 }]);
expect(result.producedByVersion).toBe('99.0.0');
// Series stayed tombstoned (or absent) — apply was refused.
await expect(series.getSeries(s.id)).rejects.toThrow();