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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: per-character story arcs + arc.transitions editorial check (#1293)
Adam Eivy59e3ad19ee08
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3bd495c042..413f4c5afb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Added+- **[issue-1293] Per-character story arcs + an editorial check that finds the beats where characters actually change.** Series now carry an authored **`characterArcs[]`** model — each cast member's *want* / *need*, *start → end* transformation, and explicit **transition beats** (a decision, realization, point-of-no-return, relapse, or sacrifice, each anchorable to an issue). Edit them inline in the Series Bible (a new **Character arcs** section, alongside the style guide); the field is local-only-additive and wire-gated (`pipelineSeries` schema v6) so a not-yet-upgraded peer can't strip-then-LWW the arcs back. A new **Character-arc transitions** editorial check (Create → Editorial Checks) reads the drafted manuscript plus the reverse-outline scene map and these authored arcs to (1) detect genuine change moments and propose them as anchored transition beats, (2) reconcile detected vs authored transitions — flagging an undocumented change the prose delivers or an authored transition the prose never pays off — and (3) flag **flat arcs**: a character who carries the story but never changes. Findings render as `Character arc` notes in the manuscript editor, highlighting the transition scenes. Ships a new stage prompt (`pipeline-editorial-arc-transitions`) that migrates for existing installs (109). (`server/lib/seriesCharacterArc.js`, `server/lib/editorial/checkRegistry.js`, `server/services/pipeline/{series,editorial/checkRunner}.js`, `client/src/pages/PipelineSeries.jsx`, #1293)+- **[issue-911] Mood Boards — an inspiration canvas that feeds the Create suite.** A new **Mood Boards** page (Create → Mood Boards, deep-linkable at `/mood-boards` and `/mood-boards/:id`, reachable via ⌘K / voice as "mood board" / "inspiration" / "references") for collecting visual + textual references, distinct from raw Media History. Create named boards with a description, then pin items: an **image** (external/pinned URL, or an app path like `/data/images/…`) or a **text note**, each with an optional caption and source backref. Items live inline in the board record; the canvas renders an image grid with inline-editable captions and an inline-confirm delete. Boards are **db-primary and local-only** — one row per board in the new `mood_boards` Postgres table (full record in `data` JSONB, modeled on `creative_director_projects`: no sync cursor/tombstone in v1), provisioned by both the boot-time `ensureSchema()` upgrade and `init-db.sql` with an audit trigger, registered via migration 108. Every write locks the board row (`SELECT … FOR UPDATE`) so concurrent add/edit affordances can't clobber each other. Cross-surface "Pin to mood board" affordances and a board picker in the universe/scene/treatment creation flows are tracked as a follow-up. (`server/services/moodBoard/`, `server/routes/moodBoard.js`, `server/lib/moodBoardValidation.js`, `client/src/pages/{MoodBoards,MoodBoardDetail}.jsx`, `client/src/services/apiMoodBoard.js`, #911)- **The series pipeline list now shows a cover thumbnail on each series card.** Like the reference-image thumbnail on the Universe list, each series in **Pipeline** now leads with a small thumbnail of its graphic-novel cover — the first rendered **volume (trade-paperback) cover**, falling back to the earliest rendered **issue cover** — so you can recognize a series at a glance instead of reading names. The thumbnail filename is **persisted onto the series record** (`series.coverImage`) rather than computed at list time, so the list stays cheap (no per-series issue scan): the two cover filename hooks stamp it when a cover render completes, and a one-time, marker-gated boot backfill (`data/series-cover-backfill.applied.json`) derives it for series whose covers rendered before this shipped. Volume covers come straight off the series record (free); the issue fallback is only scanned when no volume cover exists. The field is wire-gated (`pipelineSeries` schema v5) so an older peer can't strip-then-LWW the pointer back, and the card falls back to a book icon when no cover exists yet (or 404s on a peer that synced the pointer but not the bytes). (`server/services/pipeline/seriesCoverImage.js`, `server/services/pipeline/series.js`, `server/services/pipeline/{comicPagesFilenameHook,seasonCoverFilenameHook}.js`, `server/scripts/backfillSeriesCoverImages.js`, `client/src/pages/Pipeline.jsx`)diff --git a/client/src/components/pipeline/manuscript/constants.js b/client/src/components/pipeline/manuscript/constants.jsindex 94b6321b93..87734d166d 100644--- a/client/src/components/pipeline/manuscript/constants.js+++ b/client/src/components/pipeline/manuscript/constants.js@@ -31,9 +31,14 @@ export const SEVERITY_UNDERLINE = {export const CATEGORY_LABEL = {'missing-content': 'Missing content','arc-gap': 'Arc gap',+ // Character-arc findings (#1293/#1295): POV justification + transition beats /+ // flat-arc warnings from the arc.transitions editorial check.+ arc: 'Character arc','character-gap': 'Character gap',pacing: 'Pacing',continuity: 'Continuity',+ style: 'Style',+ exposition: 'Exposition',other: 'Note',};diff --git a/client/src/pages/PipelineSeries.jsx b/client/src/pages/PipelineSeries.jsxindex ab3e22f9bb..bef0b87bdd 100644--- a/client/src/pages/PipelineSeries.jsx+++ b/client/src/pages/PipelineSeries.jsx@@ -15,6 +15,7 @@ import { Link, useParams, useNavigate } from 'react-router-dom';import {ArrowLeft, Save, Loader2, Workflow as WorkflowIcon, Globe, NotebookPen,PanelLeftClose, PanelLeftOpen, Sparkles, BookOpen, FileInput, Compass, BookMarked,+ Plus, Trash2,} from 'lucide-react';import toast from '../components/ui/Toast';import ArcCanvas from '../components/pipeline/ArcCanvas';@@ -50,7 +51,7 @@ const STYLE_OVERRIDE_MODE_TABS = [// constants so the `useArcCanvasSync` callbacks keep a stable identity.const ARC_FLUSH_FIELDS = ['name', 'logline', 'premise', 'styleNotes', 'styleGuide', 'titleLogo', 'author', 'authorId',- 'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId',+ 'stylePromptOverride', 'stylePromptOverrideMode', 'issueCountTarget', 'universeId', 'characterArcs',];const ARC_PAYLOAD_DEFAULTS = {titleLogo: '',@@ -61,6 +62,9 @@ const ARC_PAYLOAD_DEFAULTS = {// Structured house style — null means "no style guide", which the server// sanitizer also produces from an all-empty guide.styleGuide: null,+ // Per-character story arcs (#1293) — [] means "no authored arcs"; the server+ // sanitizer drops empty arcs/beats and dedupes by character identity.+ characterArcs: [],};// Style-guide option lists — mirror the enums in server/lib/styleGuide.js. Each@@ -383,6 +387,8 @@ function BibleSidebar({ series, universes, patchSeries, onSeriesUpdate, onFlushP<StyleGuideSection series={series} patchSeries={patchSeries} />+ <CharacterArcsSection series={series} patchSeries={patchSeries} />+<div className="block"><div className="flex items-center justify-between mb-1"><label@@ -572,6 +578,158 @@ function StyleGuideSection({ series, patchSeries }) {);}+// The change-beat kinds the arc.transitions editorial check recognizes — mirror+// TRANSITION_KINDS in server/lib/seriesCharacterArc.js.+const TRANSITION_KIND_OPTIONS = [+ ['decision', 'Decision'],+ ['realization', 'Realization'],+ ['point-of-no-return', 'Point of no return'],+ ['relapse', 'Relapse'],+ ['sacrifice', 'Sacrifice'],+];++// Per-character story arcs (#1293). Authored want/need, start → end state, and+// explicit transition beats, edited into local series state via patchSeries and+// persisted on Save (characterArcs is in ARC_FLUSH_FIELDS). The server sanitizer+// drops empty arcs/beats and dedupes by character identity, so the editor stays+// permissive — a freshly-added blank arc simply doesn't persist until named. The+// arc.transitions editorial check reconciles its detected change moments against+// what's authored here and flags characters with no transition scenes (flat arcs).+function CharacterArcsSection({ series, patchSeries }) {+ const arcs = Array.isArray(series.characterArcs) ? series.characterArcs : [];+ const setArcs = (next) => patchSeries({ characterArcs: next });+ const setArc = (i, patch) => setArcs(arcs.map((a, idx) => (idx === i ? { ...a, ...patch } : a)));+ const addArc = () => setArcs([...arcs, { characterName: '', want: '', need: '', startState: '', endState: '', transitions: [] }]);+ const removeArc = (i) => setArcs(arcs.filter((_, idx) => idx !== i));++ const setTransitions = (i, next) => setArc(i, { transitions: next });+ const addTransition = (i) => {+ const cur = Array.isArray(arcs[i]?.transitions) ? arcs[i].transitions : [];+ setTransitions(i, [...cur, { kind: 'decision', label: '', atIssue: null }]);+ };+ const setTransition = (i, j, patch) => {+ const cur = Array.isArray(arcs[i]?.transitions) ? arcs[i].transitions : [];+ setTransitions(i, cur.map((t, idx) => (idx === j ? { ...t, ...patch } : t)));+ };+ const removeTransition = (i, j) => {+ const cur = Array.isArray(arcs[i]?.transitions) ? arcs[i].transitions : [];+ setTransitions(i, cur.filter((_, idx) => idx !== j));+ };++ const inputCls = 'w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-white text-sm';++ return (+ <div className="block">+ <div className="flex items-center justify-between mb-1">+ <h3 className="text-xs uppercase tracking-wider text-gray-500">Character arcs</h3>+ <button+ type="button"+ onClick={addArc}+ className="flex items-center gap-1 text-[11px] text-port-accent hover:text-blue-400"+ >+ <Plus size={12} /> Add arc+ </button>+ </div>+ <p className="text-[11px] text-gray-500 mb-3 -mt-1">+ Each cast member's want / need, start → end transformation, and the transition beats+ where they actually change. The editorial “Character-arc transitions” check reconciles+ these against the manuscript and flags characters with no change scenes.+ </p>++ {arcs.length === 0 && (+ <p className="text-[11px] text-gray-600 italic mb-2">No character arcs yet.</p>+ )}++ <div className="space-y-3">+ {arcs.map((arc, i) => {+ const transitions = Array.isArray(arc.transitions) ? arc.transitions : [];+ return (+ <div key={i} className="border border-port-border rounded p-2 bg-port-bg/40">+ <div className="flex items-center gap-2 mb-2">+ <input+ aria-label="Character name"+ value={arc.characterName || ''}+ onChange={(e) => setArc(i, { characterName: e.target.value })}+ placeholder="Character name"+ className={`${inputCls} font-medium`}+ />+ <button+ type="button"+ onClick={() => removeArc(i)}+ className="text-gray-500 hover:text-port-error shrink-0"+ title="Remove this character arc"+ >+ <Trash2 size={14} />+ </button>+ </div>+ <div className="grid grid-cols-2 gap-2">+ <input aria-label="Want" value={arc.want || ''} onChange={(e) => setArc(i, { want: e.target.value })} placeholder="Wants (external goal)" className={inputCls} />+ <input aria-label="Need" value={arc.need || ''} onChange={(e) => setArc(i, { need: e.target.value })} placeholder="Needs (internal lesson)" className={inputCls} />+ <input aria-label="Start state" value={arc.startState || ''} onChange={(e) => setArc(i, { startState: e.target.value })} placeholder="Starts as…" className={inputCls} />+ <input aria-label="End state" value={arc.endState || ''} onChange={(e) => setArc(i, { endState: e.target.value })} placeholder="Ends as…" className={inputCls} />+ </div>++ <div className="mt-2">+ <div className="flex items-center justify-between mb-1">+ <span className="text-[10px] uppercase tracking-wider text-gray-600">Transitions</span>+ <button+ type="button"+ onClick={() => addTransition(i)}+ className="flex items-center gap-1 text-[11px] text-port-accent hover:text-blue-400"+ >+ <Plus size={11} /> Add beat+ </button>+ </div>+ <div className="space-y-1.5">+ {transitions.map((t, j) => (+ <div key={j} className="flex items-center gap-1.5">+ <select+ aria-label="Transition kind"+ value={t.kind || 'decision'}+ onChange={(e) => setTransition(i, j, { kind: e.target.value })}+ className="px-1.5 py-1 bg-port-bg border border-port-border rounded text-white text-xs shrink-0"+ >+ {TRANSITION_KIND_OPTIONS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}+ </select>+ <input+ aria-label="Transition label"+ value={t.label || ''}+ onChange={(e) => setTransition(i, j, { label: e.target.value })}+ placeholder="What changes"+ className="flex-1 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ <input+ aria-label="At issue"+ type="number"+ min={0}+ value={Number.isFinite(t.atIssue) ? t.atIssue : ''}+ onChange={(e) => {+ const n = parseInt(e.target.value, 10);+ setTransition(i, j, { atIssue: Number.isFinite(n) ? n : null });+ }}+ placeholder="#"+ className="w-14 px-1.5 py-1 bg-port-bg border border-port-border rounded text-white text-xs"+ />+ <button+ type="button"+ onClick={() => removeTransition(i, j)}+ className="text-gray-500 hover:text-port-error shrink-0"+ title="Remove this transition"+ >+ <Trash2 size={12} />+ </button>+ </div>+ ))}+ </div>+ </div>+ </div>+ );+ })}+ </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.diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonindex b914ece407..cf6d82ab2e 100644--- a/data.reference/prompts/stage-config.json+++ b/data.reference/prompts/stage-config.json@@ -555,6 +555,13 @@"returnsJson": true,"variables": []},+ "pipeline-editorial-arc-transitions": {+ "name": "Pipeline — Editorial Check: Character-arc transitions",+ "description": "Editorial check (#1293): scans each character's scenes for genuine change moments (decision, realization, point-of-no-return, relapse, sacrifice) and proposes transition beats with anchor quotes. Reconciles detected change moments against the authored per-character arcs (series.characterArcs) and flags flat arcs — a carrying character with no transition scenes. Reads the stitched manuscript plus the reverse-outline scene map (degrading to a whole-issue scan when absent). Returns issue-anchored findings.",+ "model": "default",+ "returnsJson": true,+ "variables": []+ },"pipeline-editorial-object-motivation": {"name": "Pipeline — Editorial Check: Unmotivated object interaction","description": "Editorial check (#1288): flags moments where a character treats an object as significant without earned motivation — no recorded attachment and no on-page setup. Reads the stitched manuscript plus the canon object↔character attachments. Returns issue-anchored findings.",diff --git a/data.reference/prompts/stages/pipeline-editorial-arc-transitions.md b/data.reference/prompts/stages/pipeline-editorial-arc-transitions.mdnew file mode 100644index 0000000000..7e29bfb062--- /dev/null+++ b/data.reference/prompts/stages/pipeline-editorial-arc-transitions.md@@ -0,0 +1,104 @@+# Pipeline — Editorial Check: Character-arc transitions++You are a developmental editor doing a single focused pass for ONE concern:+**character-arc transitions** — the beats where a character actually *changes*.+A satisfying arc is not a character who is described differently at the end; it+is a character the reader watched turn, at specific, earned moments. Your job is+to find those moments, judge whether each character's arc has them, and+reconcile what the prose delivers against what the author planned.++A genuine transition is one of:++- **decision** — an active choice that commits the character to a new path.+- **realization** — an internal understanding that reframes how they see things.+- **point-of-no-return** — an irreversible act after which the old life is gone.+- **relapse** — a backslide into the old self (a real beat, not a failure of craft).+- **sacrifice** — giving up the external *want* to honor the internal *need*.++Do NOT flag: ordinary plot events that don't change the character; a description+of change with no scene that dramatizes it (that is itself a finding — see+below); minor characters who are not meant to carry an arc.++{{#characterArcs}}+## Authored character arcs++The author has recorded these per-character arcs (want, need, start → end state,+and any transition beats they already planned). Reconcile the prose against+them: a transition the prose delivers but the arc never recorded, an authored+transition the prose never pays off, and an authored arc that is contradicted by+what actually happens on the page.++```+{{characterArcs}}+```+{{/characterArcs}}++{{#sceneMap}}+## Scene segmentation++The reverse outline below segments the manuscript into scenes (with the recorded+setting, POV character, and characters present). Use it to attribute each+transition to a scene and its issue; judge the change itself from the prose.++```+{{sceneMap}}+```+{{/sceneMap}}++## Manuscript++The manuscript is stitched from the drafted issues. Section headers attribute+each chunk to an issue (e.g. `# Issue 3 — Title (prose)`). Use the issue number+in each header to attribute every finding to its `issueNumber`.++```+{{manuscript}}+```++## Task++For each named character who carries meaningful presence in the manuscript:++1. **Detect transition beats.** Find the genuine change moments and propose them+ as findings. Quote a short verbatim anchor (≤ 200 chars) at the moment of+ change, name the `transitionKind` (one of: `decision`, `realization`,+ `point-of-no-return`, `relapse`, `sacrifice`), and put the character's name in+ the `character` field. Set the `location` to the character + kind (e.g.+ `Mara — point-of-no-return`).+2. **Reconcile against the authored arcs** (only when authored arcs are present+ above): flag a clear change moment in the prose that the author's arc never+ recorded (`problem` says "undocumented transition"), and an authored+ transition the prose never delivers (`problem` says "authored transition not+ paid off").+3. **Flag flat arcs.** A character who plainly carries the story (a POV holder, a+ protagonist, a recurring named figure) but has NO transition beat anywhere —+ they end as they began — is a flat arc. Emit one finding with+ `transitionKind` set to `flat`, naming the character and why their flatness+ weakens the story.++Severity: a flat arc for a central character or a missing point-of-no-return is+high; an undocumented minor transition is low. If every carrying character has a+clear, earned arc and the prose matches the authored plan, return an empty+`findings` array — do not invent change where the story is intentionally steady.++## Output contract++Return ONLY valid JSON matching this shape — no prose, no markdown fence, no+commentary:++```json+{+ "findings": [+ {+ "severity": "high|medium|low",+ "issueNumber": 3,+ "character": "the character whose arc this concerns",+ "transitionKind": "decision|realization|point-of-no-return|relapse|sacrifice|flat",+ "location": "string — character + kind (e.g. 'Mara — point-of-no-return')",+ "problem": "1–3 sentences naming the transition (or its absence) and why it matters",+ "suggestion": "1–3 sentences proposing how to land, document, or create the change",+ "anchorQuote": "short verbatim quote at the moment of change (≤ 200 chars); omit for a flat-arc finding"+ }+ ]+}+```diff --git a/scripts/migrations/109-editorial-arc-transitions-stage.js b/scripts/migrations/109-editorial-arc-transitions-stage.jsnew file mode 100644index 0000000000..afa8edb59a--- /dev/null+++ b/scripts/migrations/109-editorial-arc-transitions-stage.js@@ -0,0 +1,75 @@+/**+ * Seed the `pipeline-editorial-arc-transitions` stage into existing installs (#1293).+ *+ * Mirrors `099-editorial-interiority-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 character-arc transition+ * stage unseeded and the `arc.transitions` 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-arc-transitions.md';+const STAGE_KEY = 'pipeline-editorial-arc-transitions';++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-arc-transitions prompt: already present`);+ } else {+ const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);+ if (!sampleExists) {+ console.warn(`⚠️ pipeline-editorial-arc-transitions: sample missing for ${FILENAME} — skipping copy`);+ } else {+ try {+ await copyFile(samplePath, dataPath);+ console.log(`✅ seeded ${FILENAME}`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-arc-transitions: 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-arc-transitions: 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-arc-transitions stage-config: already present`);+ return;+ }+ if (!sample?.stages?.[STAGE_KEY]) {+ console.warn(`⚠️ pipeline-editorial-arc-transitions: 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-arc-transitions stage-config (${action}): 1 added`);+ } catch (err) {+ console.warn(`⚠️ pipeline-editorial-arc-transitions: stage-config merge failed: ${err.message}`);+ }+ },+};diff --git a/scripts/migrations/109-editorial-arc-transitions-stage.test.js b/scripts/migrations/109-editorial-arc-transitions-stage.test.jsnew file mode 100644index 0000000000..59b8162332--- /dev/null+++ b/scripts/migrations/109-editorial-arc-transitions-stage.test.js@@ -0,0 +1,86 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join, dirname } from 'path';+import { fileURLToPath } from 'url';++import migration from './109-editorial-arc-transitions-stage.js';++// scripts/migrations/<this> → ../.. is the repo root (matches _testHelpers.js).+const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');++// First-shipment seed migration (mirrors 099) — no MD5 bookkeeping, so the+// seed / no-clobber behavior is asserted directly.++const FILENAME = 'pipeline-editorial-arc-transitions.md';+const STAGE_KEY = 'pipeline-editorial-arc-transitions';+const BODY = '# Character-arc transitions\n\nshipped body\n';++describe('migration 109 — seed editorial-arc-transitions stage', () => {+ let rootDir;+ let stagesDir;+ let refStagesDir;+ let installedConfigPath;++ const seedReference = ({ withConfig = true } = {}) => {+ writeFileSync(join(refStagesDir, FILENAME), BODY);+ if (withConfig) {+ const refConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');+ writeFileSync(+ refConfigPath,+ JSON.stringify({ stages: { [STAGE_KEY]: { name: STAGE_KEY, description: 'desc', model: 'default', returnsJson: true, variables: [] } } }, null, 2) + '\n',+ );+ }+ };++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-109-'));+ stagesDir = join(rootDir, 'data', 'prompts', 'stages');+ refStagesDir = join(rootDir, 'data.reference', 'prompts', 'stages');+ installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');+ mkdirSync(stagesDir, { recursive: true });+ mkdirSync(refStagesDir, { recursive: true });+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('seeds the .md template and merges the stage-config entry on a fresh install', async () => {+ seedReference();+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(BODY);+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages[STAGE_KEY]).toMatchObject({ returnsJson: true });+ });++ it('is idempotent and never clobbers a customized .md or an existing stage-config entry', async () => {+ seedReference();+ const customBody = '# CUSTOMIZED — do not overwrite\n';+ writeFileSync(join(stagesDir, FILENAME), customBody);+ writeFileSync(+ installedConfigPath,+ JSON.stringify({ stages: { [STAGE_KEY]: { name: 'user-tuned', model: 'custom' } } }, null, 2) + '\n',+ );++ await migration.up({ rootDir });++ expect(readFileSync(join(stagesDir, FILENAME), 'utf8')).toBe(customBody);+ const installed = JSON.parse(readFileSync(installedConfigPath, 'utf8'));+ expect(installed.stages[STAGE_KEY]).toEqual({ name: 'user-tuned', model: 'custom' });+ });++ it('does not throw when the data.reference samples are missing', async () => {+ await expect(migration.up({ rootDir })).resolves.not.toThrow();+ expect(existsSync(join(stagesDir, FILENAME))).toBe(false);+ });++ it('matches the live shipped stage-config key + prompt file (drift catch)', () => {+ const refConfig = JSON.parse(+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stage-config.json'), 'utf8'),+ );+ expect(refConfig.stages[STAGE_KEY], `stage-config missing ${STAGE_KEY}`).toBeTruthy();+ expect(refConfig.stages[STAGE_KEY].returnsJson).toBe(true);+ expect(existsSync(join(repoRoot, 'data.reference', 'prompts', 'stages', FILENAME))).toBe(true);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 7b68ba6d5c..9612e43f0a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -55,6 +55,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `scenePrompt.js` | Scene-prompt composer + bible matchers (chars/places/objects in text). || `sceneExtractor.js` | Split prose or teleplay into scene list via LLM. || `seasonStructure.js` | Season/episode structure recommendation. |+| `seriesCharacterArc.js` | Per-character story-arc shapes (`series.characterArcs[]`): want/need, start → end state, transition beats. Sanitizers + `renderCharacterArcsForPrompt` for the `arc.transitions` editorial check. || `seriesLlmOverride.js` | Pure `resolveSeriesLlmOverride(series, { overrideProvider, overrideModel })` → `{ provider, model, providerMatchesSeries }` — shared fallback so Pipeline LLM actions honor the series' configured provider/model, only inheriting the series model when the effective provider still matches. || `bibleExtractor.js` | LLM bible-extraction stage + sanitization. || `catalogBulkParsers.js` | Dependency-free markdown/CSV/JSON parsers for `POST /api/catalog/bulk-import` and YAML/markdown serializers for `GET /api/catalog/export`. |diff --git a/server/lib/editorial/README.md b/server/lib/editorial/README.mdindex 76866488e2..4398787e0c 100644--- a/server/lib/editorial/README.md+++ b/server/lib/editorial/README.md@@ -57,7 +57,7 @@ it. To add a new built-in check, append an entry to `EDITORIAL_CHECKS` inDeclare every input the check's `run(ctx)` reads in its `sources` array (anon-empty subset of `EDITORIAL_SOURCES`: `manuscript`, `canon`,`series.styleGuide`, `series.arc.tickingClock`, `series.arc.readerMap`,-`reverseOutline`, `editorialArcs`). The staleness+`reverseOutline`, `editorialArcs`, `series.characterArcs`). The stalenessrunner fingerprints exactly those sources, so a finding goes stale only whencontent the check actually analyzed drifts — declare too few and a finding staysfalsely fresh; a `manuscript` source must pair with `needsManuscript: true`, and@@ -65,11 +65,14 @@ falsely fresh; a `manuscript` source must pair with `needsManuscript: true`, andinject `ctx.reverseOutline` (the scenes array). `editorialArcs` (#1295) makes therunner fetch the series editorial aggregate and inject `ctx.editorialArcs` (thedetected per-character `{ name, arcDirection, issueCount, isProtagonist }`-projection — the graceful-degradation fallback for the dedicated arc model until-`#arc-transitions` lands) plus a derived `ctx.editorialArcsComplete` boolean (true-only when every analyzable issue is analyzed and fresh), so a check can tell-"absent because arc-less" from "absent because not-yet-analyzed" under a partial-coverage batch. When a new check reads a+projection — the coarse DETECTED arc signal) plus a derived+`ctx.editorialArcsComplete` boolean (true only when every analyzable issue is+analyzed and fresh), so a check can tell "absent because arc-less" from "absent+because not-yet-analyzed" under a partial coverage batch. `series.characterArcs`+(#1293) reads the AUTHORED per-character arcs off the already-loaded series+record (`series.characterArcs[]` — want/need, start → end state, transition+beats), which the `arc.transitions` check reconciles detected change moments+against. When a new check reads a`ctx.series` field (or another artifact) that isn't yet a token, add the token to`EDITORIAL_SOURCES` and a matching resolver in the runner's `SOURCE_RESOLVERS`.diff --git a/server/lib/editorial/checkRegistry.js b/server/lib/editorial/checkRegistry.jsindex 211bd86fa0..fc74eb42ea 100644--- a/server/lib/editorial/checkRegistry.js+++ b/server/lib/editorial/checkRegistry.js@@ -26,6 +26,7 @@import { z } from 'zod';import { estimateTokens } from '../contextBudget.js';+import { renderCharacterArcsForPrompt } from '../seriesCharacterArc.js';import { analyzeNamePair, findFirstLetterClusters, normalizeName } from './nameSimilarity.js';import { findCliches, findModifierStacking } from './cliches.js';import { findItalicThoughts } from './italicThoughts.js';@@ -58,8 +59,13 @@ const SEVERITIES = CHECK_SEVERITIES;// editorial analysis aggregate (#1295). The runner fetches it// (gated on this source) and injects `ctx.editorialArcs`// (`[{ name, arcDirection, issueCount, isProtagonist }]`). This-// is the graceful-degradation fallback for the dedicated arc-// model (#arc-transitions) until that lands.+// is the coarse, DETECTED arc signal — distinct from the+// AUTHORED `series.characterArcs` model below.+// - 'series.characterArcs' — the AUTHORED per-character story arcs (#1293):+// `series.characterArcs[]` (`{ characterId, characterName,+// want, need, startState, endState, transitions[] }`). The+// arc.transitions check reconciles detected change moments+// against these authored transitions + flat-arc warnings.export const EDITORIAL_SOURCES = Object.freeze(['manuscript','canon',@@ -68,6 +74,7 @@ export const EDITORIAL_SOURCES = Object.freeze(['series.arc.readerMap','reverseOutline','editorialArcs',+ 'series.characterArcs',]);// Default per-run finding cap for user-defined checks (#1346) — mirrors the@@ -181,6 +188,14 @@ export const KILL_YOUR_DARLINGS_STAGE = 'pipeline-editorial-kill-your-darlings';export const SENSORY_BALANCE_STAGE = 'pipeline-editorial-sensory-balance';export const WHITE_ROOM_STAGE = 'pipeline-editorial-white-room';+// Stage name for the character-arc transition-detection LLM check (#1293). Ships+// in data.reference/prompts/stages/ + stage-config.json (fresh installs via+// setup-data.js) and migrates to existing installs via migration 109 (boot runs+// migrations but NOT setup-data, so the migration is required). Reads the+// stitched manuscript plus the reverse-outline scene map and the AUTHORED+// per-character arcs to surface genuine change moments + flat-arc warnings.+export const ARC_TRANSITIONS_STAGE = 'pipeline-editorial-arc-transitions';+// Render the authored reader-map cliffhangers (#1298) into a compact text block// the chapter-ending check passes alongside the manuscript so the model// reconciles its DETECTED endings against the issue-boundary tugs the writer@@ -1549,6 +1564,63 @@ export const EDITORIAL_CHECKS = [return findings;},},+ {+ id: 'arc.transitions',+ sources: ['manuscript', 'reverseOutline', 'series.characterArcs'],+ label: 'Character-arc transitions (change moments + flat arcs)',+ description:+ 'Scans each character\'s scenes for genuine change moments — a decision, a realization, a point of no return, a relapse, a sacrifice — and proposes transition beats with anchor quotes. Reconciles detected change moments against the AUTHORED per-character arcs (series.characterArcs): flags a transition the prose delivers but the arc never recorded, an authored transition the prose never pays off, and a character who carries the story but has no transition scenes at all (a flat arc).',+ scope: 'series',+ kind: 'llm',+ category: 'arc',+ severityDefault: 'medium',+ defaultEnabled: true,+ // Reads the stitched manuscript corpus — so the runner only pays the+ // section-collection I/O when a manuscript-consuming check is enabled.+ 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),+ }),+ 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.',+ },+ ],+ gate: (ctx) => (ctx.manuscript || '').trim().length > 0,+ run: (ctx) => {+ // Both blocks are fixed per-call overhead (re-sent on each chunk) and pure+ // context: the scene map lets the model attribute transitions to scenes,+ // the authored arcs let it reconcile detected vs authored change moments.+ // The check degrades gracefully — no outline ⇒ {{#sceneMap}} renders+ // nothing; no authored arcs ⇒ {{#characterArcs}} renders nothing and the+ // check proposes transitions from scratch (and can't fire the+ // "missing/unjustified authored transition" reconciliation arm).+ const sceneMap = sceneGroundingSummary(ctx.reverseOutline);+ const characterArcs = renderCharacterArcsForPrompt(ctx.series?.characterArcs) || '';+ return runManuscriptLlmCheck(ctx, {+ stage: ARC_TRANSITIONS_STAGE,+ category: 'arc',+ overheadTokens:+ EDITORIAL_PROMPT_OVERHEAD_TOKENS + estimateTokens(sceneMap) + estimateTokens(characterArcs),+ buildVars: (manuscript) => ({ manuscript, sceneMap, characterArcs }),+ // Arc change moments accrue across the whole manuscript — a flat-arc+ // verdict needs to see whether a character ever changed in a LATER+ // chunk. Roll a "transitions seen so far" digest forward so a+ // multi-chunk manuscript doesn't false-flag an early-chapters-flat+ // character whose turn lands in the finale.+ crossChunkSetup: true,+ setupFocus:+ 'For each named character, note any genuine change moment so far (a decision, realization, point of no return, relapse, or sacrifice) and where it landed. Carry forward who has changed and who is still flat, so a later chunk can tell a truly flat arc from one whose turn simply has not arrived yet.',+ });+ },+ },{id: 'relationships.reciprocity',sources: ['canon'],diff --git a/server/lib/editorial/checkRegistry.test.js b/server/lib/editorial/checkRegistry.test.jsindex 8884abd189..838c80ea32 100644--- a/server/lib/editorial/checkRegistry.test.js+++ b/server/lib/editorial/checkRegistry.test.js@@ -1279,6 +1279,88 @@ describe('pov.justified — deterministic check', () => {});});+describe('arc.transitions — LLM check (#1293)', () => {+ const ARC = 'arc.transitions';+ const baseCtx = (overrides = {}) => ({+ manuscript: 'Mara stared at the bridge, then struck the match.',+ series: { characterArcs: [] },+ reverseOutline: [],+ config: { maxFindings: 12 },+ severityDefault: 'medium',+ planManuscriptChunks: async () => [overrides.manuscript ?? 'Mara stared at the bridge, then struck the match.'],+ callStagedLLM: async () => ({ content: { findings: [] } }),+ ...overrides,+ });++ it('emits arc-category transition findings from the model', async () => {+ const ctx = baseCtx({+ callStagedLLM: async (_stage, vars) => {+ // The check ships the manuscript plus its two context blocks.+ expect(vars).toHaveProperty('manuscript');+ expect(vars).toHaveProperty('sceneMap');+ expect(vars).toHaveProperty('characterArcs');+ return { content: { findings: [{ severity: 'high', issueNumber: 4, problem: 'Mara crosses the point of no return', anchorQuote: 'struck the match' }] } };+ },+ });+ const findings = await getCheck(ARC).run(ctx);+ expect(findings).toHaveLength(1);+ expect(findings[0].category).toBe('arc');+ expect(findings[0].issueNumber).toBe(4);+ });++ it('renders the authored character arcs into the prompt vars', async () => {+ let capturedArcs = null;+ const ctx = baseCtx({+ series: {+ characterArcs: [+ { characterName: 'Mara', want: 'revenge', transitions: [{ kind: 'sacrifice', label: 'spares the killer', atIssue: 6 }] },+ ],+ },+ callStagedLLM: async (_stage, vars) => {+ capturedArcs = vars.characterArcs;+ return { content: { findings: [] } };+ },+ });+ await getCheck(ARC).run(ctx);+ expect(capturedArcs).toContain('- Mara');+ expect(capturedArcs).toContain('wants: revenge');+ expect(capturedArcs).toContain('sacrifice (issue 6): spares the killer');+ });++ it('passes a scene map built from the reverse outline as context', async () => {+ let capturedSceneMap = null;+ const ctx = baseCtx({+ reverseOutline: [{ sequence: 0, issueNumber: 1, heading: 'The bridge', setting: 'a rope bridge', charactersPresent: ['Mara'] }],+ callStagedLLM: async (_stage, vars) => {+ capturedSceneMap = vars.sceneMap;+ return { content: { findings: [] } };+ },+ });+ await getCheck(ARC).run(ctx);+ expect(capturedSceneMap).toContain('The bridge');+ expect(capturedSceneMap).toContain('present: Mara');+ });++ it('is gated off when the manuscript is empty', () => {+ expect(getCheck(ARC).gate({ manuscript: ' ' })).toBe(false);+ expect(getCheck(ARC).gate({ manuscript: 'real prose' })).toBe(true);+ });++ it('degrades gracefully when no authored arcs or outline exist', async () => {+ const ctx = baseCtx({+ series: {},+ reverseOutline: undefined,+ callStagedLLM: async (_stage, vars) => {+ expect(vars.characterArcs).toBe('');+ expect(vars.sceneMap).toBe('');+ return { content: { findings: [] } };+ },+ });+ const findings = await getCheck(ARC).run(ctx);+ expect(findings).toEqual([]);+ });+});+describe('relationships.reciprocity — deterministic check', () => {const run = (characters) =>getCheck('relationships.reciprocity').run({ canon: { characters }, config: {}, severityDefault: 'low' });diff --git a/server/lib/index.js b/server/lib/index.jsindex 697dcf80e7..3e03b1e176 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -52,6 +52,7 @@ export * as editorial from './editorial/index.js';export * from './sceneExtractor.js';export * from './scenePrompt.js';export * from './seasonStructure.js';+export * from './seriesCharacterArc.js';export * from './seriesLlmOverride.js';export * from './storyArc.js';export * from './styleGuide.js';diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 4f5de5f5e9..48cbfc95a6 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -100,7 +100,14 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// recompute (a finished series renders no new cover). Gate so the older peer// rejects the ahead-version transfer instead. Per-category gate → only series// sync pauses with old peers.- pipelineSeries: 5,+ // v6 = `series.characterArcs[]` added (#1293) — per-character story arcs+ // (want/need, start → end state, transition beats). Same silent-strip-then-LWW+ // corruption as readerMap/tickingClock/styleGuide: a ≤v5 peer that re-sanitizes+ // a series through its characterArcs-unaware `sanitizeSeries` would drop the+ // arcs 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: 6,// 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 seriesdiff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex a672c3b8b8..20f2f0bbf4 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -27,9 +27,9 @@ 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 5 when series.coverImage was added (v2 = readerMap,- // v3 = tickingClock, v4 = styleGuide).- expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(5);+ // pipelineSeries bumped to 6 when series.characterArcs was added (v2 = readerMap,+ // v3 = tickingClock, v4 = styleGuide, v5 = coverImage).+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(6);});it('declares mediaCollections layout version', () => {@@ -43,7 +43,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(5);+ expect(meta.schemaVersions.pipelineSeries).toBe(6);});it('overrides merge into schemaVersions', async () => {diff --git a/server/lib/seriesCharacterArc.js b/server/lib/seriesCharacterArc.jsnew file mode 100644index 0000000000..15f06e346f--- /dev/null+++ b/server/lib/seriesCharacterArc.js@@ -0,0 +1,192 @@+/**+ * Per-character story arcs for a series (#1293).+ *+ * Sibling to `storyArc.js` — that module owns the *series-level* temporal spine+ * (the multi-season arc + the protagonist's single emotional fortune curve);+ * this one owns the *per-character* arcs: each cast member's want/need, their+ * start → end transformation, and the explicit transition beats where they+ * actually change (a decision, a realization, a point of no return).+ *+ * Where today arc lives only at the series level (`storyArc.js` protagonistArc,+ * readerMap beats) and `editorialAnalysis.js` *detects* a coarse per-character+ * arc direction (rising/falling/flat/complex), this is the AUTHORED model the+ * writer maintains and the `arc.transitions` editorial check reconciles detected+ * change moments against.+ *+ * Shape (lives at `series.characterArcs[]`):+ * {+ * characterId, // 'chr-<uuid>' pointer into the linked universe cast (or '')+ * characterName, // denormalized display name (canon name may rename)+ * want, // the external goal the character pursues+ * need, // the internal lesson/change they actually require+ * startState, // who they are at the opening+ * endState, // who they are at the close+ * transitions: [{ id, atIssue, atSceneAnchor, label, kind, note }],+ * status, // 'draft' | 'verified'+ * }+ *+ * `transitions[].kind` is one of TRANSITION_KINDS — the genre of change beat.+ *+ * Used by `services/pipeline/series.js` (sanitize on load/save) and the+ * `arc.transitions` editorial check in `lib/editorial/checkRegistry.js`.+ */++import { randomUUID } from 'crypto';+import { isStr, trimTo } from './storyBible.js';++export const CHARACTER_ARC_LIMITS = Object.freeze({+ CHARACTER_NAME_MAX: 200,+ WANT_MAX: 1000,+ NEED_MAX: 1000,+ START_STATE_MAX: 1000,+ END_STATE_MAX: 1000,+ TRANSITION_LABEL_MAX: 200,+ TRANSITION_NOTE_MAX: 1000,+ TRANSITION_ANCHOR_MAX: 300,+ TRANSITIONS_PER_ARC_MAX: 40,+ ISSUE_MAX: 9999,+ ARCS_PER_SERIES_MAX: 60,+});++export const CHARACTER_ARC_STATUSES = Object.freeze(['draft', 'verified']);++// The genre of change beat. `decision` (an active choice), `realization` (an+// internal understanding), `point-of-no-return` (an irreversible commitment),+// `relapse` (a backslide into the old self), `sacrifice` (giving up the want to+// honor the need). An unknown kind drops the transition — a beat with no+// classified kind can't be placed on the transition timeline meaningfully.+export const TRANSITION_KINDS = Object.freeze([+ 'decision',+ 'realization',+ 'point-of-no-return',+ 'relapse',+ 'sacrifice',+]);++const CHARACTER_ID_RE = /^chr-[a-zA-Z0-9-]+$/;+const TRANSITION_ID_PREFIX = 'trn-';+const TRANSITION_ID_RE = /^trn-[a-zA-Z0-9-]+$/;++const ensureTransitionId = (raw) =>+ (isStr(raw) && TRANSITION_ID_RE.test(raw) ? raw : `${TRANSITION_ID_PREFIX}${randomUUID()}`);++// Optional non-negative integer (e.g. an issue number). Absent / non-finite →+// null so the caller can distinguish "no issue pinned" from issue 0.+const optInt = (raw, max) =>+ (Number.isFinite(raw) ? Math.max(0, Math.min(max, Math.floor(raw))) : null);++/**+ * Sanitize one transition beat. Returns `null` when it carries no identifying+ * content (no label, no note, no kind survives) so `cleanTransitions` drops it.+ * A known `kind` is required — it's what places the beat on the timeline.+ */+export function sanitizeTransition(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const kind = TRANSITION_KINDS.includes(raw.kind) ? raw.kind : null;+ if (!kind) return null;+ const label = trimTo(raw.label, CHARACTER_ARC_LIMITS.TRANSITION_LABEL_MAX);+ const note = trimTo(raw.note, CHARACTER_ARC_LIMITS.TRANSITION_NOTE_MAX);+ // A kind with neither a label nor a note is an empty marker with nothing to+ // render or reason about — drop it (mirrors sanitizeReaderBeat's intent).+ if (!label && !note) return null;+ return {+ id: ensureTransitionId(raw.id),+ kind,+ label,+ atIssue: optInt(raw.atIssue, CHARACTER_ARC_LIMITS.ISSUE_MAX),+ atSceneAnchor: trimTo(raw.atSceneAnchor, CHARACTER_ARC_LIMITS.TRANSITION_ANCHOR_MAX),+ note,+ };+}++function cleanTransitions(rawList) {+ if (!Array.isArray(rawList)) return [];+ const out = [];+ for (const raw of rawList) {+ const t = sanitizeTransition(raw);+ if (t) out.push(t);+ if (out.length >= CHARACTER_ARC_LIMITS.TRANSITIONS_PER_ARC_MAX) break;+ }+ return out;+}++/**+ * Sanitize one per-character arc. Returns `null` when it carries no identifying+ * content (no character pointer/name and no authored fields) so+ * `sanitizeCharacterArcList` drops it — mirroring `sanitizeArc`/`sanitizeSeason`.+ * The `characterId` is preserved only when it matches the canon `chr-<uuid>`+ * shape; an opaque/blank id falls back to '' so a name-only arc still survives+ * (the cast link can be repaired later).+ */+export function sanitizeCharacterArc(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const characterId = isStr(raw.characterId) && CHARACTER_ID_RE.test(raw.characterId) ? raw.characterId : '';+ const characterName = trimTo(raw.characterName, CHARACTER_ARC_LIMITS.CHARACTER_NAME_MAX);+ const want = trimTo(raw.want, CHARACTER_ARC_LIMITS.WANT_MAX);+ const need = trimTo(raw.need, CHARACTER_ARC_LIMITS.NEED_MAX);+ const startState = trimTo(raw.startState, CHARACTER_ARC_LIMITS.START_STATE_MAX);+ const endState = trimTo(raw.endState, CHARACTER_ARC_LIMITS.END_STATE_MAX);+ const transitions = cleanTransitions(raw.transitions);+ // Without a character pointer/name there's nothing to attach the arc to, and+ // without any authored field or transition there's nothing to render — either+ // way it's indistinguishable from "no arc".+ if (!characterId && !characterName) return null;+ if (!want && !need && !startState && !endState && transitions.length === 0) return null;+ const status = CHARACTER_ARC_STATUSES.includes(raw.status) ? raw.status : 'draft';+ return { characterId, characterName, want, need, startState, endState, transitions, status };+}++/**+ * Sanitize the `series.characterArcs[]` field. Drops rejected entries, caps at+ * ARCS_PER_SERIES_MAX, and deduplicates by character identity (characterId when+ * present, else normalized characterName) so two arcs for the same character+ * collapse last-write-wins. Returns [] for a non-array so existing series.json+ * files migrate forward without a writer pass (first save backfills).+ */+export function sanitizeCharacterArcList(rawList) {+ if (!Array.isArray(rawList)) return [];+ const byKey = new Map();+ const order = [];+ for (const raw of rawList) {+ const arc = sanitizeCharacterArc(raw);+ if (!arc) continue;+ // Identity key: the canon pointer wins; fall back to the case-folded name so+ // a name-only arc still de-dupes against itself.+ const key = arc.characterId || `name:${arc.characterName.trim().toLowerCase()}`;+ if (!byKey.has(key)) {+ if (byKey.size >= CHARACTER_ARC_LIMITS.ARCS_PER_SERIES_MAX) continue;+ order.push(key);+ }+ byKey.set(key, arc);+ }+ return order.map((k) => byKey.get(k));+}++/**+ * Render the authored per-character arcs as a compact prompt block for the+ * `arc.transitions` editorial check. Returns null when there are no authored+ * arcs so the check's prompt template can render a "no authored arcs — propose+ * them" fallback. Mirrors `renderArcShapeGuidance` / `renderTickingClock`.+ */+export function renderCharacterArcsForPrompt(arcs) {+ if (!Array.isArray(arcs) || arcs.length === 0) return null;+ const lines = [];+ for (const arc of arcs) {+ if (!arc || typeof arc !== 'object') continue;+ const name = arc.characterName || '(unnamed character)';+ const parts = [`- ${name}`];+ if (arc.want) parts.push(`wants: ${arc.want}`);+ if (arc.need) parts.push(`needs: ${arc.need}`);+ if (arc.startState) parts.push(`starts: ${arc.startState}`);+ if (arc.endState) parts.push(`ends: ${arc.endState}`);+ lines.push(parts.join('; '));+ const transitions = Array.isArray(arc.transitions) ? arc.transitions : [];+ for (const t of transitions) {+ if (!t || typeof t !== 'object') continue;+ const at = t.atIssue != null ? ` (issue ${t.atIssue})` : '';+ const label = t.label || t.note || '(unlabeled beat)';+ lines.push(` • ${t.kind}${at}: ${label}`);+ }+ }+ return lines.length ? lines.join('\n') : null;+}diff --git a/server/lib/seriesCharacterArc.test.js b/server/lib/seriesCharacterArc.test.jsnew file mode 100644index 0000000000..ed7410553b--- /dev/null+++ b/server/lib/seriesCharacterArc.test.js@@ -0,0 +1,144 @@+import { describe, it, expect } from 'vitest';+import {+ sanitizeTransition,+ sanitizeCharacterArc,+ sanitizeCharacterArcList,+ renderCharacterArcsForPrompt,+ CHARACTER_ARC_LIMITS,+ TRANSITION_KINDS,+} from './seriesCharacterArc.js';++describe('sanitizeTransition', () => {+ it('keeps a well-formed transition and mints an id', () => {+ const t = sanitizeTransition({ kind: 'decision', label: 'Chooses to fight', note: 'turns down the deal' });+ expect(t).toMatchObject({ kind: 'decision', label: 'Chooses to fight', note: 'turns down the deal' });+ expect(t.id).toMatch(/^trn-/);+ expect(t.atIssue).toBeNull();+ expect(t.atSceneAnchor).toBe('');+ });++ it('preserves a valid trn- id', () => {+ const t = sanitizeTransition({ id: 'trn-abc-123', kind: 'realization', label: 'sees the truth' });+ expect(t.id).toBe('trn-abc-123');+ });++ it('drops a transition with an unknown kind', () => {+ expect(sanitizeTransition({ kind: 'nope', label: 'x' })).toBeNull();+ });++ it('drops a transition with a kind but no label and no note', () => {+ expect(sanitizeTransition({ kind: 'decision' })).toBeNull();+ });++ it('clamps atIssue and rejects non-finite', () => {+ expect(sanitizeTransition({ kind: 'decision', label: 'x', atIssue: -5 }).atIssue).toBe(0);+ expect(sanitizeTransition({ kind: 'decision', label: 'x', atIssue: 99999 }).atIssue)+ .toBe(CHARACTER_ARC_LIMITS.ISSUE_MAX);+ expect(sanitizeTransition({ kind: 'decision', label: 'x', atIssue: 'foo' }).atIssue).toBeNull();+ });++ it('exposes the full kind taxonomy', () => {+ expect(TRANSITION_KINDS).toContain('point-of-no-return');+ expect(TRANSITION_KINDS).toContain('sacrifice');+ });+});++describe('sanitizeCharacterArc', () => {+ it('keeps a name-only arc with no canon pointer when it has authored fields', () => {+ const arc = sanitizeCharacterArc({ characterName: 'Mara', want: 'revenge' });+ expect(arc).toMatchObject({ characterId: '', characterName: 'Mara', want: 'revenge', status: 'draft' });+ });++ it('preserves a valid chr- pointer and drops an opaque one', () => {+ expect(sanitizeCharacterArc({ characterId: 'chr-xyz', want: 'w' }).characterId).toBe('chr-xyz');+ expect(sanitizeCharacterArc({ characterId: 'bogus', characterName: 'A', want: 'w' }).characterId).toBe('');+ });++ it('returns null when there is no character identity', () => {+ expect(sanitizeCharacterArc({ want: 'something' })).toBeNull();+ });++ it('returns null when there is identity but no authored content', () => {+ expect(sanitizeCharacterArc({ characterName: 'Ghost' })).toBeNull();+ });++ it('survives on transitions alone', () => {+ const arc = sanitizeCharacterArc({+ characterName: 'Lee',+ transitions: [{ kind: 'sacrifice', label: 'gives up the throne' }],+ });+ expect(arc.transitions).toHaveLength(1);+ });++ it('drops malformed transitions and caps the list', () => {+ const many = Array.from({ length: 50 }, (_, i) => ({ kind: 'decision', label: `beat ${i}` }));+ const arc = sanitizeCharacterArc({ characterName: 'Lee', transitions: [...many, { kind: 'bad' }] });+ expect(arc.transitions).toHaveLength(CHARACTER_ARC_LIMITS.TRANSITIONS_PER_ARC_MAX);+ });++ it('coerces an unknown status to draft', () => {+ expect(sanitizeCharacterArc({ characterName: 'A', want: 'w', status: 'final' }).status).toBe('draft');+ expect(sanitizeCharacterArc({ characterName: 'A', want: 'w', status: 'verified' }).status).toBe('verified');+ });+});++describe('sanitizeCharacterArcList', () => {+ it('returns [] for a non-array', () => {+ expect(sanitizeCharacterArcList(null)).toEqual([]);+ expect(sanitizeCharacterArcList('x')).toEqual([]);+ });++ it('drops empty arcs and preserves order', () => {+ const list = sanitizeCharacterArcList([+ { characterName: 'A', want: 'w' },+ { characterName: 'Ghost' }, // dropped: no content+ { characterName: 'B', need: 'n' },+ ]);+ expect(list.map((a) => a.characterName)).toEqual(['A', 'B']);+ });++ it('dedupes by canon pointer last-write-wins', () => {+ const list = sanitizeCharacterArcList([+ { characterId: 'chr-1', characterName: 'Old', want: 'w1' },+ { characterId: 'chr-1', characterName: 'New', want: 'w2' },+ ]);+ expect(list).toHaveLength(1);+ expect(list[0]).toMatchObject({ characterName: 'New', want: 'w2' });+ });++ it('dedupes by case-folded name when no pointer', () => {+ const list = sanitizeCharacterArcList([+ { characterName: 'mara', want: 'w1' },+ { characterName: 'Mara', want: 'w2' },+ ]);+ expect(list).toHaveLength(1);+ expect(list[0].want).toBe('w2');+ });++ it('caps the arc list', () => {+ const many = Array.from({ length: 80 }, (_, i) => ({ characterName: `C${i}`, want: 'w' }));+ expect(sanitizeCharacterArcList(many)).toHaveLength(CHARACTER_ARC_LIMITS.ARCS_PER_SERIES_MAX);+ });+});++describe('renderCharacterArcsForPrompt', () => {+ it('returns null for no arcs', () => {+ expect(renderCharacterArcsForPrompt([])).toBeNull();+ expect(renderCharacterArcsForPrompt(null)).toBeNull();+ });++ it('renders arcs + transition beats', () => {+ const block = renderCharacterArcsForPrompt([+ {+ characterName: 'Mara',+ want: 'revenge',+ need: 'to forgive',+ transitions: [{ kind: 'realization', atIssue: 3, label: 'sees the cost' }],+ },+ ]);+ expect(block).toContain('- Mara');+ expect(block).toContain('wants: revenge');+ expect(block).toContain('needs: to forgive');+ expect(block).toContain('realization (issue 3): sees the cost');+ });+});diff --git a/server/routes/pipeline/series.js b/server/routes/pipeline/series.jsindex 96834e219b..74ebf74368 100644--- a/server/routes/pipeline/series.js+++ b/server/routes/pipeline/series.js@@ -21,6 +21,9 @@ 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 {+ CHARACTER_ARC_LIMITS, CHARACTER_ARC_STATUSES, TRANSITION_KINDS,+} from '../../lib/seriesCharacterArc.js';import {STYLE_GUIDE_LIMITS, STYLE_GUIDE_TENSES, STYLE_GUIDE_POV_PERSONS, STYLE_GUIDE_AUDIENCES,STYLE_GUIDE_RATINGS, STYLE_GUIDE_PROFANITY, STYLE_GUIDE_SPELLING,@@ -66,6 +69,35 @@ const arcSchema = z.object({status: z.enum(ARC_STATUSES).optional(),});+// Per-character story arc (#1293). The arc lives on the series record as+// `series.characterArcs[]`; every field optional so a partial save or an+// intentional clear both round-trip, and the service-side+// `sanitizeCharacterArcList` stays the authority (drops empty arcs/beats,+// dedupes by character identity). Mirrors the arcSchema defer-to-sanitizer+// pattern — Zod validates shape + caps, the sanitizer normalizes.+const characterArcTransitionSchema = z.object({+ id: z.string().trim().max(64).optional(),+ kind: z.enum(TRANSITION_KINDS),+ label: z.string().trim().max(CHARACTER_ARC_LIMITS.TRANSITION_LABEL_MAX).optional(),+ atIssue: z.number().int().min(0).max(CHARACTER_ARC_LIMITS.ISSUE_MAX).nullable().optional(),+ atSceneAnchor: z.string().trim().max(CHARACTER_ARC_LIMITS.TRANSITION_ANCHOR_MAX).optional(),+ note: z.string().trim().max(CHARACTER_ARC_LIMITS.TRANSITION_NOTE_MAX).optional(),+});++const characterArcSchema = z.object({+ characterId: z.string().trim().max(64).optional(),+ characterName: z.string().trim().max(CHARACTER_ARC_LIMITS.CHARACTER_NAME_MAX).optional(),+ want: z.string().trim().max(CHARACTER_ARC_LIMITS.WANT_MAX).optional(),+ need: z.string().trim().max(CHARACTER_ARC_LIMITS.NEED_MAX).optional(),+ startState: z.string().trim().max(CHARACTER_ARC_LIMITS.START_STATE_MAX).optional(),+ endState: z.string().trim().max(CHARACTER_ARC_LIMITS.END_STATE_MAX).optional(),+ transitions: z.array(characterArcTransitionSchema)+ .max(CHARACTER_ARC_LIMITS.TRANSITIONS_PER_ARC_MAX).optional(),+ status: z.enum(CHARACTER_ARC_STATUSES).optional(),+});++const characterArcsSchema = z.array(characterArcSchema).max(CHARACTER_ARC_LIMITS.ARCS_PER_SERIES_MAX);+// 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@@ -146,6 +178,7 @@ const seriesCreateSchema = z.object({writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),arc: arcSchema.nullable().optional(),seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),+ characterArcs: characterArcsSchema.optional(),locked: seriesLockedSchema.optional(),styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional().default(''),styleGuide: styleGuideSchema.nullable().optional(),@@ -170,6 +203,7 @@ const seriesPatchSchema = z.object({writersRoomWorkId: z.string().trim().max(seriesSvc.WRITERS_ROOM_WORK_ID_MAX).nullable().optional(),arc: arcSchema.nullable().optional(),seasons: z.array(seasonSchema).max(ARC_LIMITS.SEASONS_PER_SERIES_MAX).optional(),+ characterArcs: characterArcsSchema.optional(),locked: seriesLockedSchema.optional(),styleNotes: z.string().trim().max(seriesSvc.STYLE_NOTES_MAX).optional(),styleGuide: styleGuideSchema.nullable().optional(),diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 2bc660e6ff..4ff943c6d8 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: 6, pipelineIssues: 1, mediaCollections: 1 } } });+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 5, pipelineSeries: 7, 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: 6, receiverV: 5 },+ { category: 'pipelineSeries', senderV: 7, receiverV: 6 },]);expect(readSeriesState()).toEqual([]); // nothing written});diff --git a/server/services/pipeline/editorial/checkRunner.js b/server/services/pipeline/editorial/checkRunner.jsindex b41b27504d..73fd4fd0b4 100644--- a/server/services/pipeline/editorial/checkRunner.js+++ b/server/services/pipeline/editorial/checkRunner.js@@ -71,6 +71,10 @@ const SOURCE_RESOLVERS = {// flag — so a finding must go stale when it changes, not only when the arcs do.editorialArcs: ({ editorialArcs, editorialArcsComplete }) =>canonicalStringify({ arcs: editorialArcs ?? null, complete: editorialArcsComplete === true }),+ // The AUTHORED per-character story arcs the arc.transitions check reconciles+ // against (#1293). Lives on the already-loaded series record, so no extra I/O+ // — fingerprint the whole array so any arc/transition edit stales the findings.+ 'series.characterArcs': ({ series }) => canonicalStringify(series?.characterArcs ?? null),};// Stable projection of the series editorial aggregate down to the arc fields adiff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 5bd30e7c47..8b2dc538e7 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 { sanitizeCharacterArcList } from '../../lib/seriesCharacterArc.js';import { sanitizeStyleGuide } from '../../lib/styleGuide.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';@@ -186,6 +187,12 @@ const sanitizeSeries = (raw) => {// files migrate forward without a writer pass — first save backfills.arc: sanitizeArc(raw.arc),seasons: sanitizeSeasonList(raw.seasons),+ // Per-character story arcs (#1293) — each cast member's want/need, start →+ // end transformation, and explicit transition beats. Defaults to [] so+ // existing series.json files (which predate this field) migrate forward+ // without a writer pass — first save backfills. Wire-gated (pipelineSeries+ // schema v6) so a characterArcs-unaware peer can't strip-then-LWW the loss.+ characterArcs: sanitizeCharacterArcList(raw.characterArcs),locked: sanitizeSeriesLocked(raw.locked),styleNotes: trimTo(raw.styleNotes, STYLE_NOTES_MAX),// Per-series house style (tense/POV/audience/rating/reading-level/tone/@@ -273,6 +280,7 @@ export async function createSeries(input = {}) {writersRoomWorkId: input.writersRoomWorkId || null,arc: input.arc || null,seasons: input.seasons || [],+ characterArcs: input.characterArcs || [],locked: input.locked || {},styleNotes: input.styleNotes || '',styleGuide: input.styleGuide || null,@@ -431,6 +439,9 @@ export async function updateSeries(id, patch = {}) {...('writersRoomWorkId' in patch ? { writersRoomWorkId: patch.writersRoomWorkId } : {}),...('arc' in patch ? { arc: patch.arc } : {}),...('seasons' in patch ? { seasons: patch.seasons } : {}),+ // Wholesale replace — `characterArcs: []` clears all arcs; omission+ // preserves. sanitizeCharacterArcList drops empties + dedupes by identity.+ ...('characterArcs' in patch ? { characterArcs: patch.characterArcs } : {}),// Wholesale replace — `locked: {}` clears every lock; omission preserves....('locked' in patch ? { locked: patch.locked } : {}),...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),@@ -664,7 +675,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'];+const ADDITIVE_SERIES_FIELDS = ['arc', 'seasons', 'styleGuide', 'styleNotes', 'characterArcs'];// 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.jsindex 7c7d9fdc14..9dc5a89e97 100644--- a/server/services/pipeline/series.test.js+++ b/server/services/pipeline/series.test.js@@ -516,6 +516,42 @@ describe('pipeline series service', () => {});});+ describe('characterArcs (#1293)', () => {+ it('defaults to [] on a fresh series', async () => {+ const s = await svc.createSeries({ name: 'X' });+ expect(s.characterArcs).toEqual([]);+ });++ it('persists per-character arcs + transitions through an update and re-read', async () => {+ const s = await svc.createSeries({ name: 'X' });+ const updated = await svc.updateSeries(s.id, {+ characterArcs: [+ {+ characterName: 'Mara',+ want: 'revenge',+ need: 'to forgive',+ transitions: [{ kind: 'point-of-no-return', label: 'burns the bridge', atIssue: 4 }],+ },+ ],+ });+ expect(updated.characterArcs).toHaveLength(1);+ expect(updated.characterArcs[0]).toMatchObject({ characterName: 'Mara', want: 'revenge' });+ expect(updated.characterArcs[0].transitions[0]).toMatchObject({ kind: 'point-of-no-return', atIssue: 4 });+ const fresh = await svc.getSeries(s.id);+ expect(fresh.characterArcs[0].transitions[0].label).toBe('burns the bridge');+ });++ it('drops empty arcs and clears with an empty array', async () => {+ const s = await svc.createSeries({+ name: 'X',+ characterArcs: [{ characterName: 'A', want: 'w' }, { characterName: 'Ghost' }],+ });+ expect(s.characterArcs).toHaveLength(1);+ const cleared = await svc.updateSeries(s.id, { characterArcs: [] });+ expect(cleared.characterArcs).toEqual([]);+ });+ });+// Issue #1361 — a behind/legacy peer pushes a newer series payload that simply// OMITS an additive content field. sanitizeSeries flattens that absence to the// same null/[]/'' as a deliberate clear, so without the absent-vs-clear guarddiff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 38a298c90c..5f00796874 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: 5 }]);+ expect(result.ahead).toEqual([{ category: 'pipelineSeries', senderV: 99, receiverV: 6 }]);expect(result.producedByVersion).toBe('99.0.0');// Series stayed tombstoned (or absent) — apply was refused.await expect(series.getSeries(s.id)).rejects.toThrow();